Interpreter written in Bison, Flex and C++ for simple custom programming language.
- assignment -
variable_name = equation
- Print
PRINT(equation)
PRINT("text")
- IF
IF(equation comparator equation) instruction
IF(equation comparator equation) { instructions }
- WHILE
WHILE(variable, assignment) instruction
WHILE(variable, assignment) { instructions }
equation
- single number,
- single variable,
+-*/
- addition, subtraction, multiplication and division of variables/numbers,^
- variable/number to the power of variable/number.
text
- character string (ASCII signs from 32 to 126)comparator
- one of these words:==
,!=
,>
,>=
,<
,<=
.instruction
- single instruction.instructions
- multiple instructions.
- first argument - control variable for loop. Breaks the loop upon reaching the value of zero.
- second argument - assignment executed on first argument.
This program uses flags to run in normal mode or debug mode.
Possible run scenarios:
INTERPRETER -n
INTERPRETER -d
INTERPRETER -flag < program.txt
-n
- runs program in normal mode.
-d
- runs program in debug mode.
-flag
- any of above flags (used only for example).
- debug mode (enabled with flag),
- real numbers operations,
- print instruction working for numbers and texts,
- order of operations (eg. multiplication before addition),
- negative numbers and negated variables,
- nested instructions (IFs in WHILEs and conversely),
- single-line and multi-line comments (C/C++ style)
- error detection (undeclared variable, missing semi-colon, wrong WHILE second argument),
- line and column tracking (used in error detection).
var_1 = 3^5;
var_2 = -var_1 + 3 + 120 + 4*5/3;
//This is a commnet (interpreter ignores it)
/*
This is also ignored
*/
PRINT("If test");
a = 10.5^3;
b = 3 * 10^2/2 + 18/2*3 - 1;
IF ( a >= 10 ) {
IF( a < 10000 ){
print( b );
};
print( a );
};
it = -10;
check = 1;
PRINT("MAIN LOOP");
WHILE ( it, it=it+1 ) {
IF( check < 128 ) {
check = check * 2;
it2 = 2;
PRINT("");
PRINT("INTERNAL LOOP");
WHILE (it2, it2 = it2 - 1){
PRINT(check);
IF( it2 == 1 ){
check = check + 1;
PRINT(it2);
};
};
IF( it2 == 0 ){
it2 = it2 + 3*check;
PRINT(it2);
};
};
IF( check >= 128 ) {
PRINT("");
PRINT("IF false!");
};
};
PRINT("");
PRINT("Print check:");
print(check);
*code written in language defined for the interpreter
To compile this program you need:
- C++ compiler
- Flex binaries
- Bison binaries (may require additional binaries)
- MinGW - Minimalist GNU for Windows
- Flex for Windows
- Bison for Windows
- Visual Studio Code with Lex Flex Yacc Bison plugin
- bison.exe -dy interpreter.y
- flex.exe interpreter.lex
- g++.exe y.tab.c lex.yy.c -o "your_exe_name.exe"
- SuddenlyPineapple gave the idea for using enums in switch in
execute_instruction()
function.