teaching machines

CS 330 Lecture 9 – Grammars

February 12, 2016 by . Filed under cs330, lectures, spring 2016.

Agenda

TODO

Note

We discuss today the pipeline that our source code goes through on its way to becoming an executable. Whether its compiled or interpreted directly, the first step is getting our tools to understand the source. We’ll have a look at how a grammar for a language can be used to automatically generate a lexer and a parser for our own custom languages.

Code

Boo.g

grammar Boo;

expression
  : LITERAL
  | LEFT_PARENTHESIS expression RIGHT_PARENTHESIS
  | IDENTIFIER
  | NOT expression
  | expression XOR expression
  | expression AND expression
  | expression OR expression
  ;

fragment TRUE: 'true';
fragment FALSE: 'false';
LITERAL: TRUE | FALSE;

LEFT_PARENTHESIS: '(';
RIGHT_PARENTHESIS: ')';

AND: '&&';
OR: '||';
NOT: '!';
XOR: '^';

IDENTIFIER: [a-zA-Z]+;

WHITESPACE: [ \t\n\r]+ -> skip;

Interpreter.java

/usr/lib/ruby/2.7.0/rubygems/dependency.rb:311:in `to_specs': Could not find 'coderay' (>= 0) among 56 total gem(s) (Gem::MissingSpecError)
Checked in 'GEM_PATH=/.gem/ruby/2.7.0:/var/lib/gems/2.7.0:/usr/lib/ruby/gems/2.7.0:/usr/share/rubygems-integration/2.7.0:/usr/share/rubygems-integration/all:/usr/lib/x86_64-linux-gnu/rubygems-integration/2.7.0:/home/johnch/.gems', execute `gem env` for more information
	from /usr/lib/ruby/2.7.0/rubygems/dependency.rb:323:in `to_spec'
	from /usr/lib/ruby/2.7.0/rubygems/core_ext/kernel_gem.rb:62:in `gem'
	from ./coderay:24:in `
'

makefile

Note to copy and pasters: makefile rules need to be indented with real tabs, not spaces.

ANTLR_JAR = antlr-4.5.2-complete.jar

Interpreter.class: BooLexer.java BooParser.java Interpreter.java

BooLexer.java BooParser.java: Boo.g
  java -cp ${ANTLR_JAR} org.antlr.v4.Tool Boo.g

%.class: %.java
  javac -cp ${ANTLR_JAR}:. $<

clean:
  rm -rf *.class BooLexer.java BooParser.java BooBaseListener.java BooListener.java *.tokens