国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

AST 實戰

asoren / 3109人閱讀

摘要:本文除了介紹的一些基本概念外,更偏重實戰,講解如何利用它來對代碼進行修改。二基本概念全稱,也就是抽象語法樹,它是將編程語言轉換成機器語言的橋梁。四實戰下面我們來詳細看看如何對進行操作。

歡迎關注我的公眾號睿Talk,獲取我最新的文章:

一、前言

最近突然對 AST 產生了興趣,深入了解后發現它的使用場景還真的不少,很多我們日常開發使用的工具都跟它息息相關,如 Babel、ESLint 和 Prettier 等。本文除了介紹 AST 的一些基本概念外,更偏重實戰,講解如何利用它來對代碼進行修改。

二、基本概念

AST 全稱 Abstract Syntax Tree,也就是抽象語法樹,它是將編程語言轉換成機器語言的橋梁。瀏覽器在解析 JS 的過程中,會根據 ECMAScript 標準將字符串進行分詞,拆分為一個個語法單元。然后再遍歷這些語法單元,進行語義分析,構造出 AST。最后再使用 JIT 編譯器的全代碼生成器,將 AST 轉換為本地可執行的機器碼。如下面一段代碼:

</>復制代碼

  1. function add(a, b) {
  2. return a + b;
  3. }

進行分詞后,會得到這些 token:

對 token 進行分析,最終會得到這樣一棵 AST(簡化版):

</>復制代碼

  1. {
  2. "type": "Program",
  3. "body": [
  4. {
  5. "type": "FunctionDeclaration",
  6. "id": {
  7. "type": "Identifier",
  8. "name": "add"
  9. },
  10. "params": [
  11. {
  12. "type": "Identifier",
  13. "name": "a"
  14. },
  15. {
  16. "type": "Identifier",
  17. "name": "b"
  18. }
  19. ],
  20. "body": {
  21. "type": "BlockStatement",
  22. "body": [
  23. {
  24. "type": "ReturnStatement",
  25. "argument": {
  26. "type": "BinaryExpression",
  27. "left": {
  28. "type": "Identifier",
  29. "name": "a"
  30. },
  31. "operator": "+",
  32. "right": {
  33. "type": "Identifier",
  34. "name": "b"
  35. }
  36. }
  37. }
  38. ]
  39. }
  40. }
  41. ],
  42. "sourceType": "module"
  43. }

拿到 AST 后就可以根據規則轉換為機器碼了,在此不再贅述。

三、Babel 工作原理

AST 除了可以轉換為機器碼外,還能做很多事情,如 Babel 就能通過分析 AST,將 ES6 的代碼轉換成 ES5。

Babel 的編譯過程分為 3 個階段:

解析:將代碼字符串解析成抽象語法樹

變換:對抽象語法樹進行變換操作

生成:根據變換后的抽象語法樹生成新的代碼字符串

Babel 實現了一個 JS 版本的解析器Babel parser,它能將 JS 字符串轉換為 JSON 結構的 AST。為了方便對這棵樹進行遍歷和變換操作,babel 又提供了traverse工具函數。完成 AST 的修改后,可以使用generator生成新的代碼。

四、AST 實戰

下面我們來詳細看看如何對 AST 進行操作。先建好如下的代碼模板:

