Compiling principle experiment-infix suffix with variable and error handling

Source: Internet
Author: User
Tags character set constant error handling



First come to the experiment Instruction book:


First, the experimental task
design, compile and debug an infix expression into the suffix expression of the experimental program, deepen the analysis of the word, grammar analysis, semantic analysis and code generation understanding.
Ii. contents of the experiment
1. Lexical
Input: Extend ASCII character set character.  In addition to case 26 letters and numbers 0-9 (digit) and +-*/^ =; , (), all other characters are treated as equal to whitespace, and are generally used to separate words.
Output: Identifies a word, including keywords, operators, bounds, identifiers, and integer constants.
(1) Keyword: var
(2) operator and bounds: +-*/^ =; ,  (  )
Where: the multiplication operator (*,/) returns the word Mulop with different property values,
The add minus operator (+,-) returns the word Addop with different property values:
(3) identifier (ID) and integer constant (num):
Identifiers (IDs) and integer constants (num) have a maximum length of 8 characters, as defined below.
id = letter (letter | digit) *//a string of symbols with letters and numbers
num = digit digit*//The shaping constant must be greater than or equal to one
2. Grammar (main: )
According to the input sequence of words, the analysis of whether the grammatical rules, if not, should indicate the location and reason, if it is met, then perform the corresponding semantic analysis of the subroutine and the conversion of infix expression to the suffix expression process. It should be noted that the here is the differentiation grammar, which, from the semantic point of view, evaluates the expression by the first power operation (^), and then the order of precedence of the last addition and subtraction operation (+,-) of the multiplication operation (*,/); parentheses (()) are used to adjust the order of operations, in which part of the parentheses is evaluated first; The grammar rules of this experiment system are:
Program→compound
Composite function
Compound→declaration Assignstatement Compound | Ε
To define a value assignment
Declaration→var identifier_list;  | Ε
Defining identifiers
Dentifier_list→id, Dentifier_list | Id
Identifiers can be separated by commas in the middle
Assignstatement→id = expression;  | Ε
Words must have an assignment number
Expression→expression ADDOP Expression |
The plus sign must have words on both sides
Expression Mulop Expression |
Multiplication sign must have words on both sides
expression ^ Expression |
Must have words on both sides of power
(expression) |
There must be a word in the middle of parentheses
ID | Num
3. Semantic analysis and code generation
The main task of semantic analysis is to determine whether a variable is first defined and used (only this one). The main task of code generation is to convert an assignment statement from a prefix expression to a suffix expression.
Iii. Examples of experiments
Example 1:
Input:
var a, B;
A = 10;
b = 5;
var x;
x = a + (+ * b) ^ 2;
Output:
A 10 =
b 5 =
X a b * 2 ^ + =




