自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用Acorn來解析JavaScript

開發(fā) 前端
因?yàn)樽罱ぷ魃嫌行枰褂媒馕?JavaScript 的代碼,大部分情況使用正則表達(dá)式匹配就可以處理,但是一旦依賴于代碼上下文的內(nèi)容時,正則或者簡單的字符解析就很力不從心了,這個時候需要一個語言解析器來獲取整一個 AST(abstract syntax tree)。

[[176219]]

Talk

因?yàn)樽罱ぷ魃嫌行枰褂媒馕?JavaScript 的代碼,大部分情況使用正則表達(dá)式匹配就可以處理,但是一旦依賴于代碼上下文的內(nèi)容時,正則或者簡單的字符解析就很力不從心了,這個時候需要一個語言解析器來獲取整一個 AST(abstract syntax tree)。

然后我找到了多個使用 JavaScript 編寫的 JavaScript 解析器:

  • Esprima
  • Acorn
  • UglifyJS 2
  • Shift

從提交記錄來看,維護(hù)情況都蠻好的,ES 各種發(fā)展的特性都跟得上,我分別都簡單了解了一下,聊聊他們的一些情況。

<!--more-->

Esprima 是很經(jīng)典的一個解析器,Acorn 在它之后誕生,都是幾年前的事情了。按照 Acorn 作者的說法,當(dāng)時造這個輪子更多只是好玩,速度可以和 Esprima 媲美,但是實(shí)現(xiàn)代碼更少。其中比較關(guān)鍵的點(diǎn)是這兩個解析器出來的 AST 結(jié)果(對,只是 AST,tokens 不一樣)都是符合 The Estree Spec 規(guī)范(這是 Mozilla 的工程師給出的 SpiderMonkey 引擎輸出的 JavaScript AST 的規(guī)范文檔,也可以參考:SpiderMonkey in MDN)的,也就是得到的結(jié)果在很大部分上是兼容的。

現(xiàn)在很出名的 Webpack 解析代碼時用的也是 Acorn。

至于 Uglify,很出名的一個 JavaScript 代碼壓縮器,其實(shí)它自帶了一個代碼解析器,也可以輸出 AST,但是它的功能更多還是用于壓縮代碼,如果拿來解析代碼感覺不夠純粹。

Shift 這個沒做多少了解,只知道他定義了自己的一套 AST 規(guī)范。

Esprima 官網(wǎng)上有一個性能測試,我在 chrome 上跑的結(jié)果如下:

<img src="http://ww1.sinaimg.cn/large/0... alt="性能測試" style="width:100%;">

可見,Acorn 的性能很不錯,而且還有一個 Estree 的規(guī)范呢(規(guī)范很重要,我個人覺得遵循通用的規(guī)范是代碼復(fù)用的重要基礎(chǔ)),所以我就直接選用 Acorn 來做代碼解析了。

圖中做性能對比的還有 Google 的 Traceur,它更多是一個 ES6 to ES5 的 compiler,于我們想要找的解析器定位不符。

下面進(jìn)入正題,如何使用 Acorn 來解析 JavaScript。

API

解析器的 API 都是很簡單的:

  1. const ast = acorn.parse(code, options) 

Acorn 的配置項(xiàng)蠻多的,里邊還包括了一些事件可以設(shè)置回調(diào)函數(shù)。我們挑幾個比較重要的講下:

  • ecmaVersion

字面意義,很好理解,就是設(shè)置你要解析的 JavaScript 的 ECMA 版本。默認(rèn)是 ES7。

  • sourceType

這個配置項(xiàng)有兩個值:module 和 script,默認(rèn)是 script。

主要是嚴(yán)格模式和 import/export 的區(qū)別。ES6 中的模塊是嚴(yán)格模式,也就是你無須添加 use strict。我們通常瀏覽器中使用的 script 是沒有 import/export 語法的。

所以,選擇了 script 則出現(xiàn) import/export 會報錯,可以使用嚴(yán)格模式聲明,選擇了 module,則不用嚴(yán)格模式聲明,可以使用import/export 語法。

  • locations

默認(rèn)值是 false,設(shè)置為 true 之后會在 AST 的節(jié)點(diǎn)中攜帶多一個 loc 對象來表示當(dāng)前的開始和結(jié)束的行數(shù)和列數(shù)。

  • onComment

