JavaScript语法树与代码转化实践

开发 前端
JavaScript 语法树与代码转化实践 归纳于笔者的现代 JavaScript 开发:语法基础与实践技巧系列文章中。本文引用的参考资料声明于 JavaScript 学习与实践资料索引中,特别需要声明是部分代码片引用自 Babel Handbook 开源手册;也欢迎关注前端每周清单系列获得一手资讯。

JavaScript 语法树与代码转化实践 归纳于笔者的现代 JavaScript 开发:语法基础与实践技巧系列文章中。本文引用的参考资料声明于 JavaScript 学习与实践资料索引中,特别需要声明是部分代码片引用自 Babel Handbook 开源手册;也欢迎关注前端每周清单系列获得一手资讯。

JavaScript 语法树与代码转化

 

浏览器的兼容性问题一直是前端项目开发中的难点之一,往往客户端浏览器的升级无法与语法特性的迭代保持一致;因此我们需要使用大量的垫片(Polyfill),以保证现代语法编写而成的 JavaScript 顺利运行在生产环境下的浏览器中,从而在可用性与代码的可维护性之间达成较好的平衡。而以 Babel 为代表的语法转化工具能够帮我们自动将 ES6 等现代 JavaScript 代码转化为可以运行在旧版本浏览器中的 ES5 或其他同等的实现;实际上,Babel 不仅仅是语法解析器,其更是拥有丰富插件的平台,稍加扩展即可被应用在前端监控埋点、错误日志收集等场景中。笔者也利用 Babel 以及 Babylon 为 swagger-decorator 实现了 flowToDecorator 函数,其能够从 Flow 文件中自动提取出类型信息并为类属性添加合适的注解。

Babel

自 Babel 6 之后,核心的 babel-core 仅暴露了部分核心接口,并使用 Babylon 进行语法树构建,即上图中的 Parse 与 Generate 步骤;实际的转化步骤则是由配置的插件(Plugin)完成。而所谓的 Preset 则是一系列插件的合集,譬如 babel-preset-es2015 的源代码中就定义了一系列的插件:

  1. return { 
  2.    plugins: [ 
  3.      [transformES2015TemplateLiterals, { loose, spec }], 
  4.      transformES2015Literals, 
  5.      transformES2015FunctionName, 
  6.      [transformES201***rrowFunctions, { spec }], 
  7.      transformES2015BlockScopedFunctions, 
  8.      [transformES2015Classes, optsLoose], 
  9.      transformES2015ObjectSuper, 
  10.      ... 
  11.      modules === "commonjs" && [transformES2015ModulesCommonJS, optsLoose], 
  12.      modules === "systemjs" && [transformES2015ModulesSystemJS, optsLoose], 
  13.      modules === "amd" && [transformES2015ModulesAMD, optsLoose], 
  14.      modules === "umd" && [transformES2015ModulesUMD, optsLoose], 
  15.      [transformRegenerator, { async: false, asyncGenerators: false }] 
  16.    ].filter(Boolean) // filter out falsy values 
  17.  };  

Babel 能够将输入的 JavaScript 代码根据不同的配置将代码进行适当地转化,其主要步骤分为解析(Parse)、转化(Transform)与生成(Generate):

在解析步骤中,Babel 分别使用词法分析(Lexical Analysis)与语法分析(Syntactic Analysis)来将输入的代码转化为抽象语法树;其中词法分析步骤会将代码转化为令牌流,而语法分析步骤则是将令牌流转化为语言内置的 AST 表示。

在转化步骤中,Babel 会遍历上一步生成的令牌流,根据配置对节点进行添加、更新与移除等操作;Babel 本身并没有进行转化操作,而是依赖于外置的插件进行实际的转化。

***的代码生成则是将上一步中经过转化的抽象语法树重新生成为代码,并且同时创建 SourceMap;代码生成相较于前两步会简单很多,其核心思想在于深度优先遍历抽象语法树,然后生成对应的代码字符串。

抽象语法树

抽象语法树(Abstract Syntax Tree, AST)的作用在于牢牢抓住程序的脉络,从而方便编译过程的后续环节(如代码生成)对程序进行解读。AST 就是开发者为语言量身定制的一套模型,基本上语言中的每种结构都与一种 AST 对象相对应。上文提及的解析步骤中的词法分析步骤会将代码转化为所谓的令牌流,譬如对于代码 n * n,其会被转化为如下数组:

  1.   { type: { ... }, value: "n", start: 0, end: 1, loc: { ... } }, 
  2.   { type: { ... }, value: "*", start: 2, end: 3, loc: { ... } }, 
  3.   { type: { ... }, value: "n", start: 4, end: 5, loc: { ... } }, 
  4.   ... 
  5.  

