What is the

Abstract Syntax Tree (AST) is a Tree representation of Abstract Syntax structure of source code. At the heart of many libraries, such as WebPack and ESLint, is the concept of an abstract syntax tree for code inspection and analysis.

How to get

For example, js compilation will go through two steps: lexical analysis => syntax analysis => AST

  1. Lexical analysis: Also known as scanning, it translates streams of characters into streams of tokens that read our code and then compose tokens according to certain rules. For example: var a = 2, this code is usually split into var, a, =, 2
[
  { type: 'Keyword', value: 'var' },
  { type: 'Identifier', value: 'a' },
  { type: 'Punctuator', value: '=' },
  { type: 'Numeric', value: '2' },
]
Copy the code
  1. Parsers: Also called parsers, which convert morphologically parsed arrays into tree forms and validate syntax. Throw syntax errors if there are any.
{... "type": "VariableDeclarator", "id": { "type": "Identifier", "name": "a" }, ... }Copy the code

What can do

  • Syntax checking, code style checking, formatting code, syntax highlighting, error prompts, auto completion, etc
  • Code obfuscation compression
  • Optimize change code, change code structure, etc

Ast Parsing Process

For details of babael’s workflow, skip here.

Refer to the article blog.csdn.net/weixin_4243…