疑问

  • 如何操作这些节点?

    常见AST节点类型

    并不需要记什么内容对应什么 AST 节点,可以通过 axtexplorer.net 这个网站来直观的查看。
    想查看全部的 AST 可以在babel parser 仓库里的 AST 文档里查,或者直接去看 @babel/types 的typescript 类型定义

    字面量(Literal)

  • let name = guang 中的 guang 就是一个字符串字面量(StringLiteral)

  • 相应的还有数字字面量(NumericLiteral)、布尔字面量(BooleanLiteral)、正则表达式字面量 RegExpLiteral 等

    标识符(Identifier)

  • 变量名、属性名、参数名等各种声明和引用的名字,都是 Identifier。

  • 注意:console、log、和function中的name也是

    语句(Statement)

  • 语句是可以独 立执行的单位,例如 break、return 或者 if语句、声明语句、表达式语句等

    声明语句(Declaration)

  • 是一种比较特殊的语句,他是在作用域中声明一个变量、函数、class、import、export 等等

    表达式(Expression)

  • 表达式的特点是执行完后有返回值,这也是和语句的区别。

  • 有的表达式可以独立作为语句执行,会包裹一层 ExpressionStatement。

    class

  • Class的内容是 ClassBody,属性是 ClassProperty,方法是 ClassMethod

    Modules

  • es module 是语法级别的模块规范,有专门的 AST 节点。

    import(ImportDeclaration )

  • 三种import语法都对应 ImportDeclaration 节点,但 specifiers 属性不同

    • named import: importSpecifier
    • default import: importDefaultSpecifier
    • namespaced import: importNamespaceSpecifier

      export

  • named export: ExportNamedDeclaration

  • default export: ExportDefaultDeclaration
  • all export: ExportAllDeclaration 的节点。
  • 其中只有 ExportNamedDeclaration 有 specifiers 属性:exportSpecifier

    Program & Directive

  • Program 代表整个程序的节点, 是包裹具体执行语句的节点

  • Directive 则是代码中的指令部分。

    File & Comment

  • File 是 AST 最外层的节点

    • 有 program、comments、tokens等属性,分别存放 Program程序体、注释、token等。
  • 注释分为块注释和行内注释,对应 CommentBlock 和 CommentLine 节点。

    AST 的公共属性

  • type: AST 节点的类型

  • start、end、loc
    • 用于记录该节点在对应的源码字符串中的位置
  • leadingComments、innerComments、trailingComments:代表注释
  • extra:记录一些额外的信息