</>復制代碼

  1. import parser from "@babel/parser";
  2. import generator from "@babel/generator";
  3. import t from "@babel/types";
  4. import traverser from "@babel/traverse";
  5. const generate = generator.default;
  6. const traverse = traverser.default;
  7. const code = ``;
  8. const ast = parser.parse(code);
  9. // AST 變換
  10. const output = generate(ast, {}, code);
  11. console.log("Input
  12. ", code);
  13. console.log("Output
  14. ", output.code);

構造一個 hello world

打開 AST Explorer,將左側代碼清空,再輸入 hello world,可以看到前后 AST 的樣子:

</>復制代碼

  1. // 空
  2. {
  3. "type": "Program",
  4. "body": [],
  5. "sourceType": "module"
  6. }
  7. // hello world
  8. {
  9. "type": "Program",
  10. "body": [
  11. {
  12. "type": "ExpressionStatement",
  13. "expression": {
  14. "type": "Literal",
  15. "value": "hello world",
  16. "raw": ""hello world""
  17. },
  18. "directive": "hello world"
  19. }
  20. ],
  21. "sourceType": "module"
  22. }

接下來通過代碼構造這個ExpressionStatement:

</>復制代碼

  1. const code = ``;
  2. const ast = parser.parse(code);
  3. // 生成 literal
  4. const literal = t.stringLiteral("hello world")
  5. // 生成 expressionStatement
  6. const exp = t.expressionStatement(literal)
  7. // 將表達式放入body中
  8. ast.program.body.push(exp)
  9. const output = generate(ast, {}, code);

可以看到 AST 的創建過程就是自底向上創建各種節點的過程。這里我們借助 babel 提供的types對象幫我們創建各種類型的節點。更多類型可以查閱這里。

同樣道理,下面我們來看看如何構造一個賦值語句:

</>復制代碼

  1. const code = ``;
  2. const ast = parser.parse(code);
  3. // 生成 identifier
  4. const id = t.identifier("str")
  5. // 生成 literal
  6. const literal = t.stringLiteral("hello world")
  7. // 生成 variableDeclarator
  8. const declarator = t.variableDeclarator(id, literal)
  9. // 生成 variableDeclaration
  10. const declaration = t.variableDeclaration("const", [declarator])
  11. // 將表達式放入body中
  12. ast.program.body.push(declaration)
  13. const output = generate(ast, {}, code);

獲取 AST 中的節點

下面我們將對這段代碼進行操作:

</>復制代碼

  1. export default {
  2. data() {
  3. return {
  4. count: 0
  5. }
  6. },
  7. methods: {
  8. add() {
  9. ++this.count
  10. },
  11. minus() {
  12. --this.count
  13. }
  14. }
  15. }

假設我想獲取這段代碼中的data方法,可以直接這么訪問:

</>復制代碼

  1. const dataProperty = ast.program.body[0].declaration.properties[0]

也可以使用 babel 提供的traverse工具方法:

</>復制代碼

  1. const code = `
  2. export default {
  3. data() {
  4. return {
  5. count: 0
  6. }
  7. },
  8. methods: {
  9. add() {
  10. ++this.count
  11. },
  12. minus() {
  13. --this.count
  14. }
  15. }
  16. }
  17. `;
  18. const ast = parser.parse(code, {sourceType: "module"});
  19. // const dataProperty = ast.program.body[0].declaration.properties[0]
  20. traverse(ast, {
  21. ObjectMethod(path) {
  22. if (path.node.key.name === "data") {
  23. path.node.key.name = "myData";
  24. // 停止遍歷
  25. path.stop();
  26. }
  27. }
  28. })
  29. const output = generate(ast, {}, code);

traverse方法的第二個參數是一個對象,只要提供與節點類型同名的屬性,就能獲取到所有的這種類型的節點。通過path參數能訪問到節點信息,進而找出需要操作的節點。上面的代碼中,我們找到方法名為data的方法后,將其改名為myData,然后停止遍歷,生成新的代碼。

替換 AST 中的節點

可以使用replaceWithreplaceWithSourceString替換節點,例子如下:

</>復制代碼

  1. //this.count 改成 this.data.count
  2. const code = `this.count`;
  3. const ast = parser.parse(code);
  4. traverse(ast, {
  5. MemberExpression(path) {
  6. if (
  7. t.isThisExpression(path.node.object) &&
  8. t.isIdentifier(path.node.property, {
  9. name: "count"
  10. })
  11. ) {
  12. //this 替換為 this.data
  13. path
  14. .get("object")
  15. .replaceWith(
  16. t.memberExpression(t.thisExpression(), t.identifier("data"))
  17. );
  18. // 下面的操作跟上一條語句等價,更加直觀方便
  19. // path.get("object").replaceWithSourceString("this.data");
  20. }
  21. }
  22. });
  23. const output = generate(ast, {}, code);

插入新的節點

可以使用pushContainerinsertBeforeinsertAfter等方法來插入節點:

</>復制代碼

  1. // 這個例子示范了 3 種節點插入的方法
  2. const code = `
  3. const obj = {
  4. count: 0,
  5. message: "hello world"
  6. }
  7. `;
  8. const ast = parser.parse(code);
  9. const property = t.objectProperty(
  10. t.identifier("new"),
  11. t.stringLiteral("new property")
  12. );
  13. traverse(ast, {
  14. ObjectExpression(path) {
  15. path.pushContainer("properties", property);
  16. // path.node.properties.push(property);
  17. }
  18. });
  19. /*
  20. traverse(ast, {
  21. ObjectProperty(path) {
  22. if (
  23. t.isIdentifier(path.node.key, {
  24. name: "message"
  25. })
  26. ) {
  27. path.insertAfter(property);
  28. }
  29. }
  30. });
  31. */
  32. const output = generate(ast, {}, code);

刪除節點

使用remove方法來刪除節點:

</>復制代碼

  1. const code = `
  2. const obj = {
  3. count: 0,
  4. message: "hello world"
  5. }
  6. `;
  7. const ast = parser.parse(code);
  8. traverse(ast, {
  9. ObjectProperty(path) {
  10. if (
  11. t.isIdentifier(path.node.key, {
  12. name: "message"
  13. })
  14. ) {
  15. path.remove();
  16. }
  17. }
  18. });
  19. const output = generate(ast, {}, code);
五、總結

本文介紹了 AST 的一些基本概念,講解了如何使用 Babel 提供的 API,對 AST 進行增刪改查的操作。?掌握這項技能,再加上一點想象力,就能制作出實用的代碼分析和轉換工具。

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/105902.html

相關文章

  • Babylon-AST初探-實戰

    摘要:生成屬性這一步,我們要先提取原函數中的的對象。所以這里我們還是主要使用來訪問節點獲取第一級的,也就是函數體將合并的寫法用生成生成生成插入到原函數下方刪除原函數程序輸出將中的屬性提升一級這里遍歷中的屬性沒有再采用,因為這里結構是固定的。 ??經過之前的三篇文章介紹,AST的CRUD都已經完成。下面主要通過vue轉小程序過程中需要用到的部分關鍵技術來實戰。 下面的例子的核心代碼依然是最簡單...

    godiscoder 評論0 收藏0
  • Babylon-AST初探-代碼更新&刪除(Update & Remove)

    摘要:操作通常配合來完成。因為是個數組,因此,我們可以直接使用數組操作自我毀滅方法極為簡單,找到要刪除的,執行就結束了。如上述代碼,我們要刪除屬性,代碼如下到目前為止,的我們都介紹完了,下面一篇文章以轉小程序為例,我們來實戰一波。 ??通過前兩篇文章的介紹,大家已經了解了Create和Retrieve,我們接著介紹Update和 Remove操作。Update操作通常配合Create來完成。...

    levius 評論0 收藏0
  • AST抽象語法樹——最基礎的javascript重點知識,99%的人根本不了解

    摘要:抽象語法樹,是一個非常基礎而重要的知識點,但國內的文檔卻幾乎一片空白。事實上,在世界中,你可以認為抽象語法樹是最底層。通過抽象語法樹解析,我們可以像童年時拆解玩具一樣,透視這臺機器的運轉,并且重新按著你的意愿來組裝。 抽象語法樹(AST),是一個非常基礎而重要的知識點,但國內的文檔卻幾乎一片空白。本文將帶大家從底層了解AST,并且通過發布一個小型前端工具,來帶大家了解AST的強大功能 ...

    godiscoder 評論0 收藏0
  • FE.SRC-Vue實戰與原理筆記

    摘要:超出此時間則渲染錯誤組件。元素節點總共有種類型,為表示是普通元素,為表示是表達式,為表示是純文本。 實戰 - 插件 form-validate {{ error }} ...

    wangjuntytl 評論0 收藏0
  • Vue編程三部曲之模型樹優化實戰代碼

      實踐是所有展示最好的方法,因此我覺得可以不必十分細致的,但我們的展示卻是整體的流程、輸入和輸出。現在我們就看看Vue 的指令、內置組件等。也就是第二篇,模型樹優化。  分析了 Vue 編譯三部曲的第一步,「如何將 template 編譯成 AST ?」上一篇已經介紹,但我們還是來總結回顧下,parse 的目的是將開發者寫的 template 模板字符串轉換成抽象語法樹 AST ,AST 就這里...

    3403771864 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<