Type Checker - Problem
Implement a type checker for a simple expression language that can infer types, detect type mismatches, and support type coercion.
You are given an abstract syntax tree (AST) representing an expression, and a symbol table mapping variable names to their declared types. Your task is to:
- Infer the type of the entire expression
- Detect type errors and return appropriate error messages
- Apply type coercion rules when compatible types are used together
The expression language supports:
- Literals: integers, floats, strings, booleans
- Variables: identifiers that reference symbol table entries
- Binary operations: arithmetic (+, -, *, /), comparison (==, !=, <, >), logical (&&, ||)
- Type coercion: int can be promoted to float, but not vice versa
Return the inferred type as a string, or an error message starting with "ERROR:" if type checking fails.
Input & Output
Example 1 — Basic Arithmetic with Coercion
$
Input:
ast = {"type":"binary","operator":"+","left":{"type":"variable","name":"x"},"right":{"type":"literal","dataType":"float","value":3.14}}, symbolTable = {"x":"int"}
›
Output:
float
💡 Note:
Variable x is int, literal 3.14 is float. Addition of int + float requires coercion to float, so result type is float.
Example 2 — Type Error Detection
$
Input:
ast = {"type":"binary","operator":"+","left":{"type":"variable","name":"name"},"right":{"type":"literal","dataType":"int","value":5}}, symbolTable = {"name":"string"}
›
Output:
ERROR: Cannot apply + to string and int
💡 Note:
Cannot add string variable 'name' to integer 5. No valid coercion rule exists between string and int for arithmetic.
Example 3 — Logical Operation
$
Input:
ast = {"type":"binary","operator":"&&","left":{"type":"variable","name":"flag1"},"right":{"type":"variable","name":"flag2"}}, symbolTable = {"flag1":"boolean","flag2":"boolean"}
›
Output:
boolean
💡 Note:
Both operands are boolean variables. Logical AND of boolean && boolean results in boolean type.
Constraints
- AST depth ≤ 100 levels
- Symbol table size ≤ 1000 entries
- Variable names are alphanumeric strings
- Supported types: int, float, string, boolean
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code