QA
Senior LevelJavaScript & TypeScript

How to construct domain-specific languages (DSL) or AST parsers in JavaScript/TypeScript?

❓ Interview Prompt: Explain Lexical Analysis (tokenization), Parsing (Abstract Syntax Tree generation), and AST Evaluation.

Building a custom interpreter or domain-specific language (DSL) follows a 3-stage compiler architecture:

1. Lexer (Tokenizer):

Converts raw source code strings into a stream of structured Tokens ({ type: 'NUMBER', value: '42' }).

2. Parser:

Processes tokens and builds a hierarchical Abstract Syntax Tree (AST) representing code syntax rules.

3. Interpreter / Evaluator:

Traverses the AST nodes recursively to evaluate operations and execute instructions.

Code Implementation Example

typescript
type Token = { type: 'NUMBER' | 'PLUS'; value: string };
type ASTNode = { type: 'BinaryExpr'; left: number; right: number };

// Simple Lexer
function tokenize(code: string): Token[] {
  return code.split(' ').map(str => {
    if (str === '+') return { type: 'PLUS', value: '+' };
    return { type: 'NUMBER', value: str };
  });
}

// Simple Evaluator
function evaluate(node: ASTNode): number {
  switch (node.type) {
    case 'BinaryExpr': return node.left + node.right;
  }
}
💡Basic Lexer tokenization and AST node evaluation architecture.
🎯 Interview Key Takeaway

Custom DSL engines use a Lexer to produce tokens, a Parser to construct an AST, and an Evaluator to execute logic.

#AST#Parsing#Compilers#DSL#Senior
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?