Mono Compiler

Regular Expressions for Lexical Analyser: using JFlex

Grammar Rules for Syntax Analyser: using CUP2.

Intermediate Representaion(IR): independent java implementation.

GrammarCUP2.java


package dif.SyntaxAnalyser;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import dif.IntermediatRepresentation.IRGenerator;
import dif.LexicalAnalyser.LexerJFlex;
import edu.tum.cup2.grammar.NonTerminal;
import edu.tum.cup2.grammar.Terminal;
import edu.tum.cup2.spec.CUP2Specification;

import edu.tum.cup2.generator.LR1Generator;
import edu.tum.cup2.generator.Verbosity;
import edu.tum.cup2.generator.exceptions.GeneratorException;
import edu.tum.cup2.grammar.Symbol;
import edu.tum.cup2.io.LRParsingTableDump;
import edu.tum.cup2.parser.LRParser;
import edu.tum.cup2.parser.exceptions.LRParserException;
import edu.tum.cup2.parser.tables.LRParsingTable;
import edu.tum.cup2.scanner.Scanner;
import edu.tum.cup2.scanner.ScannerToken;
import edu.tum.cup2.scanner.TestScanner;
import edu.tum.cup2.semantics.Action;
import edu.tum.cup2.semantics.SymbolValue;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import static dif.SyntaxAnalyser.GrammarCUP2.Terminals.*;
import static dif.SyntaxAnalyser.GrammarCUP2.NonTerminals.*;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Block;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Decl;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Expr;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Func;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Func.Arg;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Program;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Break;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Continue;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.For;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Goto;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Label;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Return;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Struct;
import dif.SyntaxAnalyser.SyntaxTreeNodes.SyntaxTreeNode;
import edu.tum.cup2.grammar.SpecialTerminals;
import static edu.tum.cup2.scanner.ScannerTokenTestTool.terminal;
import java.io.FileReader;
import java.util.LinkedList;
import java.util.List;


/**
 *
 * @author soheildif
 */
public class GrammarCUP2 extends CUP2Specification{
    
    public enum Terminals implements Terminal
    {
       
           PLUS, 
           MINUS, 
           MUL, 
           DIV, 
           MOD,
           
           EQ,
           NEQ,
           LT,
           LTE,
           GT,
           GTE,
           AND,
           ANDAND,
           OR,
           OROR,
           
           INT,
           CHAR,
           BOOL,
           FLOAT,
           LONG,   
           
           LPAREN , 
           RPAREN, 
           
           LBRACK,
           RBRACK,
           
           LBRACE,
           RBRACE,
        
           IDENT,
           INTCONST, 
           ASSIGN, 

           SEMICOLON, COMMA, COLON,
           
           IF, ELSE, FOR,      
           
           RETURN,
           RECORD, PROCEDURE,
           BREAK, CONTINUE, GOTO           
                      
    }

    //non-terminals
    public enum NonTerminals implements NonTerminal
    {
            expr,
            binop,
            decl,
            var_dcl,
            arr_dcl,
            type,
            arr_size,
            stmt,
            assign,
            block,                        
            blk_slice,
            blk_slice_lst,
            params,
            method_call,
            func_dcl,
            args,
            prog_lst,                                             
            program,  
            prog_slice,
            struct,
            decl_lst,  
            label
            
    }

    public class INTCONST extends SymbolValue{};
    public class IDENT extends SymbolValue{};
    public class expr extends SymbolValue{};	
    public class binop extends SymbolValue{};		    
    public class decl extends SymbolValue{};
    public class var_dcl extends SymbolValue{};
    public class arr_dcl extends SymbolValue{};
    public class arr_size extends SymbolValue{};
    public class type extends SymbolValue{};    
    public class stmt extends SymbolValue{};        
    public class assign extends SymbolValue{};        
    public class block extends SymbolValue{};    
    public class blk_slice extends SymbolValue{};    
    public class blk_slice_lst extends SymbolValue>{};    
    public class params extends SymbolValue>{};     
    public class method_call extends SymbolValue{};    
    public class func_dcl extends SymbolValue{};    
    public class args extends SymbolValue>{};          
    public class program extends SymbolValue{};              
    public class prog_slice extends SymbolValue{};
    public class struct extends SymbolValue{};
    public class decl_lst extends SymbolValue>{};
    

    //public class stmt extends SymbolValue{};	    
    
