CS 330 Lecture 7 – Finishing SLOWGO, a first Makefile, and a calculator
February 6, 2012 by Chris Johnson. Filed under cs330, lectures, spring 2012.
Agenda
- smart compilation with Make
- add drawing in to SLOWGO
Code
makefile
ANTLRWORKS = $(HOME)/bin/antlrworks-1.4.3.jar
SLOWGOInterpreter.class: SLOWGOInterpreter.java SLOWGOLexer.class SLOWGOParser.class
javac -cp $(ANTLRWORKS):. SLOWGOInterpreter.java
SLOWGOLexer.class: SLOWGOLexer.java
javac -cp $(ANTLRWORKS) SLOWGOLexer.java
SLOWGOParser.class: SLOWGOParser.java
javac -cp $(ANTLRWORKS) SLOWGOParser.java
SLOWGOLexer.java SLOWGOParser.java: SLOWGO.g
java -cp $(ANTLRWORKS) org.antlr.Tool SLOWGO.g
clean:
rm -f *.class
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
{
int distance = Integer.parseInt($NUMBER.text);
int oldX = x;
int oldY = y;
x += (int) (Math.cos(Math.toRadians(theta)) * distance);
y += (int) (Math.sin(Math.toRadians(theta)) * distance);
if (isDrawing) {
System.out.printf("plot([\%d \%d], [\%d \%d])\%n", oldX, x, oldY, y);
}
}
| DRAW state NEWLINE
{
isDrawing = $state.isOn;
}
;
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'
;
Haiku
This rule changed my life:
prog -> stat* EOF
{ print "Thanks for your code. :)" }
show