teaching machines

CS 330 Lecture 6 – Lexing, parsing, and translating

February 3, 2012 by . Filed under cs330, lectures, spring 2012.

Agenda

Code

SLOWGO.g

grammar SLOWGO;

@members {
  private int x = 0;
  private int y = 0;
  private int theta = 0;
  private boolean isDrawing = false;
}

program
@init {
  System.out.println("axis equal");
  System.out.println("hold on");
}
  : command+
  ;

command
  : ROTATE NUMBER NEWLINE
    {
      theta = (theta + Integer.parseInt($NUMBER.text)) \% 360;
    }
  | FORWARD NUMBER NEWLINE
    {
      System.out.printf("plot([x1 x2], [y1 y2])\%n");
    }
  | DRAW state NEWLINE
    {
      
    }
  ;

state returns [boolean isOn]
  : ON
    {
      isOn = true;
    }
  | OFF
    {
      isOn = false;
    }
  ;

NUMBER
  : '-'? ('0'..'9')+
  ;

ROTATE
  : 'rotate'
  ;

FORWARD
  : 'forward'
  ;

ON
  : 'on'
  ;

OFF
  : 'off'
  ;

DRAW
  : 'draw'
  ;

WHITESPACE
  : (' ' | '\t') {skip();}
  ;

NEWLINE
  : '\r'? '\n'
  ;

SLOWGOInterpreter.java

import java.io.IOException;
import org.antlr.runtime.*;

public class SLOWGOInterpreter {
  public static void main(String[] args) throws IOException, RecognitionException {
    ANTLRInputStream in = new ANTLRInputStream(System.in);
    SLOWGOLexer lexer = new SLOWGOLexer(in);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    SLOWGOParser parser = new SLOWGOParser(tokens);
    parser.program();
  }
}

Haiku

paralogo.sb