    public GrammarCUP2() {       
        
        precedences( left(MUL, DIV, MOD), left(PLUS, MINUS), left(LT, LTE), left(GT, GTE), left(EQ, NEQ), left(AND), left(OR), left(ANDAND), left(OROR), left(IDENT), left(SEMICOLON), left());
                
        grammar(                
                prod(program,  rhs(program,  prog_slice),
                                    new Action() {
                                        public Program a(Program prog, SyntaxTreeNode node) {                                                                                                                                            
                                            prog.addProgSlice(node);
                                            return prog;                                           
                                        }
                                    },                                
                                rhs(),
                                    new Action() {
                                        public Program a() {                                                                                                                                                                                        
                                            return new Program();                                           
                                        }
                                    }                                
                ),                       
                
                prod(prog_slice,
                                rhs(decl),
                                    new Action() {
                                        public SyntaxTreeNode a(Decl dcl) {                                                                                                                                                                                        
                                            return dcl;                                           
                                        }
                                    },                                                        
                                rhs(func_dcl),
                                    new Action() {
                                        public SyntaxTreeNode a(Func func) {                                                                                                                                                                                        
                                            return func;                                           
                                        }
                                    },
                                rhs(struct),
                                    new Action() {
                                        public SyntaxTreeNode a(Struct struct_dcl) {                                                                                                                                                                                        
                                            return struct_dcl;                                           
                                        }
                                    }                                    
                
                ),

                prod(func_dcl,  rhs(type, IDENT, LPAREN, args, RPAREN, block),                                    
                                    new Action() {
                                        public Func a(Integer typeSize, String name, List args, Block body) {                                                    
                                            return new Func(name, typeSize, args, body);
                                        }
                                    },
                                rhs(PROCEDURE, IDENT, LPAREN, args, RPAREN, block),                                    
                                    new Action() {
                                        public Func a(String name, List args, Block body) {                                                    
                                            return new Func(name, 0, args, body);
                                        }
                                    }  
                ),
                
                prod(struct,    rhs(RECORD, IDENT, LBRACE, decl_lst, RBRACE, SEMICOLON),                                    
                                    new Action() {
                                        public Struct a(String name, List dclList) {                                                    
                                            return new Struct(name, dclList);
                                        }
                                    }                                    
                ),                
                
                prod(decl_lst,  rhs(decl_lst, decl),
                                    new Action() {
                                        public List a(List dclList, Decl dcl) {                                                    
                                            dclList.add(dcl);
                                            return dclList;
                                        }
                                    },                
                                rhs(),
                                    new Action() {
                                        public List a() {                                                                                        
                                            List l = new LinkedList<>();
                                            return l;                                            
                                        }
                                    }                                
                ),
                //prod(stmt, rhs(expr, SEMI)),                 
                prod(block,     rhs(LBRACE, blk_slice_lst, blk_slice, RBRACE),
                                    new Action() {
                                        public Block a(List nodeList, SyntaxTreeNode node) {
                                            nodeList.add(node);
                                            return new Block(nodeList);
                                        }
                                    }
                ),                                
                
                prod(blk_slice_lst, 
                                rhs(blk_slice_lst, blk_slice),
                                    new Action() {
                                        public List a(List nodeList, SyntaxTreeNode node) {
                                            nodeList.add(node);
                                            return nodeList;
                                        }
                                    },                                    
                                rhs(),
                                    new Action() {
                                        public List a() {
                                            return new LinkedList();
                                        }
                                    }
                ),
                
                prod(blk_slice, rhs(decl),
                                    new Action() {
                                        public SyntaxTreeNode a(Decl dcl) {
                                            return dcl;
                                        }
                                    },
                                rhs(stmt),
                                    new Action() {
                                        public SyntaxTreeNode a(Stmt stm) {
                                            return stm;
                                        }
                                    }
                ),                                                
                
                prod(args,      rhs(type, IDENT),
                                    new Action() {
                                            public List a(Integer typeSize, String name) {                                                    
                                                List l = new LinkedList<>();
                                                l.add(new Arg(typeSize, name));
                                                return l;                                            
                                        }
                                    },                                    
                                rhs(type, IDENT, COMMA, args),
                                    new Action() {
                                            public List a(Integer typeSize, String name, List l) {                                                
                                                l.add(new Arg(typeSize, name));
                                                return l;                                            
                                        }
                                    },
                                    
                                rhs(type, IDENT, LBRACE, RBRACE),
                                    new Action() {
                                            public List a(Integer typeSize, String name) {                                                    
                                                List l = new LinkedList<>();
                                                l.add(new Arg.ArrayArg(typeSize, name));
                                                return l;                                            
                                        }
                                    },
                                rhs(type, IDENT, LBRACE, RBRACE, args),
                                    new Action() {
                                            public List a(Integer typeSize, String name, List l) {                                                
                                                l.add(new Arg.ArrayArg(typeSize, name));
                                                return l;                                            
                                        }
                                    }
                ),
                
                prod(stmt,      rhs(assign, SEMICOLON),
                                    new Action(){
                                        public Stmt a(Stmt.Assign assStmt) {                                        
                                            return assStmt;
                                        }
                                    },                                                                       
                                    
                                rhs(IF, LPAREN, expr, RPAREN, block, ELSE, block),
                                    new Action(){
                                        public Stmt.IfThenElse a(Expr condExpr, Block thenBlk, Block elseBlk) {                                                                                    
                                            return new Stmt.IfThenElse(condExpr, thenBlk, elseBlk);
                                        }
                                    },
                                    
                                rhs(FOR, LPAREN, assign, SEMICOLON, expr, SEMICOLON, assign, RPAREN, block),
                                    new Action(){
                                        public For a(Stmt.Assign initAss, Expr stopCond, Stmt.Assign endAss, Block body) {
                                            return new For(initAss, stopCond, endAss, body);
                                        }                                            
                                    },
                                    
                                rhs(method_call, SEMICOLON), 
                                    new Action(){
                                        public Stmt.MethodCall a(Stmt.MethodCall mcall) {
                                            return mcall;
                                        }                                            
                                    },
                                    
                                rhs(RETURN, expr, SEMICOLON),
                                    new Action(){
                                        public Return a(Expr expr) {
                                            return new Return(expr);
                                        }                                            
                                    },
                                    
                                rhs(BREAK, SEMICOLON),
                                    new Action(){
                                        public Break a() {
                                            return new Break();
                                        }                                            
                                    },
                                    
                                rhs(CONTINUE, SEMICOLON),
                                    new Action(){
                                        public Continue a() {
                                            return new Continue();
                                        }                                            
                                    },
                                    
                                rhs(GOTO, IDENT, SEMICOLON),
                                    new Action(){
                                        public Goto a(String label) {
                                            return new Goto(label);
                                        }                                            
                                    },
                                    
                                rhs(IDENT, COLON),
                                    new Action(){
                                        public Label a(String label) {
                                            return new Label(label);
                                        }                                            
                                    }                
                ),
                
                prod(assign,    rhs(IDENT, ASSIGN, expr),                
                                    new Action(){
                                        public Stmt.Assign a(String varName, Expr expr) {                                        
                                            return new Stmt.Assign(varName, expr);
                                        }
                                    }                      
                ),
                        
                prod(decl,      rhs(var_dcl),                
                                    new Action(){
                                        public Decl a(Decl.VarDecl var_dcl) {                                        
                                            return var_dcl;
                                        }
                                    },       
                                    
                                rhs(arr_dcl),
                                    new Action(){
                                        public Decl a(Decl.ArrDecl arr_dcl) {                                        
                                            return arr_dcl;
                                        }
                                    }                                
                ),
                
                prod(var_dcl,   rhs(type, IDENT, SEMICOLON),                                
                                    new Action(){
                                        public Decl.VarDecl a(Integer size, String name) {                                        
                                            return new Decl.VarDecl(size, name);
                                        }
                                    }                                
                ),
                               
                prod(arr_dcl,       rhs(type, IDENT, arr_size, SEMICOLON),
                                
                                    new Action(){
                                        public Decl.ArrDecl a(Integer typeSize, String name, Integer arrSize) {                                                
                                            return new Decl.ArrDecl(typeSize, arrSize, name);
                                        }
                                    }                
                ),
                
                prod(arr_size, rhs(LBRACK, INTCONST, RBRACK, arr_size),
                                    new Action(){
                                        public Integer a(Integer intConst, Integer arrSize) {
                                            return intConst*arrSize;
                                        }
                                    },
                               rhs(),  // Epcion Production !                
                                    new Action(){
                                        public Integer a() {
                                            return 1;
                                        }
                                    }                
                ),
                
                prod(type,      rhs(INT),
                                    new Action(){
                                        public Integer a() {
                                            return 4;
                                        }
                                     }, 
                                    
                                rhs(CHAR),
                                    new Action(){
                                        public Integer a() {
                                            return 1;
                                        }
                                    }                                
                
                ),                                
                                
                prod(method_call, 
                                rhs(IDENT, LPAREN, RPAREN),
                                    new Action() {
                                        public Stmt.MethodCall a(String name) {
                                            return new Stmt.MethodCall(name);
                                        }
                                    },                                   
                                
                                rhs(IDENT, LPAREN, params, RPAREN),
                                    new Action() {
                                        public Stmt.MethodCall a(String name, List parameters) {
                                            return new Stmt.MethodCall(name, parameters);
                                        }
                                    }
                ),
                
                prod(params,    rhs(expr),
                                    new Action() {
                                        public List a(Expr e) {
                                            List l = new LinkedList();
                                            l.add(e);
                                            return l;
                                        }
                                    },
                                rhs(expr, COMMA, params),
                                    new Action() {
                                        public List a(Expr e, List l) {
                                            l.add(e);
                                            return l;
                                        }
                                    }
                ),
                                
                prod(expr,      rhs(expr, binop, expr),
                                    new Action () {
                                        public Expr a(Expr e1, Terminals binop, Expr e2) {                                                                                        
                                            return new Expr.BinExp(e1, binop, e2);                                                                                        
                                        }                                        
                                    }, 
                                                                                                                             
                                rhs(LPAREN, expr, RPAREN),
                                    new Action() {
                                        public Expr a(Expr e) {
                                            return new Expr.ParenthesisExp(e);
                                        }
                                    },                                
                                    
                                rhs(IDENT),
                                   new Action() {
                                        public Expr a(String name) {
                                            return new Expr.Identifier(name);
                                        }
                                    },                                
                                   
                                rhs(INTCONST),
                                    new Action() {
                                        public Expr a(Integer n) {
                                            return new Expr.IntConst(n);
                                        }
                                    },
                                rhs(method_call),
                                    new Action() {
                                        public Expr a(Stmt.MethodCall mcall) {
                                            return new Expr.MethodCall(mcall);
                                        }
                                    }                               
                ),
                
                prod(binop,     rhs(PLUS),
                                    new Action() {
                                        public Terminals a() {
                                            return Terminals.PLUS;
                                        }
                                    },
                                    
                                rhs(MINUS),
                                    new Action() {
                                        public Terminals a() {
                                            return MINUS;
                                        }
                                    },                                     
                                    
                                rhs(MUL),
                                    new Action() {
                                        public Terminals a() {
                                            return MUL;
                                        }
                                    },
                                    
                                rhs(DIV),
                                    new Action() {
                                        public Terminals a() {
                                            return DIV;
                                        }
                                    },
                                    
                                rhs(MOD),
                                    new Action() {
                                        public Terminals a() {
                                            return MOD;
                                        }
                                    },                                    
                                    
                                rhs(EQ),
                                    new Action() {
                                        public Terminals a() {
                                            return EQ;
                                        }
                                    },
                                rhs(NEQ),
                                    new Action() {
                                        public Terminals a() {
                                            return NEQ;
                                        }
                                    },
                                    
                                rhs(LT),
                                    new Action() {
                                        public Terminals a() {
                                            return LT;
                                        }
                                    },
                                rhs(LTE),
                                    new Action() {
                                        public Terminals a() {
                                            return LTE;
                                        }
                                    },                                    
                                rhs(GT),
                                    new Action() {
                                        public Terminals a() {
                                            return GT;
                                        }
                                    },
                                rhs(GTE),
                                    new Action() {
                                        
                                        public Terminals a() {
                                            return Terminals.GTE;
                                        }
                                    },
                                    
                                rhs(AND),
                                    new Action() {
                                        public Terminals a() {
                                            return Terminals.AND;
                                        }
                                    },
                                rhs(ANDAND),
                                    new Action() {
                                        public Terminals a() {
                                            return Terminals.ANDAND;
                                        }
                                    },                                  
                                 
                                rhs(OR),
                                    new Action() {
                                        public Terminals a() {
                                            return Terminals.OR;
                                        }
                                    },
                                rhs(OROR),
                                    new Action() {
                                        public Terminals a() {
                                            return Terminals.OROR;
                                        }
                                    }                
                )                                        
                                                
        );
            
    }                  

}
		
		
		

