本文由 AI 分析生成
Summary
AndyWu introduces Abstract Syntax Trees (AST) motivated by a practical need: writing custom ESLint rules to catch undefined variables in a messy Node.js codebase. The article explains why AST is the universal data structure used by compilers, interpreters, linters, and query optimizers to process code, shows how JavaScript code maps to a tree structure, and covers applications including transpilation, IDE features, and code transformation.
AndyWu 以撰寫客製化 ESLint 規則的實際需求為動機,介紹抽象語法樹(AST)。文章解釋為何 AST 是編譯器、直譯器、Linter 和查詢優化器處理代碼的通用數據結構,展示 JavaScript 代碼如何映射為樹狀結構,並涵蓋轉譯、IDE 功能和代碼轉換等應用。
Key Points
- Code files are strings; AST transforms them into tree data structures that computers can reason about
- AST is used by: compilers, interpreters, linters, SQL query parsers/optimizers, Babel, IDE tooling
- SQL → AST → query optimizer → query plan → execution; same pipeline as code compilation
- ESLint traverses the AST and checks nodes against rules — custom rules hook into this traversal
- Tools: astexplorer.net lets you interactively inspect the AST of any code snippet
Insights
The SQL parallel is illuminating: SQL “code” goes through the exact same AST pipeline as JavaScript code, even though SQL and JavaScript feel very different. This reveals that “parsing” is a universal step in any system that interprets structured text. The practical motivation (custom ESLint rules to catch undefined variables) grounds the abstract concept in something immediately applicable to working developers.
Connections
Raw Excerpt
以電腦的角度來看,一份程式碼文字檔終究只是一個加入了大量換行符號及縮排的字串。所以編譯器、直譯器、linter如果要讀懂這份程式碼,需要將程式碼字串先轉換為某種電腦可以辨識的資料結構後才能做後續的應用。