【技术】【JS 静态分析】Javascript 分析工具 Esprima

之前分析 JS 用到的工具,用于生成 JS 的 AST,马克一下工具用法。

Esprima

官网:https://docs.esprima.org/en/stable/getting-started.html
体验网址:https://esprima.org/demo/parse.html#
参考资料:https://www.jianshu.com/p/47d9b2a365c5

基本用法

是一个用于对 JS 代码做词法或者语法分析的工具,只支持js,不支持 flow 或者 typescript 格式。语法格式:

1
2
esprima.parseScript(input, config, delegate)
esprima.parseModule(input, config, delegate)

input 代表原始 js 字符串;config 是如下的配置对象:
配置对象

语法树解析

  • 语法树的总体结构就两种
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    interface Program {
    type: 'Program';
    sourceType: 'script';
    body: StatementListItem[];
    }
    interface Program {
    type: 'Program';
    sourceType: 'module';
    body: ModuleItem[];
    }

    // 变量声明及执行语句
    type StatementListItem = Declaration | Statement;
    // 变量声明、执行语句、导入导出模块
    type ModuleItem = ImportDeclaration | ExportDeclaration | StatementListItem;

_Declaration

1
type Declaration = ClassDeclaration | FunctionDeclaration |  VariableDeclaration;

_Statement

1
2
3
4
5
6
7
type Statement = BlockStatement | BreakStatement | ContinueStatement |
DebuggerStatement | DoWhileStatement | EmptyStatement |
ExpressionStatement | ForStatement | ForInStatement |
ForOfStatement | FunctionDeclaration | IfStatement |
LabeledStatement | ReturnStatement | SwitchStatement |
ThrowStatement | TryStatement | VariableDeclaration |
WhileStatement | WithStatement;

_其中 ExpressionStatement

1
2
3
4
5
6
7
8
9
10
11
12
interface ExpressionStatement {
type: 'ExpressionStatement';
expression: Expression;
directive?: string;
}
// Expression 类型
type Expression = ThisExpression | Identifier | Literal |
ArrayExpression | ObjectExpression | FunctionExpression | ArrowFunctionExpression | ClassExpression |
TaggedTemplateExpression | MemberExpression | Super | MetaProperty |
NewExpression | CallExpression | UpdateExpression | AwaitExpression | UnaryExpression |
BinaryExpression | LogicalExpression | ConditionalExpression |
YieldExpression | AssignmentExpression | SequenceExpression;