SyntaxAnalyser.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dif.SyntaxAnalyser;

import dif.SyntaxAnalyser.SyntaxTreeNodes.SyntaxTreeNode;
import edu.tum.cup2.generator.LR1Generator;
import edu.tum.cup2.generator.Verbosity;
import edu.tum.cup2.generator.exceptions.GeneratorException;
import edu.tum.cup2.io.LRParsingTableDump;
import edu.tum.cup2.parser.LRParser;
import edu.tum.cup2.parser.exceptions.LRParserException;
import edu.tum.cup2.parser.tables.LRParsingTable;
import edu.tum.cup2.scanner.Scanner;
import edu.tum.cup2.spec.CUP2Specification;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author soheildif
 */
public class SyntaxAnalyser {
    
    public static SyntaxTreeNode getSyntaxTree(Scanner scanner) throws GeneratorException, LRParserException, IOException {              
        
        CUP2Specification grammar = new GrammarCUP2();
        
        LRParsingTable table = new LR1Generator( grammar, Verbosity.Detailled).getParsingTable();
        
        LRParsingTableDump.dumpToHTML(table, new File("SpecTest3NoPrec.html")); //TEST	                                                                   

        SyntaxTreeNode node = (SyntaxTreeNode) new LRParser(table).parse(scanner);                                     
        
        return node;
    }
}

//                 Decl decl  = (Decl) new LRParser(table).parse(scanner);
//                 
//                IRGenerator irGenerator = new IRGenerator();
//                
//                decl.dfs(irGenerator);            
        
//                Expr syntaxTree = (Expr) new LRParser(table).parse(scanner);
//                
//                IRGenerator irGenerator = new IRGenerator();
//                
//                syntaxTree.dfs(irGenerator);
                
                // testing "a+a*(b+c)+(b+c)*d" as input to compile
                //result must be: 
                //t0 = b+c
                //t1 = a*t0
                //t2 = a+t1
                //t3 = b+c
                //t4 = t3*d
                //t5 = t2+t4                                   
  
                
                
//                // Another Test ( Comment previous test and uncomment this test)
                
//                //check generated parser with a small computation : "a+a*(b+c)+(b+c)*d"
//                new LRParser(table).parse(new TestScanner(
//                        terminal(IDENT, "a"),
//                        terminal(PLUS),
//                        terminal(IDENT, "b"),
//                        terminal(MUL),                        
//                        terminal(IDENT, "c"),
//                        terminal(PLUS),
//                        terminal(IDENT, "d"),
//                        terminal(MUL),
//                        terminal(IDENT, "e")                                                
//                        ));
//                // testing "a + b*c + d*e" as input to compile
//                //result must be:                 
//                //t0 = b*c
//                //t1 = a+t0
//                //t2 = d*e
//                //t3 = t1+t2   

		
		
		

IRGenerator.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dif.IntermediatRepresentation;

import dif.SyntaxAnalyser.GrammarCUP2;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Expr;

import static dif.SyntaxAnalyser.GrammarCUP2.Terminals;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Decl;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Func;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Func.Arg;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Break;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Continue;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Goto;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Label;
import dif.SyntaxAnalyser.SyntaxTreeNodes.Stmt.Return;
import dif.SyntaxAnalyser.SyntaxTreeNodes.SyntaxTreeNode;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author soheildif
 */
public class IRGenerator {
    
    static PrintWriter writer;    
    
    Integer tcounter = 0;     
    int labelCounter;
    int breakLbl;       // for keyword break, stores last break jump label;
    int countinueLbl;   // for keyword countinue, stores last countinue jump label;