其中每个 type 是一系列描述该令牌属性的集合:

  1.   type: { 
  2.     label: 'name'
  3.     keyword: undefined, 
  4.     beforeExpr: false
  5.     startsExpr: true
  6.     rightAssociative: false
  7.     isLoop: false
  8.     isAssign: false
  9.     prefix: false
  10.     postfix: false
  11.     binop: null
  12.     updateContext: null 
  13.   }, 
  14.   ... 
  15.  

这里的每一个 type 类似于 AST 中的节点都拥有 start、end、loc 等属性;在实际应用中,譬如对于 ES6 中的箭头函数,我们可以通过 babylon 解释器生成如下的 AST 表示:

  1.   type: { 
  2.     label: 'name'
  3.     keyword: undefined, 
  4.     beforeExpr: false
  5.     startsExpr: true
  6.     rightAssociative: false
  7.     isLoop: false
  8.     isAssign: false
  9.     prefix: false
  10.     postfix: false
  11.     binop: null
  12.     updateContext: null 
  13.   }, 
  14.   ... 
  15.  

我们可以使用 AST Explorer 这个工具进行在线预览与编辑;在上述的 AST 表示中,顾名思义,ArrowFunctionExpression 就表示该表达式为箭头函数表达式。该函数拥有 foo 与 bar 这两个参数,参数所属的 Identifiers 类型是没有任何子节点的变量名类型;接下来我们发现加号运算符被表示为了 BinaryExpression 类型,并且其 operator 属性设置为 +,而左右两个参数分别挂载于 left 与 right 属性下。在接下来的转化步骤中,我们即是需要对这样的抽象语法树进行转换,该步骤主要由 Babel Preset 与 Plugin 控制;Babel 内部提供了 babel-traverse 这个库来辅助进行 AST 遍历,该库还提供了一系列内置的替换与操作接口。而经过转化之后的 AST 表示如下,在实际开发中我们也常常首先对比转化前后代码的 AST 表示的不同,以了解应该进行怎样的转化操作:

  1. // AST shortened for clarity 
  2.     "program": { 
  3.         "type""Program"
  4.         "body": [ 
  5.             { 
  6.                 "type""ExpressionStatement"
  7.                 "expression": { 
  8.                     "type""Literal"
  9.                     "value""use strict" 
  10.                 } 
  11.             }, 
  12.             { 
  13.                 "type""ExpressionStatement"
  14.                 "expression": { 
  15.                     "type""FunctionExpression"
  16.                     "async"false
  17.                     "params": [ 
  18.                         { 
  19.                             "type""Identifier"
  20.                             "name""foo" 
  21.                         }, 
  22.                         { 
  23.                             "type""Identifier"
  24.                             "name""bar" 
  25.                         } 
  26.                     ], 
  27.                     "body": { 
  28.                         "type""BlockStatement"
  29.                         "body": [ 
  30.                             { 
  31.                                 "type""ReturnStatement"
  32.                                 "argument": { 
  33.                                     "type""BinaryExpression"
  34.                                     "left": { 
  35.                                         "type""Identifier"
  36.                                         "name""foo" 
  37.                                     }, 
  38.                                     "operator""+"
  39.                                     "right": { 
  40.                                         "type""Identifier"
  41.                                         "name""bar" 
  42.                                     } 
  43.                                 } 
  44.                             } 
  45.                         ] 
  46.                     }, 
  47.                     "parenthesizedExpression"true 
  48.                 } 
  49.             } 
  50.         ] 
  51.     } 
  52.  

自定义插件

Babel 支持以观察者(Visitor)模式定义插件,我们可以在 visitor 中预设想要观察的 Babel 结点类型,然后进行操作;譬如我们需要将下述箭头函数源代码转化为 ES5 中的函数定义:

  1. // Source Code 
  2. const func = (foo, bar) => foo + bar; 
  3.  
  4. // Transformed Code 
  5. "use strict"
  6. const _func = function(_foo, _bar) { 
  7.   return _foo + _bar; 
  8. };  

