Skip to content

Latest commit

 

History

History
135 lines (91 loc) · 2.93 KB

File metadata and controls

135 lines (91 loc) · 2.93 KB

Dana Semantic Analyzer

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.

Features

  • 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 / continue outside loops
    • Invalid return statements
    • Undeclared identifiers
    • Type mismatches
  • Stable exit codes (0 on success, non-zero on error).

Prerequisites

  • The lexer and parser must be built first (semantic analysis depends on their headers).
  • Requires: make, flex, bison, and a C++17 compiler.

Build

From this directory:

make            # build semantic analyzer
make clean      # remove generated .cpp/.o files
make distclean  # remove all generated files, including the semantic binary

The build produces the binary: ./semantic.

Usage

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 stdin

Successful Analysis Output

For the classic hello world program:

Input

def hello
    writeString: "Hello world!\n"

Command

./semantic hello.dana

Output

AST: FuncDef(Header(hello), Block(ProcCall(writeString, Lvalue("Hello world!\n"))))
Semantic analysis completed successfully

Error Reporting

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.dana

Output

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.).

Exit Codes

  • 0 — success (valid semantics)
  • non-zero — semantic error (message printed to stderr)

Testing

Use the repository’s Python test harness:

cd ../testing
python3 test_semantic.py

The 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.

Tips & Troubleshooting

  • 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.