    public IRGenerator(String output) {
        try {
            writer = new PrintWriter(output + ".mini");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(IRGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }       
        
    public static void generateIRCode(SyntaxTreeNode startNode) {
        startNode.dfs(new IRGenerator("output"));
        writer.flush();
    }
    
    public void visit(Return ret) {
        writer.println("RET " + ret.expr.name);
    }
    
    public void visit(Break brk) {
        writer.println("JMP L" + breakLbl);
    }    
    
    public void visit(Continue cnt) {
        writer.println("JMP L" + countinueLbl);
    }
    
    public void visit(Goto go2) {
        writer.println("JMP " + go2.label);
    } 
    
    public void visit(Label label) {
        writer.println(label.label + ":");
    }    
    
    public void visit(Func func) {
        
        writer.println("FUN " + func.name + "," + func.typeSize);
        
        for(Arg arg : func.args)
            writer.println("ARG " + arg.typeSize + "," + arg.name);    
        
        func.body.dfs(this);
        
        writer.println("END " + func.name);
    }
    
    public void visit(Expr.MethodCall mcall) {
        String t = "$t"+ (tcounter++).toString();    
        mcall.name = t; 
        mcall.methodCall.dfs(this);        
        writer.println( "= "  + t +" "+ mcall.methodCall.name);                                                                                 
    }
    
    private String getTypeName(Integer typeSize) {
        String type = null;        
        switch (typeSize) {
            case 4: type = "int";break;
            case 1: type = "char";break;                                    
        }
        return type;
    }
       
    public void postvisit(Expr.BinExp binExp) {                
        String t = "$t"+ (tcounter++).toString();    
        binExp.name = t;                
        String opStr = null;
        switch (binExp.op) {
            case PLUS:  opStr = "+";break;
            case MUL:   opStr = "*";break;            
            case MINUS:   opStr = "-";break;                
            case MOD:   opStr = "%";break;
            case DIV:   opStr = "/";break;
            case LT:   opStr = "<";break;
            case LTE:   opStr = "<=";break;
            case GT:   opStr = ">";break;                
            case GTE:   opStr = ">=";break;                
            case EQ:   opStr = "==";break;
            case NEQ:   opStr = "!=";break;
            case AND:   opStr = "&";break;
            case ANDAND:   opStr = "&&";break;
            case OR:   opStr = "|";break;
            case OROR:   opStr = "||";break;                               
                
        }
        String ir_code = opStr + " " + t + " " + binExp.e1.name + " " + binExp.e2.name;    
        writer.println(ir_code);                                                                         
    }

    public void postvisit(Expr.ParenthesisExp parExp) {
        parExp.name = parExp.e.name;
    }    

    public void visit(Decl.VarDecl decl) {
        writer.println("VAR " + decl.typeSize + ", " + decl.name);
    }

    public void visit(Decl.ArrDecl arrDecl) {
        writer.println("ARR " + arrDecl.typeSize + "," + arrDecl.arrSize + "," + arrDecl.name);
    }

    public void postvisit(Stmt.Assign ass) {        
        writer.println( "= "  + ass.varName + " " + ass.expr.name);
        tcounter = 0;
    }

    public void previsit(Stmt.IfThenElse ifStmt) {
        
        int elseLbl = labelCounter++;
        int ifStmtNextLbl = labelCounter++;        
        
        ifStmt.condExpr.dfs(this); // Cond.code
        
        writer.println("JZ L" + elseLbl + " " + ifStmt.condExpr.name); // 
        
        ifStmt.thenBlk.dfs(this);
        
        writer.println("JMP L" + ifStmtNextLbl);
       
        writer.println("L" + elseLbl + ":");
        
        ifStmt.elseBlk.dfs(this);        
        
        writer.println("L" + ifStmtNextLbl + ":");                        
        
    }

    public void privisit(Stmt.For forStmt) {
        
        int initNxtLbl = countinueLbl = labelCounter++;        
        int forStmtNxtLbl = breakLbl = labelCounter++;
                                
        forStmt.initAss.dfs(this);
        writer.println("L" + initNxtLbl + ":");
        forStmt.stopCond.dfs(this);
        writer.println("JZ L" + forStmtNxtLbl + " " + forStmt.stopCond.name);        
        forStmt.body.dfs(this);
        forStmt.endAss.dfs(this);
        writer.println("JMP L" + initNxtLbl);
        writer.println("L" + forStmtNxtLbl + ":");
    }
    
    public void postvisit(Stmt.MethodCall mcall) {
        writer.print("CALL " + mcall.name);
                
        if(mcall.params != null)             
            for(Expr e : mcall.params)
                writer.print("," + e.name);
               
        writer.println();
        
    }
    
}

LexicalAnalyser.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dif.LexicalAnalyser;

import edu.tum.cup2.grammar.SpecialTerminals;
import edu.tum.cup2.scanner.Scanner;
import edu.tum.cup2.scanner.ScannerToken;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 *
 * @author soheildif
 */
public class LexicalAnalyser {
    
    public static Scanner getScanner(String inputFile) throws FileNotFoundException {    
        
        Scanner scanner = new LexerJFlex(new FileReader(inputFile)); 
        
        return scanner;
    }
    
    public static void testScanner(String inputFile) throws FileNotFoundException, IOException {
    
        Scanner scanner = new LexerJFlex(new FileReader(inputFile)); 
                       
        //Reading from JFlex Scanner (Lexical Analyser) for testing input tokens
        ScannerToken s;
        do {
          s = scanner.readNextTerminal();
          System.out.println("token: " + s);
        } while (!s.getSymbol().equals(SpecialTerminals.EndOfInputStream));      
        
    }
    
}

SyntaxTreeNode.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dif.SyntaxAnalyser.SyntaxTreeNodes;

import dif.IntermediatRepresentation.IRGenerator;

/**
 *
 * @author soheildif
 */
public interface SyntaxTreeNode{
    
    public void dfs(IRGenerator irGenerator);     
    
}
		

Expr.java


package dif.SyntaxAnalyser.SyntaxTreeNodes;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import dif.IntermediatRepresentation.IRGenerator;
import static dif.SyntaxAnalyser.GrammarCUP2.Terminals;

/**
 *
 * @author soheildif
 */
public abstract class Expr implements SyntaxTreeNode{
    
    public String name;    
    
    public abstract void dfs(IRGenerator irGenerator);    
    
    public static class BinExp extends Expr {
                        
        public Expr e1, e2;
        public Terminals op;        

        public BinExp(Expr e1, Terminals op, Expr e2) {
            this.e1 = e1;            
            this.op = op;          
            this.e2 = e2;
        }               

        @Override
        public void dfs(IRGenerator irGenerator) {
            
            e1.dfs(irGenerator);
            e2.dfs(irGenerator);
            
            irGenerator.postvisit(this);
        }
        
    }
    
    public static class ParenthesisExp extends Expr {

        public Expr e;

        public ParenthesisExp(Expr e) {
            this.e = e;
        }        

        @Override
        public void dfs(IRGenerator irGenerator) {
            e.dfs(irGenerator);            
            irGenerator.postvisit(this);
        }
        
    }
    
    
    public static class Identifier extends Expr {
        
        public Identifier(String name) {
            this.name = name;
        }                

        @Override
        public void dfs(IRGenerator irGenerator) {
            return;
        }
        
    }
    
    
    public static class IntConst extends Expr {
        
        public IntConst(Integer i) {
            this.name = i.toString();
        }        

        @Override
        public void dfs(IRGenerator irGenerator) {            
            return;
        }
        
    }
    
    public static class MethodCall extends Expr {
        
        public Stmt.MethodCall methodCall;

        public MethodCall(Stmt.MethodCall methodCall) {
            this.methodCall = methodCall;
            this.name = methodCall.name;
        }             
        @Override
        public void dfs(IRGenerator irGenerator) {
            irGenerator.visit(this);            
        }
    
    }
    
}

Stmt.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dif.SyntaxAnalyser.SyntaxTreeNodes;

import dif.IntermediatRepresentation.IRGenerator;
import java.util.List;

/**
 *
 * @author soheildif
 */
public abstract class Stmt implements SyntaxTreeNode{
    
    public abstract void dfs(IRGenerator irGenerator);    
        
    public static class Assign extends Stmt {
        // varName = expr;
        public String varName; 
        public Expr expr;        

        public Assign(String varName, Expr expr) {
            this.varName = varName;
            this.expr = expr;            
        }               
                
        @Override
        public void dfs(IRGenerator irGenerator) {
            
            expr.dfs(irGenerator);
            
            irGenerator.postvisit(this);
        }
    
    }
    
    public static class IfThenElse extends Stmt {
        
        public Expr condExpr;
        public Block thenBlk;
        public Block elseBlk;

        public IfThenElse(Expr condExpr, Block thenBlk, Block elseBlk) {
            this.condExpr = condExpr;
            this.thenBlk = thenBlk;
            this.elseBlk = elseBlk;
        }                
                
        @Override
        public void dfs(IRGenerator irGenerator) {
            irGenerator.previsit(this);
        }
    
    }
    
    public static class For extends Stmt {
        
        public Assign initAss;       
        public Expr stopCond;        
        public Assign endAss;
        public Block body;  

        public For(Assign initAss, Expr stopCond, Assign endAss, Block body) {
            this.initAss = initAss;
            this.stopCond = stopCond;
            this.endAss = endAss;
            this.body = body;
        }
                      
        @Override
        public void dfs(IRGenerator irGenerator) {
            irGenerator.privisit(this);
        }
        
    }
    
    public static class MethodCall extends Stmt{
        
        public String name;
        public List params;
        
        public MethodCall(String name){
            this.name = name;
        }

        public MethodCall(String name, List params) {
            this(name);
            this.params = params;
        }                                        

        @Override
        public void dfs(IRGenerator irGenerator) {            
            if(params != null)
                for(Expr e : params)              
                    e.dfs(irGenerator);
            
            irGenerator.postvisit(this);
        }
    
    }
    
    public static class Return extends Stmt {        
        
        public Expr expr;

        public Return(Expr expr) {
            this.expr = expr;
        }                

        @Override
        public void dfs(IRGenerator irGenerator) {
            expr.dfs(irGenerator);
            irGenerator.visit(this);
        }
        
    }
    
    public static class Break extends Stmt {                

        @Override
        public void dfs(IRGenerator irGenerator) {
            irGenerator.visit(this);
        }        
        
    }
    
    public static class Continue extends Stmt {                

        @Override
        public void dfs(IRGenerator irGenerator) {
            irGenerator.visit(this);
        }        
        
    }    
    
    public static class Goto extends Stmt {                
        
        public String label;

        public Goto(String label) {
            this.label = label;
        }
             
        @Override
        public void dfs(IRGenerator irGenerator) {
            irGenerator.visit(this);
        }        
        
    }     
    
    public static class Label extends Stmt {                
        
        public String label;

        public Label(String label) {
            this.label = label;
        }               

        @Override
        public void dfs(IRGenerator irGenerator) {
            irGenerator.visit(this);
        }        
        
    }    
}


Decl.java

		

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dif.SyntaxAnalyser.SyntaxTreeNodes;

/**
 *
 * @author soheildif
 */

import dif.IntermediatRepresentation.IRGenerator;
import static dif.SyntaxAnalyser.GrammarCUP2.Terminals;

public abstract class Decl implements SyntaxTreeNode{    
    public Integer typeSize;
    public String name;    

    public abstract void dfs(IRGenerator irGenerator);    
    
    public Decl(Integer size, String name) {
        this.typeSize = size;
        this.name = name;
    }
          
    public static class VarDecl extends Decl {

        public VarDecl(Integer size, String name) {
            super(size, name);
        }            
        
        public void dfs(IRGenerator irGen){
            irGen.visit(this);
        }          
    }
    
    public static class ArrDecl extends Decl {
        
        public int arrSize;

        public ArrDecl(Integer typeSize, Integer arrSize, String name) {
            super(typeSize, name);
            this.arrSize = arrSize;
        }            
        
        public void dfs(IRGenerator irGen){
            irGen.visit(this);
        }          
    }  
   
}

LexerJFlex.java


/* The following code was generated by JFlex 1.6.1 */

/* Copy in .java Class Section */

package dif.LexicalAnalyser;

import edu.tum.cup2.grammar.*;
import edu.tum.cup2.scanner.*;

import static dif.SyntaxAnalyser.GrammarCUP2.Terminals.*;
import static dif.SyntaxAnalyser.GrammarCUP2.NonTerminals.*;

/**
 * This class is a scanner for the {@link GrammarCUP2} grammar.
 * It was generated by JFlex, using the file LexerJFlex.jflex
 *
 * @author Andreas Wenger
 */
 


/* CUP2 imports */
import edu.tum.cup2.scanner.*;
import edu.tum.cup2.grammar.*;

public class LexerJFlex implements Scanner {

  /** This character denotes the end of file */
  public static final int YYEOF = -1;

  /** initial size of the lookahead buffer */
  private static final int ZZ_BUFFERSIZE = 16384;

  /** lexical states */
  public static final int YYINITIAL = 0;

  /**
   * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
   * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
   *                  at the beginning of a line
   * l is of the form l = 2*k, k a non negative integer
   */
  private static final int ZZ_LEXSTATE[] = { 
     0, 0
  };

  /** 
   * Translates characters to character classes
   */
  private static final String ZZ_CMAP_PACKED = 
    "\11\0\1\7\1\5\1\0\1\7\1\4\22\0\1\7\1\42\2\0"+
    "\1\1\1\37\1\43\1\0\1\45\1\46\1\35\1\33\1\53\1\34"+
    "\1\0\1\36\1\3\11\2\1\54\1\6\1\40\1\32\1\41\2\0"+
    "\32\1\1\47\1\0\1\50\1\0\1\1\1\0\1\15\1\27\1\13"+
    "\1\25\1\20\1\17\1\31\1\14\1\10\1\1\1\30\1\21\1\1"+
    "\1\11\1\23\1\26\1\1\1\16\1\22\1\12\1\24\5\1\1\51"+
    "\1\44\1\52\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uff92\0";

  /** 
   * Translates characters to character classes
   */
  private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);

  /** 
   * Translates DFA states to action switch labels.
   */
  private static final int [] ZZ_ACTION = zzUnpackAction();

  private static final String ZZ_ACTION_PACKED_0 =
    "\1\0\1\1\2\2\2\3\1\4\10\1\1\5\1\6"+
    "\1\7\1\10\1\11\1\12\1\13\1\14\1\0\1\15"+
    "\1\16\1\17\1\20\1\21\1\22\1\23\1\24\1\25"+
    "\1\26\1\0\1\1\1\27\10\1\1\30\1\31\1\32"+
    "\1\33\1\34\1\35\1\36\4\1\1\37\4\1\1\40"+
    "\3\1\1\41\2\1\1\42\4\1\1\43\1\1\1\44"+
    "\1\45\3\1\1\46\1\1\1\47";

  private static int [] zzUnpackAction() {
    int [] result = new int[83];
    int offset = 0;
    offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
    return result;
  }

  private static int zzUnpackAction(String packed, int offset, int [] result) {
    int i = 0;       /* index in packed string  */
    int j = offset;  /* index in unpacked array */
    int l = packed.length();
    while (i < l) {
      int count = packed.charAt(i++);
      int value = packed.charAt(i++);
      do result[j++] = value; while (--count > 0);
    }
    return j;
  }


  /** 
   * Translates a state to a row index in the transition table
   */
  private static final int [] ZZ_ROWMAP = zzUnpackRowMap();

  private static final String ZZ_ROWMAP_PACKED_0 =
    "\0\0\0\55\0\132\0\207\0\264\0\207\0\207\0\341"+
    "\0\u010e\0\u013b\0\u0168\0\u0195\0\u01c2\0\u01ef\0\u021c\0\u0249"+
    "\0\207\0\207\0\207\0\207\0\207\0\u0276\0\u02a3\0\u02d0"+
    "\0\u02fd\0\u032a\0\207\0\207\0\207\0\207\0\207\0\207"+
    "\0\207\0\207\0\u0357\0\u0384\0\55\0\u03b1\0\u03de\0\u040b"+
    "\0\u0438\0\u0465\0\u0492\0\u04bf\0\u04ec\0\207\0\207\0\207"+
    "\0\207\0\207\0\207\0\55\0\u0519\0\u0546\0\u0573\0\u05a0"+
    "\0\55\0\u05cd\0\u05fa\0\u0627\0\u0654\0\55\0\u0681\0\u06ae"+
    "\0\u06db\0\55\0\u0708\0\u0735\0\55\0\u0762\0\u078f\0\u07bc"+
    "\0\u07e9\0\55\0\u0816\0\55\0\55\0\u0843\0\u0870\0\u089d"+
    "\0\55\0\u08ca\0\55";

  private static int [] zzUnpackRowMap() {
    int [] result = new int[83];
    int offset = 0;
    offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
    return result;
  }

  private static int zzUnpackRowMap(String packed, int offset, int [] result) {
    int i = 0;  /* index in packed string  */
    int j = offset;  /* index in unpacked array */
    int l = packed.length();
    while (i < l) {
      int high = packed.charAt(i++) << 16;
      result[j++] = high | packed.charAt(i++);
    }
    return j;
  }

  /** 
   * The transition table of the DFA
   */
  private static final int [] ZZ_TRANS = zzUnpackTrans();

  private static final String ZZ_TRANS_PACKED_0 =
    "\1\0\1\2\1\3\1\4\1\5\1\6\1\7\1\6"+
    "\1\10\2\2\1\11\2\2\1\12\1\13\1\14\5\2"+
    "\1\15\1\16\1\2\1\17\1\20\1\21\1\22\1\23"+
    "\1\24\1\25\1\26\1\27\1\30\1\31\1\32\1\33"+
    "\1\34\1\35\1\36\1\37\1\40\1\41\1\42\1\0"+
    "\3\2\4\0\22\2\25\0\2\3\133\0\1\43\50\0"+
    "\3\2\4\0\1\2\1\44\5\2\1\45\12\2\24\0"+
    "\3\2\4\0\4\2\1\46\6\2\1\47\6\2\24\0"+
    "\3\2\4\0\10\2\1\50\11\2\24\0\3\2\4\0"+
    "\13\2\1\51\6\2\24\0\3\2\4\0\11\2\1\52"+
    "\10\2\24\0\3\2\4\0\6\2\1\53\13\2\24\0"+
    "\3\2\4\0\6\2\1\54\13\2\24\0\3\2\4\0"+
    "\13\2\1\55\6\2\55\0\1\56\54\0\1\57\54\0"+
    "\1\60\54\0\1\61\65\0\1\62\55\0\1\63\16\0"+
    "\1\6\47\0\3\2\4\0\2\2\1\64\17\2\24\0"+
    "\3\2\4\0\5\2\1\65\14\2\24\0\3\2\4\0"+
    "\1\2\1\66\20\2\24\0\3\2\4\0\2\2\1\67"+
    "\1\70\16\2\24\0\3\2\4\0\6\2\1\71\13\2"+
    "\24\0\3\2\4\0\12\2\1\72\7\2\24\0\3\2"+
    "\4\0\13\2\1\73\6\2\24\0\3\2\4\0\10\2"+
    "\1\74\11\2\24\0\3\2\4\0\2\2\1\75\17\2"+
    "\24\0\3\2\4\0\6\2\1\76\13\2\24\0\3\2"+
    "\4\0\2\2\1\77\17\2\24\0\3\2\4\0\14\2"+
    "\1\100\5\2\24\0\3\2\4\0\13\2\1\101\6\2"+
    "\24\0\3\2\4\0\10\2\1\102\11\2\24\0\3\2"+
    "\4\0\3\2\1\103\16\2\24\0\3\2\4\0\5\2"+
    "\1\104\14\2\24\0\3\2\4\0\13\2\1\105\6\2"+
    "\24\0\3\2\4\0\1\106\21\2\24\0\3\2\4\0"+
    "\6\2\1\107\13\2\24\0\3\2\4\0\6\2\1\110"+
    "\13\2\24\0\3\2\4\0\10\2\1\111\11\2\24\0"+
    "\3\2\4\0\20\2\1\112\1\2\24\0\3\2\4\0"+
    "\1\2\1\113\20\2\24\0\3\2\4\0\1\2\1\114"+
    "\20\2\24\0\3\2\4\0\15\2\1\115\4\2\24\0"+
    "\3\2\4\0\15\2\1\116\4\2\24\0\3\2\4\0"+
    "\14\2\1\117\5\2\24\0\3\2\4\0\14\2\1\120"+
    "\5\2\24\0\3\2\4\0\10\2\1\121\11\2\24\0"+
    "\3\2\4\0\6\2\1\122\13\2\24\0\3\2\4\0"+
    "\10\2\1\123\11\2\23\0";

  private static int [] zzUnpackTrans() {
    int [] result = new int[2295];
    int offset = 0;
    offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
    return result;
  }

  private static int zzUnpackTrans(String packed, int offset, int [] result) {
    int i = 0;       /* index in packed string  */
    int j = offset;  /* index in unpacked array */
    int l = packed.length();
    while (i < l) {
      int count = packed.charAt(i++);
      int value = packed.charAt(i++);
      value--;
      do result[j++] = value; while (--count > 0);
    }
    return j;
  }


  /* error codes */
  private static final int ZZ_UNKNOWN_ERROR = 0;
  private static final int ZZ_NO_MATCH = 1;
  private static final int ZZ_PUSHBACK_2BIG = 2;

  /* error messages for the codes above */
  private static final String ZZ_ERROR_MSG[] = {
    "Unknown internal scanner error",
    "Error: could not match input",
    "Error: pushback value was too large"
  };

  /**
   * ZZ_ATTRIBUTE[aState] contains the attributes of state aState
   */
  private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();

  private static final String ZZ_ATTRIBUTE_PACKED_0 =
    "\1\0\2\1\1\11\1\1\2\11\11\1\5\11\2\1"+
    "\1\0\2\1\10\11\1\0\12\1\6\11\40\1";

  private static int [] zzUnpackAttribute() {
    int [] result = new int[83];
    int offset = 0;
    offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
    return result;
  }

  private static int zzUnpackAttribute(String packed, int offset, int [] result) {
    int i = 0;       /* index in packed string  */
    int j = offset;  /* index in unpacked array */
    int l = packed.length();
    while (i < l) {
      int count = packed.charAt(i++);
      int value = packed.charAt(i++);
      do result[j++] = value; while (--count > 0);
    }
    return j;
  }

  /** the input device */
  private java.io.Reader zzReader;

  /** the current state of the DFA */
  private int zzState;

  /** the current lexical state */
  private int zzLexicalState = YYINITIAL;

  /** this buffer contains the current text to be matched and is
      the source of the yytext() string */
  private char zzBuffer[] = new char[ZZ_BUFFERSIZE];

  /** the textposition at the last accepting state */
  private int zzMarkedPos;

  /** the current text position in the buffer */
  private int zzCurrentPos;

  /** startRead marks the beginning of the yytext() string in the buffer */
  private int zzStartRead;

  /** endRead marks the last character in the buffer, that has been read
      from input */
  private int zzEndRead;

  /** number of newlines encountered up to the start of the matched text */
  private int yyline;

  /** the number of characters up to the start of the matched text */
  private int yychar;

  /**
   * the number of characters from the last newline up to the start of the 
   * matched text
   */
  private int yycolumn;

  /** 
   * zzAtBOL == true <=> the scanner is currently at the beginning of a line
   */
  private boolean zzAtBOL = true;

  /** zzAtEOF == true <=> the scanner is at the EOF */
  private boolean zzAtEOF;

  /** denotes if the user-EOF-code has already been executed */
  private boolean zzEOFDone;
  
  /** 
   * The number of occupied positions in zzBuffer beyond zzEndRead.
   * When a lead/high surrogate has been read from the input stream
   * into the final zzBuffer position, this will have a value of 1;
   * otherwise, it will have a value of 0.
   */
  private int zzFinalHighSurrogate = 0;

  /* user code: */
  private void error(String message)
  {
    System.out.println("Error at line "+(yyline+1)+", column "+(yycolumn+1)+" : "+message);
  }


  /* CUP2 code: */
  private  ScannerToken token(Terminal terminal, T value) {
    return new ScannerToken(terminal, value, yyline, yycolumn);
  }

  private ScannerToken token(Terminal terminal) {
    return new ScannerToken(terminal, yyline, yycolumn);
  }


  /**
   * Creates a new scanner
   *
   * @param   in  the java.io.Reader to read input from.
   */
  public LexerJFlex(java.io.Reader in) {
    this.zzReader = in;
  }


  /** 
   * Unpacks the compressed character translation table.
   *
   * @param packed   the packed character translation table
   * @return         the unpacked character translation table
   */
  private static char [] zzUnpackCMap(String packed) {
    char [] map = new char[0x110000];
    int i = 0;  /* index in packed string  */
    int j = 0;  /* index in unpacked array */
    while (i < 158) {
      int  count = packed.charAt(i++);
      char value = packed.charAt(i++);
      do map[j++] = value; while (--count > 0);
    }
    return map;
  }


  /**
   * Refills the input buffer.
   *
   * @return      false, iff there was new input.
   * 
   * @exception   java.io.IOException  if any I/O-Error occurs
   */
  private boolean zzRefill() throws java.io.IOException {

    /* first: make room (if you can) */
    if (zzStartRead > 0) {
      zzEndRead += zzFinalHighSurrogate;
      zzFinalHighSurrogate = 0;
      System.arraycopy(zzBuffer, zzStartRead,
                       zzBuffer, 0,
                       zzEndRead-zzStartRead);

      /* translate stored positions */
      zzEndRead-= zzStartRead;
      zzCurrentPos-= zzStartRead;
      zzMarkedPos-= zzStartRead;
      zzStartRead = 0;
    }

    /* is the buffer big enough? */
    if (zzCurrentPos >= zzBuffer.length - zzFinalHighSurrogate) {
      /* if not: blow it up */
      char newBuffer[] = new char[zzBuffer.length*2];
      System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
      zzBuffer = newBuffer;
      zzEndRead += zzFinalHighSurrogate;
      zzFinalHighSurrogate = 0;
    }

    /* fill the buffer with new input */
    int requested = zzBuffer.length - zzEndRead;
    int numRead = zzReader.read(zzBuffer, zzEndRead, requested);

    /* not supposed to occur according to specification of java.io.Reader */
    if (numRead == 0) {
      throw new java.io.IOException("Reader returned 0 characters. See JFlex examples for workaround.");
    }
    if (numRead > 0) {
      zzEndRead += numRead;
      /* If numRead == requested, we might have requested to few chars to
         encode a full Unicode character. We assume that a Reader would
         otherwise never return half characters. */
      if (numRead == requested) {
        if (Character.isHighSurrogate(zzBuffer[zzEndRead - 1])) {
          --zzEndRead;
          zzFinalHighSurrogate = 1;
        }
      }
      /* potentially more input available */
      return false;
    }

    /* numRead < 0 ==> end of stream */
    return true;
  }

    
  /**
   * Closes the input stream.
   */
  public final void yyclose() throws java.io.IOException {
    zzAtEOF = true;            /* indicate end of file */
    zzEndRead = zzStartRead;  /* invalidate buffer    */

    if (zzReader != null)
      zzReader.close();
  }


  /**
   * Resets the scanner to read from a new input stream.
   * Does not close the old reader.
   *
   * All internal variables are reset, the old input stream 
   * cannot be reused (internal buffer is discarded and lost).
   * Lexical state is set to ZZ_INITIAL.
   *
   * Internal scan buffer is resized down to its initial length, if it has grown.
   *
   * @param reader   the new input stream 
   */
  public final void yyreset(java.io.Reader reader) {
    zzReader = reader;
    zzAtBOL  = true;
    zzAtEOF  = false;
    zzEOFDone = false;
    zzEndRead = zzStartRead = 0;
    zzCurrentPos = zzMarkedPos = 0;
    zzFinalHighSurrogate = 0;
    yyline = yychar = yycolumn = 0;
    zzLexicalState = YYINITIAL;
    if (zzBuffer.length > ZZ_BUFFERSIZE)
      zzBuffer = new char[ZZ_BUFFERSIZE];
  }


  /**
   * Returns the current lexical state.
   */
  public final int yystate() {
    return zzLexicalState;
  }


  /**
   * Enters a new lexical state
   *
   * @param newState the new lexical state
   */
  public final void yybegin(int newState) {
    zzLexicalState = newState;
  }


  /**
   * Returns the text matched by the current regular expression.
   */
  public final String yytext() {
    return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
  }


  /**
   * Returns the character at position pos from the 
   * matched text. 
   * 
   * It is equivalent to yytext().charAt(pos), but faster
   *
   * @param pos the position of the character to fetch. 
   *            A value from 0 to yylength()-1.
   *
   * @return the character at position pos
   */
  public final char yycharat(int pos) {
    return zzBuffer[zzStartRead+pos];
  }


  /**
   * Returns the length of the matched text region.
   */
  public final int yylength() {
    return zzMarkedPos-zzStartRead;
  }


  /**
   * Reports an error that occured while scanning.
   *
   * In a wellformed scanner (no or only correct usage of 
   * yypushback(int) and a match-all fallback rule) this method 
   * will only be called with things that "Can't Possibly Happen".
   * If this method is called, something is seriously wrong
   * (e.g. a JFlex bug producing a faulty scanner etc.).
   *
   * Usual syntax/scanner level error handling should be done
   * in error fallback rules.
   *
   * @param   errorCode  the code of the errormessage to display
   */
  private void zzScanError(int errorCode) {
    String message;
    try {
      message = ZZ_ERROR_MSG[errorCode];
    }
    catch (ArrayIndexOutOfBoundsException e) {
      message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
    }

    throw new Error(message);
  } 


  /**
   * Pushes the specified amount of characters back into the input stream.
   *
   * They will be read again by then next call of the scanning method
   *
   * @param number  the number of characters to be read again.
   *                This number must not be greater than yylength()!
   */
  public void yypushback(int number)  {
    if ( number > yylength() )
      zzScanError(ZZ_PUSHBACK_2BIG);

    zzMarkedPos -= number;
  }


  /**
   * Contains user EOF-code, which will be executed exactly once,
   * when the end of file is reached
   */
  private void zzDoEOF() throws java.io.IOException {
    if (!zzEOFDone) {
      zzEOFDone = true;
      yyclose();
    }
  }


  /**
   * Resumes scanning until the next regular expression is matched,
   * the end of input is encountered or an I/O-Error occurs.
   *
   * @return      the next token
   * @exception   java.io.IOException  if any I/O-Error occurs
   */
  public ScannerToken readNextTerminal() throws java.io.IOException {
    int zzInput;
    int zzAction;

    // cached fields:
    int zzCurrentPosL;
    int zzMarkedPosL;
    int zzEndReadL = zzEndRead;
    char [] zzBufferL = zzBuffer;
    char [] zzCMapL = ZZ_CMAP;

    int [] zzTransL = ZZ_TRANS;
    int [] zzRowMapL = ZZ_ROWMAP;
    int [] zzAttrL = ZZ_ATTRIBUTE;

    while (true) {
      zzMarkedPosL = zzMarkedPos;

      boolean zzR = false;
      int zzCh;
      int zzCharCount;
      for (zzCurrentPosL = zzStartRead  ;
           zzCurrentPosL < zzMarkedPosL ;
           zzCurrentPosL += zzCharCount ) {
        zzCh = Character.codePointAt(zzBufferL, zzCurrentPosL, zzMarkedPosL);
        zzCharCount = Character.charCount(zzCh);
        switch (zzCh) {
        case '\u000B':
        case '\u000C':
        case '\u0085':
        case '\u2028':
        case '\u2029':
          yyline++;
          yycolumn = 0;
          zzR = false;
          break;
        case '\r':
          yyline++;
          yycolumn = 0;
          zzR = true;
          break;
        case '\n':
          if (zzR)
            zzR = false;
          else {
            yyline++;
            yycolumn = 0;
          }
          break;
        default:
          zzR = false;
          yycolumn += zzCharCount;
        }
      }

      if (zzR) {
        // peek one character ahead if it is \n (if we have counted one line too much)
        boolean zzPeek;
        if (zzMarkedPosL < zzEndReadL)
          zzPeek = zzBufferL[zzMarkedPosL] == '\n';
        else if (zzAtEOF)
          zzPeek = false;
        else {
          boolean eof = zzRefill();
          zzEndReadL = zzEndRead;
          zzMarkedPosL = zzMarkedPos;
          zzBufferL = zzBuffer;
          if (eof) 
            zzPeek = false;
          else 
            zzPeek = zzBufferL[zzMarkedPosL] == '\n';
        }
        if (zzPeek) yyline--;
      }
      zzAction = -1;

      zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
  
      zzState = ZZ_LEXSTATE[zzLexicalState];

      // set up zzAction for empty match case:
      int zzAttributes = zzAttrL[zzState];
      if ( (zzAttributes & 1) == 1 ) {
        zzAction = zzState;
      }


      zzForAction: {
        while (true) {
    
          if (zzCurrentPosL < zzEndReadL) {
            zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
            zzCurrentPosL += Character.charCount(zzInput);
          }
          else if (zzAtEOF) {
            zzInput = YYEOF;
            break zzForAction;
          }
          else {
            // store back cached positions
            zzCurrentPos  = zzCurrentPosL;
            zzMarkedPos   = zzMarkedPosL;
            boolean eof = zzRefill();
            // get translated positions and possibly new buffer
            zzCurrentPosL  = zzCurrentPos;
            zzMarkedPosL   = zzMarkedPos;
            zzBufferL      = zzBuffer;
            zzEndReadL     = zzEndRead;
            if (eof) {
              zzInput = YYEOF;
              break zzForAction;
            }
            else {
              zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
              zzCurrentPosL += Character.charCount(zzInput);
            }
          }
          int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
          if (zzNext == -1) break zzForAction;
          zzState = zzNext;

          zzAttributes = zzAttrL[zzState];
          if ( (zzAttributes & 1) == 1 ) {
            zzAction = zzState;
            zzMarkedPosL = zzCurrentPosL;
            if ( (zzAttributes & 8) == 8 ) break zzForAction;
          }

        }
      }

      // store back cached position
      zzMarkedPos = zzMarkedPosL;

      if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
        zzAtEOF = true;
            zzDoEOF();
          { return token(SpecialTerminals.EndOfInputStream); }
      }
      else {
        switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
          case 1: 
            { return token(IDENT, yytext());
            }
          case 40: break;
          case 2: 
            { return token(INTCONST, new Integer(Integer.parseInt(yytext())));
            }
          case 41: break;
          case 3: 
            { /* ignore */
            }
          case 42: break;
          case 4: 
            { return token(SEMICOLON);
            }
          case 43: break;
          case 5: 
            { return token(ASSIGN);
            }
          case 44: break;
          case 6: 
            { return token(PLUS);
            }
          case 45: break;
          case 7: 
            { return token(MINUS);
            }
          case 46: break;
          case 8: 
            { return token(MUL);
            }
          case 47: break;
          case 9: 
            { return token(DIV);
            }
          case 48: break;
          case 10: 
            { return token(MOD);
            }
          case 49: break;
          case 11: 
            { return token(LT);
            }
          case 50: break;
          case 12: 
            { return token(GT);
            }
          case 51: break;
          case 13: 
            { return token(AND);
            }
          case 52: break;
          case 14: 
            { return token(OR);
            }
          case 53: break;
          case 15: 
            { return token(LPAREN);
            }
          case 54: break;
          case 16: 
            { return token(RPAREN);
            }
          case 55: break;
          case 17: 
            { return token(LBRACK);
            }
          case 56: break;
          case 18: 
            { return token(RBRACK);
            }
          case 57: break;
          case 19: 
            { return token(LBRACE);
            }
          case 58: break;
          case 20: 
            { return token(RBRACE);
            }
          case 59: break;
          case 21: 
            { return token(COMMA);
            }
          case 60: break;
          case 22: 
            { return token(COLON);
            }
          case 61: break;
          case 23: 
            { return token(IF);
            }
          case 62: break;
          case 24: 
            { return token(EQ);
            }
          case 63: break;
          case 25: 
            { return token(LTE);
            }
          case 64: break;
          case 26: 
            { return token(GTE);
            }
          case 65: break;
          case 27: 
            { return token(NEQ);
            }
          case 66: break;
          case 28: 
            { return token(ANDAND);
            }
          case 67: break;
          case 29: 
            { return token(OROR);
            }
          case 68: break;
          case 30: 
            { return token(INT);
            }
          case 69: break;
          case 31: 
            { return token(FOR);
            }
          case 70: break;
          case 32: 
            { return token(CHAR);
            }
          case 71: break;
          case 33: 
            { return token(ELSE);
            }
          case 72: break;
          case 34: 
            { return token(GOTO);
            }
          case 73: break;
          case 35: 
            { return token(BREAK);
            }
          case 74: break;
          case 36: 
            { return token(RETURN);
            }
          case 75: break;
          case 37: 
            { return token(RECORD);
            }
          case 76: break;
          case 38: 
            { return token(CONTINUE);
            }
          case 77: break;
          case 39: 
            { return token(PROCEDURE);
            }
          case 78: break;
          default:
            zzScanError(ZZ_NO_MATCH);
        }
      }
    }
  }


}
		
}
      
    
	    

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dif.LexicalAnalyser;

