Skip to content

About

Compiler for a small subset of C++: hand-written scanner, recursive-descent parser, semantic analysis with a symbol tree, and an interpreter with classes, constructors and destructors

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

11 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mini C++ Compiler

CI

Compiler for a small subset of C++, written in C++11 as a series of compiler constructions. It implements every stage by hand — no generators:

  1. Lexical analysis — a hand-written scanner (TScanner).
  2. Syntax analysis — a recursive-descent parser (TParser).
  3. Semantic analysis — a tree-shaped symbol table (Tree) that checks 16 context conditions while the program is parsed.
  4. Interpretation — the program is executed directly during parsing, including classes, constructors, destructors and method calls, with a trace of every assignment.

The language

A program is a sequence of class declarations, global variables and a void main() function.

  • Types: int, float, bool and user-defined classes.
  • Classes contain fields (optionally initialized), void methods without parameters, a constructor and a destructor; members may be public: or private: (public by default).
  • Statements: empty statement ;, block { ... }, assignment, if / else, method call obj.method(); and, inside a method, a call of another method of the same object: method();.
  • Operators: arithmetic + - * / %, comparison < <= > >=, equality == !=, logical && || !, unary + -.
  • Comments: // ... and /* ... */ (at most 150 characters).
  • Identifiers and numeric constants are at most 30 characters long.
int count = 0;

class Counter
{
private:
    int value = 10;
public:
    Counter()  { count = count + 1; }
    ~Counter() { count = count - 1; }
    void inc() { value = value + 1; }
}

void main()
{
    Counter c;
    c.inc();
    if (count == 1)
        count = 100;
}

Grammar

The parser follows this grammar; every rule is a method of TParser with the same number in its comment (see src/Parser.cpp).

 1) Program     -> TopDecl* EOF
 2) TopDecl     -> ClassDecl | MainFunc | VarDecl
 3) ClassDecl   -> class IDENT { ClassMember* }
 5) ClassMember -> AccessSpec
                 | void IDENT ( ) Block         method
                 | IDENT ( ) Block              constructor
                 | ~ IDENT ( ) Block            destructor
                 | VarDecl                      field
 6) AccessSpec  -> ( public | private ) :
 7) VarDecl     -> Type IdInit ( , IdInit )* ;
    IdInit      -> IDENT ( = Expr )?
 8) Type        -> int | float | bool | IDENT
 9) MainFunc    -> void main ( ) Block
10) Block       -> { ( VarDecl | Stmt )* }
11) Stmt        -> ; | Block | if ( Expr ) Stmt ElseOpt
                 | IDENT ( ) ;                  call of an own method
                 | LValue StmtTail
12) StmtTail    -> = Expr ;  |  . IDENT ( ) ;
13) ElseOpt     -> else Stmt | ε
14) LValue      -> IDENT ( . IDENT )*
15) Expr        -> AndExpr ( || AndExpr )*
16) AndExpr     -> RelExpr ( && RelExpr )*
17) RelExpr     -> EqExpr ( ( < | <= | > | >= ) EqExpr )*
18) EqExpr      -> AddExpr ( ( == | != ) AddExpr )*
19) AddExpr     -> MulExpr ( ( + | - ) MulExpr )*
20) MulExpr     -> UnaryExpr ( ( * | / | % ) UnaryExpr )*
21) UnaryExpr   -> ( + | - | ! )? Primary
22) Primary     -> LValue | Constant | ( Expr )
23) Constant    -> DEC_CONST | REAL_CONST | true | false

Note that in this language equality (==, !=) binds tighter than the relational operators, and unary operators do not nest (--x is an error).

Context conditions

The semantic analyzer checks that:

  1. names are unique within a scope;
  2. identifiers are declared before use;
  3. a name is used only within the scope of its declaration;
  4. a class used as a type is declared;
  5. assignment and initialization types are compatible (int ↔ float, bool only to bool, objects only of the same class);
  6. arithmetic operands are numeric (% requires integers);
  7. comparison operands are numeric;
  8. equality operands have compatible types;
  9. logical operands are bool;
  10. an if condition is bool;
  11. accessed fields exist in the object's class;
  12. called methods exist in the object's class;
  13. the left-hand side of = is a variable or a field;
  14. class and method names are not used as variables;
  15. constructor and destructor names match the class name;
  16. private members are accessed only from methods of their class.

Building

Requirements: a C++11 compiler (GCC or Clang) and GNU Make.

make          # builds ./compiler
make test     # builds and runs all tests
make clean    # removes build artifacts

Usage

./compiler [-t|--tree] <source-file>
make run                      # runs examples/classes.txt
make run FILE=path/to/program

