---
name: interpreter
description: This skill should be used when the user asks about "interpreter pattern", "when to use interpreter", "implement interpreter", "parse expression", "evaluate grammar", "DSL", or mentions needing to interpret or evaluate language expressions.
version: 1.0.0
---

# Interpreter Pattern

## What Is It
The Interpreter pattern defines a representation for a language's grammar along with an interpreter that uses the representation to interpret sentences in the language. It's used to evaluate expressions in a custom language or DSL.

## When to Use
- **Expression evaluation** - Mathematical expressions, boolean logic
- **Query languages** - SQL-like syntax, search queries
- **Configuration DSLs** - Rule engines, validation rules
- **Template engines** - Variable substitution, conditionals
- **Regular expressions** - Pattern matching (built-in use case)
- **Scripting** - Embedded scripting languages

## When NOT to Use
- **Complex grammars** - Use parser generators instead
- **Performance critical** - Interpreters are slower than compiled code
- **Large grammars** - Class explosion with many rules
- **Simple parsing** - Direct parsing is more efficient

## How to Implement

### Implementation Steps
1. Define an abstract expression interface with interpret() method
2. Create terminal expressions for leaf nodes (values, variables)
3. Create non-terminal expressions for operators/composites
4. Build an abstract syntax tree (AST) from expressions
5. Client invokes interpret() on the AST root

### TypeScript Implementation

```typescript
// Abstract expression
interface Expression {
  interpret(context: Map<string, number>): number;
}

// Terminal expression
class NumberExpression implements Expression {
  constructor(private value: number) {}

  interpret(_context: Map<string, number>): number {
    return this.value;
  }
}

// Non-terminal expression
class AddExpression implements Expression {
  constructor(private left: Expression, private right: Expression) {}

  interpret(context: Map<string, number>): number {
    return this.left.interpret(context) + this.right.interpret(context);
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/interpreter.ts` - Basic implementation with arithmetic expressions
- `examples/interpreter-advanced.ts` - Real-world example with rule engine

## Related Patterns
- **Composite** - Abstract syntax tree is a Composite structure
- **Visitor** - Can be used to interpret the AST
- **Iterator** - Can traverse the AST