import edu.tum.cup2.grammar.SpecialTerminals;
import edu.tum.cup2.scanner.Scanner;
import edu.tum.cup2.scanner.ScannerToken;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 *
 * @author soheildif
 */
public class LexicalAnalyser {
    
    public static Scanner getScanner(String inputFile) throws FileNotFoundException {    
        
        Scanner scanner = new LexerJFlex(new FileReader(inputFile)); 
        
        return scanner;
    }
    
    public static void testScanner(String inputFile) throws FileNotFoundException, IOException {
    
        Scanner scanner = new LexerJFlex(new FileReader(inputFile)); 
                       
        //Reading from JFlex Scanner (Lexical Analyser) for testing input tokens
        ScannerToken s;
        do {
          s = scanner.readNextTerminal();
          System.out.println("token: " + s);
        } while (!s.getSymbol().equals(SpecialTerminals.EndOfInputStream));      
        
    }
    
}
		
}
#include "iostream"
#include 
#include 
#include 
#include 

using namespace std;


struct Edge{

	int to;

	int w;

	Edge(int node, int weight) : to(node), w(weight) {}
};

typedef vector Vertex;

typedef Vertex* Graph;

class Disjoint_Set {

	int n;

	int *s;

public:
	Disjoint_Set(int size) {

		n = size;
		s = new int[n];

		make_set(n);
	}

