PageRenderTime 47ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Dependencies/boo/lib/antlr-2.7.5/doc/runtime.html

https://github.com/w4x/boolangstudio
HTML | 1235 lines | 1201 code | 34 blank | 0 comment | 0 complexity | c22ad16a634f09209d75967a566f3e13 MD5 | raw file
Possible License(s): GPL-2.0
  1. <html>
  2. <head>
  3. <title>ANTLR Specification: Run-time</title>
  4. </head>
  5. <body bgcolor="#FFFFFF" text="#000000">
  6. <h1><a name="_bb1">Java Runtime Model</a></h1>
  7. <hr>
  8. <h2><a name="_bb2">Programmer's Interface</a></h2>
  9. <p>
  10. In this section, we describe what ANTLR generates after reading your grammar file and how to use that output to parse input. The classes from which your lexer, token, and parser classes are derived are provided as well.
  11. </p>
  12. <h3><a name="_bb3">What ANTLR generates</a></h3>
  13. <p>
  14. ANTLR generates the following types of files, where <i>MyParser</i>, <i>MyLexer</i>, and <i>MyTreeParser</i> are names of grammar classes specified in the grammar file. You may have an arbitrary number of parsers, lexers, and tree-parsers per grammar file; a separate class file will be generated for each. In addition, token type files will be generated containing the token vocabularies used in the parsers and lexers. One or more token vocabularies may be defined in a grammar file, and shared between different grammars. For example, given the grammar file: <tt>
  15. </p>
  16. <pre>class MyParser extends Parser;
  17. options {
  18. exportVocab=My;
  19. }
  20. ... rules ...
  21. class MyLexer extends Lexer;
  22. options {
  23. exportVocab=My;
  24. }
  25. ... rules ...
  26. class MyTreeParser extends TreeParser;
  27. options {
  28. exportVocab=My;
  29. }
  30. ... rules ...</tt></pre>
  31. <p>
  32. The following files will be generated:
  33. <ul>
  34. <li>
  35. <tt><i>MyParser</i>.java</tt>. The parser with member methods for the parser rules.
  36. </li>
  37. <li>
  38. <tt><i>MyLexer</i>.java</tt>. The lexer with the member methods for the lexical rules.
  39. </li>
  40. <li>
  41. <tt><i>MyTreeParser</i>.java</tt>. The tree-parser with the member methods for the tree-parser rules.
  42. </li>
  43. <li>
  44. <tt><i>My</i>TokenTypes.java</tt>. An interface containing all of the token types defined by your parsers and lexers using the exported vocabulary named <tt>My</tt>.
  45. </li>
  46. <li>
  47. <tt><i>My</i>TokenTypes.txt</tt>. A text file containing all of the token types, literals, and paraphrases defined by parsers and lexers contributing vocabulary <tt>My</tt>.
  48. </li>
  49. </ul>
  50. <p>
  51. The programmer uses the classes by referring to them:
  52. <ol>
  53. <li>
  54. Create a lexical analyzer. The constructor with no arguments implies that you want to read from standard input.
  55. </li>
  56. <li>
  57. Create a parser and attach it to the lexer (or other TokenStream).
  58. </li>
  59. <li>
  60. Call one of the methods in the parser to begin parsing.
  61. </li>
  62. </ol>
  63. <p>
  64. If your parser generates an AST, then get the AST value, create a tree-parser, and invoke one of the tree-parser rules using the AST.
  65. </p>
  66. <tt><pre>MyLexer lex = new MyLexer();
  67. MyParser p =
  68. new MyParser(lex,<i>user-defined-args-if-any</i>);
  69. p.<i>start-rule</i>();
  70. // and, if you are tree parsing the result...
  71. MyTreeParser tp = new MyTreeParser();
  72. tp.<i>start-rule</i>(p.getAST());</tt></pre>
  73. <p>
  74. You can also specify the name of the token and/or AST objects that you want the lexer/parser to create. Java's support of dynamic programming makes this quite painless:
  75. </p>
  76. <pre><tt>MyLexer lex = new MyLexer();
  77. lex.setTokenObjectClass(&quot;mypackage.MyToken&quot;);
  78. // defaults to &quot;antlr.CommonToken&quot;
  79. ...
  80. parser.setASTNodeClass(&quot;mypackage.MyASTNode&quot;);
  81. // defaults to &quot;antlr.CommonAST&quot;</tt></pre>
  82. <p>
  83. Make sure you give a fully-qualified class name.
  84. <p>
  85. The lexer and parser can cause IOExceptions as well as RecognitionExceptions, which you must catch:
  86. </p>
  87. <pre> CalcLexer lexer =
  88. new CalcLexer(new DataInputStream(System.in));
  89. CalcParser parser = new CalcParser(lexer);
  90. // Parse the input expression
  91. try {
  92. parser.expr();
  93. }
  94. catch (IOException io) {
  95. System.err.println(&quot;IOException&quot;);
  96. }
  97. catch(RecognitionException e) {
  98. System.err.println(&quot;exception: &quot;+e);
  99. }</pre> <h3><a name="sharingstate">Multiple Lexers/Parsers With Shared Input State</a></h3>
  100. <p>
  101. Occasionally, you will want two parsers or two lexers to share input state; that is, you will want them to pull input from the same source token stream or character stream. &nbsp; The section on <a href="streams.html#lexerstates">multiple lexer &quot;states&quot;</a> describes such a situation.
  102. </p>
  103. <p>
  104. ANTLR factors the input variables such as line number, guessing state, input stream, etc... into a separate object so that another lexer or parser could same that state.&nbsp; The <small><font face="Courier New">LexerSharedInputState</font></small> and <small><font face="Courier New">ParserSharedInputState</font></small> embody this factoring. &nbsp; Method <small><font face="Courier New">getInputState()</font></small> can be used on either <small><font face="Courier New">CharScanner</font></small> or <small><font face="Courier New">Parser</font></small> objects.&nbsp; Here is how to construct two lexers sharing the same input stream:
  105. </p>
  106. <pre><small>// create Java lexer</small>
  107. <small>JavaLexer mainLexer = new JavaLexer(input);
  108. // create javadoc lexer; attach to shared</small>
  109. <small>// input state of java lexer
  110. JavaDocLexer doclexer =</small>
  111. <small> new JavaDocLexer(mainLexer.getInputState());</small></pre>
  112. <p>
  113. Parsers with shared input state can be created similarly:
  114. </p>
  115. <pre><small>JavaDocParser jdocparser =</small>
  116. <small> new JavaDocParser(getInputState());
  117. jdocparser.content(); // go parse the comment</small></pre>
  118. <p>
  119. Sharing state is easy, but what happens upon exception during the execution of the &quot;subparser&quot;?&nbsp; What about syntactic predicate execution?&nbsp; It turns out that invoking a subparser with the same input state is exactly the same as calling another rule in the same parser as far as error handling and syntactic predicate guessing are concerned.&nbsp; If the parser is guessing before the call to the subparser, the subparser must continue guessing, right?&nbsp; Exceptions thrown inside the subparser must exit the subparser and return to enclosing erro handler or syntactic predicate handler.
  120. </p>
  121. <h2><a name="_bb4">Parser Implementation</a></h2> <h3><a name="_bb5">Parser Class</a></h3>
  122. <p>
  123. ANTLR generates a parser class (an extension of <tt>LLkParser</tt>) that contains a method for every rule in your grammar. The general format looks like: <tt>
  124. </p>
  125. <pre>
  126. public class MyParser extends LLkParser
  127. implements MyLexerTokenTypes
  128. {
  129. protected P(TokenBuffer tokenBuf, int k) {
  130. super(tokenBuf,k);
  131. tokenNames = _tokenNames;
  132. }
  133. public P(TokenBuffer tokenBuf) {
  134. this(tokenBuf,1);
  135. }
  136. protected P(TokenStream lexer, int k) {
  137. super(lexer,k);
  138. tokenNames = _tokenNames;
  139. }
  140. public P(TokenStream lexer) {
  141. this(lexer,1);
  142. }
  143. public P(ParserSharedInputState state) {
  144. super(state,1);
  145. tokenNames = _tokenNames;
  146. }
  147. ...
  148. // add your own constructors here...
  149. <i>rule-definitions</i>
  150. }
  151. </tt> </pre> <h3><a name="_bb6">Parser Methods</a></h3>
  152. <p>
  153. ANTLR generates recursive-descent parsers, therefore, every rule in the grammar will result in a method that applies the specified grammatical structure to the input token stream. The general form of a parser method looks like: <tt>
  154. </p>
  155. <pre>
  156. public void rule()
  157. throws RecognitionException,
  158. TokenStreamException
  159. {
  160. <i>init-action-if-present</i>
  161. if ( <i>lookahead-predicts-production-1</i> ) {
  162. <i>code-to-match-production-1</i>
  163. }
  164. else if ( <i>lookahead-predicts-production-2</i> ) {
  165. <i>code-to-match-production-2</i>
  166. }
  167. ...
  168. else if ( <i>lookahead-predicts-production-n</i> ) {
  169. <i>code-to-match-production-n</i>
  170. }
  171. else {
  172. // syntax error
  173. throw new NoViableAltException(LT(1));
  174. }
  175. }
  176. </tt> This code results from a rule of the form: <tt></pre> <pre>
  177. rule: <i>production-1</i>
  178. | <i>production-2</i>
  179. ...
  180. | <i>production-n</i>
  181. ;
  182. </tt> </pre>
  183. <p>
  184. If you have specified arguments and a return type for the rule, the method header changes to: <tt>
  185. </p>
  186. <pre>
  187. /* generated from:
  188. * rule(<i>user-defined-args</i>)
  189. * returns <i>return-type</i> : ... ;
  190. */
  191. public <i>return-type</i> rule(<i>user-defined-args</i>)
  192. throws RecognitionException,
  193. TokenStreamException
  194. {
  195. ...
  196. }
  197. </tt> </pre>
  198. <p>
  199. Token types are integers and we make heavy use of bit sets and range comparisons to avoid excessively-long test expressions.
  200. </p>
  201. <h3><a name="_bb7">EBNF Subrules</a></h3>
  202. <p>
  203. Subrules are like unlabeled rules, consequently, the code generated for an EBNF subrule mirrors that generated for a rule. The only difference is induced by the EBNF subrule operators that imply optionality or looping.
  204. </p>
  205. <p>
  206. <b><tt>(...)?</tt> optional subrule</b>. The only difference between the code generated for an optional subrule and a rule is that there is no default <tt>else</tt>-clause to throw an exception--the recognition continues on having ignored the optional subrule. <tt>
  207. </p>
  208. <pre>
  209. {
  210. <i>init-action-if-present</i>
  211. if ( <i>lookahead-predicts-production-1</i> ) {
  212. <i>code-to-match-production-1</i>
  213. }
  214. else if ( <i>lookahead-predicts-production-2</i> ) {
  215. <i>code-to-match-production-2</i>
  216. }
  217. ...
  218. else if ( <i>lookahead-predicts-production-n</i> ) {
  219. <i>code-to-match-production-n</i>
  220. }
  221. }
  222. </tt> </pre>
  223. <p>
  224. Not testing the optional paths of optional blocks has the potential to delay the detection of syntax errors.
  225. </p>
  226. <p>
  227. <b><tt>(...)*</tt> closure subrule</b>. A closure subrule is like an optional looping subrule, therefore, we wrap the code for a simple subrule in a &quot;forever&quot; loop that exits whenever the lookahead is not consistent with any of the alternative productions. <tt>
  228. </p>
  229. <pre>
  230. {
  231. <i>init-action-if-present</i>
  232. loop:
  233. do {
  234. if ( <i>lookahead-predicts-production-1</i> ) {
  235. <i>code-to-match-production-1</i>
  236. }
  237. else if ( <i>lookahead-predicts-production-2</i> ) {
  238. <i>code-to-match-production-2</i>
  239. }
  240. ...
  241. else if ( <i>lookahead-predicts-production-n</i> ) {
  242. <i>code-to-match-production-n</i>
  243. }
  244. else {
  245. break loop;
  246. }
  247. }
  248. while (true);
  249. }
  250. </tt> </pre>
  251. <p>
  252. While there is no need to explicity test the lookahead for consistency with the exit path, the grammar analysis phase computes the lookahead of what follows the block. The lookahead of what follows much be disjoint from the lookahead of each alternative otherwise the loop will not know when to terminate. For example, consider the following subrule that is nondeterministic upon token <tt>A</tt>. <tt>
  253. </p>
  254. <pre>
  255. ( A | B )* A
  256. </tt> </pre>
  257. <p>
  258. Upon <tt>A</tt>, should the loop continue or exit? One must also ask if the loop should even begin. Because you cannot answer these questions with only one symbol of lookahead, the decision is non-LL(1).
  259. </p>
  260. <p>
  261. Not testing the exit paths of closure loops has the potential to delay the detection of syntax errors.
  262. </p>
  263. <p>
  264. As a special case, a closure subrule with one alternative production results in: <tt>
  265. </p>
  266. <pre>
  267. {
  268. <i>init-action-if-present</i>
  269. loop:
  270. while ( <i>lookahead-predicts-production-1</i> ) {
  271. <i>code-to-match-production-1</i>
  272. }
  273. }
  274. </tt> </pre>
  275. <p>
  276. This special case results in smaller, faster, and more readable code.
  277. </p>
  278. <p>
  279. <b><tt>(...)+</tt> positive closure subrule</b>. A positive closure subrule is a loop around a series of production prediction tests like a closure subrule. However, we must guarantee that at least one iteration of the loop is done before proceeding to the construct beyond the subrule.
  280. </p>
  281. <tt><pre>
  282. {
  283. int _cnt = 0;
  284. <i>init-action-if-present</i>
  285. loop:
  286. do {
  287. if ( <i>lookahead-predicts-production-1</i> ) {
  288. <i>code-to-match-production-1</i>
  289. }
  290. else if ( <i>lookahead-predicts-production-2</i> ) {
  291. <i>code-to-match-production-2</i>
  292. }
  293. ...
  294. else if ( <i>lookahead-predicts-production-n</i> ) {
  295. <i>code-to-match-production-n</i>
  296. }
  297. else if ( _cnt&gt;1 ) {
  298. // lookahead predicted nothing and we've
  299. // done an iteration
  300. break loop;
  301. }
  302. else {
  303. throw new NoViableAltException(LT(1));
  304. }
  305. _cnt++; // track times through the loop
  306. }
  307. while (true);
  308. }
  309. </tt> </pre>
  310. <p>
  311. While there is no need to explicity test the lookahead for consistency with the exit path, the grammar analysis phase computes the lookahead of what follows the block. The lookahead of what follows much be disjoint from the lookahead of each alternative otherwise the loop will not know when to terminate. For example, consider the following subrule that is nondeterministic upon token <tt>A</tt>. <tt>
  312. </p>
  313. <pre>
  314. ( A | B )+ A
  315. </tt> </pre>
  316. <p>
  317. Upon <tt>A</tt>, should the loop continue or exit? Because you cannot answer this with only one symbol of lookahead, the decision is non-LL(1).
  318. </p>
  319. <p>
  320. Not testing the exit paths of closure loops has the potential to delay the detection of syntax errors.
  321. </p>
  322. <p>
  323. You might ask why we do not have a <tt>while</tt> loop that tests to see if the lookahead is consistent with any of the alternatives (rather than having series of tests inside the loop with a <tt>break</tt>). It turns out that we can generate smaller code for a series of tests than one big one. Moreover, the individual tests must be done anyway to distinguish between alternatives so a <tt>while</tt> condition would be redundant.
  324. </p>
  325. <p>
  326. As a special case, if there is only one alternative, the following is generated: <tt>
  327. </p>
  328. <pre>
  329. {
  330. <i>init-action-if-present</i>
  331. do {
  332. <i>code-to-match-production-1</i>
  333. }
  334. while ( <i>lookahead-predicts-production-1</i> );
  335. }
  336. </tt> </pre>
  337. <p>
  338. <b>Optimization.</b> When there are a large (where large is user-definable) number of strictly LL(1) prediction alternatives, then a <tt>switch</tt>-statement can be used rather than a sequence of <tt>if</tt>-statements. The non-LL(1) cases are handled by generating the usual <tt>if</tt>-statements in the <tt>default</tt> case. For example: <tt>
  339. </p>
  340. <pre>
  341. switch ( LA(1) ) {
  342. case KEY_WHILE :
  343. case KEY_IF :
  344. case KEY_DO :
  345. statement();
  346. break;
  347. case KEY_INT :
  348. case KEY_FLOAT :
  349. declaration();
  350. break;
  351. default :
  352. // do whatever else-clause is appropriate
  353. }
  354. </tt> </pre>
  355. <p>
  356. This optimization relies on the compiler building a more direct jump (via jump table or hash table) to the ith production matching code. This is also more readable and faster than a series of bit set membership tests.
  357. </p>
  358. <h3><a name="_bb8">Production Prediction</a> </h3>
  359. <p>
  360. <b>LL(1) prediction.</b> Any LL(1) prediction test is a simple set membership test. If the set is a singleton set (a set with only one element), then an integer token type <tt>==</tt> comparison is done. If the set degree is greater than one, a bit set is created and the single input token type is tested for membership against that set. For example, consider the following rule: <tt>
  361. </p>
  362. <pre>
  363. a : A | b ;
  364. b : B | C | D | E | F;
  365. </tt> </pre>
  366. <p>
  367. The lookahead that predicts production one is {<tt>A</tt>} and the lookahead that predicts production two is {<tt>B,C,D,E,F</tt>}. The following code would be generated by ANTLR for rule <tt>a</tt> (slightly cleaned up for clarity):
  368. </p>
  369. <tt><pre>
  370. public void a() {
  371. if ( LA(1)==A ) {
  372. match(A);
  373. }
  374. else if (token_set1.member(LA(1))) {
  375. b();
  376. }
  377. }
  378. </tt> </pre>
  379. <p>
  380. The prediction for the first production can be done with a simple integer comparison, but the second alternative uses a bit set membership test for speed, which you probably didn't recognize as testing <tt>LA(1) member {B,C,D,E,F}</tt>. The complexity threshold above which bitset-tests are generated is user-definable.
  381. </p>
  382. <p>
  383. We use arrays of <tt>long int</tt>s (64 bits) to hold bit sets. The ith element of a bitset is stored in the word number <tt>i/64</tt> and the bit position within that word is <tt>i % 64</tt>. The divide and modulo operations are extremely expensive and, but fortunately, a strength reduction can be done. Dividing by a power of two is the same as shifting right and modulo a power of two is the same as masking with that power minus one. All of these details are hidden inside the implementation of the <tt>BitSet</tt> class in the package <tt>antlr.collections.impl</tt>.
  384. </p>
  385. <p>
  386. The various bit sets needed by ANTLR are created and initialized in the generated parser (or lexer) class.
  387. </p>
  388. <p>
  389. <b>Approximate LL(k) prediction.</b> An extension of LL(1)...basically we do a series of up to k bit set tests rather than a single as we do in LL(1) prediction. Each decision will use a different amount of lookahead, with LL(1) being the dominant decision type.
  390. </p>
  391. <h3><a name="_bb9"></a><a name="Production Element Recognition">Production Element Recognition</a> </h3>
  392. <p>
  393. <b>Token references.</b> Token references are translated to: <tt>
  394. </p>
  395. <pre>
  396. match(<i>token-type</i>);
  397. </tt> </pre>
  398. <p>
  399. For example, a reference to token <tt>KEY_BEGIN</tt> results in: <tt>
  400. </p>
  401. <pre>
  402. match(KEY_BEGIN);
  403. </tt> </pre>
  404. <p>
  405. where <tt>KEY_BEGIN</tt> will be an integer constant defined in the <tt><i>MyParser</i>TokenType</tt> interface generated by ANTLR.
  406. </p>
  407. <p>
  408. <b>String literal references.</b> String literal references are references to automatically generated tokens to which ANTLR automatically assigns a token type (one for each unique string). String references are translated to:
  409. </p>
  410. <tt><pre>
  411. match(<i>T</i>);
  412. </tt> </pre>
  413. <p>
  414. where <tt><i>T</i></tt> is the token type assigned by ANTLR to that token.
  415. </p>
  416. <p>
  417. <b>Character literal references.</b> Referencing a character literal implies that the current rule is a lexical rule. Single characters, '<i>t</i>', are translated to:
  418. </p>
  419. <tt><pre>
  420. match('<i>t</i>');
  421. </tt> </pre>
  422. <p>
  423. which can be manually inlined with: <tt>
  424. </p>
  425. <pre>
  426. if ( c=='<i>t</i>' ) consume();
  427. else throw new MismatchedCharException(
  428. &quot;mismatched char: '&quot;+(char)c+&quot;'&quot;);
  429. </tt> </pre>
  430. <p>
  431. if the method call proves slow (at the cost of space).
  432. </p>
  433. <p>
  434. <b>Wildcard references.</b> In lexical rules, the wildcard is translated to: <tt>
  435. </p>
  436. <pre>
  437. consume();
  438. </tt> </pre>
  439. <p>
  440. which simply gets the next character of input without doing a test.
  441. </p>
  442. <p>
  443. References to the wildcard in a parser rule results in the same thing except that the <tt>consume</tt> call will be with respect to the parser.
  444. </p>
  445. <p>
  446. <b>Not operator.</b> When operating on a token, <tt>~<i>T</i></tt> is translated to:
  447. </p>
  448. <tt><pre>
  449. matchNot(<i>T</i>);
  450. </tt> </pre>
  451. <p>
  452. When operating on a character literal, <tt>'<i>t</i>'</tt> is translated to: <tt>
  453. </p>
  454. <pre>
  455. matchNot('<i>t</i>');
  456. </tt> </pre>
  457. <p>
  458. <b>Range operator.</b> In parser rules, the range operator (<tt><i>T1</i>..<i>T2</i></tt>) is translated to: <tt>
  459. </p>
  460. <pre>
  461. matchRange(<i>T1</i>,<i>T2</i>);
  462. </tt> </pre>
  463. <p>
  464. In a lexical rule, the range operator for characters <tt><i>c1..c2</i></tt> is translated to: <tt>
  465. </p>
  466. <pre>
  467. matchRange(<i>c1</i>,<i>c2</i>);
  468. </tt> </pre>
  469. <p>
  470. <b>Labels.</b> Element labels on atom references become <tt>Token</tt> references in parser rules and <tt>int</tt>s in lexical rules. For example, the parser rule: <tt>
  471. </p>
  472. <pre>
  473. a : id:ID {System.out.println(&quot;id is &quot;+id);} ;
  474. </tt> would be translated to: <tt></pre> <pre>
  475. public void a() {
  476. Token id = null;
  477. id = LT(1);
  478. match(ID);
  479. System.out.println(&quot;id is &quot;+id);
  480. }
  481. </tt> For lexical rules such as: <tt></pre> <pre>
  482. ID : w:. {System.out.println(&quot;w is &quot;+(char)w);};
  483. </tt> the following code would result: <tt></pre> <pre>
  484. public void ID() {
  485. int w = 0;
  486. w = c;
  487. consume(); // match wildcard (anything)
  488. System.out.println(&quot;w is &quot;+(char)w);
  489. }
  490. </tt> </pre>
  491. <p>
  492. Labels on rule references result in <tt>AST</tt> references, when generating trees, of the form <tt><i>label</i>_ast</tt>.
  493. </p>
  494. <p>
  495. <b>Rule references.</b> Rule references become method calls. Arguments to rules become arguments to the invoked methods. Return values are assigned like Java assignments. Consider rule reference <tt>i=list[1]</tt> to rule: <tt>
  496. </p>
  497. <pre>
  498. list[int scope] returns int
  499. : { return scope+3; }
  500. ;
  501. </tt> The rule reference would be translated to: <tt></pre> <pre>
  502. i = list(1);
  503. </tt> </pre>
  504. <p>
  505. <b>Semantic actions.</b> Actions are translated verbatim to the output parser or lexer except for the <a href="trees.html#Action Translation">translations required for AST generation</a> and the following:
  506. <ul>
  507. <li><tt>$FOLLOW(r)</tt>: FOLLOW set name for rule r
  508. <li><tt>$FIRST(r)</tt>: FIRST set name for rule r
  509. </ul>
  510. <p>
  511. Omitting the rule argument implies you mean the current rule. The result type is a BitSet, which you can test via $FIRST(a).member(LBRACK) etc...
  512. <p>
  513. Here is a sample rule:
  514. <pre>
  515. a : A {System.out.println($FIRST(a));} B
  516. exception
  517. catch [RecognitionException e] {
  518. if ( $FOLLOW.member(SEMICOLON) ) {
  519. consumeUntil(SEMICOLON);
  520. }
  521. else {
  522. consume();
  523. }
  524. }
  525. ;
  526. </pre>
  527. Results in
  528. <pre>
  529. public final void a() throws RecognitionException, TokenStreamException {
  530. try {
  531. match(A);
  532. System.out.println(_tokenSet_0);
  533. match(B);
  534. }
  535. catch (RecognitionException e) {
  536. if ( _tokenSet_1.member(SEMICOLON) ) {
  537. consumeUntil(SEMICOLON);
  538. }
  539. else {
  540. consume();
  541. }
  542. }
  543. }
  544. </pre>
  545. <p>
  546. To add members to a lexer or parser class definition, add the class member definitions enclosed in {} immediately following the class specification, for example: <tt>
  547. </p>
  548. <pre>
  549. class MyParser;
  550. {
  551. protected int i;
  552. public MyParser(TokenStream lexer,
  553. int aUsefulArgument) {
  554. i = aUsefulArgument;
  555. }
  556. }
  557. ... rules ...
  558. </tt></pre>
  559. <p>
  560. ANTLR collects everything inside the {...} and inserts it in the class definition before the rule-method definitions. When generating C++, this may have to be extended to allow actions after the rules due to the wacky ordering restrictions of C++.
  561. </p>
  562. <h3><a name="_bb10">Standard Classes</a></h3>
  563. <p>
  564. ANTLR constructs parser classes that are subclasses of the <tt>antlr.LLkParser</tt> class, which is a subclass of the <tt>antlr.Parser</tt> class. We summarize the more important members of these classes here. See Parser.java and LLkParser.java for details of the implementation. <tt>
  565. </p>
  566. <pre>
  567. public abstract class Parser {
  568. protected ParserSharedInputState inputState;
  569. protected ASTFactory ASTFactory;
  570. public abstract int LA(int i);
  571. public abstract Token LT(int i);
  572. public abstract void consume();
  573. public void consumeUntil(BitSet set) { ... }
  574. public void consumeUntil(int tokenType) { ... }
  575. public void match(int t)
  576. throws MismatchedTokenException { ... }
  577. public void matchNot(int t)
  578. throws MismatchedTokenException { ... }
  579. ...
  580. }
  581. public class LLkParser extends Parser {
  582. public LLkParser(TokenBuffer tokenBuf, int k_)
  583. { ... }
  584. public LLkParser(TokenStream lexer, int k_)
  585. { ... }
  586. public int LA(int i) { return input.LA(i); }
  587. public Token LT(int i) { return input.LT(i); }
  588. public void consume() { input.consume(); }
  589. ...
  590. }
  591. </pre> </tt><h2><a name="_bb11">Lexer Implementation</a></h2> <h3><a name="_bb12">Lexer Form</a></h3>
  592. <p>
  593. The lexers produced by ANTLR are a lot like the parsers produced by ANTLR. They only major differences are that (a) scanners use characters instead of tokens, and (b) ANTLR generates a special <tt>nextToken</tt> rule for each scanner which is a production containing each public lexer rule as an alternate. The name of the lexical grammar class provided by the programmer results in a subclass of <tt>CharScanner</tt>, for example <tt>
  594. </p>
  595. <pre>
  596. public class MyLexer extends antlr.CharScanner
  597. implements LTokenTypes, TokenStream
  598. {
  599. public L(InputStream in) {
  600. this(new ByteBuffer(in));
  601. }
  602. public L(Reader in) {
  603. this(new CharBuffer(in));
  604. }
  605. public L(InputBuffer ib) {
  606. this(new LexerSharedInputState(ib));
  607. }
  608. public L(LexerSharedInputState state) {
  609. super(state);
  610. caseSensitiveLiterals = true;
  611. setCaseSensitive(true);
  612. literals = new Hashtable();
  613. }
  614. public Token nextToken() throws TokenStreamException {
  615. <i>scanning logic</i>
  616. ...
  617. }
  618. <i>recursive and other non-inlined lexical methods</i>
  619. ...
  620. }
  621. </tt> </pre>
  622. <p>
  623. When an ANTLR-generated parser needs another token from its lexer, it calls a method called <tt>nextToken</tt>. The general form of the <tt>nextToken</tt> method is: <tt>
  624. </p>
  625. <pre>
  626. public Token nextToken()
  627. throws TokenStreamException {
  628. int tt;
  629. for (;;) {
  630. try {
  631. resetText();
  632. switch ( c ) {
  633. <i>case for each char predicting lexical rule</i>
  634. <i>call lexical rule gets token type -&gt;</i> tt
  635. default :
  636. throw new NoViableAltForCharException(
  637. &quot;bad char: '&quot;+(char)c+&quot;'&quot;);
  638. }
  639. if ( tt!=Token.SKIP ) {
  640. return makeToken(tt);
  641. }
  642. }
  643. catch (RecognitionException ex) {
  644. reportError(ex.toString());
  645. }
  646. }
  647. }
  648. </tt> </pre>
  649. <p>
  650. For example, the lexical rules: <tt>
  651. </p>
  652. <pre>
  653. lexclass Lex;
  654. WS : ('\t' | '\r' | ' ') {_ttype=Token.SKIP;} ;
  655. PLUS : '+';
  656. MINUS: '-';
  657. INT : ( '0'..'9' )+ ;
  658. ID : ( 'a'..'z' )+ ;
  659. UID : ( 'A'..'Z' )+ ;
  660. </tt> would result in something like: <tt></pre> <pre>
  661. public class Lex extends CharScanner
  662. implements TTokenTypes {
  663. ...
  664. public Token nextToken()
  665. throws TokenStreamException {
  666. int _tt = Token.EOF_TYPE;
  667. for (;;) {
  668. try {
  669. resetText();
  670. switch ( _c ) {
  671. case '\t': case '\r': case ' ':
  672. _tt=mWS();
  673. break;
  674. case '+':
  675. _tt=mPLUS();
  676. break;
  677. case '-':
  678. _tt=mMINUS();
  679. break;
  680. case '0': case '1': case '2': case '3':
  681. case '4': case '5': case '6': case '7':
  682. case '8': case '9':
  683. _tt=mINT();
  684. break;
  685. case 'a': case 'b': case 'c': case 'd':
  686. case 'e': case 'f': case 'g': case 'h':
  687. case 'i': case 'j': case 'k': case 'l':
  688. case 'm': case 'n': case 'o': case 'p':
  689. case 'q': case 'r': case 's': case 't':
  690. case 'u': case 'v': case 'w': case 'x':
  691. case 'y': case 'z':
  692. _tt=mID();
  693. break;
  694. case 'A': case 'B': case 'C': case 'D':
  695. case 'E': case 'F': case 'G': case 'H':
  696. case 'I': case 'J': case 'K': case 'L':
  697. case 'M': case 'N': case 'O': case 'P':
  698. case 'Q': case 'R': case 'S': case 'T':
  699. case 'U': case 'V': case 'W': case 'X':
  700. case 'Y': case 'Z':
  701. _tt=mUID();
  702. break;
  703. case EOF_CHAR :
  704. _tt = Token.EOF_TYPE;
  705. break;
  706. default :
  707. throw new NoViableAltForCharException(
  708. &quot;invalid char &quot;+_c);
  709. }
  710. if ( _tt!=Token.SKIP ) {
  711. return makeToken(_tt);
  712. }
  713. } // try
  714. catch (RecognitionException ex) {
  715. reportError(ex.toString());
  716. }
  717. } // for
  718. }
  719. public int mWS()
  720. throws RecognitionException,
  721. CharStreamException,
  722. TokenStreamException {
  723. int _ttype = WS;
  724. switch ( _c) {
  725. case '\t':
  726. match('\t');
  727. break;
  728. case '\r':
  729. match('\r');
  730. break;
  731. case ' ':
  732. match(' ');
  733. break;
  734. default :
  735. {
  736. throw new NoViableAltForException(
  737. &quot;no viable for char: &quot;+(char)_c);
  738. }
  739. }
  740. _ttype = Token.SKIP;
  741. return _ttype;
  742. }
  743. public int mPLUS()
  744. throws RecognitionException,
  745. CharStreamException,
  746. TokenStreamException {
  747. int _ttype = PLUS;
  748. match('+');
  749. return _ttype;
  750. }
  751. public int mMINUS()
  752. throws RecognitionException,
  753. CharStreamException,
  754. TokenStreamException {
  755. int _ttype = MINUS;
  756. match('-');
  757. return _ttype;
  758. }
  759. public int mINT()
  760. throws RecognitionException,
  761. CharStreamException,
  762. TokenStreamException {
  763. int _ttype = INT;
  764. {
  765. int _cnt=0;
  766. _loop:
  767. do {
  768. if ( _c&gt;='0' &amp;&amp; _c&lt;='9')
  769. { matchRange('0','9'); }
  770. else
  771. if ( _cnt&gt;=1 ) break _loop;
  772. else {
  773. throw new ScannerException(
  774. &quot;no viable alternative for char: &quot;+
  775. (char)_c);
  776. }
  777. _cnt++;
  778. } while (true);
  779. }
  780. return _ttype;
  781. }
  782. public int mID()
  783. throws RecognitionException,
  784. CharStreamException,
  785. TokenStreamException {
  786. int _ttype = ID;
  787. {
  788. int _cnt=0;
  789. _loop:
  790. do {
  791. if ( _c&gt;='a' &amp;&amp; _c&lt;='z')
  792. { matchRange('a','z'); }
  793. else
  794. if ( _cnt&gt;=1 ) break _loop;
  795. else {
  796. throw new NoViableAltForCharException(
  797. &quot;no viable alternative for char: &quot;+
  798. (char)_c);
  799. }
  800. _cnt++;
  801. } while (true);
  802. }
  803. return _ttype;
  804. }
  805. public int mUID()
  806. throws RecognitionException,
  807. CharStreamException,
  808. TokenStreamException {
  809. int _ttype = UID;
  810. {
  811. int _cnt=0;
  812. _loop:
  813. do {
  814. if ( _c&gt;='A' &amp;&amp; _c&lt;='Z')
  815. { matchRange('A','Z'); }
  816. else
  817. if ( _cnt&gt;=1 ) break _loop;
  818. else {
  819. throw new NoViableAltForCharException(
  820. &quot;no viable alternative for char: &quot;+
  821. (char)_c);
  822. }
  823. _cnt++;
  824. } while (true);
  825. }
  826. return _ttype;
  827. }
  828. }
  829. </tt> </pre>
  830. <p>
  831. ANTLR-generated lexers assume that you will be reading streams of characters. If this is not the case, you must create your own lexer.
  832. </p>
  833. <h3><a name="_bb13">Creating Your Own Lexer</a></h3>
  834. <p>
  835. To create your own lexer, your Java class that will doing the lexing must implement interface <tt>TokenStream</tt>, which simply states that you must be able to return a stream of tokens via <tt>nextToken</tt>: <tt>
  836. </p>
  837. <pre>
  838. /**This interface allows any object to
  839. * pretend it is a stream of tokens.
  840. * @author Terence Parr, MageLang Institute
  841. */
  842. public interface TokenStream {
  843. public Token nextToken();
  844. }
  845. </tt> </pre>
  846. <p>
  847. ANTLR will not generate a lexer if you do not specify a lexical class.
  848. </p>
  849. <p>
  850. Launching a parser with a non-ANTLR-generated lexer is the same as launching a parser with an ANTLR-generated lexer:
  851. </p>
  852. <tt><pre>HandBuiltLexer lex = new HandBuiltLexer(...);
  853. MyParser p = new MyParser(lex);
  854. p.<i>start-rule</i>();</tt></pre>
  855. <p>
  856. The parser does not care what kind of object you use for scanning as as long as it can answer <tt>nextToken</tt>.
  857. </p>
  858. <p>
  859. If you build your own lexer, and the token values are also generated by that lexer, then you should inform the ANTLR-generated parsers about the token type values generated by that lexer. Use the <a href="options.html#importVocab">importVocab</a> in the parsers that use the externally-generated token set, and create a token definition file following the requirements of the importVocab option.
  860. </p>
  861. <h3><a name="_bb14"></a><a name="Lexical Rules">Lexical Rules</a> </h3>
  862. <p>
  863. Lexical rules are essentially the same as parser rules except that lexical rules apply a structure to a series of characters rather than a series of tokens. As with parser rules, each lexical rule results in a method in the output lexer class.
  864. </p>
  865. <p>
  866. <b>Alternative blocks.</b> Consider a simple series of alternatives within a block: <tt>
  867. </p>
  868. <pre>
  869. FORMAT : 'x' | 'f' | 'd';
  870. </tt> </pre>
  871. <p>
  872. The lexer would contain the following method: <tt>
  873. </p>
  874. <pre>
  875. public int mFORMAT() {
  876. if ( c=='x' ) {
  877. match('x');
  878. }
  879. else if ( c=='x' ) {
  880. match('x');
  881. }
  882. else if ( c=='f' ) {
  883. match('f');
  884. }
  885. else if ( c=='d' ) {
  886. match('d');
  887. }
  888. else {
  889. throw new NoViableAltForCharException(
  890. &quot;no viable alternative: '&quot;+(char)c+&quot;'&quot;);
  891. }
  892. return FORMAT;
  893. }
  894. </tt> </pre>
  895. <p>
  896. The only real differences between lexical methods and grammar methods are that lookahead prediction expressions do character comparisons rather than <tt>LA(i)</tt> comparisons, <tt>match</tt> matches characters instead of tokens, a <tt>return</tt> is added to the bottom of the rule, and lexical methods throw <tt>CharStreamException</tt> objects in addition to <font face="Courier New">TokenStreamException</font> and <font face="Courier New">RecognitionException</font> objects.
  897. </p>
  898. <p>
  899. <b>Optimization: Non-Recursive lexical rules.</b> Rules that do not directly or indirectly call themselves can be inlined into the lexer entry method: <tt>nextToken</tt>. For example, the common identifier rule would be placed directly into the <tt>nextToken</tt> method. That is, rule: <tt>
  900. </p>
  901. <pre>
  902. ID : ( 'a'..'z' | 'A'..'Z' )+
  903. ;
  904. </tt> </pre>
  905. <p>
  906. would not result in a method in your lexer class. This rule would become part of the resulting lexer as it would be probably inlined by ANTLR: <tt>
  907. </p>
  908. <pre>
  909. public Token nextToken() {
  910. switch ( c ) {
  911. <i>cases for operators and such here</i>
  912. case '0': // chars that predict ID token
  913. case '1':
  914. case '2':
  915. case '3':
  916. case '4':
  917. case '5':
  918. case '6':
  919. case '7':
  920. case '8':
  921. case '9':
  922. while ( c&gt;='0' &amp;&amp; c&lt;='9' ) {
  923. matchRange('0','9');
  924. }
  925. return makeToken(ID);
  926. default :
  927. <i>check harder stuff here like rules
  928. beginning with a..z</i>
  929. }
  930. </tt> </pre>
  931. <p>
  932. If not inlined, the method for scanning identifiers would look like: <tt>
  933. </p>
  934. <pre>
  935. public int mID() {
  936. while ( c&gt;='0' &amp;&amp; c&lt;='9' ) {
  937. matchRange('0','9');
  938. }
  939. return ID;
  940. }
  941. </tt> </pre>
  942. <p>
  943. where token names are converted to method names by prefixing them with the letter <tt>m</tt>. The <tt>nextToken</tt> method would become: <tt>
  944. </p>
  945. <pre>
  946. public Token nextToken() {
  947. switch ( c ) {
  948. <i>cases for operators and such here</i>
  949. case '0': // chars that predict ID token
  950. case '1':
  951. case '2':
  952. case '3':
  953. case '4':
  954. case '5':
  955. case '6':
  956. case '7':
  957. case '8':
  958. case '9':
  959. return makeToken(mID());
  960. default :
  961. <i>check harder stuff here like rules
  962. beginning with a..z</i>
  963. }
  964. </tt> </pre>
  965. <p>
  966. Note that this type of range loop is so common that it should probably be optimized to: <tt>
  967. </p>
  968. <pre>
  969. while ( c&gt;='0' &amp;&amp; c&lt;='9' ) {
  970. consume();
  971. }
  972. </tt> </pre>
  973. <p>
  974. <b>Optimization: Recursive lexical rules.</b> Lexical rules that are directly or indirectly recursive are not inlined. For example, consider the following rule that matches nested actions: <tt>
  975. </p>
  976. <pre>
  977. ACTION
  978. : '{' ( ACTION | ~'}' )* '}'
  979. ;
  980. </tt> </pre>
  981. <p>
  982. <tt>ACTION</tt> would be result in (assuming a character vocabulary of 'a'..'z', '{', '}'): <tt>
  983. </p>
  984. <pre>
  985. public int mACTION()
  986. throws RecognitionException,
  987. CharStreamException,
  988. TokenStreamException {
  989. int _ttype = ACTION;
  990. match('{');
  991. {
  992. _loop:
  993. do {
  994. switch ( _c) {
  995. case '{':
  996. mACTION();
  997. break;
  998. case 'a': case 'b': case 'c': case 'd':
  999. case 'e': case 'f': case 'g': case 'h':
  1000. case 'i': case 'j': case 'k': case 'l':
  1001. case 'm': case 'n': case 'o': case 'p':
  1002. case 'q': case 'r': case 's': case 't':
  1003. case 'u': case 'v': case 'w': case 'x':
  1004. case 'y': case 'z':
  1005. matchNot('}');
  1006. break;
  1007. default :
  1008. break _loop;
  1009. }
  1010. } while (true);
  1011. }
  1012. match('}');
  1013. return _ttype;
  1014. }
  1015. </tt> </pre> <h2><a name="_bb15">Token Objects</a></h2>
  1016. <p>
  1017. The basic token knows only about a token type:
  1018. </p>
  1019. <pre><tt>public class Token {
  1020. // constants
  1021. public static final int MIN_USER_TYPE = 3;
  1022. public static final int INVALID_TYPE = 0;
  1023. public static final int EOF_TYPE = 1;
  1024. public static final int SKIP = -1;
  1025. // each Token has at least a token type
  1026. int type=INVALID_TYPE;
  1027. // the illegal token object
  1028. public static Token badToken =
  1029. new Token(INVALID_TYPE, &quot;<no text>&quot;);
  1030. public Token() {;}
  1031. public Token(int t) { type = t; }
  1032. public Token(int t, String txt) {
  1033. type = t; setText(txt);
  1034. }
  1035. public void setType(int t) { type = t; }
  1036. public void setLine(int l) {;}
  1037. public void setColumn(int c) {;}
  1038. public void setText(String t) {;}
  1039. public int getType() { return type; }
  1040. public int getLine() { return 0; }
  1041. public int getColumn() { return 0; }
  1042. public String getText() {...}
  1043. }
  1044. </tt></pre>
  1045. <p>
  1046. The raw <tt>Token</tt> class is not very useful.&nbsp; ANTLR supplies a &quot;common&quot; token class that it uses by default, which contains the line number and text associated with the token:<tt>
  1047. </p>
  1048. </tt>
  1049. <p>
  1050. <tt>public class CommonToken extends Token {
  1051. <br>
  1052. &nbsp; // most tokens will want line, text information
  1053. <br>
  1054. &nbsp; int line;
  1055. <br>
  1056. &nbsp; String text = null;
  1057. <br>
  1058. &nbsp;
  1059. <br>
  1060. &nbsp; public CommonToken() {}
  1061. <br>
  1062. &nbsp; public CommonToken(String s)&nbsp; { text = s; }
  1063. <br>
  1064. &nbsp; public CommonToken(int t, String txt) {
  1065. <br>
  1066. &nbsp;&nbsp;&nbsp; type = t;
  1067. <br>
  1068. &nbsp;&nbsp;&nbsp; setText(txt);
  1069. <br>
  1070. &nbsp; }
  1071. <br>
  1072. <br>
  1073. &nbsp; public void setLine(int l)&nbsp;&nbsp;&nbsp; { line = l; }
  1074. <br>
  1075. &nbsp; public int&nbsp; getLine()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; { return line; }
  1076. <br>
  1077. &nbsp; public void setText(String s) { text = s; }
  1078. <br>
  1079. &nbsp; public String getText()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; { return text; }
  1080. <br>
  1081. }</tt>
  1082. </p>
  1083. <p>
  1084. ANTLR will generate an interface that defines the types of tokens in a token vocabulary. Parser and lexers that share this token vocabulary are generated such that they implement the resulting token types interface: <tt>
  1085. </p>
  1086. <pre>public interface MyLexerTokenTypes {
  1087. public static final int ID = 2;
  1088. public static final int BEGIN = 3;
  1089. ...
  1090. }</tt></pre>
  1091. <p>
  1092. ANTLR defines a token object for use with the <small><font face="Courier New">TokenStreamHiddenTokenFilter</font></small> object called <small><font face="Courier New">CommonHiddenStreamToken</font></small>:
  1093. </p>
  1094. <pre>public class CommonHiddenStreamToken
  1095. extends CommonToken {
  1096. protected CommonHiddenStreamToken hiddenBefore;
  1097. protected CommonHiddenStreamToken hiddenAfter;
  1098. public CommonHiddenStreamToken
  1099. <strong>getHiddenAfter</strong>() {...}
  1100. public CommonHiddenStreamToken
  1101. <strong>getHiddenBefore</strong>() {...}
  1102. }</pre>
  1103. <p>
  1104. Hidden tokens are weaved amongst the normal tokens.&nbsp; Note that, for garbage collection reasons, hidden tokens never point back to normal tokens (preventing a linked list of the entire token stream).
  1105. </p>
  1106. <h2><a name="_bb16">Token Lookahead Buffer</a></h2>
  1107. <p>
  1108. The parser must always have fast access to k symbols of lookahead. In a world without syntactic predicates, a simple buffer of k <tt>Token</tt> references would suffice. However, given that even LL(1) ANTLR parsers must be able to backtrack, an arbitrarily-large buffer of <tt>Token</tt> references must be maintained. <tt>LT(i)</tt> looks into the token buffer.
  1109. </p>
  1110. <p>
  1111. Fortunately, the parser itself does not implement the token-buffering and lookahead algorithm. That is handled by the <tt>TokenBuffer</tt> object. We begin the discussion of lookahead by providing an LL(k) parser framework: <tt>
  1112. </p>
  1113. <pre>
  1114. public class LLkParser extends Parser {
  1115. TokenBuffer input;
  1116. public int LA(int i) {
  1117. return input.LA(i);
  1118. }
  1119. public Token LT(int i) {
  1120. return input.LT(i);
  1121. }
  1122. public void consume() {
  1123. input.consume();
  1124. }
  1125. }
  1126. </tt> </pre>
  1127. <p>
  1128. All lookahead-related calls are simply forwarded to the <tt>TokenBuffer</tt> object. In the future, some simple caching may be performed in the parser itself to avoid the extra indirection, or ANTLR may generate the call to input.LT(i) directly.
  1129. </p>
  1130. <p>
  1131. The <tt>TokenBuffer</tt> object caches the token stream emitted by the scanner. It supplies <tt>LT()</tt> and <tt>LA()</tt> methods for accessing the k<sup>th</sup> lookahead token or token type, as well as methods for consuming tokens, guessing, and backtracking. <tt>
  1132. </p>
  1133. <pre>
  1134. public class TokenBuffer {
  1135. ...
  1136. /** Mark another token for
  1137. * deferred consumption */
  1138. public final void consume() {...}
  1139. /** Get a lookahead token */
  1140. public final Token LT(int i) { ... }
  1141. /** Get a lookahead token value */
  1142. public final int LA(int i) { ... }
  1143. /**Return an integer marker that can be used to
  1144. * rewind the buffer to its current state. */
  1145. public final int mark() { ... }
  1146. /**Rewind the token buffer to a marker.*/
  1147. public final void rewind(int mark) { ... }
  1148. }
  1149. </pre> </tt>
  1150. <p>
  1151. To begin backtracking, a <tt>mark</tt> is issued, which makes the <tt>TokenBuffer</tt> record the current position so that it can rewind the token stream. A subsequent <tt>rewind</tt> directive will reset the internal state to the point before the last <tt>mark</tt>.
  1152. </p>
  1153. <p>
  1154. Consider the following rule that employs backtracking:
  1155. </p>
  1156. <tt><pre>
  1157. stat: (list EQUAL) =&gt; list EQUAL list
  1158. | list
  1159. ;
  1160. list: LPAREN (ID)* RPAREN
  1161. ;
  1162. </tt> </pre>
  1163. <p>
  1164. Something like the following code would be generated: <tt>
  1165. </p>
  1166. <pre>
  1167. public void stat()
  1168. throws RecognitionException,
  1169. TokenStreamException
  1170. {
  1171. boolean synPredFailed;
  1172. if ( LA(1)==LPAREN ) { // check lookahead
  1173. int marker = tokenBuffer.mark();
  1174. try {
  1175. list();
  1176. match(EQUAL);
  1177. synPredFailed = false;
  1178. }
  1179. catch (RecognitionException e) {
  1180. tokenBuffer.rewind(marker);
  1181. synPredFailed = true;
  1182. }
  1183. }
  1184. if ( LA(1)==LPAREN &amp;&amp; !synPredFailed ) {
  1185. // test prediction of alt 1
  1186. list();
  1187. match(EQUAL);
  1188. list();
  1189. }
  1190. else if ( LA(1)==LPAREN ) {
  1191. list();
  1192. }
  1193. }
  1194. </tt> </pre>
  1195. <p>
  1196. The token lookahead buffer uses a circular token buffer to perform quick indexed access to the lookahead tokens. The circular buffer is expanded as necessary to calculate LT(i) for arbitrary i. <tt>TokenBuffer.consume()</tt> does not actually read more tokens. Instead, it defers the read by counting how many tokens have been consumed, and then adjusts the token buffer and/or reads new tokens when LA() or LT() is called.
  1197. </p>
  1198. <p>
  1199. <font face="Arial" size="2">Version: $Id: //depot/code/org.antlr/release/antlr-2.7.5/doc/runtime.html#1 $</font>
  1200. </body>
  1201. </html>