本文為來自 字節(jié)教育-成人與創(chuàng)新前端團隊 成員的文章,已授權(quán) ELab 發(fā)布。
簡介
在計算機科學(xué)中,抽象語法樹是源代碼語法結(jié)構(gòu)的一種抽象表示。它以樹狀的形式表現(xiàn)編程語言的語法結(jié)構(gòu),樹上的每個節(jié)點都表示源代碼中的一種結(jié)構(gòu)。之所以說語法是“抽象”的,是因為這里的語法并不會表示出真實語法中出現(xiàn)的每個細(xì)節(jié)。
——維基百科
在前端基建中,ast可以說是必不可少的。對ast進行操作,其實就相當(dāng)于對源代碼進行操作。
ast的應(yīng)用包括:
- 開發(fā)輔助:eslint、prettier、ts檢查
- 代碼變更:壓縮、混淆、css modules
- 代碼轉(zhuǎn)換:jsx、vue、ts轉(zhuǎn)換為js
ast的生成
通過詞法分析和語法分析,可以得出一顆ast。
- 詞法分析
詞法分析的過程是將代碼喂給有限狀態(tài)機,結(jié)果是將代碼單詞轉(zhuǎn)換為令牌(token),一個token包含的信息包括其的種類、屬性值等。
例如將 ??const a = 1 + 1?
? 轉(zhuǎn)換為token的話,結(jié)果大概如下
[
{type: 關(guān)鍵字, value: const},
{type: 標(biāo)識符, value: a},
{type: 賦值操作符, value: =},
{type: 常數(shù), value: 1},
{type: 運算符, value: +},
{type: 常數(shù), value: 1},
]
- 語法分析
面對一串代碼,先通過詞法分析,獲得第一個token,為其建立一個ast節(jié)點,此時的ast節(jié)點的屬性以及子節(jié)點都不完整。
為了補充這些缺少的部分,接下來移動到下一個單詞,生成token,并且將其轉(zhuǎn)換成子節(jié)點,添加進現(xiàn)有的ast中,然后重復(fù)這個 移動&生成 的遞歸的過程。
- 讓我們來看看
const a = 1
是怎么變成一顆ast的。
- 讀取const,生成一個VariableDeclaration節(jié)點
- 讀取a,新建VariableDeclarator節(jié)點
- 讀取=
- 讀取1,新建NumericLiteral節(jié)點
- 將NumericLiteral賦值給VariableDeclarator的init屬性
- 將VariableDeclarator賦值給VariableDeclaration的declaration屬性
前端編譯
隨著前端技術(shù)和理念的不斷進步,涌現(xiàn)了各種新奇的代碼以及帶來了新的項目組織方式。
但在這些新技術(shù)中,有許多代碼不能在瀏覽器中直接執(zhí)行,比如typescript、jsx等,這種情況下我們的項目就需要通過編譯、打包,將其轉(zhuǎn)換為可以直接在瀏覽器中執(zhí)行的代碼。
以webpack為例,打包工具作用就是基于代碼的import、export、require構(gòu)建依賴樹,將其做成一個或多個bundles。它解決的是模塊化的問題,但它自帶的能力只能支持javascript以及json文件,而平時我們遇到的ts、jsx、vue文件,則需要先經(jīng)過編譯工具的編譯。例如如果我們想用webpack對含有ts文件的項目進行打包,進行如下配置。
// webpack.config.js
const path = require('path');
module.exports = {
// ...
module: {
rules: [{
test: /.ts$/,
use: 'babel-loader',
options: {
presets: [
'@babel/typescript'
]
}
}],
},
};
配置的含義則是:當(dāng)webpack解析到.ts文件時,先使用babel-loader進行轉(zhuǎn)換,再進行打包。
操作ast進行代碼編譯
?編譯工具?
常見的編譯工具有這幾種
- babel:目前最主流的編譯工具,使用javascript編寫。
- esbuild:使用Go語言開發(fā)的打包工具(也包含了編譯功能), 被Vite用于開發(fā)環(huán)境的編譯。
- swc:使用rust編寫的編譯工具。
在對外提供直接操作ast的能力上,babel和swc使用的是訪問者模式,插件編寫上有較多的共通之處,最大的區(qū)別就是語言不同。esbuild沒有對外提供直接操作ast的能力,但是可以通過接入其他的編譯工具達(dá)到操作ast的效果。
編譯過程
代碼編譯的過程分為三步,接(parse)、化(transform)、發(fā)(generate)
parse的過程則是上文中提到的,將代碼從字符串轉(zhuǎn)化為樹狀結(jié)構(gòu)的ast。
transform則是對ast節(jié)點進行遍歷,遍歷的過程中對ast進行修改。
generate則是將被修改過的ast,重新生成為代碼。
編譯插件
一般我們提起babel,就會想到是用來將新標(biāo)準(zhǔn)的js轉(zhuǎn)化為兼容性更高的舊標(biāo)準(zhǔn)js。
如果babel默認(rèn)的編譯效果不能滿足我們的需求,那我們要如何插手編譯過程,將ast修改成我們想要的ast呢。此時就需要用到babel plugin,也就是babel插件。
就如同上文中的配置
const path = require('path');
module.exports = {
module: {
rules: [{
test: /.ts$/,
use: 'babel-loader',
options: {
presets: [
// presets也就是已經(jīng)配置好的插件集合,也就是“預(yù)設(shè)”
'@babel/preset-typescript'
]
}
}],
},
};
除了以上將typescript轉(zhuǎn)換為javscript的插件外,日常中我們還會用到許多其他的插件/預(yù)設(shè),例如
- @babel/react 轉(zhuǎn)換react文件
- react-refresh/babel 熱刷新
- babel-plugin-react-css-modules css模塊化 避免樣式污染
- istanbul 收集代碼覆蓋率
- ......
Hello plugin!
babel在將代碼轉(zhuǎn)換為ast后,會對ast進行遍歷,在遍歷時,會應(yīng)用插件所提供的訪問者對相應(yīng)的ast節(jié)點進行訪問,以達(dá)到修改ast的目的。
我們在編寫插件時,首先我們需要知道我們想要訪問的ast節(jié)點對應(yīng)的類型是什么。假如我們要對函數(shù)類型的ast節(jié)點進行修改,先來看看這一段代碼經(jīng)過babel的轉(zhuǎn)換以后會生成什么樣的ast。
https://astexplorer.net/
function a() {};
const b = function() {
}
const c = () => {};
ast:(刪除部分結(jié)構(gòu)后)
[
{
"type": "FunctionDeclaration",
"id": {
"type": "Identifier",
"name": "a"
}
},
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "b"
},
"init": {
"type": "FunctionExpression",
}
}
],
"kind": "const"
},
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "c"
},
"init": {
"type": "ArrowFunctionExpression",
}
}
],
"kind": "const"
}
]
新建my-plugin.js,在其中編寫如下代碼,對外暴露出訪問者,babel在遍歷到對應(yīng)節(jié)點時會調(diào)用相應(yīng)的訪問者。
// my-plugin.js
module.exports = () => ({
visitor: {
// 對一種ast節(jié)點進行訪問
FunctionDeclaration: {
enter: enterFunction,
// 在babel對ast進行深度優(yōu)先遍歷時,
// 我們有enter和exit兩次機會訪問同一個ast節(jié)點。
exit: exitFunction
},
// 對多種ast節(jié)點進行訪問
"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression": {
enter: enterFunction
}
// 使用“別名”進行訪問
Function: enterFunction
}
})
function enterFunction() {
console.log('hello plugin!')
};
function exitFunction() {};
接入插件
// .babelrc
{
"plugins": [
'./my-plugin.js'
]
}
實踐
接下來我們來通過編寫一個完整的babel插件來看看如何對ast進行修改:打印出函數(shù)的執(zhí)行時間
代碼:
async function a() {
function b() {
for (let i = 0; i < 10000000; i += Math.random()) {}
}
b();
await new Promise(resolve => {
setTimeout(resolve, 1000);
})
}
運行效果:
b cost: 219 // 函數(shù)b耗時219毫秒
anonymous cost: 0 // promise中的匿名函數(shù)耗時0毫秒
a cost: 1222 // 函數(shù)a耗時1222毫秒
實現(xiàn)思路:在函數(shù)的第一行,插入一個ast節(jié)點,定義一個變量記錄剛開始執(zhí)行函數(shù)的時間。在函數(shù)的的最后一行,以及return時,打印出當(dāng)前時間與開始時間的差。
新增&插入節(jié)點
除了手寫一個ast節(jié)點以外我們可以通過兩種babel為我們提供的輔助工具生成ast節(jié)點
@babel/types
一個工具集,可以用來新建、校驗節(jié)點等。
在這里我們需要新建一個 var fnName_start_time = Date.now()的ast節(jié)點。
import * as t from 'babel-types';
function functionEnter(path, state) {
const node = path.node;
const fnName = node.name || node.id?.name || 'anonymous';
// 新建一個變量聲明
const ast = t.variableDeclarator(
// 變量名
t.identifier(`${fnName}_start_time`),
// Date.now()
t.callExpression(
t.memberExpression(
t.identifier('Date'),
t.identifier('now')
),
// 參數(shù)為空
[]
)
);
}
@babel/template
通過模板的方式,可以直接將代碼轉(zhuǎn)換成ast,也可以替換掉模版中的節(jié)點,方便快捷。
import template from "babel-template";
const varName = `${fnName}_start_time`;
// 直接通過代碼生成
const ast = template(`const ${varName} = Date.now()`)();
// 或者
const ast = template('const fnName = Date.now()')({
fnName: t.identifier(varName)
})
在生成了我們想要的ast節(jié)點后,我們可以將其插入到我們現(xiàn)有的節(jié)點中。
function functionEnter(path, state) {
const node = path.node;
const fnName = node.name || node.id?.name || 'anonymous';
const varName = `${fnName}_start_time`;
const start = template(`const ${varName} = Date.now()`)();
const end = template(
`console.log('${fnName} cost:', Date.now() - ${varName})`
)();
if (!node.body) {
return;
}
// 插入到容器中,函數(shù)的第一行添加const fnName_start_time = Date.now()
path.get('body').unshiftContainer('body', start);
path.get('body').pushContainer('body', end);
}
module.exports = () => ({
visitor: {
Function: enterFunction
}
})
主動遍歷&停止遍歷&狀態(tài)
雖然我們在函數(shù)的第一行和最后一行添加了相應(yīng)的代碼,但是還是不能完整的實現(xiàn)我們需要的功能——如果函數(shù)在執(zhí)行最后一行之前進行了return,則不能打印出耗時數(shù)據(jù)。
找出該函數(shù)進行return的ast節(jié)點,在return之前,先把函數(shù)的耗時打印出來。
function a() {
if (Math.random() > 0.5) {
// 需要逮出來的return
return 'a';
}
function b() {
// 需要跳過的return
return 'b';
}
}
通過主動遍歷的方法,我們把returnStatement的訪問者放到Function的訪問者中。
當(dāng)我們進行主動遍歷時,需要跳過子節(jié)點中的函數(shù)節(jié)點的遍歷,因為我們的目的只是在遍歷函數(shù)a節(jié)點時,訪問其return,而不想去修改子函數(shù)節(jié)點的return。
function functionEnter(path, state) {
// 主動遍歷
path.traverse({
// 訪問遍歷到子函數(shù),則跳過子函數(shù)及其的子節(jié)點遍歷
Function(innerPath) {
innerPath.skip();
},
// 訪問類型為ReturnStatement的子節(jié)點
ReturnStatement: returnEnter
// 傳遞狀態(tài)
}, { fnName })
}
function returnEnter(path, state) {
// 讀取狀態(tài)
const { fnName } = state;
// 代碼為resutn xxx; 新建 const fnName_result = xxx 的節(jié)點
const resultVar = t.identifier(`${fnName}_result`);
const returnResult = template(`const RESULT_VAR = RESULT`)({
RESULT_VAR: resultVar,
RESULT: path.node.argument || t.identifier('undefined')
})
// 插入兄弟節(jié)點
path.insertBefore(returnResult);
// 修改return xxx為
// return (console.log('耗時'), fnName_result)
const varName = `${fnName}_start_time`;
const end = template(
`console.log('${fnName} cost:', Date.now() - ${varName})`
)();
const ast = t.sequenceExpression([
end.expression,
resultVar
]);
path.node.argument = ast;
}
最終效果
// 原代碼
function a() {
function b() {
for (let i = 0; i < 10000000; i += Math.random()) {}
function c() {
for (let i = 0; i < 10000000; i += Math.random()) {}
}
return c();
}
b();
for (let i = 0; i < 10000000; i += Math.random()) {}
}
// 經(jīng)過babel編譯的代碼
function a() {
var a_start_time = Date.now();
function b() {
var b_start_time = Date.now();
for (var i = 0; i < 10000000; i += Math.random()) {}
function c() {
var c_start_time = Date.now();
for (var _i = 0; _i < 10000000; _i += Math.random()) {}
console.log('c cost:', Date.now() - c_start_time);
}
var b_result = c();
return console.log('b cost:', Date.now() - b_start_time), b_result;
console.log('b cost:', Date.now() - b_start_time);
}
b();
for (var i = 0; i < 10000000; i += Math.random()) {}
console.log('a cost:', Date.now() - a_start_time);
}
// 運行后控制臺打印結(jié)果
c cost: 290
b cost: 603
a cost: 895