The semantic analyzer runs after the lexer and parser. It validates the meaning of Dana programs (scope rules, type rules, undeclared identifiers, etc.) and produces a detailed Abstract Syntax Tree (AST) for valid inputs.
-
Builds and prints the AST for each program.
-
Reports semantic errors with line/column info and a caret indicator.
-
Detects invalid constructs, such as:
- Misuse of
break/continueoutside loops - Invalid
returnstatements - Undeclared identifiers
- Type mismatches
- Misuse of
-
Stable exit codes (
0on success, non-zero on error).
- The lexer and parser must be built first (semantic analysis depends on their headers).
- Requires:
make,flex,bison, and a C++17 compiler.
From this directory:
make # build semantic analyzer
make clean # remove generated .cpp/.o files
make distclean # remove all generated files, including the semantic binaryThe build produces the binary: ./semantic.
Usage: ./semantic [OPTIONS] [FILE]
Parse and analyze input from FILE, or standard input if FILE is omitted or '-'.
Options:
-h, --help Show this help and exit
Examples:
./semantic program.dana # Parse + analyze a file
./semantic - # Parse + analyze from stdinFor the classic hello world program:
Input
def hello
writeString: "Hello world!\n"
Command
./semantic hello.danaOutput
AST: FuncDef(Header(hello), Block(ProcCall(writeString, Lvalue("Hello world!\n"))))
Semantic analysis completed successfully
Semantic errors produce clear diagnostics with context.
Example — Call to Undefined Function
Input
# Error: call to undefined function 'printInt'
def main
begin
printInt: 42
end
Command
./semantic main.danaOutput
Semantic error at line 5, column 10
5: printInt: 42
^
Call to undeclared procedure 'printInt'
Each error type has a tailored message (undeclared identifiers, type errors, invalid returns, etc.).
0— success (valid semantics)- non-zero — semantic error (message printed to stderr)
Use the repository’s Python test harness:
cd ../testing
python3 test_semantic.pyThe script:
- Runs the analyzer on valid programs (must succeed) and invalid programs in
testing/invalid_semantic(must fail). - For invalid programs, captures and displays the stderr error messages.
- Ensure you’ve built the parser first — the semantic analyzer links against it.
- If AST output looks truncated, check that your terminal encoding is UTF-8.
- To debug issues, run on minimal programs (e.g., a single function) and gradually expand.