PageRenderTime 30ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/javacc-5.0/www/doc/lookahead.html

https://gitlab.com/essere.lab.public/qualitas.class-corpus
HTML | 986 lines | 894 code | 61 blank | 31 comment | 0 complexity | d595b141bd0f05c48ffd8f11760c2d4a MD5 | raw file
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <!--
  4. Copyright (c) 2006, Sun Microsystems, Inc.
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright notice,
  9. this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright
  11. notice, this list of conditions and the following disclaimer in the
  12. documentation and/or other materials provided with the distribution.
  13. * Neither the name of the Sun Microsystems, Inc. nor the names of its
  14. contributors may be used to endorse or promote products derived from
  15. this software without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  20. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  21. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  22. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  23. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  24. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  25. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  26. THE POSSIBILITY OF SUCH DAMAGE.
  27. -->
  28. <head>
  29. <title>JavaCC: LOOKAHEAD MiniTutorial</title>
  30. <!-- Changed by: Michael Van De Vanter, 14-Jan-2003 -->
  31. </head>
  32. <body bgcolor="#FFFFFF" >
  33. <h1>JavaCC [tm]: LOOKAHEAD MiniTutorial</h1>
  34. <p>
  35. <strong>This tutorial refers
  36. to examples that are available in the Lookahead directory under the
  37. examples directory of the release. Currently, this page is a copy of
  38. the contents of the README file within that directory.
  39. </strong>
  40. </p>
  41. <h1>Lookahead tutorial</h1>
  42. <p>
  43. We assume that you have already taken a look at some of the simple
  44. examples provided in the release before you read this section.
  45. </p>
  46. <h2>WHAT IS LOOKAHEAD?</h2>
  47. <p>
  48. The job of a parser is to read an input stream and determine whether
  49. or not the input stream conforms to the grammar.
  50. </p>
  51. <p>
  52. This determination in its most general form can be quite time
  53. consuming. Consider the following example (file Example1.jj):
  54. </p>
  55. <pre><tt>
  56. void Input() :
  57. {}
  58. {
  59. "a" BC() "c"
  60. }
  61. void BC() :
  62. {}
  63. {
  64. "b" [ "c" ]
  65. }
  66. </tt></pre>
  67. <p>
  68. In this simple example, it is quite clear that there are exactly two
  69. strings that match the above grammar, namely:
  70. </p>
  71. <pre><tt>
  72. abc
  73. abcc
  74. </tt></pre>
  75. <p>
  76. The general way to perform this match is to walk through the grammar
  77. based on the string as follows. Here, we use "abc" as the input
  78. string:
  79. </p>
  80. <ul>
  81. <li><b>Step 1.</b>
  82. There is only one choice here - the first input character
  83. must be 'a' - and since that is indeed the case, we are OK.
  84. </li>
  85. <li><b>Step 2.</b>
  86. We now proceed on to non-terminal BC. Here again, there is
  87. only one choice for the next input character - it must be 'b'. The
  88. input matches this one too, so we are still OK.
  89. </li>
  90. <li><b>Step 3.</b>
  91. We now come to a "choice point" in the grammar.
  92. We can either
  93. go inside the [...] and match it, or ignore it altogether. We decide
  94. to go inside. So the next input character must be a 'c'. We are
  95. again OK.
  96. </li>
  97. <li><b>Step 4.</b>
  98. Now we have completed with non-terminal BC and go back to
  99. non-terminal Input. Now the grammar says the next character must be
  100. yet another 'c'. But there are no more input characters. So we have
  101. a problem.
  102. </li>
  103. <li><b>Step 5.</b>
  104. When we have such a problem in the general case, we conclude
  105. that we may have made a bad choice somewhere. In this case, we made
  106. the bad choice in Step 3. So we retrace our steps back to step 3 and
  107. make another choice and try that. This process is called
  108. "backtracking".
  109. </li>
  110. <li><b>Step 6.</b>
  111. We have now backtracked and made the other choice we could
  112. have made at Step 3 - namely, ignore the [...]. Now we have completed
  113. with non-terminal BC and go back to non-terminal Input. Now the
  114. grammar says the next character must be yet another 'c'. The next
  115. input character is a 'c', so we are OK now.
  116. </li>
  117. <li><b>Step 7.</b>
  118. We realize we have reached the end of the grammar (end of
  119. non-terminal Input) successfully. This means we have successfully
  120. matched the string "abc" to the grammar.
  121. </li>
  122. </ul>
  123. <p>
  124. As the above example indicates, the general problem of matching an
  125. input with a grammar may result in large amounts of backtracking and
  126. making new choices and this can consume a lot of time. The amount of
  127. time taken can also be a function of how the grammar is written. Note
  128. that many grammars can be written to cover the same set of inputs - or
  129. the same language (i.e., there can be multiple equivalent grammars for
  130. the same input language).
  131. </p>
  132. <hr />
  133. <p>
  134. For example, the following grammar would speed up the parsing of the
  135. same language as compared to the previous grammar:
  136. </p>
  137. <pre><tt>
  138. void Input() :
  139. {}
  140. {
  141. "a" "b" "c" [ "c" ]
  142. }
  143. </tt></pre>
  144. <p>
  145. while the following grammar slows it down even more since the parser
  146. has to backtrack all the way to the beginning:
  147. </p>
  148. <pre><tt>
  149. void Input() :
  150. {}
  151. {
  152. "a" "b" "c" "c"
  153. |
  154. "a" "b" "c"
  155. }
  156. </tt></pre>
  157. <p>
  158. One can even have a grammar that looks like the following:
  159. </p>
  160. <pre><tt>
  161. void Input() :
  162. {}
  163. {
  164. "a" ( BC1() | BC2() )
  165. }
  166. void BC1() :
  167. {}
  168. {
  169. "b" "c" "c"
  170. }
  171. void BC2() :
  172. {}
  173. {
  174. "b" "c" [ "c" ]
  175. }
  176. </tt></pre>
  177. <p>
  178. This grammar can match "abcc" in two ways, and is therefore considered
  179. "ambiguous".
  180. </p>
  181. <hr />
  182. <p>
  183. The performance hit from such backtracking is unacceptable for most
  184. systems that include a parser. Hence most parsers do not backtrack in
  185. this general manner (or do not backtrack at all), rather they make
  186. decisions at choice points based on limited information and then
  187. commit to it.
  188. </p>
  189. <p>
  190. Parsers generated by Java Compiler Compiler make decisions at choice
  191. points based on some exploration of tokens further ahead in the input
  192. stream, and once they make such a decision, they commit to it. i.e.,
  193. No backtracking is performed once a decision is made.
  194. </p>
  195. <p>
  196. The process of exploring tokens further in the input stream is termed
  197. "looking ahead" into the input stream - hence our use of the term
  198. "LOOKAHEAD".
  199. </p>
  200. <p>
  201. Since some of these decisions may be made with less than perfect
  202. information (JavaCC [tm] will warn you in these situations, so you don't
  203. have to worry), you need to know something about LOOKAHEAD to make
  204. your grammar work correctly.
  205. </p>
  206. <p>
  207. The two ways in which you make the choice decisions work properly are:
  208. </p>
  209. <ul>
  210. <li>
  211. Modify the grammar to make it simpler.
  212. </li>
  213. <li>
  214. Insert hints at the more complicated choice points to help the
  215. parser make the right choices.
  216. </li>
  217. </ul>
  218. <h2>CHOICE POINTS IN JAVACC GRAMMARS</h2>
  219. <p>
  220. There are 4 different kinds of choice points in JavaCC:
  221. </p>
  222. <ol>
  223. <li>
  224. An expansion of the form: ( exp1 | exp2 | ... ). In this case, the
  225. generated parser has to somehow determine which of exp1, exp2, etc.
  226. to select to continue parsing.
  227. </li>
  228. <li>
  229. An expansion of the form: ( exp )?. In this case, the generated parser
  230. must somehow determine whether to choose exp or to continue beyond
  231. the ( exp )? without choosing exp. Note: ( exp )? may also be written
  232. as [ exp ].
  233. </li>
  234. <li>
  235. An expansion of the form ( exp )*. In this case, the generated parser
  236. must do the same thing as in the previous case, and furthermore, after
  237. each time a successful match of exp (if exp was chosen) is completed,
  238. this choice determination must be made again.
  239. </li>
  240. <li>
  241. An expansion of the form ( exp )+. This is essentially similar to
  242. the previous case with a mandatory first match to exp.
  243. </li>
  244. </ol>
  245. <p>
  246. Remember that token specifications that occur within angular
  247. brackets &lt;...&gt; also have choice points. But these choices are made
  248. in different ways and are the subject of a different tutorial.
  249. </p>
  250. <h2>THE DEFAULT CHOICE DETERMINATION ALGORITHM</h2>
  251. <p>
  252. The default choice determination algorithm looks ahead 1 token in the
  253. input stream and uses this to help make its choice at choice points.
  254. </p>
  255. <p>
  256. The following examples will describe the default algorithm fully:
  257. </p>
  258. <p>
  259. Consider the following grammar (file Example2.jj):
  260. </p>
  261. <pre><tt>
  262. void basic_expr() :
  263. {}
  264. {
  265. &lt;ID&gt; "(" expr() ")" // Choice 1
  266. |
  267. "(" expr() ")" // Choice 2
  268. |
  269. "new" &lt;ID&gt; // Choice 3
  270. }
  271. </tt></pre>
  272. <p>
  273. The choice determination algorithm works as follows:
  274. </p>
  275. <pre><tt>
  276. if (next token is &lt;ID&gt;) {
  277. choose Choice 1
  278. } else if (next token is "(") {
  279. choose Choice 2
  280. } else if (next token is "new") {
  281. choose Choice 3
  282. } else {
  283. produce an error message
  284. }
  285. </tt></pre>
  286. <hr />
  287. <p>
  288. In the above example, the grammar has been written such that the
  289. default choice determination algorithm does the right thing. Another
  290. thing to note is that the choice determination algorithm works in a
  291. top to bottom order - if Choice 1 was selected, the other choices are
  292. not even considered. While this is not an issue in this example
  293. (except for performance), it will become important later below when
  294. local ambiguities require the insertion of LOOKAHEAD hints.
  295. </p>
  296. <p>
  297. Suppose the above grammar was modified to (file Example3.jj):
  298. </p>
  299. <pre><tt>
  300. void basic_expr() :
  301. {}
  302. {
  303. &lt;ID&gt; "(" expr() ")" // Choice 1
  304. |
  305. "(" expr() ")" // Choice 2
  306. |
  307. "new" &lt;ID&gt; // Choice 3
  308. |
  309. &lt;ID&gt; "." &lt;ID&gt; // Choice 4
  310. }
  311. </tt></pre>
  312. <p>
  313. Then the default algorithm will always choose Choice 1 when the next
  314. input token is &lt;ID&gt; and never choose Choice 4 even if the token
  315. following &lt;ID&gt; is a ".". More on this later.
  316. </p>
  317. <p>
  318. You can try running the parser generated from Example3.jj on the input
  319. "id1.id2". It will complain that it encountered a "." when it was
  320. expecting a "(". Note - when you built the parser, it would have
  321. given you the following warning message:
  322. </p>
  323. <pre><tt>
  324. Warning: Choice conflict involving two expansions at
  325. line 25, column 3 and line 31, column 3 respectively.
  326. A common prefix is: &lt;ID&gt;
  327. Consider using a lookahead of 2 for earlier expansion.
  328. </tt></pre>
  329. <p>
  330. Essentially, JavaCC is saying it has detected a situation in your
  331. grammar which may cause the default lookahead algorithm to do strange
  332. things. The generated parser will still work using the default
  333. lookahead algorithm - except that it may not do what you expect of it.
  334. </p>
  335. <hr />
  336. <p>
  337. Now consider the following example (file Example 4.jj):
  338. </p>
  339. <pre><tt>
  340. void identifier_list() :
  341. {}
  342. {
  343. &lt;ID&gt; ( "," &lt;ID&gt; )*
  344. }
  345. </tt></pre>
  346. <p>
  347. Suppose the first &lt;ID&gt; has already been matched and that the parser
  348. has reached the choice point (the (...)* construct). Here's how the
  349. choice determination algorithm works:
  350. </p>
  351. <pre><tt>
  352. while (next token is ",") {
  353. choose the nested expansion (i.e., go into the (...)* construct)
  354. consume the "," token
  355. if (next token is &lt;ID&gt;) consume it, otherwise report error
  356. }
  357. </tt></pre>
  358. <hr />
  359. <p>
  360. In the above example, note that the choice determination algorithm
  361. does not look beyond the (...)* construct to make its decision.
  362. Suppose there was another production in that same grammar as follows
  363. (file Example5.jj):
  364. </p>
  365. <pre><tt>
  366. void funny_list() :
  367. {}
  368. {
  369. identifier_list() "," &lt;INT&gt;
  370. }
  371. </tt></pre>
  372. <p>
  373. When the default algorithm is making a choice at ( "," &lt;ID&gt; )*, it
  374. will always go into the (...)* construct if the next token is a ",".
  375. It will do this even when identifier_list was called from funny_list
  376. and the token after the "," is an &lt;INT&gt;. Intuitively, the right thing
  377. to do in this situation is to skip the (...)* construct and return to
  378. funny_list. More on this later.
  379. </p>
  380. <p>
  381. As a concrete example, suppose your input was "id1, id2, 5", the
  382. parser will complain that it encountered a 5 when it was expecting an
  383. &lt;ID&gt;. Note - when you built the parser, it would have given you the
  384. following warning message:
  385. </p>
  386. <pre><tt>
  387. Warning: Choice conflict in (...)* construct at line 25, column 8.
  388. Expansion nested within construct and expansion following construct
  389. have common prefixes, one of which is: ","
  390. Consider using a lookahead of 2 or more for nested expansion.
  391. </tt></pre>
  392. <p>
  393. Essentially, JavaCC is saying it has detected a situation in your
  394. grammar which may cause the default lookahead algorithm to do strange
  395. things. The generated parser will still work using the default
  396. lookahead algorithm - except that it may not do what you expect of it.
  397. </p>
  398. <hr />
  399. <p>We have shown you examples of two kinds of choice points in the
  400. examples above - "exp1 | exp2 | ...", and "(exp)*". The other two
  401. kinds of choice points - "(exp)+" and "(exp)?" - behave similarly to
  402. (exp)* and we will not be providing examples of their use here.
  403. </p>
  404. <h3>MULTIPLE TOKEN LOOKAHEAD SPECIFICATIONS</h3>
  405. <p>
  406. So far, we have described the default lookahead algorithm of the
  407. generated parsers. In the majority of situations, the default
  408. algorithm works just fine. In situations where it does not work
  409. well, Java Compiler Compiler provides you with warning messages like
  410. the ones shown above. If you have a grammar that goes through
  411. Java Compiler Compiler without producing any warnings, then the
  412. grammar is a LL(1) grammar. Essentially, LL(1) grammars are those
  413. that can be handled by top-down parsers (such as those generated
  414. by Java Compiler Compiler) using at most one token of LOOKAHEAD.
  415. </p>
  416. <p>
  417. When you get these warning messages, you can do one of two things.
  418. </p>
  419. <p><b>Option 1</b></p>
  420. <p>
  421. You can modify your grammar so that the warning messages go away.
  422. That is, you can attempt to make your grammar LL(1) by making some
  423. changes to it.
  424. </p>
  425. <p>
  426. The following (file Example6.jj) shows how you may change Example3.jj
  427. to make it LL(1):
  428. </p>
  429. <pre><tt>
  430. void basic_expr() :
  431. {}
  432. {
  433. &lt;ID&gt; ( "(" expr() ")" | "." &lt;ID&gt; )
  434. |
  435. "(" expr() ")"
  436. |
  437. "new" &lt;ID&gt;
  438. }
  439. </tt></pre>
  440. <p>
  441. What we have done here is to factor the fourth choice into the first
  442. choice. Note how we have placed their common first token &lt;ID&gt; outside
  443. the parentheses, and then within the parentheses, we have yet another
  444. choice which can now be performed by looking at only one token in the
  445. input stream and comparing it with "(" and ".". This process of
  446. modifying grammars to make them LL(1) is called "left factoring".
  447. </p>
  448. <p>
  449. The following (file Example7.jj) shows how Example5.jj may be changed
  450. to make it LL(1):
  451. </p>
  452. <pre><tt>
  453. void funny_list() :
  454. {}
  455. {
  456. &lt;ID&gt; "," ( &lt;ID&gt; "," )* &lt;INT&gt;
  457. }
  458. </tt></pre>
  459. <p>
  460. Note that this change is somewhat more drastic.
  461. </p>
  462. <hr />
  463. <p><b>Option 2</b></p>
  464. <p>
  465. You can provide the generated parser with some hints to help it out
  466. in the non-LL(1) situations that the warning messages bring to your
  467. attention.
  468. </p>
  469. <p>
  470. All such hints are specified using either setting the global LOOKAHEAD
  471. value to a larger value (see below) or by using the LOOKAHEAD(...)
  472. construct to provide a local hint.
  473. </p>
  474. <p>
  475. A design decision must be made to determine if Option 1 or Option 2 is
  476. the right one to take. The only advantage of choosing Option 1 is
  477. that it makes your grammar perform better. JavaCC generated parsers
  478. can handle LL(1) constructs much faster than other constructs.
  479. However, the advantage of choosing Option 2 is that you have a simpler
  480. grammar - one that is easier to develop and maintain - one that
  481. focuses on human-friendliness and not machine-friendliness.
  482. </p>
  483. <p>
  484. Sometimes Option 2 is the only choice - especially in the presence of
  485. user actions. Suppose Example3.jj contained actions as shown below:
  486. </p>
  487. <pre><tt>
  488. void basic_expr() :
  489. {}
  490. {
  491. { initMethodTables(); } &lt;ID&gt; "(" expr() ")"
  492. |
  493. "(" expr() ")"
  494. |
  495. "new" &lt;ID&gt;
  496. |
  497. { initObjectTables(); } &lt;ID&gt; "." &lt;ID&gt;
  498. }
  499. </tt></pre>
  500. <p>
  501. Since the actions are different, left-factoring cannot be performed.
  502. </p>
  503. <h3>SETTING A GLOBAL LOOKAHEAD SPECIFICATION</h3>
  504. <p>
  505. You can set a global LOOKAHEAD specification by using the option
  506. "LOOKAHEAD" either from the command line, or at the beginning of the
  507. grammar file in the options section. The value of this option is an
  508. integer which is the number of tokens to look ahead when making choice
  509. decisions. As you may have guessed, the default value of this option
  510. is 1 - which derives the default LOOKAHEAD algorithm described above.
  511. </p>
  512. <p>
  513. Suppose you set the value of this option to 2. Then the LOOKAHEAD
  514. algorithm derived from this looks at two tokens (instead of just one
  515. token) before making a choice decision. Hence, in Example3.jj, choice
  516. 1 will be taken only if the next two tokens are &lt;ID&gt; and "(", while
  517. choice 4 will be taken only if the next two tokens are &lt;ID&gt; and ".".
  518. Hence, the parser will now work properly for Example3.jj. Similarly,
  519. the problem with Example5.jj also goes away since the parser goes into
  520. the (...)* construct only when the next two tokens are "," and &lt;ID&gt;.
  521. </p>
  522. <p>
  523. By setting the global LOOKAHEAD to 2, the parsing algorithm
  524. essentially becomes LL(2). Since you can set the global LOOKAHEAD to
  525. any value, parsers generated by Java Compiler Compiler are called
  526. LL(k) parsers.
  527. </p>
  528. <h3>SETTING A LOCAL LOOKAHEAD SPECIFICATION</h3>
  529. <p>
  530. You can also set a local LOOKAHEAD specification that affects only a
  531. specific choice point. This way, the majority of the grammar can
  532. remain LL(1) and hence perform better, while at the same time one gets
  533. the flexibility of LL(k) grammars. Here's how Example3.jj is modified
  534. with local LOOKAHEAD to fix the choice ambiguity problem (file
  535. Example8.jj):
  536. </p>
  537. <pre><tt>
  538. void basic_expr() :
  539. {}
  540. {
  541. LOOKAHEAD(2)
  542. &lt;ID&gt; "(" expr() ")" // Choice 1
  543. |
  544. "(" expr() ")" // Choice 2
  545. |
  546. "new" &lt;ID&gt; // Choice 3
  547. |
  548. &lt;ID&gt; "." &lt;ID&gt; // Choice 4
  549. }
  550. </tt></pre>
  551. <p>
  552. Only the first choice (the first condition in the translation below)
  553. is affected by the LOOKAHEAD specification. All others continue to
  554. use a single token of LOOKAHEAD:
  555. </p>
  556. <pre><tt>
  557. if (next 2 tokens are &lt;ID&gt; and "(" ) {
  558. choose Choice 1
  559. } else if (next token is "(") {
  560. choose Choice 2
  561. } else if (next token is "new") {
  562. choose Choice 3
  563. } else if (next token is &lt;ID&gt;) {
  564. choose Choice 4
  565. } else {
  566. produce an error message
  567. }
  568. </tt></pre>
  569. <p>
  570. Similarily, Example5.jj can be modified as shown below (file
  571. Example9.jj):
  572. </p>
  573. <pre><tt>
  574. void identifier_list() :
  575. {}
  576. {
  577. &lt;ID&gt; ( LOOKAHEAD(2) "," &lt;ID&gt; )*
  578. }
  579. </tt></pre>
  580. <p>
  581. Note, the LOOKAHEAD specification has to occur inside the (...)* which
  582. is the choice is being made. The translation for this construct is
  583. shown below (after the first &lt;ID&gt; has been consumed):
  584. </p>
  585. <pre><tt>
  586. while (next 2 tokens are "," and &lt;ID&gt;) {
  587. choose the nested expansion (i.e., go into the (...)* construct)
  588. consume the "," token
  589. consume the &lt;ID&gt; token
  590. }
  591. </tt></pre>
  592. <hr />
  593. <p>
  594. We strongly discourage you from modifying the global LOOKAHEAD
  595. default. Most grammars are predominantly LL(1), hence you will be
  596. unnecessarily degrading performance by converting the entire grammar
  597. to LL(k) to facilitate just some portions of the grammar that are not
  598. LL(1). If your grammar and input files being parsed are very small,
  599. then this is okay.
  600. </p>
  601. <p>
  602. You should also keep in mind that the warning messages JavaCC prints
  603. when it detects ambiguities at choice points (such as the two messages
  604. shown earlier) simply tells you that the specified choice points are
  605. not LL(1). JavaCC does not verify the correctness of your local
  606. LOOKAHEAD specification - it assumes you know what you are doing, in
  607. fact, it really cannot verify the correctness of local LOOKAHEAD's as
  608. the following example of if statements illustrates (file
  609. Example10.jj):
  610. </p>
  611. <pre><tt>
  612. void IfStm() :
  613. {}
  614. {
  615. "if" C() S() [ "else" S() ]
  616. }
  617. void S() :
  618. {}
  619. {
  620. ...
  621. |
  622. IfStm()
  623. }
  624. </tt></pre>
  625. <p>
  626. This example is the famous "dangling else" problem. If you have a
  627. program that looks like:
  628. </p>
  629. <pre><tt>
  630. "if C1 if C2 S1 else S2"
  631. </tt></pre>
  632. <p>
  633. The "else S2" can be bound to either of the two if statements. The
  634. standard interpretation is that it is bound to the inner if statement
  635. (the one closest to it). The default choice determination algorithm
  636. happens to do the right thing, but it still prints the following
  637. warning message:
  638. </p>
  639. <pre><tt>
  640. Warning: Choice conflict in [...] construct at line 25, column 15.
  641. Expansion nested within construct and expansion following construct
  642. have common prefixes, one of which is: "else"
  643. Consider using a lookahead of 2 or more for nested expansion.
  644. </tt></pre>
  645. <p>
  646. To suppress the warning message, you could simply tell JavaCC that
  647. you know what you are doing as follows:
  648. </p>
  649. <pre><tt>
  650. void IfStm() :
  651. {}
  652. {
  653. "if" C() S() [ LOOKAHEAD(1) "else" S() ]
  654. }
  655. </tt></pre>
  656. <p>
  657. To force lookahead ambiguity checking in such instances, set the option
  658. FORCE_LA_CHECK to true.
  659. </p>
  660. <h3>SYNTACTIC LOOKAHEAD</h3>
  661. <p>
  662. Consider the following production taken from the Java grammar:
  663. </p>
  664. <pre><tt>
  665. void TypeDeclaration() :
  666. {}
  667. {
  668. ClassDeclaration()
  669. |
  670. InterfaceDeclaration()
  671. }
  672. </tt></pre>
  673. <p>
  674. At the syntactic level, ClassDeclaration can start with any number of
  675. "abstract"s, "final"s, and "public"s. While a subsequent semantic
  676. check will produce error messages for multiple uses of the same
  677. modifier, this does not happen until parsing is completely over.
  678. Similarly, InterfaceDeclaration can start with any number of
  679. "abstract"s and "public"s.
  680. </p>
  681. <p>
  682. What if the next tokens in the input stream are a very large number of
  683. "abstract"s (say 100 of them) followed by "interface"? It is clear
  684. that a fixed amount of LOOKAHEAD (such as LOOKAHEAD(100) for example)
  685. will not suffice. One can argue that this is such a weird situation
  686. that it does not warrant any reasonable error message and that it is
  687. okay to make the wrong choice in some pathological situations. But
  688. suppose one wanted to be precise about this.
  689. </p>
  690. <p>
  691. The solution here is to set the LOOKAHEAD to infinity - that is set no
  692. bounds on the number of tokens to look ahead. One way to do this is
  693. to use a very large integer value (such as the largest possible
  694. integer) as follows:
  695. </p>
  696. <pre><tt>
  697. void TypeDeclaration() :
  698. {}
  699. {
  700. LOOKAHEAD(2147483647)
  701. ClassDeclaration()
  702. |
  703. InterfaceDeclaration()
  704. }
  705. </tt></pre>
  706. <p>
  707. One can also achieve the same effect with "syntactic LOOKAHEAD". In
  708. syntactic LOOKAHEAD, you specify an expansion to try out and it that
  709. succeeds, then the following choice is taken. The above example is
  710. rewritten using syntactic LOOKAHEAD below:
  711. </p>
  712. <pre><tt>
  713. void TypeDeclaration() :
  714. {}
  715. {
  716. LOOKAHEAD(ClassDeclaration())
  717. ClassDeclaration()
  718. |
  719. InterfaceDeclaration()
  720. }
  721. </tt></pre>
  722. <p>
  723. Essentially, what this is saying is:
  724. </p>
  725. <pre><tt>
  726. if (the tokens from the input stream match ClassDeclaration) {
  727. choose ClassDeclaration()
  728. } else if (next token matches InterfaceDeclaration) {
  729. choose InterfaceDeclaration()
  730. } else {
  731. produce an error message
  732. }
  733. </tt></pre>
  734. <p>
  735. The problem with the above syntactic LOOKAHEAD specification is that
  736. the LOOKAHEAD calculation takes too much time and does a lot of
  737. unnecessary checking. In this case, the LOOKAHEAD calculation can
  738. stop as soon as the token "class" is encountered, but the
  739. specification forces the calculation to continue until the end of the
  740. class declaration has been reached - which is rather time consuming.
  741. This problem can be solved by placing a shorter expansion to try out
  742. in the syntactic LOOKAHEAD specification as in the following example:
  743. </p>
  744. <pre><tt>
  745. void TypeDeclaration() :
  746. {}
  747. {
  748. LOOKAHEAD( ( "abstract" | "final" | "public" )* "class" )
  749. ClassDeclaration()
  750. |
  751. InterfaceDeclaration()
  752. }
  753. </tt></pre>
  754. <p>
  755. Essentially, what this is saying is:
  756. </p>
  757. <pre><tt>
  758. if (the nest set of tokens from the input stream are a sequence of
  759. "abstract"s, "final"s, and "public"s followed by a "class") {
  760. choose ClassDeclaration()
  761. } else if (next token matches InterfaceDeclaration) {
  762. choose InterfaceDeclaration()
  763. } else {
  764. produce an error message
  765. }
  766. </tt></pre>
  767. <p>
  768. By doing this, you make the choice determination algorithm stop as
  769. soon as it sees "class" - i.e., make its decision at the earliest
  770. possible time.
  771. </p>
  772. <p>
  773. You can place a bound on the number of tokens to consume during
  774. syntactic lookahead as follows:
  775. </p>
  776. <pre><tt>
  777. void TypeDeclaration() :
  778. {}
  779. {
  780. LOOKAHEAD(10, ( "abstract" | "final" | "public" )* "class" )
  781. ClassDeclaration()
  782. |
  783. InterfaceDeclaration()
  784. }
  785. </tt></pre>
  786. <p>
  787. In this case, the LOOKAHEAD determination is not permitted to go beyond
  788. 10 tokens. If it reaches this limit and is still successfully matching
  789. ( "abstract" | "final" | "public" )* "class", then ClassDeclaration is
  790. selected.
  791. </p>
  792. <p>
  793. Actually, when such a limit is not specified, it defaults to the largest
  794. integer value (2147483647).
  795. </p>
  796. <h3>SEMANTIC LOOKAHEAD</h3>
  797. <p>
  798. Let us go back to Example1.jj:
  799. </p>
  800. <pre><tt>
  801. void Input() :
  802. {}
  803. {
  804. "a" BC() "c"
  805. }
  806. void BC() :
  807. {}
  808. {
  809. "b" [ "c" ]
  810. }
  811. </tt></pre>
  812. <p>
  813. Let us suppose that there is a good reason for writing a grammar this
  814. way (maybe the way actions are embedded). As noted earlier, this
  815. grammar recognizes two string "abc" and "abcc". The problem here is
  816. that the default LL(1) algorithm will choose the [ "c" ] every time
  817. it sees a "c" and therefore "abc" will never be matched. We need to
  818. specify that this choice must be made only when the next token is a
  819. "c", and the token following that is not a "c". This is a negative
  820. statement - one that cannot be made using syntactic LOOKAHEAD.
  821. </p>
  822. <p>
  823. We can use semantic LOOKAHEAD for this purpose. With semantic
  824. LOOKAHEAD, you can specify any arbitrary boolean expression whose
  825. evaluation determines which choice to take at a choice point. The
  826. above example can be instrumented with semantic LOOKAHEAD as follows:
  827. </p>
  828. <pre><tt>
  829. void BC() :
  830. {}
  831. {
  832. "b"
  833. [ LOOKAHEAD( { getToken(1).kind == C &amp;&amp; getToken(2).kind != C } )
  834. &lt;C:"c"&gt;
  835. ]
  836. }
  837. </tt></pre>
  838. <p>
  839. First we give the token "c" a label C so that we can refer to it from
  840. the semantic LOOKAHEAD. The boolean expression essentially states the
  841. desired property. The choice determination decision is therefore:
  842. </p>
  843. <pre><tt>
  844. if (next token is "c" and following token is not "c") {
  845. choose the nested expansion (i.e., go into the [...] construct)
  846. } else {
  847. go beyond the [...] construct without entering it.
  848. }
  849. </tt></pre>
  850. <p>
  851. This example can be rewritten to combine both syntactic and semantic
  852. LOOKAHEAD as follows (recognize the first "c" using syntactic
  853. LOOKAHEAD and the absence of the second using semantic LOOKAHEAD):
  854. </p>
  855. <pre><tt>
  856. void BC() :
  857. {}
  858. {
  859. "b"
  860. [ LOOKAHEAD( "c", { getToken(2).kind != C } )
  861. &lt;C:"c"&gt;
  862. ]
  863. }
  864. </tt></pre>
  865. <h3>GENERAL STRUCTURE OF LOOKAHEAD</h3>
  866. <p>
  867. We've pretty much covered the various aspects of LOOKAHEAD in the
  868. previous sections. A couple of advanced topics follow. However,
  869. we shall now present a formal language reference for LOOKAHEAD in
  870. Java Compiler Compiler:
  871. </p>
  872. <p>
  873. The general structure of a LOOKAHEAD specification is:
  874. </p>
  875. <pre><tt>
  876. LOOKAHEAD( amount,
  877. expansion,
  878. { boolean_expression }
  879. )
  880. </tt></pre>
  881. <p>
  882. "amount" specifies the number of tokens to LOOKAHEAD,"expansion"
  883. specifies the expansion to use to perform syntactic LOOKAHEAD, and
  884. "boolean_expression" is the expression to use for semantic
  885. LOOKAHEAD.
  886. </p>
  887. <p>
  888. At least one of the three entries must be present. If more than
  889. one are present, they are separated by commas. The default values
  890. for each of these entities is defined below:
  891. </p>
  892. <pre><tt>
  893. "amount":
  894. - if "expansion is present, this defaults to 2147483647.
  895. - otherwise ("boolean_expression" must be present then) this
  896. defaults to 0.
  897. Note: When "amount" is 0, no syntactic LOOKAHEAD is performed. Also,
  898. "amount" does not affect the semantic LOOKAHEAD.
  899. "expansion":
  900. - defaults to the expansion being considered.
  901. "boolean_expression":
  902. - defaults to true.
  903. </tt></pre>
  904. <h3>NESTED EVALUATION OF SEMANTIC LOOKAHEAD</h3>
  905. <p>
  906. To be done.
  907. </p>
  908. <h3>JAVACODE PRODUCTIONS</h3>
  909. <p>
  910. To be done.
  911. </p>
  912. </body>
  913. </html>