Compiler AST explorer
Concept and boundary
Build a read-only AST explorer with a stable output shape: collect named variable declarations and report their text and source offsets. Use public guards and traversal rather than regex matching; semantic types require a Program and checker. The Node tool works on supplied source text.
Accepted project
Create a fresh folder with exactly these files. Use TypeScript 5.8.3 and Node.js 22.16.0. For the AST explorer only, install the pinned typescript package locally (npm install --save-dev typescript@5.8.3).
const ts=require("typescript"); const src=ts.createSourceFile("input.ts","const count=7; function f(){let x=2;}",ts.ScriptTarget.ES2022,true); const items=[]; function visit(n){if(ts.isVariableDeclaration(n)&&ts.isIdentifier(n.name))items.push({name:n.name.text,offset:n.name.getStart(src)});ts.forEachChild(n,visit)} visit(src); console.log(JSON.stringify(items));type Entry={name:string;offset:number}; const x:Entry={name:"count",offset:6}; console.log(JSON.stringify(x));tsconfig.json
{ "compilerOptions": { "strict": true, "target": "ES2022", "module": "CommonJS", "moduleResolution": "Node10", "moduleDetection": "force", "skipLibCheck": true, "noEmitOnError": true, "types": [] }, "include": [ "**/*" ], "exclude": [ "node_modules", "dist", "build", "cache" ]}From the project root run: tsc -p tsconfig.json --pretty false.
Compilation succeeds (exit 0).
Run node explore.cjs. Expected stdout:
[{"name":"count","offset":6},{"name":"x","offset":32}]Rejected project — diagnosis
Intentionally rejected variant. Do not execute it.
Use a fresh copy of the accepted project, changing only the files shown below.
type Entry={name:string;offset:number}; const x:Entry={name:"count",offset:"6"};From the project root run: tsc -p tsconfig.json --pretty false.
Expected compiler diagnostic: TS2322
No runtime execution is required for this check.
The report schema requires numeric source offsets. Restore the accepted configuration/source to compare the result.
Practice and recap
Extend the explorer with function declarations and document whether offsets are UTF-16.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compiler AST explorer — knowledge check
Check the concept, interpret the tested project result, and diagnose a rejected configuration or source.
Which statement correctly describes Compiler AST explorer?
Using the complete accepted project and the exact command in the lesson, which result is expected?
type Entry={name:string;offset:number}; const x:Entry={name:"count",offset:6}; console.log(JSON.stringify(x));Why does the rejected project fail under its stated configuration?
type Entry={name:string;offset:number}; const x:Entry={name:"count",offset:"6"};