	void make_set(int n) {

		s = new int[n];

		for(int i=0; i j  ? s[find(j)] = find(i) : s[find(i)] = find(j);

	}

	int find(int i) {

		int temp = i;

		while(s[i] != i) 
			i = s[i];

		//!!!! nakh keshi !!!!!// bedune nakh keshi order mishe O(nlogn) vali ba nakh keshi order mishe O(n); bedune nakhkeshi TLE (time limit error) khordam az judge uva
		while(s[temp] != i) {

			int z = s[temp];

			s[temp] = i;

			temp = z;

		}

		return i;
	}

	bool has_Same_Set(int i, int j) {
	
		return find(i) == find(j);
	}
};

class Tree {

private :

	Disjoint_Set dset;

public:

	Graph G;

	int size;

	int weight;

	int edges;

	Tree(int n) : dset(n) {

		size = n;

		G = new Vertex[n];

		edges = weight = 0;
	}

	void add(int i, int j, int w) {
	
		if(dset.has_Same_Set(i, j) == false) {

			G[i].push_back(Edge(j,w));

			dset.merge(i, j);

			weight += w;

			edges++;

			//cout<< i<< " and "<< j<< "had added, they have not cyle"<< endl;

		}
		//	else cout<< i<< " and "<< j<< "had not add because they have cyle"<< endl;
	}

