Code Formatter
Overview
In this assignment, you will design and implement code formatter (pretty printer) for the language described in the lexer, parser, and interpreter assignments. Your program will take syntactically valid, but possibly poorly formatted code, and produce a neatly formatted version according to a fixed style guide.
The goal is to deepen your understanding of program structure, syntax trees, and the relationship between syntax and presentation, while practicing robust handling of nested and compound statements.
Formatting Rules
Your code formatter must output code following exactly these rules.
General Rules
- Use 4 spaces per indentation level
- Do not use tabs
- Each statement appears on its own line (except where noted below)
- Do not preserve original whitespace or line breaks
Braces
- Opening braces { appear on the same line as the controlling statement
- Closing braces } appear on their own line, aligned with the start of the corresponding block
elsemust appear on the same line as the closing brace of the if block when applicable
Expressions
- Expressions are printed in a single line
- Do not insert line breaks inside expressions
- Parentheses are included only when required by syntax or these rules
- Insert exactly one space on each side of binary operators.
- Unary operators have no space between the operator and operand.
Parentheses
- have no spaces immediately inside parentheses
- one space may appear outside parentheses if required by surrounding operators or syntax
- must be inserted when required to reflect correct precedence
- must not be removed if doing so changes semantics
Specifications
The program takes a command line argument indicating the text file with the source code. The output of the program is a formatted version of the same program, written to standard output. The output must follow exactly the formatting rules described above
Example:
Input file contents
if(x){y=1;}else{if(y){z=2;}}
Output
if (x) {
y = 1;
} else {
if (y) {
z = 2;
}
}
Turning in the Assignment
To submit your assignment, create a zip file of a DIRECTORY named
formatter-handin containing ONLY the files required to build the
project. The project must build with dune. Then submit that file to
the appropriate folder on D2L.