Debian Codegraph @

doc/python-runtime.html

raw symbols SCIP
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
2 <html>
3 <head>
4 <title>Notes for using the ANTLR Python Code Generator</title>
5 </head>
6 <body bgcolor="#FFFFFF">
7 <h1><strong>Python Code Generator for ANTLR 2.7.7</strong></h1>
8 <p>As of ANTLR 2.7.5, you can generate your Lexers,
9 Parsers and TreeParsers in Python. This feature extends the benefits of
10 ANTLR's predicated-LL(k) parsing technology to the Python language and
11 platform.</p>
12 <p>To be able to build and use the Python language Lexers, Parsers and
13 TreeParsers, you will need to have the ANTLR Python runtime library
14 installed in your Python path. The Python runtime model is based on the
15 existing runtime model for <a href="runtime.html">Java</a> and is thus
16 immediately familiar. The Python runtime and the Java runtime are very
17 similar although there a number of subtle (and not so subtle)
18 differences. Some of these result from differences in the respective
19 runtime environments.</p>
20 <p>ANTLR Python support was contributed (and is to be maintained) by
21 Wolfgang Haefelinger and Marq Kole.</p>
22 <h2><a name="#building">Building the ANTLR Python Runtime</a></h2>
23 <p>The ANTLR Python runtime source and build files are completely
24 integrated in the ANTLR build process.The ANTLR runtime support module
25 for Python is located in the <b><code>lib/python</code></b> subdirectory
26 of the ANTLR distribution. Installation of the Python runtime support
27 is enabled automatically if Python can be found on your system by the
28 <tt>configure</tt> script.</p>
29 <p>With Python support enabled the current distribution will look for
30 the presence of a python executable of version 2.2 or higher. If it has
31 found such a beast, it will generate and install the ANTLR Python
32 runtime as part of the overall ANTLR building and installation
33 process.</p>
34 <p>If the python distribution you are using is at an unusual location,
35 perhaps because you are using a local installation instead of a
36 system-wide one, you can provide the location of that python executable
37 using the <tt>--with-python=&lt;path&gt;</tt> option for the configure
38 script, for instance:</p>
39 <blockquote>
40 <pre>
41 ./configure --with-python=$HOME/bin/python2.3
42 </pre>
43 </blockquote>
44 <p>Also, if the python executable is at a regular location, but has a
45 name that differs from &quot;python&quot;, you can specify the correct
46 name through the <tt>--with-python=&lt;path&gt;</tt>, as shown above, or through
47 environment variable <tt>$PYTHON</tt></p>
48 <blockquote>
49 <pre>
50 PYTHON=python2.3
51 export PYTHON
52 ./configure
53 </pre>
54 </blockquote>
55 <p>All the example grammars for the ANTLR Python runtime are built when
56 ANTLR itself is built. They can be run in one go by running <tt>make
57 test</tt> in the same directory where you ran the configure script in
58 the ANTLR distribution. So after you've run <tt>configure</tt> you can
59 do:</p>
60 <blockquote>
61 <pre>
62 # Build ANTLR and all examples
63 make
64 # Run them
65 make test
66 # Install everything
67 make install
68 </pre>
69 </blockquote>
70
71 <p>Note that <tt>make install</tt> will not add the ANTLR Python
72 runtime (i.e. antlr.py) to your Python installation but rather install
73 antlr.py in <tt>${prefix}/lib</tt>. To be able to use antlr.py you
74 would need to adjust Python's <tt>sys.path<tt>.</p>
75
76 <p>However, there a script is provided that let's you easily add antlr.py
77 as module to your Python installation. After installation just run</p>
78 <blockquote>
79 <pre>
80 ${prefix}/sbin/pyantlr.sh install
81 </pre>
82 </blockquote>
83 <p>Note that usually you need to be superuser in order to succeed. Also
84 note that you can run this command later at any time again, for
85 example, if you have a second Python installation etc. Just make sure
86 that <tt>python</tt> is in your $PATH when running pyantlr.sh.</p>
87
88 <p>Note further that you can also do this to install ANTLR Python
89 runtime immediatly after having called <tt>./configure</tt>:</p>
90 <blockquote>
91 <pre>
92 scripts/pyantlr.sh install
93 </pre>
94 </blockquote>
95
96 <h2><a name="#codegen">Specifying Code Generation</a></h2>
97 <p>You can instruct ANTLR to generate your Lexers, Parsers and
98 TreeParsers using the Python code generator by adding the following
99 entry to the global options section at the beginning of your grammar
100 file.</p>
101 <blockquote>
102 <pre>
103 {
104 language="Python";
105 }
106 </pre>
107 </blockquote>
108 <p>After that things are pretty much the same as in the default
109 <b>java</b> code generation mode. See the examples in
110 <code>examples/python</code> for some illustrations.</p>
111 <p>One particular issue that is worth mentioning is the handling of
112 comments in ANTLR Python. Java, C++, and C# all use the same lexical
113 structures to define comments: <code>//</code> for single-line
114 comments, and <code>/* ... */</code> for block comments. Unfortunately,
115 Python does not handle comments this way. It only knows about
116 single-line comments, and these start off with a <code>#</code>
117 symbol.</p>
118 <p>Normally, all comments outside of actions are actually comments in
119 the ANTLR input language. These comments, and that is both block
120 comments and single-line comments are translated into Python
121 single-line comments.</p>
122 <p>Secondly, all comments inside actions should be comments in the
123 target language, Python in this case. Unfortunately, if the actions
124 contain ANTLR actions, such as <code>$getText</code>, the code
125 generator seems to choke on Python comments as the <code>#</code> sign
126 is also used in tree construction. The solution is to use Java/C++-style
127 comments in all actions; these will be translated into Python comments
128 by the ANTLR as it checks these actions for the presence of predefined
129 action symbols such as <code>$getText</code>.</p>
130 <p>So, as a general issue: all comments in an ANTLR grammar for the
131 Python target should be in Java/C++ style, not in Python style.</p>
132 <h2><a name="#sections">Python-Specific ANTLR Sections</a></h2>
133 <ul>
134 <li>
135 <b>header - specify additional <code>import</code> directives</b>
136 <p>You can instruct the ANTLR Python code generator to import
137 additional Python packages in your generated
138 Lexer/Parser/TreeParser by adding code to the header section which
139 must be the first section at the beginning of your ANTLR grammar
140 file, apart from any other header sections.</p>
141 <blockquote>
142 <pre>
143 header {
144 import os, sys
145 }
146 </pre>
147 </blockquote>
148 </li>
149 <li>
150 <b>header "__init__" - specify additional code in the
151 <code>__init__</code> method</b>
152 <p>You can instruct the ANTLR Python code generator to include
153 additional Python code in your generated Lexer/Parser/TreeParser by
154 adding code to the <code>init</code> header section which must
155 be the first section at the beginning of your ANTLR grammar file,
156 apart from any other header sections. The code in the header is
157 appended to the end of the <code>__init__</code> method.</p>
158 <blockquote>
159 <pre>
160 header "__init__" {
161 self.message = "This is the default message"
162 }
163 </pre>
164 </blockquote>
165 <p>If your grammar file contains both a Lexer and a Parser (or any
166 other multiple of definitions), the code in the
167 <code>__init__</code> header will be reproduced in the
168 <code>__init__</code> methods of all of these definitions without
169 change. If you really want to update only one of the definitions,
170 for instance, the <code>__init__</code> method of the Lexer class
171 you are creating, use</p>
172 <blockquote>
173 <pre>
174 header "&lt;LexerGrammar&gt;.__init__" {
175 self.message = "This is the default message"
176 }
177 </pre>
178 </blockquote>
179 <p>where <tt>&lt;LexerGrammar&gt;</tt> is the name of the Lexer
180 grammar. The same construction also works with the Parsers and
181 TreeParsers, of course.</p>
182 <p>In the case both a generic init header and a grammar-specific
183 header are present, the grammar-specific one will override the
184 generic one.</p>
185 </li>
186 <li>
187 <b>header "__main__" - specify additional code after the class
188 definition</b>
189 <p>You can instruct the ANTLR Python code generator to add
190 additional Python code at the end of your generated
191 Lexer/Parser/TreeParser, so after the class definition itself by
192 adding code to the <code>__main__</code> header section which must
193 be the first section at the beginning of your ANTLR grammar file,
194 apart from any other header sections.</p>
195 <blockquote>
196 <pre>
197 header "__main__" {
198 print "You cannot execute this file!"
199 }
200 </pre>
201 </blockquote>
202 <p>If your grammar file contains both a Lexer and a Parser (or any
203 other multiple of definitions), the code in the <code>__main__</code>
204 header will be reproduced at the end of all of the generated class
205 definitions. If you really want to add code after only one of the
206 definitions, for instance, after the Lexer class, use</p>
207 <blockquote>
208 <pre>
209 header "&lt;LexerGrammar&gt;.__main__" {
210 print "You cannot execute this file!"
211 }
212 </pre>
213 </blockquote>
214 <p>where <tt>&lt;LexerGrammar&gt;</tt> is the name of the Lexer
215 grammar. The same construction also works with the Parsers and
216 TreeParsers, of course.</p>
217 <p>In the case both a generic init header and a grammar-specific
218 header are present, the grammar-specific one will override the
219 generic one. If no <code>__main__</code> headers are present and the
220 grammar is for a Lexer, automated test code for that lexer is
221 automatically added at the end of the generated module. This can be
222 prevented by providing an empty <code>__main__</code> header. In the
223 latter case it is good practise to provide a comment explaining why
224 an empty header is present.</p>
225 <blockquote>
226 <pre>
227 header "&lt;LexerGrammar&gt;.__main__" {
228 // Empty main header to prevent automatic test code from being added
229 // to the generated lexer module.
230 }
231 </pre>
232 </blockquote>
233 <p>This automated test code can be executed by running Python with
234 the generated lexer file (<tt>&lt;LexerGrammar&gt;.py</tt>where
235 <tt>&lt;LexerGrammar&gt;</tt> is the name of the Lexer grammar) and
236 providing some test input on <tt>stdin</tt>:</p>
237 <blockquote>
238 <pre>
239 python &lt;LexerGrammar&gt;.py &lt; test.in
240 </pre>
241 </blockquote>
242 </li>
243 </ul>
244 <h2><a name="#options">Python-Specific ANTLR Options</a></h2>
245 <ul>
246 <li>
247 <b>className - change the default name of the generated class</b>
248 <p></p>
249 <blockquote>
250 <pre>
251 options {
252 className="Scanner";
253 }
254 </pre>
255 </blockquote>
256 <p>If you are using the <tt>className</tt> option conjunction with the
257 Python specific header options, there will be no collisions. The
258 <tt>className</tt> option changes the class name, while the
259 <code>main</code> headers require the use of the grammar name which
260 will become the module name after code generation.</p>
261 <blockquote>
262 <pre>
263 header "ParrotSketch.init" {
264 self.state = JohnCleese.select("dead", "pushing up daisies", \
265 "no longer", "in Parrot Heaven")
266 print "This parrot is", self.state
267 }
268
269 class ParrotSketch extends Lexer;
270
271 options {
272 className="Scanner";
273 }
274 </pre>
275 </blockquote>
276 </li>
277 </ul>
278 <h2><a name="#template">A Template Python ANTLR Grammar File</a></h2>
279 <p>As the handling of modules &emdash; packages in Java speak &emdash;
280 in Python differs from that in Java, the current approach in ANTLR to
281 call both the file and the class they contain after the name of the
282 grammar is kind of awkward. Instead, a different approach is chosen that
283 better reflects the handling of modules in Python. The name of the
284 generated Python file is still derived from the name of the grammar, but
285 the name of the class is fixed to the particular kind of grammar. A
286 lexer grammar will be used to generate a class <tt>Lexer</tt>; a parser
287 grammar will be used to generate a class <tt>Parser</tt>; and a
288 treeparser grammar will be used to generate a class <tt>Walker</tt>.</p>
289 <blockquote>
290 <pre>
291 header {
292 // gets inserted in the Python source file before any generated
293 // declarations
294 ...
295 }
296 header "__init__" {
297 // gets inserted in the __init__ method of each of the generated Python
298 // classes
299 ...
300 }
301 header "MyParser.__init__" {
302 // gets inserted in the __init__ method of the generated Python class
303 // for the MyParser grammar
304 ...
305 }
306 header "__main__" {
307 // gets inserted at the end of each of the generated Python files in an
308 // indented section preceeded by the conditional:
309 // if __name__ == "__main__":
310 ...
311 }
312 header "MyLexer.__init__" {
313 // gets inserted at the end of the generated Python file for the MyLexer
314 // grammar in an indented section preceeded by the conditional:
315 // if __name__ == "__main__":
316 // and preventing the insertion of automatic test code in the same place.
317 ...
318 }
319 options {
320 language = "Python";
321 }
322 {
323 // global code stuff that will be included in the 'MyParser.py' source
324 // file just before the 'Parser' class below
325 ...
326 }
327 class MyParser extends Parser;
328 options {
329 exportVocab=My;
330 }
331 {
332 // additional methods and members for the generated 'Parser' class
333 ...
334 }
335 ... generated RULES go here ...
336 {
337 // global code stuff that will be included in the 'MyLexer' source file
338 // just before the 'Lexer' class below
339 ...
340 }
341 class MyLexer extends Lexer;
342 options {
343 exportVocab=My;
344 }
345 {
346 // additional methods and members for the generated 'Lexer' class
347 ...
348 }
349 ... generated RULES go here ...
350 {
351 // global code stuff that will be included in the 'MyTreeParser' source
352 // file just before the 'Walker' class below
353 ...
354 }
355 class MyTreeParser extends TreeParser;
356 options {
357 exportVocab=My;
358 }
359 {
360 // additional methods and members for the generated 'Walker' class
361 ...
362 }
363 ... generated RULES go here ...
364 </pre>
365 <p>Version number in parentheses shows the tool version used to
366 develop and test. It may work with older versions as well. Python 2.2
367 or better is required as some recent Python features (like
368 <tt>super()</tt> for example) are being used.</p>
369 <h2><a name="#notes">More notes on using ANTLR Python</a></h2>
370 <ul>
371 <li>
372 <p>The API of the generated lexers, parsers, and treeparsers is
373 supposed to be similar to the Java ones. However, calling a lexer
374 is somewhat simplified:</p>
375 <blockquote>
376 <pre>
377 ### class "calcLexer extends Lexer" will generate python
378 ### module "calcLexer" with class "Lexer".
379 import calcLexer
380 ### read from stdin ..
381 L = calcLexer.Lexer()
382 ### read from file "test.in" ..
383 L = calcLexer.Lexer("test.in")
384 ### open a file and read from it ..
385 f = file("test.in", "r")
386 L = calcLexer.Lexer(f)
387 ### this works of course as well
388 import sys
389 L = calcLexer.Lexer(sys.stdin)
390 ### use a shared input state
391 L1 = calcLexer.Lexer(...)
392 state = L1.inputState
393 L2 = calcLexer.Lexer(state)
394 </pre>
395 </blockquote>
396 </li>
397 <li>
398 <p>The loop for the lexer to retrieve token by token can be written
399 as:</p>
400 <blockquote>
401 <pre>
402 lexer = calcLexer.Lexer() ### create a lexer for calculator
403 for token in lexer:
404 ## do something with token
405 print token
406 </pre>
407 </blockquote>
408 or even:
409 <blockquote>
410 <pre>
411 for token in calcLexer.Lexer(): ### create a lexer for calculator
412 ## do something with token
413 print token
414 </pre>
415 </blockquote>
416 <p>As an iterator is available for all <tt>TokenStreams</tt>, you
417 can apply the same technique with a <tt>TokenStreamSelector</tt>.</p>
418 </li>
419 <li>
420 <p>However, writing this particular lexer loop is rarely necessary as it
421 is generated by default in each generated lexer. Just run:</p>
422 <blockquote>
423 <pre>
424 python calcLexer.py &lt; calc.in
425 </pre>
426 </blockquote>
427 to test the generated lexer.<br>
428 </li>
429 <li>
430 <p>Symbolic token number, table of literals bitsets and bitset data
431 functions are generated on file (module) scope instead of class
432 scope. For example:</p>
433 <blockquote>
434 <pre>
435 import calcLexer # import calc lexer module
436
437 calcLexer.EOF_TYPE # prints 1
438 calcLexer.literals # { ';': 11, 'end': 12, 'begin': 10 }
439 </pre>
440 </blockquote>
441 </li>
442 <li>
443 <p>Comments in action should be in Java/C++ formats, ie. <tt>//</tt>
444 and <tt>/* ... */</tt> are valid comments. However, make sure
445 that you put a comment before or after a statement, but not
446 within. For example, this will not work:</p>
447 <blockquote>
448 <pre>
449 x = /* one */ 1
450 </pre>
451 </blockquote>
452 <p>The reason is that Python only supports single-line comments. Such
453 a Python comment skips everything till end-of-line. Therefore in
454 the translation of the comment a newline will be introduced on
455 reaching <tt>*/</tt>. The code above would result in the following
456 Python code in the generated file:</p>
457 <blockquote>
458 <pre>
459 x = # one
460 1
461 </pre>
462 </blockquote>
463 <p>which is probably not what you want.</p>
464 </li>
465 <li>The Lexer actions <tt>$newline</tt>, <tt>$nl</tt> and
466 <tt>$skip</tt> have been introduced as language independent
467 shortcuts for calling <tt>self.newline()</tt> (<tt>$newline</tt>,
468 <tt>$nl</tt>) and <tt>_ttype = SKIP</tt> (<tt>$skip</tt>).<br>
469 </li>
470 <li>
471 <p>In Python arguments to function and method calls do not have a
472 declared type. Also, functionns and methdos do not have to declare
473 a return type. If you want to pass a value to a rule in your grammar,
474 you can do so by providing simply the name of a variable.</p>
475 <blockquote>
476 <pre>
477 ident [symtable]
478 : ( 'a'..'z' | '0'..'9' )+
479 ;
480 </pre>
481 </blockquote>
482 <p>Similarly, is you want a rule to pass a return value, you do not
483 have to provide a type either. It is possible to provide a default
484 value.</p>
485 <blockquote>
486 <pre>
487 sign returns [isPos = False]
488 : '-' { /* default value is OK */ }
489 | '+' { isPos = True }
490 ;
491 </pre>
492 </blockquote>
493 </li>
494 <li>
495 <p>The <tt>__init__</tt> method of the generated Lexer, Parser, or
496 TreeParser has the following heading:</p>
497 <blockquote>
498 <pre>
499 def __init__(self, *args, **kwargs):
500 ...
501 </pre>
502 </blockquote>
503 <p>So if you need to pass special arguments to your generated class,
504 you can use the <tt>**kwargs</tt> to check for a particular keyword
505 argument, irrespective of any non-keyword arguments that you did
506 provide. So if you have a <tt>TokenStreamSelector</tt> that you want
507 to access locally, you can pass it to the Lexer in the following
508 call:</p>
509 <blockquote>
510 <pre>
511 MySpecialLexer.Lexer(sys.stdin, selector=TokenStreamSelector())
512 </pre>
513 </blockquote>
514 <p>while in the <tt>__init__</tt> header of this particular grammar
515 you can specify the handling of the <tt>selector</tt> keyword
516 argument in the following way:</p>
517 <blockquote>
518 <pre>
519 header "MyParser.__init__" {
520 self.selector = None
521 if kwargs.has_key("selector"):
522 self.selector = kwargs["selector"]
523 assert(isinstance(self.selector, TokenStreamSelector))
524
525 }
526 </pre>
527 </blockquote>
528 </li>
529 <li>
530 <p>Because of limitations in the lexer of the ANTLR compiler
531 generator itself, you cannot use single quoted strings of more than
532 one character in your Python code.<br>
533 So if you use a Python string like <tt>'wink, wink, nudge,
534 nudge'</tt> in one of your actions, ANTLR will give a parse error
535 when you try to compile this grammar. Instead you should use double
536 quotes: <tt>"wink, wink, nudge, nudge"</tt>.</p>
537 </li>
538 <li>
539 <p>Unicode is supported but it's easy to run into errors if your
540 terminal(output device) is not able to handle unicode chars.<br>
541 Here are some rules when using Unicode input:</p>
542 <ol>
543 <li>
544 You need to wrap your input stream by a stream reader which
545 translates bytes into unicode chars. This requires usually
546 knowledge about your input's encoding. Assume for example
547 that your input is 'latin1', you would do this:
548 <blockquote>
549 <pre>
550 ### replace stdin with a wrapper that spits out
551 ### unicode chars.
552 sys.stdin = codecs.lookup('latin1')[-2](sys.stdin)
553 </pre>
554 </blockquote>
555 Here reading from stdin gets wrapped.
556 </li>
557 <li>
558 When printing tokens etc containing Unicode chars it appears
559 to be best to translate explicit to a unicode string before
560 printing. Consider:
561 <blockquote>
562 <pre>
563 for token in unicode_l.Lexer() :
564 print unicode(token) ## explict cast
565 </pre>
566 </blockquote>
567 This explicit cast appears to be a bug in Python found during
568 development (discussion still in progress).
569 </li>
570 </ol>
571 </li>
572 </ul>
573 </blockquote>
574 </body>
575 </html>