傳入一個回調(diào)函數(shù),每當(dāng)解析到代碼中的注釋時會觸發(fā),可以獲取當(dāng)年注釋內(nèi)容,參數(shù)列表是:[block, text, start, end]。

block 表示是否是塊注釋,text 是注釋內(nèi)容,start 和 end 是注釋開始和結(jié)束的位置。

上邊提及的 Espree 需要 Esprima 的 attachComment 的配置項(xiàng),設(shè)置為 true 后,Esprima 會在代碼解析結(jié)果的節(jié)點(diǎn)中攜帶注釋相關(guān)信息(trailingComments 和 leadingComments)。Espree 則是利用 Acorn 的 onComment 配置來實(shí)現(xiàn)這個 Esprima 特性的兼容。

解析器通常還會有一個獲取詞法分析結(jié)果的接口:

  1. const tokens = [...acorn.tokenizer(code, options)] 

tokenizer 方法的第二個參數(shù)也能夠配置 locations。

詞法結(jié)果 token 和 Esprima 的結(jié)果數(shù)據(jù)結(jié)構(gòu)上有一定的區(qū)別(Espree 又是做了這一層的兼容),有興趣了解的可以看下 Esprima 的解析結(jié)果:http://esprima.org/demo/parse...

至于 Acorn 解析的 AST 和 token 的內(nèi)容我們接下來詳述。

Token

我找了半天,沒找到關(guān)于 token 數(shù)據(jù)結(jié)構(gòu)的詳細(xì)介紹,只能自己動手來看一下了。

我用來測試解析的代碼是:

  1. import "hello.js" 
  2.  
  3. var a = 2; 
  4.  
  5. // test 
  6. function name() { console.log(arguments); }  

解析出來的 token 數(shù)組是一個個類似這樣的對象:

  1. Token { 
  2.     type: 
  3.      TokenType { 
  4.        label: 'import'
  5.        keyword: 'import'
  6.        beforeExpr: false
  7.        startsExpr: false
  8.        isLoop: false
  9.        isAssign: false
  10.        prefix: false
  11.        postfix: false
  12.        binop: null
  13.        updateContext: null }, 
  14.     value: 'import'
  15.     start: 5, 
  16.     end: 11 },  

看上去其實(shí)很好理解對不對,在 type 對應(yīng)的對象中,label 表示當(dāng)前標(biāo)識的一個類型,keyword 就是關(guān)鍵詞,像例子中的import,或者 function 之類的。

value 則是當(dāng)前標(biāo)識的值,start/end 分別是開始和結(jié)束的位置。

通常我們需要關(guān)注的就是 label/keyword/value 這些了。其他的詳細(xì)可以參考源碼:tokentype.js。

The Estree Spec

這一部分是重頭戲,因?yàn)閷?shí)際上我需要的還是解析出來的 AST。最原滋原味的內(nèi)容來自于:The Estree Spec,我只是閱讀了之后的搬運(yùn)工。

提供了標(biāo)準(zhǔn)文檔的好處是,很多東西有跡可循,這里還有一個工具,用于把滿足 Estree 標(biāo)準(zhǔn)的 AST 轉(zhuǎn)換為 ESMAScript 代碼:escodegen。

好吧,回到正題,我們先來看一下 ES5 的部分,可以在 Esprima: Parser 這個頁面測試各種代碼的解析結(jié)果。

