You are writing a three-pass compiler for a simple programming language into a small…
- User
You are writing a three-pass compiler for a simple programming language into a small assembly language.
The programming language has this syntax:
function ::= '[' arg-list ']' expression arg-list ::= /* nothing */ | variable arg-list expression ::= term | expression '+' term | expression '-' term term ::= factor | term '*' factor | term '/' factor factor ::= number | variable | '(' expression ')'Variables are strings of alphabetic characters. Numbers are strings of decimal digits representing integers. So, for example, a function which computes a^2 + b^2 might look like:
[ a b ] a*a + b*bA function which computes the average of two numbers might look like:
[ first second ] (first + second) / 2You need write a three-pass compiler. All test cases will be valid programs, so you needn't concentrate on error-handling.
The first pass will be the method
pass1which takes a string representing a function in the original programming language and will return a (JSON) object that represents that Abstract Syntax Tree. The Abstract Syntax Tree must use the following representations:// Each node is of type 'AST' and has the following fields: // 'string op', 'AST* a', 'AST* b', and 'int n' AST ("+", a, b) // add subtree a to subtree b AST ("-", a, b) // subtract subtree b from subtree a AST ("*", a, b) // multiply subtree a by subtree b AST ("/", a, b) // divide subtree a from subtree b AST ("arg", n) // reference to n-th argument, n integer AST ("imm", n) // immediate value n, n integerNote: arguments are indexed from zero. So, for example, the function
[ x y ] ( x + y ) / 2would look like:new AST ("/", new AST ("+", new AST ("arg", 0), new AST ("arg", 1)), new AST ("imm", 2))The second pass of the compiler will be called
pass2. This pass will take the output frompass1and return a new Abstract Syntax Tree (with the same format) with all constant expressions reduced as much as possible. So, if for example, the function is[ x ] x + 2*5, the result ofpass1would be:new AST ("+", new AST ("arg", 0), new AST ("*", new AST ("imm", 2), new AST ("imm", 5)))This would be passed into
pass2which would return:new AST ("+", new AST ("arg", 0), new AST ("imm", 10))The third pass of the compiler is
pass3. The method takes in an Abstract Syntax Tree and returns an array of strings. Each string is an assembly directive. You are working on a small processor with two registers ( and ), a stack, and an array of input arguments. The result of a function is expected to be in . The processor supports the following instructions: - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.