Example 2:
Input:
var A;
A = 10;
b = 5;
var x;
x = a + (+ * b ^ 2;
Output:
Line 3rd Error: Variable b is not defined.
5th line error: missing closing parenthesis.


This Tuo code all the way is a large pressure than the case, the high number of review progress is slow, but the feeling and suffering from obsessive-compulsive disorder, code does not want to stop, ah quite simple experiment I knocked more than 350 lines, or insufficient capacity, should come up with a better method. First use inverse Poland to solve the infix suffix, and then the error is handled. He here is not satisfied with all the grammar is wrong, divided into the word French and semantics, and then find out 17 kinds of errors, and then compare trouble to convert to signal array error, processing these errors painted a lot of time, more than 100 lines of code into more than 300 lines.


Here I simulated is the interpreter program, the teacher later let to change the translation program, changed a bit ugly, here is posted explanation program:

Test data included:

6
5
var A,
a = ten;
B = 5;
var x;
x = a + (* b  ) ^ 2;
5
var A;
A = 10; B = 5;
var x;
x = a + (+ * b ^ 2;
2
3 = 1 + 2;
3 = 1 & 2;
7
Var apple666,banana,fffffffff,ff,0ccc,666p,12 34;
Banana = (apple666 + 3) * 2;
FF = (apple666 + 333333333) * 2;
Banana = (apple666 + 3) * 2
Var, b c D;
var banana;
9 + (3-1) * 3 + 10/2 =;
+
var x;
X = 9 + (3-1) * 3 + 10/2;
x = 999999999 + 1;
x = 9 + (3-1) * +/2;
x = 9 + (3-1) *-/2;
x = 9 + (3-1) + */2;
x = 9 + (3-1) * 3 +  /;
x = 9 + (3-1) * 3 +  ^;
x = 9 + (-) * 3 + 10/2;
x = 9 + () * 3 + 10/2;
x = 9 + (3-1) * 3 +  2;
x = 9 + ((((3-1) * 3 + 10/2;
x = 9 + (3-1))))) * 3 + 10/2;
3
Var affffffffff,0xx;
Affffffffff = 1+2;
0xx = 1+2;



#include <stdio.h> #include <algorithm> #include <string.h> #include <stack> #include <

string> #include <iostream> #include <algorithm> using namespace std;
const int N = 1005;

const int INF = 0X3F3F3F3F; struct node {string id;}
table[n];//identifier string ans; BOOL Flag0;//true The number of illegal words that define the statement int flag1;//Word length greater than 8 int flag2;//begins with the number of illegal words that have a letter followed by a number bool flag3;//determine if the sealed int flag4;// The number of variables that are not a comma but a space before the first variable bool flag5;//true represents a variable with a redefinition of bool flag51;//defines the variable length greater than 8 bool flag52;//The first letter is a number of illegal variable bool flag6;//
True indicates that there must be a word or parenthesis on both sides of the bool flag7;//plus sign without an assignment number flag8;//the minus sign must have a word or bracket bool flag9;//multiplication Sign Both sides must have a word or bracket bool flag10;//Division sign Both sides must have words or parentheses BOOL flag11;//power on both sides must have a word or bracket bool flag12;//brackets must have the word bool flag13;//two digits in a block, between the missing operator int flag14;//not 0 is the missing closing parenthesis, less than 0 missing opening parenthesis, Greater than 0 missing closing parenthesis bool flag15;//error type, indicating variable undefined int signal[n];//converting infix to signal marker int signalnum;//signal Mark number int priority (char ch) {Switch
    (CH)
        {case ' + ': return 1;
        Case '-': return 1;
        Case ' * ': return 2; Case '/': return 2;
        Case ' ^ ': return 3;
    Default:return 0;
    }} void Initcase () {for (int i = 0; I <= N; i++) {table[i].id.clear ();
    }} void Initrow () {flag0 = false;
    Flag1 = 0;
    Flag2 = 0;
    Flag3 = false;
    Flag4 = 0;
    Flag5 = Flag51 = Flag52 = false;
    Flag6 = false;
    Flag7 = Flag8 = Flag9 = Flag10 = Flag11 = Flag12 = Flag13 = false;
    FLAG14 = 0;
    Flag15 = false;
    memset (Signal, 0, sizeof (Signal));
Signalnum = 0; } void Check () {for (int i = 0; i < Signalnum; i++) {if (signal[i]==5)//Plus {if (Si GNAL[I-1]&GT;3&AMP;&AMP;SIGNAL[I+1]&GT;3) | | (signal[i-1]==2&&signal[i+1]==3))
        Flag7 = true; } else if (signal[i]==6)//minus {if (signal[i-1]>3&&signal[i+1]>3) | | (signal[i-1]==2&&signal[i+1]==3))
        Flag8 = true; } else if (signal[i]==7)//Multiply {if (signal[i-1]>3&&signal[i+1]> 3) | | (signal[i-1]==2&&signal[i+1]==3))
        Flag9 = true; } else if (signal[i]==8)//except {if ((signal[i-1]>3&&signal[i+1]>3) | | | (signal[i-1]==2&&signal[i+1]==3))
        Flag10 = true; } else if (signal[i]==9)//Power {if (signal[i-1]>3&&signal[i+1]>3) | | (signal[i-1]==2&&signal[i+1]==3))
        Flag11 = true;
        } else if (signal[i]==2)//Two parentheses are next to each other {if (signal[i+1]==3) Flag12 = true;
        } else if (signal[i]==1)//Two words are together {if (signal[i+1]==1) Flag13 = true;
    }}} int main () {freopen ("In.txt", "R", stdin);
    int T, allrow, case = 0;
    scanf ("%d", &t);
        while (t--)//Use Case number {scanf ("%d", &allrow),//A sample read-in instruction number GetChar ();
        Initcase ();
        printf ("Case%d:\n", ++case);
        int cnt = 0;
   for (int row = 1; row <= Allrow; row++) {Initrow ();         string S;
            String wa1;//error parameter getline (cin,s);
            int len = S.size ();
            if (s[len-1]== '; ' && flag3==false) Flag3 = true;
            if (s[0]== ' V ' &&s[1]== ' a ' &&s[2]== ' r ' &&s[3]== ')//define statement {flag0 = true;
                printf ("There are currently defined keywords:");
                int i = 4, varnum = 0;
                String Tmp1;
                    while (I<len) {varnum++;
                    Tmp1.clear ();
                    BOOL Judge = false; if ((s[i]>= ' a ' &&s[i]<= ' z ') | | (s[i]>= ' A ' &&s[i]<= ' Z '))
                        && (s[i-1]== ', ' | | s[i-1]== '))//Legal variable {judge = true;//description is a variable
                            if (varnum!=1 && s[i-1]== ") {flag4++;
     Judge = false;//No comma in front of the variable definition error}                   Tmp1+=s[i];
                        i++; while ((s[i]>= ' 0 ' &&s[i]<= ' 9 ') | | (s[i]>= ' A ' &&s[i]<= ' z ') | |
                        (s[i]>= ' A ' &&s[i]<= ' Z '))
                            {Tmp1+=s[i];
                        i++; }} else if ((s[i]>= ' 0 ' &&s[i]<= ' 9 ') && (s[i-1]== ', ' | | | s[i-1]
                        = = "))//The number that starts with is the illegal variable {if (varnum!=1 && s[i-1]== ') flag4++;
                        Tmp1+=s[i];
                        i++;
                        Flag52 = true; while ((s[i]>= ' 0 ' &&s[i]<= ' 9 ') | | (s[i]>= ' A ' &&s[i]<= ' z ') | |
                        (s[i]>= ' A ' &&s[i]<= ' Z '))
                            {Tmp1+=s[i];
                        i++; } if (Tmp1.size () > 8) flag51 =True
                    } else i++;
                    Determine the redefined variable int m;
                        for (m = 0; m < cnt; m++) {if (!tmp1.compare (table[m].id))//If this character variable is found in the definition table
                            {Flag5 = true;
                        Judge = false;//illegal variable, no longer defines break; }} if (Judge && flag3) {table
                        [cnt++].id = TMP1;
                    if (Tmp1.size () > 8) flag51 = true; }}/* for (int k = 0; k < cnt; k++) {cout <<
                    Table[k].id;
                printf (""); 
                } printf ("\ n"); */} else//assignment Statement {stack<char>sta;
  Sta.push (' # ');              int i = 0, Wordid = 0;//wordid represents the first few words behind Ans.clear ();
                    while (I < len) {if (Wordid==1 && (s[i+1]! = ' = ')) Flag6 = true;
                    if (s[i]== ') {i++; } else if (s[i]== '; ' | | s[i]== ' = ') {signal[signalnum++] =
                        4;
                    i++;
                        } else if (s[i]== ' (') {Sta.push (s[i]);
                        signal[signalnum++] = 2;
                        i++;
                    flag14++;
                        } else if (s[i]== ') ') {flag14--;
                        signal[signalnum++] = 3;
           if (flag14 >= 0) {while (Sta.top ()! = ' (')                 {ans+=sta.top ();
                                Sta.pop ();
                            ans+= ";
                        } sta.pop ();
                    } i++;
                        } else if (s[i]== ' + ' | | | s[i]== '-' | | s[i]== ' * ' | | s[i]== '/' | | s[i]== ' ^ ') {
                        if (s[i]== ' + ') signal[signalnum++] = 5;
                        else if (s[i]== '-') signal[signalnum++] = 6;
                        else if (s[i]== ' * ') signal[signalnum++] = 7;
                        else if (s[i]== '/') signal[signalnum++] = 8;
                        else if (s[i]== ' ^ ') signal[signalnum++] = 9;
                            while (Priority (Sta.top ()) >= priority (S[i])) {ans+=sta.top ();
                            ans+= ";
                        Sta.pop ();
         }               Sta.push (S[i]);
                    i++; } else if (s[i]>= ' 0 ' &&s[i]<= ' 9 ')//is the number {Signa
                        l[signalnum++] = 1;
                        int num = 1;
                        Ans+=s[i];
                        i++;
                        BOOL letter = false;; while ((s[i]>= ' 0 ' &&s[i]<= ' 9 ') | | (s[i]>= ' A ' &&s[i]<= ' z ') | |
                        (s[i]>= ' A ' &&s[i]<= ' Z ')) {if (s[i]>= ' a ' &&s[i]<= ' z ') | | (s[i]>= ' A ' &&s[i]<= ' Z '))
                            letter = true;
                            Ans+=s[i];
                            i++;
                        num++;
                        } ans+= ';
                        if (num > 8) flag1++;
                    if (letter) flag2++; } else if ((s[i]>= ' a ' &&s[i]<= ' z ') | | (s[i]>= ' A ' &&s[i]<= ' Z '))
                        Is the letter {signal[signalnum++] = 1;
                        int num = 1;
                        String tmp2;
                        Tmp2+=s[i];
                        i++; while ((s[i]>= ' a ' &&s[i]<= ' z ') | | (s[i]>= ' A ' &&s[i]<= ' Z ') | |
                        (s[i]>= ' 0 ' &&s[i]<= ' 9 '))
                            {Tmp2+=s[i];
                            i++;
                        num++;
                        } if (num > 8) flag1++;
                        See if this variable is present in the table int k; for (k = 0; k < cnt; k++) {if (!tmp2.compare (table[k].id))//If you are looking in the definition table
                                To this character variable {ans+=tmp2;
                                ans+= "; Break; }} if (k = = CNT) {FLA
                            G15 = 1;
                            Wa1.clear ();
                        WA1 = TMP2;
                    }} else i++;
                wordid++;
                    } while (Sta.top ()! = ' # ') {ans+=sta.top ();
                    Sta.pop ();
                ans+= ";
             } ans+= ' = ';
                /* printf ("Signal!............: \ n");
                for (int z = 0; z < signalnum; z++) {printf ("%d", signal[z]);
            } printf ("\ n"); */check (); } if (flag0)//definition statement may appear error {if (!FLAG3) cout << "" "<< row <<" line fault
                Error: not sealed "<< Endl; if (Flag4 > 0) cout << "<< row <<" line error: "<< flag4 <<" Not the first variable is not a comma but a space "<< Endl;
                if (FLAG5) cout << "section" << row << "line error: There are redefined variables" << Endl;
                if (flag51) cout << "section" << row << "line error: Define variable length greater than 8" << Endl;
                if (flag52) cout << "First" << row << "line error: illegal variable with first digit" << Endl;
            Continue } if (Flag1 | | flag2 | | (!FLAG3) | | Flag6 | | Flag7 | | Flag8 | | Flag9 | | Flag10 | | flag11 | | Flag12 | | Flag13 | | Flag14 | |
                FLAG15) {//printf ("[%d]\n", FLAG14);
                if (Flag1 > 0) cout << "First" << row << "line error: There are" << Flag1 << "illegal words with a length greater than 8" << Endl; if (Flag2 > 0) cout << "First" << row << "line error: There is an illegal word" << flag2 << "with a letter behind the beginning number"
                << Endl; if (!FLAG3) cout << "section" << row << "line error: not sealed" << Endl;
                if (FLAG6) cout << "section" << row << "line error: The first word is not an assignment number" << Endl;
                if (Flag7) cout << "<< row <<" line error: the plus sign can only have words and parentheses on both sides, and cannot be both left and right brackets "<< Endl;
                if (FLAG8) cout << "<< row <<" line error: The minus sign can have only words and parentheses on both sides, and cannot be both left and right brackets "<< Endl;
                if (flag9) cout << "<< row <<" Row error: Multiplication sign can have only words and parentheses on both sides, and cannot be both left and right brackets "<< Endl;
                if (FLAG10) cout << "<< row <<" Row error: Division sign can have only words and parentheses on both sides, and cannot be both left and right brackets "<< Endl;
                if (flag11) cout << "<< row <<" line error: Only words and parentheses can be on both sides of the power, and cannot be both left and right brackets "<< Endl;
                if (flag12) cout << "section" << row << "line error: The opening parenthesis and the closing parenthesis are close together, the middle cannot be empty" << Endl;
                if (FLAG13) cout << "section" << row << "line error: Two words are in the middle, there should be operators" << Endl; if (Flag14 > 0) cout << "First" << row << "line error: Missing" << flag14 << "A closing parenthesis "<< Endl;
                if (Flag14 < 0) cout << "First" << row << "line error: Missing" << flag14* ( -1) << "opening parenthesis" << Endl; 
            if (flag15 = = 1) cout << "section" << row << "Row error: Variable" << wa1 << "undefined" << Endl;
        } else cout << ans << "\ n";
    } printf ("\ n");
} return 0;
 }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.