Five minute introduction to ANTLR For Delphi Target
Five minute introduction to ANTLR For Delphi Target
Submitted by sharpplus on Wednesday, July 23, 2008 - 16:10
1. Get ANTLR For Delphi Target 3.1
After registering , You can get a download link of Antlr For Delphi Target.Download and Copy the files to some folder such as D:\antlr\310\lib, add all the jar to your classpath.
set classpath=D:\antlr\310\lib\stringtemplate-3.2.jar;D:\antlr\310\lib\antlr-runtime-3.1.jar;D:\antlr\310\lib\antlr-3.1.jar;D:\antlr\310\lib\antlr-2.7.7.jar
2. Create a simple grammar
grammar T;
options {
language=Delphi;
k=2;
}
prog : method ;
method
scope {
String name;
}
: 'method' ID '(' ')' {$method::name:=$ID.text;} body
;
body: '{' stat* '}'
;
stat: ID '=' expr ';'
| method // allow nested methods to demo stack nature of dynamic attributes
;
expr: mul ('+' mul)*
;
mul : atom ('*' atom)*
;
/** Demonstrate that 'name' is a dynamically-scoped attribute defined
* within rule method. With lexical-scoping (variables go away at
* the end of the '}'), you'd have to pass the current method name
* down through all rules as a parameter. Ick. This is much much better.
*/
atom: ID {Writeln('ref '+$ID.text+' from method '+$method::name);}
| INT {Writeln('int '+$INT.text+' in method '+$method::name);}
;
ID : ('a'..'z'|'A'..'Z')+ ;
INT : '0'..'9'+ ;
WS : (' '|'\t'|'\n'|'\r')+ {$channel:=HIDDEN;}
;
The following table list the difference between Delphi , Java Grammar.
Delphi
Java
Comment
options {
language=Delphi;
k=2;
}
options {
k=2;
}
language option tell antlr to generate Delphi Source for gramar
$channel:=HIDDEN;
$channel=HIDDEN;
Delphi Assign expression is ‘:=’, Java is ‘=’
3 Run ANTLR For Delphi Target on the simple grammar
under command line input following command
>>java org.antlr.Tool *.g
ANTLR will generate source files for the lexer and parser (e.g. TLexer.pas and TParser.pas).
4.Create a console project named as Scope, and write a function to call the generated parser and lexer
7. Some minor difference between Java and Delphi target which is not include in above example
7.1 Container library
Java uses the default JDK Container library .
Delphi does not has a complete hash, set, list library in VCL, so we use the JCL Container library (you can download them from http://jcl.sourceforge.net which is MPL license).
7.2 embed user defined function to generated Delphi class.
unlike the java , in Delphi you need define the interface and implement par of class separately .For example , to add a function to java class, you could write it as