	void print_edges() {
		
		for(int i=0; i::iterator it=G[i].begin(); it!=G[i].end(); it++)
				cout<< i<< "==>"<< (*it).to<< " w : "<< (*it).w<< endl;
	}

};


Graph make_your_graph(int n){

	Graph G = new Vertex[n];

	G[0].push_back(Edge(1, 5));
	G[0].push_back(Edge(5, 6));
	G[0].push_back(Edge(4, 7));

	G[1].push_back(Edge(5, 5));
	G[1].push_back(Edge(2, 5));
	G[1].push_back(Edge(6, 4));

	G[2].push_back(Edge(6, 3));
	G[2].push_back(Edge(3,3));

	G[3].push_back(Edge(6, 1));
	G[3].push_back(Edge(5, 3));
	G[3].push_back(Edge(4, 2));

	G[4].push_back(Edge(5, 2));

	G[5].push_back(Edge(6, 2));

	for(int i=0; i::iterator it=G[i].begin(); it!=G[i].end(); it++) {
			if( (*it).to > i) {
				G[(*it).to].push_back(Edge(i, (*it).w));
			}
		}
	}

	return G;
}

class comparatro
{
public:
	bool operator() (const pair & lp, const pair&rp) const {
		return lp.second.w > rp.second.w;
	}
};

void make_set(int n);
void merge(int i, int j);
int find(int i);
bool has_Same_Set(int i, int j);
Tree Kruskal(Graph G, int n);
Tree Prime(Graph G, int n);

int main(){

	//int n = 7;

	//Graph G = make_your_graph(n);

	//Tree MST = Kruskal(G, n);

	//MST.print_edges();
	//cout<< "Total Weight "<<  MST.weight<< endl;

	//system("pause");

#ifdef _DEBUG
	freopen("testI.txt", "r", stdin);
	freopen("testO.txt", "w", stdout);
#endif

	int n,m;

	while(true) {

		scanf("%d %d", &n, &m);
		if(n==0 && m==0)
			break;

		Graph G = new Vertex[n];

		int i, j, w;

		int totalW = 0;

		for(int k=0; k, vector >, comparatro> pq;

	for(int i=0; i::iterator it=G[i].begin(); it!=G[i].end(); it++)
			pq.push(pair(i, *it));

	while(tree.edges != n-1) {
		pair p = pq.top();
		tree.add(p.first, p.second.to, p.second.w);
		pq.pop();
	}

	return tree;
}