Compiler Construction with ANTLR and Java
Gary L. Schaps

Example 1: 
//  This is the start rule for the parser.
compilationUnit
    :   // A pattern file consists of language elements,
        //  possibly intermixed with import directives
        (( importDirective ) | ( languageElement ))*
        EOF
	;

Example 2:
// ... parse the file ...
public static void parseFile(InputStream s, String fname) 
    throws Exception {  
    try {
        // Create a scanner that reads from the input stream
        KPLLexer lexer = new KPLLexer(s);
        // Create a parser that reads from the scanner
        KPLParser parser = new KPLParser(lexer);
        parser.setCurrentFile(fname);
        // start parsing at the compilationUnit rule
        parser.compilationUnit();
        ...

Example 3: 
// import directive
importDirective
// init-action
{File f=null; String str=null;}
// rule
:    "import" str=fileName
    // semantic actions
    {
        f = new File(str);  KPLLexer lexer = null;
        lexer = new KPLLexer(new FileInputStream(f));
        parser = new KPLParser(lexer);
        //  this file's either another pattern file ...
        if (str.substring(str.length()-4).equals(".kpl")) { 
            parser.compilationUnit();
        }else{
            // ... or else it's a test program program ...
            parser.testProgram();
        }
    }
;

Example 4: 
// cycle names
cycleNames

// init-action 
{CycleNames cycleN = null; int startLine=LT(1).getLine();}
// rule
:   "CYCLE_NAMES" ASSIGN LCURLY 
    {cycleN = new CycleNames();}
    // rest of rule
    cycleSet[cycleN] (COMMA cycleSet[cycleN])* RCURLY SEMI 
    // semantic action
    {
        try{
            PBIBuilder.registerCycleNames(cycleN);
        }catch (IllegalStateException ex){
            PBIBuilder.foundBadCode();
            System.err.println("Error: line(" + (startLine) +  
             "), " + ex.getMessage());
        }
    }
;


Example 5: 
try {
    DataOutputStream out = new DataOutputStream(
      new FileOutputStream(
      patFile.substring(0, patFile.length() - 3) + "pbi"));
    // generate code
    PBIWriter writer = new PBIWriter();
    writer.generateCode(out);
} catch(IOException ex) {
      ...
}


Example 6:
/** convert big endian integer to little endian format  */
 public static int toInt(int v) {
     int littleInt = (v & 0xFF) << 24;        // LSB -> MSB
     littleInt |= (v & 0xFF00) << 8;          // LSB + 1 -> LSB + 2
     littleInt |= ((v & 0xFF0000) >>> 8);     // LSB + 2 -> LSB + 1
     littleInt |= ((v & 0xFF000000) >>> 24);  // MSB -> LSB

     return(littleInt);
 }


Example 7: 

{PBIBuilder.getPMode(PG) == 1}? ( lvmVector[pat] )*
{pat.analyzeLVMFormats();}
|
( pgInstruction[pat] )*






3


