// Infix to postfix for subset of C expressions // 3302 lab2fall12 (with connections to lab1fall12) // BPW, 9/2012 // Also computes abstract syntax tree // Does Java-style type checking, i.e. bools are not confused with ints #include #include #include // Not much of a language, but representative of expression elements // 10 character lower-case alphabetic identifiers (name) // +, - numop // *, / numop // <, >, ==, !=, <=, >= compop // && boolop // || boolop // ! boolop // ( lparen // ) rparen // ? condop // : condsep // Expression is delimited by $ and # // Operators and corresponding precedences char alpha[][3]={"(",")","!","*","/","+","-","<",">","<=",">=","==","!=","&&","||","?",":","$","#"}; int prec[]= {10, 15, 60, 55, 55, 50, 50, 45, 45, 45, 45, 40, 40, 35, 30, 25, 25, 0, 5}; //int prec[]= {10, 15, 60, 55, 55, 50, 50, 45, 45, 45, 45, 40, 40, 35, 30, 25, 20, 0, 5}; //int prec[]= {20, 30, 90, 80, 80, 70, 70, 60, 60, 60, 60, 55, 55, 50, 40, 33, 32, 0, 10}; int m,n,p; // #s of boolean identifier, integer identifiers, & tokens from lab 1 char **boolId,**intId; // Symbol tables typedef enum {UNKNOWN,BOOLVAL,INTVAL} expType; typedef struct { char token[11]; char classif[8]; expType typ; } tokenPair; tokenPair *program; int operatorStack[2000]; // entries point to program[] int operatorSP=(-1); // initial empty stack int nextSymbol; // Simple scan int postfixIndex[1000]; // Needed to build AST int postfixLength=0; int waitingOperands=0; // Indicates hypothetical unconsumed operands typedef struct { int left,right; } astType; astType ast[1000]; int isName(tokenPair x) { return strcmp(x.classif,"name")==0; } int isNamePicBool(tokenPair x) { return strcmp(x.classif,"name")==0 || strcmp(x.classif,"pic")==0 || strcmp(x.classif,"bool")==0; } int symbol2prec(char ch[11]) { int i; for (i=0; i")==0 || strcmp(x.token,"==")==0 || strcmp(x.token,"!=")==0 || strcmp(x.token,"<=")==0 || strcmp(x.token,">=")==0 || strcmp(x.token,"&&")==0 || strcmp(x.token,"||")==0 || strcmp(x.token,"?")==0 // even though ternary, ? : is treated as two binary ops, see postfix2ast() || strcmp(x.token,":")==0; } void translate() { tokenPair lastSymbol; // For detecting improper adjacent symbols strcpy(lastSymbol.token,"("); // Safe way to initialize this strcpy(lastSymbol.classif,"lparen"); operatorStack[++operatorSP]=0; // push initial $ to stack nextSymbol=1; for (nextSymbol=1; nextSymbol