Description
In this task, you are required to write an interpreter of a very simple language, i.e. the Y language.
The Y language consists of identifiers, integers, assignments, and additions.
There may or may not be white spaces between assignments, and/or between operands (identifiers or integers) and operators (= or +).
Only uppercase and lowercase letters, and decimal digits are allowed in valid identifiers, e.g. abc, xyz123.
The first character of an identifier must be a letter. So identifier 123xyz is invalid.
Integers are represented in decimal formats. Only decimal digits are allowed in valid integers. All the numbers (including calculation results) are very small. So int will be OK for just everything here.
The only operator for calculation is +, i.e. addition. You should NOT implement other arithmetic operators.
A valid assignment starts with a valid identifier, followed by =, then a valid expression. There may or may not be spaces around the identifier and/or =.
A valid expression consists of a single valid operand, or several valid operands separated by +. There may or may not be spaces around operands and/or +.
A valid operand is a valid integer, or a valid identifier which is already assigned a value. (See sample 2.)
A valid Y language program should contain at least one assignment.
Evaluate the expression first, then assign the value to the identifier.
You can use isspace(c) to determine whether c is a space.
The following (possibly informal) grammar may help you understand the language syntax better. But remember that spaces are omitted for brevity in the grammar.
program ::= assignment+
assignment ::= identifier '=' expression
expression ::= operand ('+' operand)*
operand ::= identifier | integer
In case you still do not understand the language clearly, you may just consider the Y language as a variant of C++ where there's no main, no variable declaration, no types other than int, no ; after a single line, and no operators other than +.
Do understand the language before you start. Be robust and good luck!
Input Format
A Y language program.
Output Format
For each assignment, print the value of the identifier after assignment in a single line. Once a syntax error is detected, print ERROR in a single line and stop interpreting the program.
Sample Input 1
a = 1
b = a + 2 + 3
Sample Output 1
1
6
Sample Input 2
a = 123
b = a + c
c = 456
Sample Output 2
123
ERROR
Sample Input 3
a = b = 1
xyz = 123
Sample Output 3
ERROR
Limits
Time limit: 500ms, memory limit: 20000kb. There are 20 test cases and 5 points for each.
这样一道题 写一个简单的解释器。 求指导,先谢了!