符合這個規(guī)范的解析出來的 AST 節(jié)點(diǎn)用 Node 對象來標(biāo)識,Node 對象應(yīng)該符合這樣的接口:

  1. interface Node { 
  2.     type: string; 
  3.     loc: SourceLocation | null
  4.  

type 字段表示不同的節(jié)點(diǎn)類型,下邊會再講一下各個類型的情況,分別對應(yīng)了 JavaScript 中的什么語法。

loc 字段表示源碼的位置信息,如果沒有相關(guān)信息的話為 null,否則是一個對象,包含了開始和結(jié)束的位置。接口如下:

  1. interface SourceLocation { 
  2.     source: string | null
  3.     start: Position; 
  4.     end: Position; 
  5.  

這里的 Position 對象包含了行和列的信息,行從 1 開始,列從 0 開始:

  1. interface Position { 
  2.     line: number; // >= 1 
  3.     column: number; // >= 0 
  4.  

好了,基礎(chǔ)部分就是這樣,接下來看各種類型的節(jié)點(diǎn),順帶溫習(xí)一下 JavaScript 語法的一些東西吧。對于這里每一部分的內(nèi)容,會簡單談一下,但不會展開(內(nèi)容不少),對 JavaScript 了解的人很容易就明白的。

我覺得看完就像把 JavaScript 的基礎(chǔ)語法整理了一遍。

Identifier

標(biāo)識符,我覺得應(yīng)該是這么叫的,就是我們寫 JS 時自定義的名稱,如變量名,函數(shù)名,屬性名,都?xì)w為標(biāo)識符。相應(yīng)的接口是這樣的:

  1. interface Identifier <: Expression, Pattern { 
  2.     type: "Identifier"
  3.     name: string; 
  4.  

一個標(biāo)識符可能是一個表達(dá)式,或者是解構(gòu)的模式(ES6 中的解構(gòu)語法)。我們等會會看到 Expression 和 Pattern 相關(guān)的內(nèi)容的。

Literal

字面量,這里不是指 [] 或者 {} 這些,而是本身語義就代表了一個值的字面量,如 1,“hello”, true 這些,還有正則表達(dá)式(有一個擴(kuò)展的 Node 來表示正則表達(dá)式),如 /d?/。我們看一下文檔的定義:

  1. interface Literal <: Expression { 
  2.     type: "Literal"
  3.     value: string | boolean | null | number | RegExp; 
  4.  

value 這里即對應(yīng)了字面量的值,我們可以看出字面量值的類型,字符串,布爾,數(shù)值,null 和正則。

RegExpLiteral

這個針對正則字面量的,為了更好地來解析正則表達(dá)式的內(nèi)容,添加多一個 regex 字段,里邊會包括正則本身,以及正則的flags。

  1. interface RegExpLiteral <: Literal { 
  2.   regex: { 
  3.     pattern: string; 
  4.     flags: string; 
  5.   }; 
  6.  

Programs

一般這個是作為跟節(jié)點(diǎn)的,即代表了一棵完整的程序代碼樹。

  1. interface Program <: Node { 
  2.     type: "Program"
  3.     body: [ Statement ]; 
  4.  

body 屬性是一個數(shù)組,包含了多個 Statement(即語句)節(jié)點(diǎn)。

Functions

函數(shù)聲明或者函數(shù)表達(dá)式節(jié)點(diǎn)。

  1. interface Function <: Node { 
  2.     id: Identifier | null
  3.     params: [ Pattern ]; 
  4.     body: BlockStatement; 
  5.  

id 是函數(shù)名,params 屬性是一個數(shù)組,表示函數(shù)的參數(shù)。body 是一個塊語句。

有一個值得留意的點(diǎn)是,你在測試過程中,是不會找到 type: "Function" 的節(jié)點(diǎn)的,但是你可以找到 type: "FunctionDeclaration" 和 type: "FunctionExpression",因?yàn)楹瘮?shù)要么以聲明語句出現(xiàn),要么以函數(shù)表達(dá)式出現(xiàn),都是節(jié)點(diǎn)類型的組合類型,后邊會再提及 FunctionDeclaration 和 FunctionExpression 的相關(guān)內(nèi)容。

這讓人感覺這個文檔規(guī)劃得蠻細(xì)致的,函數(shù)名,參數(shù)和函數(shù)塊是屬于函數(shù)部分的內(nèi)容,而聲明或者表達(dá)式則有它自己需要的東西。

Statement

語句節(jié)點(diǎn)沒什么特別的,它只是一個節(jié)點(diǎn),一種區(qū)分,但是語句有很多種,下邊會詳述。

  1. interface Statement <: Node { } 

ExpressionStatement

表達(dá)式語句節(jié)點(diǎn),a = a + 1 或者 a++ 里邊會有一個 expression 屬性指向一個表達(dá)式節(jié)點(diǎn)對象(后邊會提及表達(dá)式)。

  1. interface ExpressionStatement <: Statement { 
  2.     type: "ExpressionStatement"
  3.     expression: Expression; 
  4.  

BlockStatement

塊語句節(jié)點(diǎn),舉個例子:if (...) { // 這里是塊語句的內(nèi)容 },塊里邊可以包含多個其他的語句,所以有一個 body 屬性,是一個數(shù)組,表示了塊里邊的多個語句。

  1. interface BlockStatement <: Statement { 
  2.     type: "BlockStatement"
  3.     body: [ Statement ]; 
  4.  

EmptyStatement

一個空的語句節(jié)點(diǎn),沒有執(zhí)行任何有用的代碼,例如一個單獨(dú)的分號 ;

  1. interface EmptyStatement  <: Statement { 
  2.     type: "EmptyStatement "
  3.  

DebuggerStatement

debugger,就是表示這個,沒有其他了。

  1. interface DebuggerStatement <: Statement { 
  2.     type: "DebuggerStatement"
  3.  

WithStatement

with 語句節(jié)點(diǎn),里邊有兩個特別的屬性,object 表示 with 要使用的那個對象(可以是一個表達(dá)式),body 則是對應(yīng) with 后邊要執(zhí)行的語句,一般會是一個塊語句。

  1. interface WithStatement <: Statement { 
  2.     type: "WithStatement"
  3.     object: Expression; 
  4.     body: Statement; 
  5.  

下邊是控制流的語句:

ReturnStatement

返回語句節(jié)點(diǎn),argument 屬性是一個表達(dá)式,代表返回的內(nèi)容。 

  1. interface ReturnStatement <: Statement { 
  2.     type: "ReturnStatement"
  3.     argument: Expression | null
  4.  

LabeledStatement

label 語句,平時可能會比較少接觸到,舉個例子:

  1. loop: for(let i = 0; i < len; i++) { 
  2.     // ... 
  3.     for (let j = 0; j < min; j++) { 
  4.         // ... 
  5.         break loop; 
  6.     } 
  7.  

這里的 loop 就是一個 label 了,我們可以在循環(huán)嵌套中使用 break loop 來指定跳出哪個循環(huán)。所以這里的 label 語句指的就是loop: ... 這個。

一個 label 語句節(jié)點(diǎn)會有兩個屬性,一個 label 屬性表示 label 的名稱,另外一個 body 屬性指向?qū)?yīng)的語句,通常是一個循環(huán)語句或者 switch 語句。

  1. interface LabeledStatement <: Statement { 
  2.     type: "LabeledStatement"
  3.     label: Identifier; 
  4.     body: Statement; 
  5.  

BreakStatement

break 語句節(jié)點(diǎn),會有一個 label 屬性表示需要的 label 名稱,當(dāng)不需要 label 的時候(通常都不需要),便是 null。

  1. interface BreakStatement <: Statement { 
  2.     type: "BreakStatement"
  3.     label: Identifier | null
  4.  

ContinueStatement

continue 語句節(jié)點(diǎn),和 break 類似。

  1. interface ContinueStatement <: Statement { 
  2.     type: "ContinueStatement"
  3.     label: Identifier | null
  4.  

下邊是條件語句:

IfStatement

if 語句節(jié)點(diǎn),很常見,會帶有三個屬性,test 屬性表示 if (...) 括號中的表達(dá)式。

consequent 屬性是表示條件為 true 時的執(zhí)行語句,通常會是一個塊語句。

alternate 屬性則是用來表示 else 后跟隨的語句節(jié)點(diǎn),通常也會是塊語句,但也可以又是一個 if 語句節(jié)點(diǎn),即類似這樣的結(jié)構(gòu):

if (a) { //... } else if (b) { // ... }。

alternate 當(dāng)然也可以為 null。

  1. interface IfStatement <: Statement { 
  2.     type: "IfStatement"
  3.     test: Expression; 
  4.     consequent: Statement; 
  5.     alternate: Statement | null
  6.  

SwitchStatement

switch 語句節(jié)點(diǎn),有兩個屬性,discriminant 屬性表示 switch 語句后緊隨的表達(dá)式,通常會是一個變量,cases 屬性是一個case 節(jié)點(diǎn)的數(shù)組,用來表示各個 case 語句。

  1. interface SwitchStatement <: Statement { 
  2.     type: "SwitchStatement"
  3.     discriminant: Expression; 
  4.     cases: [ SwitchCase ]; 
  5.  

SwitchCase

switch 的 case 節(jié)點(diǎn)。test 屬性代表這個 case 的判斷表達(dá)式,consequent 則是這個 case 的執(zhí)行語句。

當(dāng) test 屬性是 null 時,則是表示 default 這個 case 節(jié)點(diǎn)。 

  1. interface SwitchCase <: Node { 
  2.     type: "SwitchCase"
  3.     test: Expression | null
  4.     consequent: [ Statement ]; 
  5.  

下邊是異常相關(guān)的語句:

ThrowStatement

throw 語句節(jié)點(diǎn),argument 屬性用以表示 throw 后邊緊跟的表達(dá)式。

  1. interface ThrowStatement <: Statement { 
  2.     type: "ThrowStatement"
  3.     argument: Expression; 
  4.  

TryStatement

try 語句節(jié)點(diǎn),block 屬性表示 try 的執(zhí)行語句,通常是一個塊語句。

hanlder 屬性是指 catch 節(jié)點(diǎn),finalizer 是指 finally 語句節(jié)點(diǎn),當(dāng) hanlder 為 null 時,finalizer 必須是一個塊語句節(jié)點(diǎn)。

  1. interface TryStatement <: Statement { 
  2.     type: "TryStatement"
  3.     block: BlockStatement; 
  4.     handler: CatchClause | null
  5.     finalizer: BlockStatement | null
  6.  

CatchClause

catch 節(jié)點(diǎn),param 用以表示 catch 后的參數(shù),body 則表示 catch 后的執(zhí)行語句,通常是一個塊語句。

  1. interface CatchClause <: Node { 
  2.     type: "CatchClause"
  3.     param: Pattern; 
  4.     body: BlockStatement; 
  5.  

下邊是循環(huán)語句:

WhileStatement

while 語句節(jié)點(diǎn),test 表示括號中的表達(dá)式,body 是表示要循環(huán)執(zhí)行的語句。

  1. interface WhileStatement <: Statement { 
  2.     type: "WhileStatement"
  3.     test: Expression; 
  4.     body: Statement; 
  5.  

DoWhileStatement

do/while 語句節(jié)點(diǎn),和 while 語句類似。

  1. interface DoWhileStatement <: Statement { 
  2.     type: "DoWhileStatement"
  3.     body: Statement; 
  4.     test: Expression; 
  5.  

ForStatement

for 循環(huán)語句節(jié)點(diǎn),屬性 init/test/update 分別表示了 for 語句括號中的三個表達(dá)式,初始化值,循環(huán)判斷條件,每次循環(huán)執(zhí)行的變量更新語句(init 可以是變量聲明或者表達(dá)式)。這三個屬性都可以為 null,即 for(;;){}。

body 屬性用以表示要循環(huán)執(zhí)行的語句。

  1. interface ForStatement <: Statement { 
  2.     type: "ForStatement"
  3.     init: VariableDeclaration | Expression | null
  4.     test: Expression | null
  5.     update: Expression | null
  6.     body: Statement; 
  7.  

ForInStatement

for/in 語句節(jié)點(diǎn),left 和 right 屬性分別表示在 in 關(guān)鍵詞左右的語句(左側(cè)可以是一個變量聲明或者表達(dá)式)。body 依舊是表示要循環(huán)執(zhí)行的語句。

  1. interface ForInStatement <: Statement { 
  2.     type: "ForInStatement"
  3.     left: VariableDeclaration |  Pattern; 
  4.     right: Expression; 
  5.     body: Statement; 
  6.  

Declarations

聲明語句節(jié)點(diǎn),同樣也是語句,只是一個類型的細(xì)化。下邊會介紹各種聲明語句類型。

  1. interface Declaration <: Statement { } 

FunctionDeclaration

函數(shù)聲明,和之前提到的 Function 不同的是,id 不能為 null。

  1. interface FunctionDeclaration <: Function, Declaration { 
  2.     type: "FunctionDeclaration"
  3.     id: Identifier; 
  4.  

VariableDeclaration

變量聲明,kind 屬性表示是什么類型的聲明,因?yàn)?ES6 引入了 const/let。

declarations 表示聲明的多個描述,因?yàn)槲覀兛梢赃@樣:let a = 1, b = 2;。

  1. interface VariableDeclaration <: Declaration { 
  2.     type: "VariableDeclaration"
  3.     declarations: [ VariableDeclarator ]; 
  4.     kind: "var"
  5.  

VariableDeclarator

變量聲明的描述,id 表示變量名稱節(jié)點(diǎn),init 表示初始值的表達(dá)式,可以為 null。

  1. interface VariableDeclarator <: Node { 
  2.     type: "VariableDeclarator"
  3.     id: Pattern; 
  4.     init: Expression | null
  5.  

Expressions

表達(dá)式節(jié)點(diǎn)。

  1. interface Expression <: Node { } 

ThisExpression

表示 this。

  1. interface ThisExpression <: Expression { 
  2.     type: "ThisExpression"
  3.  

ArrayExpression

數(shù)組表達(dá)式節(jié)點(diǎn),elements 屬性是一個數(shù)組,表示數(shù)組的多個元素,每一個元素都是一個表達(dá)式節(jié)點(diǎn)。

  1. interface ArrayExpression <: Expression { 
  2.     type: "ArrayExpression"
  3.     elements: [ Expression | null ]; 
  4.  

ObjectExpression

對象表達(dá)式節(jié)點(diǎn),property 屬性是一個數(shù)組,表示對象的每一個鍵值對,每一個元素都是一個屬性節(jié)點(diǎn)。

  1. interface ObjectExpression <: Expression { 
  2.     type: "ObjectExpression"
  3.     properties: [ Property ]; 
  4.  

Property

對象表達(dá)式中的屬性節(jié)點(diǎn)。key 表示鍵,value 表示值,由于 ES5 語法中有 get/set 的存在,所以有一個 kind 屬性,用來表示是普通的初始化,或者是 get/set。

  1. interface Property <: Node { 
  2.     type: "Property"
  3.     key: Literal | Identifier; 
  4.     value: Expression; 
  5.     kind: "init" | "get" | "set"
  6.  

FunctionExpression

函數(shù)表達(dá)式節(jié)點(diǎn)。

  1. interface FunctionExpression <: Function, Expression { 
  2.     type: "FunctionExpression"
  3.  

下邊是一元運(yùn)算符相關(guān)的表達(dá)式部分:

UnaryExpression

一元運(yùn)算表達(dá)式節(jié)點(diǎn)(++/-- 是 update 運(yùn)算符,不在這個范疇內(nèi)),operator 表示運(yùn)算符,prefix 表示是否為前綴運(yùn)算符。argument 是要執(zhí)行運(yùn)算的表達(dá)式。

  1. interface UnaryExpression <: Expression { 
  2.     type: "UnaryExpression"
  3.     operator: UnaryOperator; 
  4.     prefix: boolean; 
  5.     argument: Expression; 
  6.  

UnaryOperator

一元運(yùn)算符,枚舉類型,所有值如下:

  1. enum UnaryOperator { 
  2.     "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" 
  3.  

UpdateExpression

update 運(yùn)算表達(dá)式節(jié)點(diǎn),即 ++/--,和一元運(yùn)算符類似,只是 operator 指向的節(jié)點(diǎn)對象類型不同,這里是 update 運(yùn)算符。

  1. interface UpdateExpression <: Expression { 
  2.     type: "UpdateExpression"
  3.     operator: UpdateOperator; 
  4.     argument: Expression; 
  5.     prefix: boolean; 
  6.  

UpdateOperator

update 運(yùn)算符,值為 ++ 或 --,配合 update 表達(dá)式節(jié)點(diǎn)的 prefix 屬性來表示前后。

  1. enum UpdateOperator { 
  2.   "++" | "--" 
  3.  

下邊是二元運(yùn)算符相關(guān)的表達(dá)式部分:

BinaryExpression

二元運(yùn)算表達(dá)式節(jié)點(diǎn),left 和 right 表示運(yùn)算符左右的兩個表達(dá)式,operator 表示一個二元運(yùn)算符。

  1. interface BinaryExpression <: Expression { 
  2.     type: "BinaryExpression"
  3.     operator: BinaryOperator; 
  4.     left: Expression; 
  5.     right: Expression; 
  6. } 

BinaryOperator

二元運(yùn)算符,所有值如下:

  1. enum BinaryOperator { 
  2.     "==" | "!=" | "===" | "!==" 
  3.          | "<" | "<=" | ">" | ">=" 
  4.          | "<<" | ">>" | ">>>" 
  5.          | "+" | "-" | "*" | "/" | "%" 
  6.          | "|" | "^" | "&" | "in" 
  7.          | "instanceof" 
  8.  

AssignmentExpression

賦值表達(dá)式節(jié)點(diǎn),operator 屬性表示一個賦值運(yùn)算符,left 和 right 是賦值運(yùn)算符左右的表達(dá)式。

  1. interface AssignmentExpression <: Expression { 
  2.     type: "AssignmentExpression"
  3.     operator: AssignmentOperator; 
  4.     left: Pattern | Expression; 
  5.     right: Expression; 
  6.  

AssignmentOperator

賦值運(yùn)算符,所有值如下:(常用的并不多)

  1. enum AssignmentOperator { 
  2.     "=" | "+=" | "-=" | "*=" | "/=" | "%=" 
  3.         | "<<=" | ">>=" | ">>>=" 
  4.         | "|=" | "^=" | "&=" 
  5.  

LogicalExpression

邏輯運(yùn)算表達(dá)式節(jié)點(diǎn),和賦值或者二元運(yùn)算類型,只不過 operator 是邏輯運(yùn)算符類型。

  1. interface LogicalExpression <: Expression { 
  2.     type: "LogicalExpression"
  3.     operator: LogicalOperator; 
  4.     left: Expression; 
  5.     right: Expression; 
  6.  

LogicalOperator

邏輯運(yùn)算符,兩種值,即與或。

  1. enum LogicalOperator { 
  2.     "||" | "&&" 
  3.  

MemberExpression

成員表達(dá)式節(jié)點(diǎn),即表示引用對象成員的語句,object 是引用對象的表達(dá)式節(jié)點(diǎn),property 是表示屬性名稱,computed 如果為false,是表示 . 來引用成員,property 應(yīng)該為一個 Identifier 節(jié)點(diǎn),如果 computed 屬性為 true,則是 [] 來進(jìn)行引用,即property 是一個 Expression 節(jié)點(diǎn),名稱是表達(dá)式的結(jié)果值。

  1. interface MemberExpression <: Expression, Pattern { 
  2.     type: "MemberExpression"
  3.     object: Expression; 
  4.     property: Expression; 
  5.     computed: boolean; 
  6.  

下邊是其他的一些表達(dá)式:

ConditionalExpression

條件表達(dá)式,通常我們稱之為三元運(yùn)算表達(dá)式,即 boolean ? true : false。屬性參考條件語句。

  1. interface ConditionalExpression <: Expression { 
  2.     type: "ConditionalExpression"
  3.     test: Expression; 
  4.     alternate: Expression; 
  5.     consequent: Expression; 
  6.  

CallExpression

函數(shù)調(diào)用表達(dá)式,即表示了 func(1, 2) 這一類型的語句。callee 屬性是一個表達(dá)式節(jié)點(diǎn),表示函數(shù),arguments 是一個數(shù)組,元素是表達(dá)式節(jié)點(diǎn),表示函數(shù)參數(shù)列表。

  1. interface CallExpression <: Expression { 
  2.     type: "CallExpression"
  3.     callee: Expression; 
  4.     arguments: [ Expression ]; 
  5.  

NewExpression

new 表達(dá)式。

  1. interface NewExpression <: CallExpression { 
  2.     type: "NewExpression"
  3.  

SequenceExpression

這個就是逗號運(yùn)算符構(gòu)建的表達(dá)式(不知道確切的名稱),expressions 屬性為一個數(shù)組,即表示構(gòu)成整個表達(dá)式,被逗號分割的多個表達(dá)式。

  1. interface SequenceExpression <: Expression { 
  2.     type: "SequenceExpression"
  3.     expressions: [ Expression ]; 
  4.  

Patterns

模式,主要在 ES6 的解構(gòu)賦值中有意義,在 ES5 中,可以理解為和 Identifier 差不多的東西。

  1. interface Pattern <: Node { } 

這一部分的內(nèi)容比較多,但都可以舉一反三,寫這個的時候我就當(dāng)把 JavaScript 語法再復(fù)習(xí)一遍。這個文檔還有 ES2015,ES2016,ES2017 相關(guān)的內(nèi)容,涉及的東西也蠻多,但是理解了上邊的這一些,然后從語法層面去思考這個文檔,其他的內(nèi)容也就很好理解了,這里略去,有需要請參閱:The Estree Spec。

Plugins

回到我們的主角,Acorn,提供了一種擴(kuò)展的方式來編寫相關(guān)的插件:Acorn Plugins。

我們可以使用插件來擴(kuò)展解析器,來解析更多的一些語法,如 .jsx 語法,有興趣的看看這個插件:acorn-jsx。

官方表示 Acorn 的插件是用于方便擴(kuò)展解析器,但是需要對 Acorn 內(nèi)部的運(yùn)行***比較了解,擴(kuò)展的方式會在原本的基礎(chǔ)上重新定義一些方法。這里不展開講了,如果我需要插件的話,會再寫文章聊聊這個東西。

Examples

現(xiàn)在我們來看一下如何應(yīng)用這個解析器,例如我們需要用來解析出一個符合 CommonJS 規(guī)范的模塊依賴了哪些模塊,我們可以用 Acorn 來解析 require 這個函數(shù)的調(diào)用,然后取出調(diào)用時的傳入?yún)?shù),便可以獲取依賴的模塊。

下邊是示例代碼:

  1. // 遍歷所有節(jié)點(diǎn)的函數(shù) 
  2. function walkNode(node, callback) { 
  3.   callback(node) 
  4.  
  5.   // 有 type 字段的我們認(rèn)為是一個節(jié)點(diǎn) 
  6.   Object.keys(node).forEach((key) => { 
  7.     const item = node[key
  8.     if (Array.isArray(item)) { 
  9.       item.forEach((sub) => { 
  10.         sub.type && walkNode(sub, callback) 
  11.       }) 
  12.     } 
  13.  
  14.     item && item.type && walkNode(item, callback) 
  15.   }) 
  16.  
  17. function parseDependencies(str) { 
  18.   const ast = acorn.parse(str, { ranges: true }) 
  19.   const resource = [] // 依賴列表 
  20.  
  21.   // 從根節(jié)點(diǎn)開始 
  22.   walkNode(ast, (node) => { 
  23.     const callee = node.callee 
  24.     const args = node.arguments 
  25.  
  26.     // require 我們認(rèn)為是一個函數(shù)調(diào)用,并且函數(shù)名為 require,參數(shù)只有一個,且必須是字面量 
  27.     if ( 
  28.       node.type === 'CallExpression' && 
  29.       callee.type === 'Identifier' && 
  30.       callee.name === 'require' && 
  31.       args.length === 1 && 
  32.       args[0].type === 'Literal' 
  33.     ) { 
  34.       const args = node.arguments 
  35.  
  36.       // 獲取依賴的相關(guān)信息 
  37.       resource.push({ 
  38.         string: str.substring(node.range[0], node.range[1]), 
  39.         path: args[0].value, 
  40.         start: node.range[0], 
  41.         end: node.range[1] 
  42.       }) 
  43.     } 
  44.   }) 
  45.  
  46.   return resource 
  47.  

這只是簡單的一個情況的處理,但是已經(jīng)給我們呈現(xiàn)了如何使用解析器,Webpack 則在這個的基礎(chǔ)上做了更多的東西,包括 var r = require; r('a') 或者 require.async('a') 等的處理。

AST 這個東西對于前端來說,我們無時無刻不在享受著它帶來的成果(模塊構(gòu)建,代碼壓縮,代碼混淆),所以了解一下總歸有好處。

有問題歡迎討論。

責(zé)任編輯:龐桂玉 來源: segmentfault
相關(guān)推薦

2019-02-26 13:00:11

JavaScriptURL前端

2021-08-11 22:50:53

JavaScript編程開發(fā)

2010-10-08 12:46:27

Javascriptreplace()

2010-10-08 14:27:25

JavascriptSplit

2022-04-07 08:00:00

Javascript開發(fā)

2013-04-08 12:41:35

JavaScriptJS

2023-06-06 07:50:50

Symbol類型ECMAScript

2021-07-29 10:00:43

XMLXMLStarletLinux

2019-12-11 09:23:51

JavaScriptHTMLXML

2019-12-06 10:59:20

JavaScript運(yùn)行引擎

2009-03-23 13:08:07

PHP擴(kuò)展PHPJavascript

2017-05-23 15:47:04

JavaScriptthis解析

2011-09-09 19:23:52

Widget

2011-03-15 09:50:41

XMLWeb

2013-02-18 11:31:00

JavaScriptPerl語言

2024-03-28 10:17:03

JDK 17字符串十六進(jìn)制

2010-10-08 15:11:28

JavaScript數(shù)

2016-10-09 08:38:01

JavaScript瀏覽器事件

2020-06-01 08:39:12

JavaScript開發(fā)技術(shù)

2010-09-26 17:21:07

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號