The compiler runs all four stages in turn. After the semantic analysis it prints the semantic tree, then interprets the program and traces every assignment:

Lexical analysis: no errors
Syntax analysis: no errors
Semantic analysis: no errors

semantic tree:
  { global scope (line 1)
    count : int (line 3, column 5)
    Bar : class Bar (line 5, column 7)
      a : int (line 6, column 9)
...
Interpretation:
DEBUG: [global] (line 3:5) Assign: count = 0 (int)
DEBUG: [Foo f2] (line 20:9) Assign: count = 1 (int)
DEBUG: [Foo f3] (line 20:9) Assign: count = 2 (int)
DEBUG: [main] (line 50:5) Assign: f2 = f3 (Foo)
DEBUG: [main] (line 50:5) Copy: f2.flag = f3.flag, value true (bool)
...
DEBUG: [Bar f2.bar] (line 12:13) Assign: count = 10 (int)
DEBUG: [Foo f3] (line 34:9) Assign: count = 100 (int)
DEBUG: [Foo f3] (line 23:9) Assign: count = 99 (int)
DEBUG: [Foo f2] (line 23:9) Assign: count = 98 (int)
Interpretation finished: no errors

The label in brackets is the scope being executed: global, main or the object whose method runs (Foo f2, Bar f2.bar). Implicit conversions produce warnings:

Warning: value 2.9 is truncated when converted to int (line 3, column 9)

With -t the semantic tree, including variable values, is also printed before and after entering and leaving every block.

On the first error the compiler stops and reports its kind and location (the exit code is 1):

Lexical error (line 2, column 9): invalid character. Fragment: "#"
Syntax error (line 4, column 5): expected: ;, found: identifier "a"
Semantic error (line 5, column 9): incompatible types in assignment: int = bool
Runtime error (line 4, column 15): division by zero

Tests

make test builds and runs three test programs:

Program What it checks
syntax_tests programs the parser must accept or reject with a syntax error
semantic_tests lexical, syntax and semantic errors with exact locations; symbol table unit tests
interpreter_tests final variable values, runtime errors, assignment and tree traces

Most test programs live in tests/data/ in a simple text format, so new cases can be added without touching C++ code:

// TEST: <name> | accept
// TEST: <name> | values: a=1, f=2.5, ok=true
// TEST: <name> | error | <LEX|SYN|SEM|RUN> | <line> | <column> | <message part>
<program>
// END

Program lines are numbered from 1 right after the header. The format is documented in tests/test_framework.h.

GitHub Actions runs the tests on every push and pull request with GCC and Clang (warnings are errors), and once more under AddressSanitizer and UndefinedBehaviorSanitizer. The same sanitizer build can be run locally:

make clean
make test CXXFLAGS="-std=c++11 -g -fsanitize=address,undefined"

Project layout

src/
  defs.h            token codes, limits and the error class hierarchy
  Scanner.h/.cpp    lexical analyzer
  Parser.h/.cpp     recursive-descent parser with semantic actions and interpretation
  SemTree.h/.cpp    semantic tree (symbol table), runtime values and objects
  Interp.h/.cpp     expression evaluation, type conversions, assignment tracing
  main.cpp          command-line driver running the four stages
tests/
  test_framework.h  shared test helpers and the data file loader
  syntax_tests.cpp
  semantic_tests.cpp
  interpreter_tests.cpp
  data/             test programs
examples/
  classes.txt       demo program with classes, recursion and object copying

Implementation notes

  • One parser, several modes. The same TParser performs syntax analysis only, syntax and semantic analysis, or full interpretation, depending on constructor flags. The driver runs it three times over the same scanner.
  • Symbol table. Tree is a binary tree in the left child, right sibling form. Scopes are nodes of type TYPE_SCOPE; a class node holds its members as children. Lookup walks up through the enclosing scopes.
  • Executing while parsing. The exec flag tells the parser whether the current fragment is executed. The branch of an if that is not taken, the right operand of a short-circuited && / || and class bodies are parsed with exec == false.
  • Methods. A method body is parsed once when the class is declared; its position is saved. A call starts a nested parser at that position with the receiver object as curObj. Recursion depth is limited to 200 calls.
  • Objects. Each TObject stores its own field values. Member objects are constructed before the enclosing object and destroyed after it; objects are destroyed in reverse order when their block ends, global objects when the program ends. Assigning an object copies it field by field.
  • Integer arithmetic wraps around on overflow instead of being undefined.

About

Compiler for a small subset of C++: hand-written scanner, recursive-descent parser, semantic analysis with a symbol tree, and an interpreter with classes, constructors and destructors

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages