This is a project for a compilers course that implements a source-to-source compiler. It takes programs written in a custom, simple language and translates them into equivalent, runnable C code. It is built using Flex and Bison.
- Data Types:
int,float,bool,string - Variables: Multi-character names (e.g.,
my_var,counter_1). - Declarations: Variables must be declared with their type before use (e.g.,
int x;). All variables are currently global. - Assignments:
variable = expression; - Functions:
- Declaration:
return_type func function_name(param1, param2) { ... } - Return: Use the
returnstatement to return a value from a function. - Calls: Standard function call syntax
function_name(arg1, arg2).
- Declaration:
- Control Flow:
if (condition) { ... } else { ... }statements.while (condition) { ... }loops.for (init; condition; increment) { ... }loops.spidey (expression) { ... }statements (equivalent toswitch).3mk value: { ... }(equivalent tocase).otherwise: { ... }(equivalent todefault).cut;(equivalent tobreak).
- Expressions: Arithmetic (
+,-,*,/) and relational (==,!=,<,>,<=,>=) operators are supported. - Statement Blocks: Code can be grouped into blocks using curly braces
{ ... }. - Printing: The
printstatement can be used to output the value of any expression. - Comments: Single-line comments starting with
//are supported.
A PowerShell script run_lang.ps1 is provided to automate the entire compilation and execution process. It will place all generated files in an out/ directory.
-
Build the Compiler: If you haven't already, build the compiler once:
win_bison -d compiler.y win_flex compiler.l gcc compiler.tab.c lex.yy.c -o my_compiler.exe
-
Run Your Code: Use the script to compile and run any of your
.txtsource files../run_lang.ps1 test_spidey.txt
If you prefer to run the steps manually:
-
Prerequisites: Ensure you have Flex, Bison, and a C compiler (like GCC) installed.
-
Compile the Compiler: Run the following commands in your terminal to build
my_compiler.exe:win_bison -d compiler.y win_flex compiler.l gcc compiler.tab.c lex.yy.c -o my_compiler.exe
-
Translate Your Code to C: Use the compiled compiler to translate a source file (e.g.,
test.txt) into C code. This will generate anoutput.cfile../my_compiler.exe test.txt
-
Compile and Run the C Output: Use a C compiler (like GCC) to compile the generated
output.cinto a final executable, and then run it.gcc output.c -o output.exe ./output.exe