在上一节中我们对比过转化前后两个函数语法树的差异,这里我们就开始定义转化插件。首先每个插件都是以 babel 对象为输入参数,返回某个包含 visitor 的对象的函数。***我们需要调用 babel-core 提供的 transform 函数来注册插件,并且指定需要转化的源代码或者源代码文件:

  1. // plugin.js 文件,定义插件 
  2. import type NodePath from "babel-traverse"
  3.  
  4. export default function(babel) { 
  5.   const { types: t } = babel; 
  6.  
  7.   return { 
  8.     name"ast-transform", // not required 
  9.     visitor: { 
  10.       Identifier(path) { 
  11.         path.node.name = `_${path.node.name}`; 
  12.       }, 
  13.       ArrowFunctionExpression(path: NodePath<BabelNodeArrowFunctionExpression>, state: Object) { 
  14.         // In some conversion cases, it may have already been converted to a function while this callback 
  15.         // was queued up. 
  16.         if (!path.isArrowFunctionExpression()) return
  17.  
  18.         path.arrowFunctionToExpression({ 
  19.           // While other utils may be fine inserting other arrows to make more transforms possible, 
  20.           // the arrow transform itself absolutely cannot insert new arrow functions. 
  21.           allowInsertArrow: false
  22.           specCompliant: !!state.opts.spec 
  23.         }); 
  24.       } 
  25.     } 
  26.   }; 
  27.  
  28. // babel.js 使用插件 
  29. var babel = require('babel-core'); 
  30. var plugin= require('./plugin'); 
  31.  
  32. var out = babel.transform(src, { 
  33.   plugins: [plugin] 
  34. });  

常用转化操作

遍历

  • 获取子节点路径

我们可以通过 path.node.{property} 的方式来访问 AST 中节点属性:

  1. // the BinaryExpression AST node has properties: `left`, `right`, `operator` 
  2. BinaryExpression(path) { 
  3.   path.node.left
  4.   path.node.right
  5.   path.node.operator; 
  6.  

我们也可以使用某个路径对象的 get 方法,通过传入子路径的字符串表示来访问某个属性:

  1. BinaryExpression(path) { 
  2.   path.get('left'); 
  3. Program(path) { 
  4.   path.get('body.0'); 
  5.  
  • 判断某个节点是否为指定类型

内置的 type 对象提供了许多可以直接用来判断节点类型的工具函数:

  1. BinaryExpression(path) { 
  2.   if (t.isIdentifier(path.node.left)) { 
  3.     // ... 
  4.   } 
  5.  

或者同时以浅比较来查看节点属性:

  1. BinaryExpression(path) { 
  2.   if (t.isIdentifier(path.node.left, { name"n" })) { 
  3.     // ... 
  4.   } 
  5.  
  6. // 等价于 
  7. BinaryExpression(path) { 
  8.   if ( 
  9.     path.node.left != null && 
  10.     path.node.left.type === "Identifier" && 
  11.     path.node.left.name === "n" 
  12.   ) { 
  13.     // ... 
  14.   } 
  15.  
  • 判断某个路径对应的节点是否为指定类型
  1. BinaryExpression(path) { 
  2.   if (path.get('left').isIdentifier({ name"n" })) { 
  3.     // ... 
  4.   } 
  5.  
  • 获取指定路径的父节点

有时候我们需要从某个指定节点开始向上遍历获取某个父节点,此时我们可以通过传入检测的回调来判断:

  1. path.findParent((path) => path.isObjectExpression()); 
  2.  
  3. // 获取最近的函数声明节点 
  4. path.getFunctionParent();  
  • 获取兄弟路径

如果某个路径存在于 Function 或者 Program 中的类似列表的结构中,那么其可能会包含兄弟路径:

  1. // 源代码 
  2. var a = 1; // pathA, path.key = 0 
  3. var b = 2; // pathB, path.key = 1 
  4. var c = 3; // pathC, path.key = 2 
  5.  
  6. // 插件定义 
  7. export default function({ types: t }) { 
  8.   return { 
  9.     visitor: { 
  10.       VariableDeclaration(path) { 
  11.         // if the current path is pathA 
  12.         path.inList // true 
  13.         path.listKey // "body" 
  14.         path.key // 0 
  15.         path.getSibling(0) // pathA 
  16.         path.getSibling(path.key + 1) // pathB 
  17.         path.container // [pathA, pathB, pathC] 
  18.       } 
  19.     } 
  20.   }; 
  21.  
  • 停止遍历

部分情况下插件需要停止遍历,我们此时只需要在插件中添加 return 表达式:

  1. BinaryExpression(path) { 
  2.   if (path.node.operator !== '**'return
  3.  

我们也可以指定忽略遍历某个子路径:

  1. outerPath.traverse({ 
  2.   Function(innerPath) { 
  3.     innerPath.skip(); // if checking the children is irrelevant 
  4.   }, 
  5.   ReferencedIdentifier(innerPath, state) { 
  6.     state.iife = true
  7.     innerPath.stop(); // if you want to save some state and then stop traversal, or deopt 
  8.   } 
  9. });  

操作

  • 替换节点
  1. // 插件定义 
  2. BinaryExpression(path) { 
  3.   path.replaceWith( 
  4.     t.binaryExpression("**", path.node.left, t.numberLiteral(2)) 
  5.   ); 
  6.  
  7. // 代码结果 
  8.   function square(n) { 
  9. -   return n * n; 
  10. +   return n ** 2; 
  11.   }  
  • 将某个节点替换为多个节点
  1. // 插件定义 
  2. ReturnStatement(path) { 
  3.   path.replaceWithMultiple([ 
  4.     t.expressionStatement(t.stringLiteral("Is this the real life?")), 
  5.     t.expressionStatement(t.stringLiteral("Is this just fantasy?")), 
  6.     t.expressionStatement(t.stringLiteral("(Enjoy singing the rest of the song in your head)")), 
  7.   ]); 
  8.  
  9. // 代码结果 
  10.   function square(n) { 
  11. -   return n * n; 
  12. +   "Is this the real life?"
  13. +   "Is this just fantasy?"
  14. +   "(Enjoy singing the rest of the song in your head)"
  15.   }  
  • 将某个节点替换为源代码字符串
  1. // 插件定义 
  2. FunctionDeclaration(path) { 
  3.   path.replaceWithSourceString(`function add(a, b) { 
  4.     return a + b; 
  5.   }`); 
  6.  
  7. // 代码结果 
  8. function square(n) { 
  9. -   return n * n; 
  10. function add(a, b) { 
  11. +   return a + b; 
  12.   }  
  • 插入兄弟节点
  1. // 插件定义 
  2. FunctionDeclaration(path) { 
  3.   path.insertBefore(t.expressionStatement(t.stringLiteral("Because I'm easy come, easy go."))); 
  4.   path.insertAfter(t.expressionStatement(t.stringLiteral("A little high, little low."))); 
  5.  
  6. // 代码结果 
  7. "Because I'm easy come, easy go."
  8.   function square(n) { 
  9.     return n * n; 
  10.   } 
  11. "A little high, little low." 
  • 移除某个节点
  1. // 插件定义 
  2. FunctionDeclaration(path) { 
  3.   path.remove(); 
  4.  
  5. // 代码结果 
  6. function square(n) { 
  7. -   return n * n; 
  8. - }  
  • 替换节点
  1. // 插件定义 
  2. BinaryExpression(path) { 
  3.   path.parentPath.replaceWith( 
  4.     t.expressionStatement(t.stringLiteral("Anyway the wind blows, doesn't really matter to me, to me.")) 
  5.   ); 
  6.  
  7. // 代码结果 
  8.   function square(n) { 
  9. -   return n * n; 
  10. +   "Anyway the wind blows, doesn't really matter to me, to me."
  11.   }  
  • 移除某个父节点
  1. // 插件定义 
  2. BinaryExpression(path) { 
  3.   path.parentPath.remove(); 
  4.  
  5. // 代码结果 
  6.   function square(n) { 
  7. -   return n * n; 
  8.   }  

作用域

  • 判断某个局部变量是否被绑定:
  1. FunctionDeclaration(path) { 
  2.   if (path.scope.hasBinding("n")) { 
  3.     // ... 
  4.   } 
  5.  
  6. FunctionDeclaration(path) { 
  7.   if (path.scope.hasOwnBinding("n")) { 
  8.     // ... 
  9.   } 
  10.  
  • 创建 UID
  1. FunctionDeclaration(path) { 
  2.   path.scope.generateUidIdentifier("uid"); 
  3.   // Node { type: "Identifier"name"_uid" } 
  4.   path.scope.generateUidIdentifier("uid"); 
  5.   // Node { type: "Identifier"name"_uid2" } 
  6.  
  • 将某个变量声明提取到副作用中
  1. // 插件定义 
  2. FunctionDeclaration(path) { 
  3.   const id = path.scope.generateUidIdentifierBasedOnNode(path.node.id); 
  4.   path.remove(); 
  5.   path.scope.parent.push({ id, init: path.node }); 
  6.  
  7. // 代码结果 
  8. function square(n) { 
  9. + var _square = function square(n) { 
  10.     return n * n; 
  11. - } 
  12. + };  
责任编辑:庞桂玉 来源: segmentfault
相关推荐

2017-07-24 09:45:15

JavaScript语法代码

2018-04-09 14:26:06

Go语法实践

2021-05-26 08:50:37

JavaScript代码重构函数

2017-01-20 09:45:20

JavaScript代码质量

2023-10-10 10:57:12

JavaScript代码优化

2017-02-06 09:20:23

JavaScript实践

2016-06-20 11:32:27

JS原型class

2018-06-27 11:36:43

陈国兴

2009-07-06 16:01:52

ASP与JSPJSP功能

2019-07-10 10:00:42

PHPPython语法

2010-05-27 17:35:36

MYSQL DELET

2013-12-04 14:19:40

JavaScript代码重用

2012-05-22 01:20:14

SyntaxHighlJavaScriptJava

2020-02-25 20:55:20

JavaScript开发 技巧

2010-05-18 18:01:27

MySQLunion

2021-02-21 16:21:19

JavaScript闭包前端

2022-12-22 08:51:40

vivo代码

2021-04-01 17:04:34

Javascript语法数组

2010-09-30 15:19:33

2024-02-26 08:15:43

语言模型低代码
点赞
收藏

51CTO技术栈公众号