Remove hand-written node pointers in doc/misc/wisent.texi
[bpt/emacs.git] / doc / misc / wisent.texi
1 \input texinfo @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename ../../info/wisent
4 @set TITLE Wisent Parser Development
5 @set AUTHOR Eric M. Ludlam, David Ponce, and Richard Y. Kim
6 @settitle @value{TITLE}
7
8 @c *************************************************************************
9 @c @ Header
10 @c *************************************************************************
11
12 @c Merge all indexes into a single index for now.
13 @c We can always separate them later into two or more as needed.
14 @syncodeindex vr cp
15 @syncodeindex fn cp
16 @syncodeindex ky cp
17 @syncodeindex pg cp
18 @syncodeindex tp cp
19
20 @c @footnotestyle separate
21 @c @paragraphindent 2
22 @c @@smallbook
23 @c %**end of header
24
25 @copying
26 Copyright @copyright{} 1988--1993, 1995, 1998--2004, 2007, 2012
27 Free Software Foundation, Inc.
28
29 @c Since we are both GNU manuals, we do not need to ack each other here.
30 @ignore
31 Some texts are borrowed or adapted from the manual of Bison version
32 1.35. The text in section entitled ``Understanding the automaton'' is
33 adapted from the section ``Understanding Your Parser'' in the manual
34 of Bison version 1.49.
35 @end ignore
36
37 @quotation
38 Permission is granted to copy, distribute and/or modify this document
39 under the terms of the GNU Free Documentation License, Version 1.3 or
40 any later version published by the Free Software Foundation; with no
41 Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
42 and with the Back-Cover Texts as in (a) below. A copy of the license
43 is included in the section entitled ``GNU Free Documentation License''.
44
45 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
46 modify this GNU manual.''
47 @end quotation
48 @end copying
49
50 @dircategory Emacs misc features
51 @direntry
52 * Wisent: (wisent). Semantic Wisent parser development.
53 @end direntry
54
55 @iftex
56 @finalout
57 @end iftex
58
59 @c @setchapternewpage odd
60 @c @setchapternewpage off
61
62 @titlepage
63 @sp 10
64 @title @value{TITLE}
65 @author by @value{AUTHOR}
66 @page
67 @vskip 0pt plus 1 fill
68 @insertcopying
69 @end titlepage
70 @page
71
72 @macro semantic{}
73 @i{Semantic}
74 @end macro
75
76 @c *************************************************************************
77 @c @ Document
78 @c *************************************************************************
79 @contents
80
81 @node top
82 @top @value{TITLE}
83
84 Wisent (the European Bison ;-) is an Emacs Lisp implementation of the
85 GNU Compiler Compiler Bison.
86
87 This manual describes how to use Wisent to develop grammars for
88 programming languages, and how to use grammars to parse language
89 source in Emacs buffers.
90
91 It also describes how Wisent is used with the @semantic{} tool set
92 described in the @ref{Top, Semantic Manual, Semantic Manual, semantic}.
93
94 @ifnottex
95 @insertcopying
96 @end ifnottex
97
98 @menu
99 * Wisent Overview::
100 * Wisent Grammar::
101 * Wisent Parsing::
102 * Wisent Semantic::
103 * GNU Free Documentation License::
104 * Index::
105 @end menu
106
107 @node Wisent Overview
108 @chapter Wisent Overview
109
110 @dfn{Wisent} (the European Bison) is an implementation in Emacs Lisp
111 of the GNU Compiler Compiler Bison. Its code is a port of the C code
112 of GNU Bison 1.28 & 1.31.
113
114 For more details on the basic concepts for understanding Wisent, it is
115 worthwhile to read the @ref{Top, Bison Manual, bison}.
116 @ifhtml
117 @uref{http://www.gnu.org/manual/bison/html_node/index.html}.
118 @end ifhtml
119
120 Wisent can generate compilers compatible with the @semantic{} tool set.
121 See the @ref{Top, Semantic Manual, , semantic}.
122
123 It benefits from these Bison features:
124
125 @itemize @bullet
126 @item
127 It uses a fast but not so space-efficient encoding for the parse
128 tables, described in Corbett's PhD thesis from Berkeley:
129 @quotation
130 @cite{Static Semantics in Compiler Error Recovery}@*
131 June 1985, Report No. UCB/CSD 85/251.
132 @end quotation
133
134 @item
135 For generating the lookahead sets, Wisent uses the well-known
136 technique of F. DeRemer and A. Pennello described in:
137 @quotation
138 @cite{Efficient Computation of LALR(1) Look-Ahead Sets}@*
139 October 1982, ACM TOPLAS Vol 4 No 4, 615--49,
140 @uref{http://dx.doi.org/10.1145/69622.357187}.
141 @end quotation
142
143 @item
144 Wisent resolves shift/reduce conflicts using operator precedence and
145 associativity.
146
147 @item
148 Parser error recovery is accomplished using rules which match the
149 special token @code{error}.
150 @end itemize
151
152 Nevertheless there are some fundamental differences between Bison and
153 Wisent.
154
155 @itemize
156 @item
157 Wisent is intended to be used in Emacs. It reads and produces Emacs
158 Lisp data structures. All the additional code used in grammars is
159 Emacs Lisp code.
160
161 @item
162 Contrary to Bison, Wisent does not generate a parser which combines
163 Emacs Lisp code and grammar constructs. They exist separately.
164 Wisent reads the grammar from a Lisp data structure and then generates
165 grammar constructs as tables. Afterward, the derived tables can be
166 included and byte-compiled in separate Emacs Lisp files, and be used
167 at a later time by the Wisent's parser engine.
168
169 @item
170 Wisent allows multiple start nonterminals and allows a call to the
171 parsing function to be made for a particular start nonterminal. For
172 example, this is particularly useful to parse a region of an Emacs
173 buffer. @semantic{} heavily depends on the availability of this feature.
174 @end itemize
175
176 @node Wisent Grammar
177 @chapter Wisent Grammar
178
179 @cindex context-free grammar
180 @cindex rule
181 In order for Wisent to parse a language, it must be described by a
182 @dfn{context-free grammar}. That is a grammar specified as rules that
183 can be applied regardless of context. For more information, see
184 @ref{Language and Grammar, , , bison}, in the Bison manual.
185
186 @cindex terminal
187 @cindex nonterminal
188 The formal grammar is formulated using @dfn{terminal} and
189 @dfn{nonterminal} items. Terminals can be Emacs Lisp symbols or
190 characters, and nonterminals are symbols only.
191
192 @cindex token
193 Terminals (also known as @dfn{tokens}) represent the lexical
194 elements of the language like numbers, strings, etc..
195
196 For example @samp{PLUS} can represent the operator @samp{+}.
197
198 Nonterminal symbols are described by rules:
199
200 @example
201 @group
202 RESULT @equiv{} COMPONENTS@dots{}
203 @end group
204 @end example
205
206 @samp{RESULT} is a nonterminal that this rule describes and
207 @samp{COMPONENTS} are various terminals and nonterminals that are put
208 together by this rule.
209
210 For example, this rule:
211
212 @example
213 @group
214 exp @equiv{} exp PLUS exp
215 @end group
216 @end example
217
218 Says that two groupings of type @samp{exp}, with a @samp{PLUS} token
219 in between, can be combined into a larger grouping of type @samp{exp}.
220
221 @menu
222 * Grammar format::
223 * Example::
224 * Compiling a grammar::
225 * Conflicts::
226 @end menu
227
228 @node Grammar format
229 @section Grammar format
230
231 @cindex grammar format
232 To be acceptable by Wisent a context-free grammar must respect a
233 particular format. That is, must be represented as an Emacs Lisp list
234 of the form:
235
236 @code{(@var{terminals} @var{assocs} . @var{non-terminals})}
237
238 @table @var
239 @item terminals
240 Is the list of terminal symbols used in the grammar.
241
242 @cindex associativity
243 @item assocs
244 Specify the associativity of @var{terminals}. It is @code{nil} when
245 there is no associativity defined, or an alist of
246 @w{@code{(@var{assoc-type} . @var{assoc-value})}} elements.
247
248 @var{assoc-type} must be one of the @code{default-prec},
249 @code{nonassoc}, @code{left} or @code{right} symbols. When
250 @var{assoc-type} is @code{default-prec}, @var{assoc-value} must be
251 @code{nil} or @code{t} (the default). Otherwise it is a list of
252 tokens which must have been previously declared in @var{terminals}.
253
254 For details, see @ref{Contextual Precedence, , , bison}, in the
255 Bison manual.
256
257 @item non-terminals
258 Is the list of nonterminal definitions. Each definition has the form:
259
260 @code{(@var{nonterm} . @var{rules})}
261
262 Where @var{nonterm} is the nonterminal symbol defined and
263 @var{rules} the list of rules that describe this nonterminal. Each
264 rule is a list:
265
266 @code{(@var{components} [@var{precedence}] [@var{action}])}
267
268 Where:
269
270 @table @var
271 @item components
272 Is a list of various terminals and nonterminals that are put together
273 by this rule.
274
275 For example,
276
277 @example
278 @group
279 (exp ((exp ?+ exp)) ;; exp: exp '+' exp
280 ) ;; ;
281 @end group
282 @end example
283
284 Says that two groupings of type @samp{exp}, with a @samp{+} token in
285 between, can be combined into a larger grouping of type @samp{exp}.
286
287 @cindex grammar coding conventions
288 By convention, a nonterminal symbol should be in lower case, such as
289 @samp{exp}, @samp{stmt} or @samp{declaration}. Terminal symbols
290 should be upper case to distinguish them from nonterminals: for
291 example, @samp{INTEGER}, @samp{IDENTIFIER}, @samp{IF} or
292 @samp{RETURN}. A terminal symbol that represents a particular keyword
293 in the language is conventionally the same as that keyword converted
294 to upper case. The terminal symbol @code{error} is reserved for error
295 recovery.
296
297 @cindex middle-rule actions
298 Scattered among the components can be @dfn{middle-rule} actions.
299 Usually only @var{action} is provided (@pxref{action}).
300
301 If @var{components} in a rule is @code{nil}, it means that the rule
302 can match the empty string. For example, here is how to define a
303 comma-separated sequence of zero or more @samp{exp} groupings:
304
305 @example
306 @group
307 (expseq (nil) ;; expseq: ;; empty
308 ((expseq1)) ;; | expseq1
309 ) ;; ;
310
311 (expseq1 ((exp)) ;; expseq1: exp
312 ((expseq1 ?, exp)) ;; | expseq1 ',' exp
313 ) ;; ;
314 @end group
315 @end example
316
317 @cindex precedence level
318 @item precedence
319 Assign the rule the precedence of the given terminal item, overriding
320 the precedence that would be deduced for it, that is the one of the
321 last terminal in it. Notice that only terminals declared in
322 @var{assocs} have a precedence level. The altered rule precedence
323 then affects how conflicts involving that rule are resolved.
324
325 @var{precedence} is an optional vector of one terminal item.
326
327 Here is how @var{precedence} solves the problem of unary minus.
328 First, declare a precedence for a fictitious terminal symbol named
329 @code{UMINUS}. There are no tokens of this type, but the symbol
330 serves to stand for its precedence:
331
332 @example
333 @dots{}
334 ((default-prec t) ;; This is the default
335 (left '+' '-')
336 (left '*')
337 (left UMINUS))
338 @end example
339
340 Now the precedence of @code{UMINUS} can be used in specific rules:
341
342 @example
343 @group
344 (exp @dots{} ;; exp: @dots{}
345 ((exp ?- exp)) ;; | exp '-' exp
346 @dots{} ;; @dots{}
347 ((?- exp) [UMINUS]) ;; | '-' exp %prec UMINUS
348 @dots{} ;; @dots{}
349 ) ;; ;
350 @end group
351 @end example
352
353 If you forget to append @code{[UMINUS]} to the rule for unary minus,
354 Wisent silently assumes that minus has its usual precedence. This
355 kind of problem can be tricky to debug, since one typically discovers
356 the mistake only by testing the code.
357
358 Using @code{(default-prec nil)} declaration makes it easier to
359 discover this kind of problem systematically. It causes rules that
360 lack a @var{precedence} modifier to have no precedence, even if the
361 last terminal symbol mentioned in their components has a declared
362 precedence.
363
364 If @code{(default-prec nil)} is in effect, you must specify
365 @var{precedence} for all rules that participate in precedence conflict
366 resolution. Then you will see any shift/reduce conflict until you
367 tell Wisent how to resolve it, either by changing your grammar or by
368 adding an explicit precedence. This will probably add declarations to
369 the grammar, but it helps to protect against incorrect rule
370 precedences.
371
372 The effect of @code{(default-prec nil)} can be reversed by giving
373 @code{(default-prec t)}, which is the default.
374
375 For more details, see @ref{Contextual Precedence, , , bison}, in the
376 Bison manual.
377
378 It is important to understand that @var{assocs} declarations defines
379 associativity but also assign a precedence level to terminals. All
380 terminals declared in the same @code{left}, @code{right} or
381 @code{nonassoc} association get the same precedence level. The
382 precedence level is increased at each new association.
383
384 On the other hand, @var{precedence} explicitly assign the precedence
385 level of the given terminal to a rule.
386
387 @cindex semantic actions
388 @item @anchor{action}action
389 An action is an optional Emacs Lisp function call, like this:
390
391 @code{(identity $1)}
392
393 The result of an action determines the semantic value of a rule.
394
395 From an implementation standpoint, the function call will be embedded
396 in a lambda expression, and several useful local variables will be
397 defined:
398
399 @table @code
400 @vindex $N
401 @item $@var{n}
402 Where @var{n} is a positive integer. Like in Bison, the value of
403 @code{$@var{n}} is the semantic value of the @var{n}th element of
404 @var{components}, starting from 1. It can be of any Lisp data
405 type.
406
407 @vindex $region@var{n}
408 @item $regionN
409 Where @var{n} is a positive integer. For each @code{$@var{n}}
410 variable defined there is a corresponding @code{$region@var{n}}
411 variable. Its value is a pair @code{(@var{start-pos} .
412 @var{end-pos})} that represent the start and end positions (in the
413 lexical input stream) of the @code{$@var{n}} value. It can be
414 @code{nil} when the component positions are not available, like for an
415 empty string component for example.
416
417 @vindex $region
418 @item $region
419 Its value is the leftmost and rightmost positions of input data
420 matched by all @var{components} in the rule. This is a pair
421 @code{(@var{leftmost-pos} . @var{rightmost-pos})}. It can be
422 @code{nil} when components positions are not available.
423
424 @vindex $nterm
425 @item $nterm
426 This variable is initialized with the nonterminal symbol
427 (@var{nonterm}) the rule belongs to. It could be useful to improve
428 error reporting or debugging. It is also used to automatically
429 provide incremental re-parse entry points for @semantic{} tags
430 (@pxref{Wisent Semantic}).
431
432 @vindex $action
433 @item $action
434 The value of @code{$action} is the symbolic name of the current
435 semantic action (@pxref{Debugging actions}).
436 @end table
437
438 When an action is not specified a default value is supplied, it is
439 @code{(identity $1)}. This means that the default semantic value of a
440 rule is the value of its first component. Excepted for a rule
441 matching the empty string, for which the default action is to return
442 @code{nil}.
443 @end table
444 @end table
445
446 @node Example
447 @section Example
448
449 @cindex grammar example
450 Here is an example to parse simple infix arithmetic expressions. See
451 @ref{Infix Calc, , , bison}, in the Bison manual for details.
452
453 @lisp
454 @group
455 '(
456 ;; Terminals
457 (NUM)
458
459 ;; Terminal associativity & precedence
460 ((nonassoc ?=)
461 (left ?- ?+)
462 (left ?* ?/)
463 (left NEG)
464 (right ?^))
465
466 ;; Rules
467 (input
468 ((line))
469 ((input line)
470 (format "%s %s" $1 $2))
471 )
472
473 (line
474 ((?;)
475 (progn ";"))
476 ((exp ?;)
477 (format "%s;" $1))
478 ((error ?;)
479 (progn "Error;")))
480 )
481
482 (exp
483 ((NUM)
484 (string-to-number $1))
485 ((exp ?= exp)
486 (= $1 $3))
487 ((exp ?+ exp)
488 (+ $1 $3))
489 ((exp ?- exp)
490 (- $1 $3))
491 ((exp ?* exp)
492 (* $1 $3))
493 ((exp ?/ exp)
494 (/ $1 $3))
495 ((?- exp) [NEG]
496 (- $2))
497 ((exp ?^ exp)
498 (expt $1 $3))
499 ((?\( exp ?\))
500 (progn $2))
501 )
502 )
503 @end group
504 @end lisp
505
506 In the bison-like @dfn{WY} format (@pxref{Wisent Semantic}) the
507 grammar looks like this:
508
509 @example
510 @group
511 %token <number> NUM
512
513 %nonassoc '=' ;; comparison
514 %left '-' '+'
515 %left '*' '/'
516 %left NEG ;; negation--unary minus
517 %right '^' ;; exponentiation
518
519 %%
520
521 input:
522 line
523 | input line
524 (format "%s %s" $1 $2)
525 ;
526
527 line:
528 ';'
529 @{";"@}
530 | exp ';'
531 (format "%s;" $1)
532 | error ';'
533 @{"Error;"@}
534 ;
535
536 exp:
537 NUM
538 (string-to-number $1)
539 | exp '=' exp
540 (= $1 $3)
541 | exp '+' exp
542 (+ $1 $3)
543 | exp '-' exp
544 (- $1 $3)
545 | exp '*' exp
546 (* $1 $3)
547 | exp '/' exp
548 (/ $1 $3)
549 | '-' exp %prec NEG
550 (- $2)
551 | exp '^' exp
552 (expt $1 $3)
553 | '(' exp ')'
554 @{$2@}
555 ;
556
557 %%
558 @end group
559 @end example
560
561 @node Compiling a grammar
562 @section Compiling a grammar
563
564 @cindex automaton
565 After providing a context-free grammar in a suitable format, it must
566 be translated into a set of tables (an @dfn{automaton}) that will be
567 used to derive the parser. Like Bison, Wisent translates grammars that
568 must be @dfn{LALR(1)}.
569
570 @cindex LALR(1) grammar
571 @cindex look-ahead token
572 A grammar is @acronym{LALR(1)} if it is possible to tell how to parse
573 any portion of an input string with just a single token of look-ahead:
574 the @dfn{look-ahead token}. See @ref{Language and Grammar, , ,
575 bison}, in the Bison manual for more information.
576
577 @cindex grammar compilation
578 Grammar translation (compilation) is achieved by the function:
579
580 @cindex compiling a grammar
581 @vindex wisent-single-start-flag
582 @findex wisent-compile-grammar
583 @defun wisent-compile-grammar grammar &optional start-list
584 Compile @var{grammar} and return an @acronym{LALR(1)} automaton.
585
586 Optional argument @var{start-list} is a list of start symbols
587 (nonterminals). If @code{nil} the first nonterminal defined in the
588 grammar is the default start symbol. If @var{start-list} contains
589 only one element, it defines the start symbol. If @var{start-list}
590 contains more than one element, all are defined as potential start
591 symbols, unless @code{wisent-single-start-flag} is non-@code{nil}. In
592 that case the first element of @var{start-list} defines the start
593 symbol and others are ignored.
594
595 The @acronym{LALR(1)} automaton is a vector of the form:
596
597 @code{[@var{actions gotos starts functions}]}
598
599 @table @var
600 @item actions
601 A state/token matrix telling the parser what to do at every state
602 based on the current look-ahead token. That is shift, reduce, accept
603 or error. See also @ref{Wisent Parsing}.
604
605 @item gotos
606 A state/nonterminal matrix telling the parser the next state to go to
607 after reducing with each rule.
608
609 @item starts
610 An alist which maps the allowed start symbols (nonterminals) to
611 lexical tokens that will be first shifted into the parser stack.
612
613 @item functions
614 An obarray of semantic action symbols. A semantic action is actually
615 an Emacs Lisp function (lambda expression).
616 @end table
617 @end defun
618
619 @node Conflicts
620 @section Conflicts
621
622 Normally, a grammar should produce an automaton where at each state
623 the parser has only one action to do (@pxref{Wisent Parsing}).
624
625 @cindex ambiguous grammar
626 In certain cases, a grammar can produce an automaton where, at some
627 states, there are more than one action possible. Such a grammar is
628 @dfn{ambiguous}, and generates @dfn{conflicts}.
629
630 @cindex deterministic automaton
631 The parser can't be driven by an automaton which isn't completely
632 @dfn{deterministic}, that is which contains conflicts. It is
633 necessary to resolve the conflicts to eliminate them. Wisent resolves
634 conflicts like Bison does.
635
636 @cindex grammar conflicts
637 @cindex conflicts resolution
638 There are two sorts of conflicts:
639
640 @table @dfn
641 @cindex shift/reduce conflicts
642 @item shift/reduce conflicts
643 When either a shift or a reduction would be valid at the same state.
644
645 Such conflicts are resolved by choosing to shift, unless otherwise
646 directed by operator precedence declarations.
647 See @ref{Shift/Reduce , , , bison}, in the Bison manual for more
648 information.
649
650 @cindex reduce/reduce conflicts
651 @item reduce/reduce conflicts
652 That occurs if there are two or more rules that apply to the same
653 sequence of input. This usually indicates a serious error in the
654 grammar.
655
656 Such conflicts are resolved by choosing to use the rule that appears
657 first in the grammar, but it is very risky to rely on this. Every
658 reduce/reduce conflict must be studied and usually eliminated. See
659 @ref{Reduce/Reduce , , , bison}, in the Bison manual for more
660 information.
661 @end table
662
663 @menu
664 * Grammar Debugging::
665 * Understanding the automaton::
666 @end menu
667
668 @node Grammar Debugging
669 @subsection Grammar debugging
670
671 @cindex grammar debugging
672 @cindex grammar verbose description
673 To help writing a new grammar, @code{wisent-compile-grammar} can
674 produce a verbose report containing a detailed description of the
675 grammar and parser (equivalent to what Bison reports with the
676 @option{--verbose} option).
677
678 To enable the verbose report you can set to non-@code{nil} the
679 variable:
680
681 @vindex wisent-verbose-flag
682 @deffn Option wisent-verbose-flag
683 non-@code{nil} means to report verbose information on generated parser.
684 @end deffn
685
686 Or interactively use the command:
687
688 @findex wisent-toggle-verbose-flag
689 @deffn Command wisent-toggle-verbose-flag
690 Toggle whether to report verbose information on generated parser.
691 @end deffn
692
693 The verbose report is printed in the temporary buffer
694 @code{*wisent-log*} when running interactively, or in file
695 @file{wisent.output} when running in batch mode. Different
696 reports are separated from each other by a line like this:
697
698 @example
699 @group
700 *** Wisent @var{source-file} - 2002-06-27 17:33
701 @end group
702 @end example
703
704 where @var{source-file} is the name of the Emacs Lisp file from which
705 the grammar was read. See @ref{Understanding the automaton}, for
706 details on the verbose report.
707
708 @table @strong
709 @item Please Note
710 To help debugging the grammar compiler itself, you can set this
711 variable to print the content of some internal data structures:
712
713 @vindex wisent-debug-flag
714 @defvar wisent-debug-flag
715 non-@code{nil} means enable some debug stuff.
716 @end defvar
717 @end table
718
719 @node Understanding the automaton
720 @subsection Understanding the automaton
721
722 @cindex understanding the automaton
723 This section (took from the manual of Bison 1.49) describes how to use
724 the verbose report printed by @code{wisent-compile-grammar} to
725 understand the generated automaton, to tune or fix a grammar.
726
727 We will use the following example:
728
729 @example
730 @group
731 (let ((wisent-verbose-flag t)) ;; Print a verbose report!
732 (wisent-compile-grammar
733 '((NUM STR) ; %token NUM STR
734
735 ((left ?+ ?-) ; %left '+' '-';
736 (left ?*)) ; %left '*'
737
738 (exp ; exp:
739 ((exp ?+ exp)) ; exp '+' exp
740 ((exp ?- exp)) ; | exp '-' exp
741 ((exp ?* exp)) ; | exp '*' exp
742 ((exp ?/ exp)) ; | exp '/' exp
743 ((NUM)) ; | NUM
744 ) ; ;
745
746 (useless ; useless:
747 ((STR)) ; STR
748 ) ; ;
749 )
750 'nil) ; no %start declarations
751 )
752 @end group
753 @end example
754
755 When evaluating the above expression, grammar compilation first issues
756 the following two clear messages:
757
758 @example
759 @group
760 Grammar contains 1 useless nonterminals and 1 useless rules
761 Grammar contains 7 shift/reduce conflicts
762 @end group
763 @end example
764
765 The @samp{*wisent-log*} buffer details things!
766
767 The first section reports conflicts that were solved using precedence
768 and/or associativity:
769
770 @example
771 @group
772 Conflict in state 7 between rule 1 and token '+' resolved as reduce.
773 Conflict in state 7 between rule 1 and token '-' resolved as reduce.
774 Conflict in state 7 between rule 1 and token '*' resolved as shift.
775 Conflict in state 8 between rule 2 and token '+' resolved as reduce.
776 Conflict in state 8 between rule 2 and token '-' resolved as reduce.
777 Conflict in state 8 between rule 2 and token '*' resolved as shift.
778 Conflict in state 9 between rule 3 and token '+' resolved as reduce.
779 Conflict in state 9 between rule 3 and token '-' resolved as reduce.
780 Conflict in state 9 between rule 3 and token '*' resolved as reduce.
781 @end group
782 @end example
783
784 The next section reports useless tokens, nonterminal and rules (note
785 that useless tokens might be used by the scanner):
786
787 @example
788 @group
789 Useless nonterminals:
790
791 useless
792
793
794 Terminals which are not used:
795
796 STR
797
798
799 Useless rules:
800
801 #6 useless: STR;
802 @end group
803 @end example
804
805 The next section lists states that still have conflicts:
806
807 @example
808 @group
809 State 7 contains 1 shift/reduce conflict.
810 State 8 contains 1 shift/reduce conflict.
811 State 9 contains 1 shift/reduce conflict.
812 State 10 contains 4 shift/reduce conflicts.
813 @end group
814 @end example
815
816 The next section reproduces the grammar used:
817
818 @example
819 @group
820 Grammar
821
822 Number, Rule
823 1 exp -> exp '+' exp
824 2 exp -> exp '-' exp
825 3 exp -> exp '*' exp
826 4 exp -> exp '/' exp
827 5 exp -> NUM
828 @end group
829 @end example
830
831 And reports the uses of the symbols:
832
833 @example
834 @group
835 Terminals, with rules where they appear
836
837 $EOI (-1)
838 error (1)
839 NUM (2) 5
840 STR (3) 6
841 '+' (4) 1
842 '-' (5) 2
843 '*' (6) 3
844 '/' (7) 4
845
846
847 Nonterminals, with rules where they appear
848
849 exp (8)
850 on left: 1 2 3 4 5, on right: 1 2 3 4
851 @end group
852 @end example
853
854 The report then details the automaton itself, describing each state
855 with it set of @dfn{items}, also known as @dfn{pointed rules}. Each
856 item is a production rule together with a point (marked by @samp{.})
857 that the input cursor.
858
859 @example
860 @group
861 state 0
862
863 NUM shift, and go to state 1
864
865 exp go to state 2
866 @end group
867 @end example
868
869 State 0 corresponds to being at the very beginning of the parsing, in
870 the initial rule, right before the start symbol (@samp{exp}). When
871 the parser returns to this state right after having reduced a rule
872 that produced an @samp{exp}, it jumps to state 2. If there is no such
873 transition on a nonterminal symbol, and the lookahead is a @samp{NUM},
874 then this token is shifted on the parse stack, and the control flow
875 jumps to state 1. Any other lookahead triggers a parse error.
876
877 In the state 1...
878
879 @example
880 @group
881 state 1
882
883 exp -> NUM . (rule 5)
884
885 $default reduce using rule 5 (exp)
886 @end group
887 @end example
888
889 the rule 5, @samp{exp: NUM;}, is completed. Whatever the lookahead
890 (@samp{$default}), the parser will reduce it. If it was coming from
891 state 0, then, after this reduction it will return to state 0, and
892 will jump to state 2 (@samp{exp: go to state 2}).
893
894 @example
895 @group
896 state 2
897
898 exp -> exp . '+' exp (rule 1)
899 exp -> exp . '-' exp (rule 2)
900 exp -> exp . '*' exp (rule 3)
901 exp -> exp . '/' exp (rule 4)
902
903 $EOI shift, and go to state 11
904 '+' shift, and go to state 3
905 '-' shift, and go to state 4
906 '*' shift, and go to state 5
907 '/' shift, and go to state 6
908 @end group
909 @end example
910
911 In state 2, the automaton can only shift a symbol. For instance,
912 because of the item @samp{exp -> exp . '+' exp}, if the lookahead if
913 @samp{+}, it will be shifted on the parse stack, and the automaton
914 control will jump to state 3, corresponding to the item
915 @samp{exp -> exp . '+' exp}:
916
917 @example
918 @group
919 state 3
920
921 exp -> exp '+' . exp (rule 1)
922
923 NUM shift, and go to state 1
924
925 exp go to state 7
926 @end group
927 @end example
928
929 Since there is no default action, any other token than those listed
930 above will trigger a parse error.
931
932 The interpretation of states 4 to 6 is straightforward:
933
934 @example
935 @group
936 state 4
937
938 exp -> exp '-' . exp (rule 2)
939
940 NUM shift, and go to state 1
941
942 exp go to state 8
943
944
945
946 state 5
947
948 exp -> exp '*' . exp (rule 3)
949
950 NUM shift, and go to state 1
951
952 exp go to state 9
953
954
955
956 state 6
957
958 exp -> exp '/' . exp (rule 4)
959
960 NUM shift, and go to state 1
961
962 exp go to state 10
963 @end group
964 @end example
965
966 As was announced in beginning of the report, @samp{State 7 contains 1
967 shift/reduce conflict.}:
968
969 @example
970 @group
971 state 7
972
973 exp -> exp . '+' exp (rule 1)
974 exp -> exp '+' exp . (rule 1)
975 exp -> exp . '-' exp (rule 2)
976 exp -> exp . '*' exp (rule 3)
977 exp -> exp . '/' exp (rule 4)
978
979 '*' shift, and go to state 5
980 '/' shift, and go to state 6
981
982 '/' [reduce using rule 1 (exp)]
983 $default reduce using rule 1 (exp)
984 @end group
985 @end example
986
987 Indeed, there are two actions associated to the lookahead @samp{/}:
988 either shifting (and going to state 6), or reducing rule 1. The
989 conflict means that either the grammar is ambiguous, or the parser
990 lacks information to make the right decision. Indeed the grammar is
991 ambiguous, as, since we did not specify the precedence of @samp{/},
992 the sentence @samp{NUM + NUM / NUM} can be parsed as @samp{NUM + (NUM
993 / NUM)}, which corresponds to shifting @samp{/}, or as @samp{(NUM +
994 NUM) / NUM}, which corresponds to reducing rule 1.
995
996 Because in @acronym{LALR(1)} parsing a single decision can be made,
997 Wisent arbitrarily chose to disable the reduction, see
998 @ref{Conflicts}. Discarded actions are reported in between square
999 brackets.
1000
1001 Note that all the previous states had a single possible action: either
1002 shifting the next token and going to the corresponding state, or
1003 reducing a single rule. In the other cases, i.e., when shifting
1004 @emph{and} reducing is possible or when @emph{several} reductions are
1005 possible, the lookahead is required to select the action. State 7 is
1006 one such state: if the lookahead is @samp{*} or @samp{/} then the
1007 action is shifting, otherwise the action is reducing rule 1. In other
1008 words, the first two items, corresponding to rule 1, are not eligible
1009 when the lookahead is @samp{*}, since we specified that @samp{*} has
1010 higher precedence that @samp{+}. More generally, some items are
1011 eligible only with some set of possible lookaheads.
1012
1013 States 8 to 10 are similar:
1014
1015 @example
1016 @group
1017 state 8
1018
1019 exp -> exp . '+' exp (rule 1)
1020 exp -> exp . '-' exp (rule 2)
1021 exp -> exp '-' exp . (rule 2)
1022 exp -> exp . '*' exp (rule 3)
1023 exp -> exp . '/' exp (rule 4)
1024
1025 '*' shift, and go to state 5
1026 '/' shift, and go to state 6
1027
1028 '/' [reduce using rule 2 (exp)]
1029 $default reduce using rule 2 (exp)
1030
1031
1032
1033 state 9
1034
1035 exp -> exp . '+' exp (rule 1)
1036 exp -> exp . '-' exp (rule 2)
1037 exp -> exp . '*' exp (rule 3)
1038 exp -> exp '*' exp . (rule 3)
1039 exp -> exp . '/' exp (rule 4)
1040
1041 '/' shift, and go to state 6
1042
1043 '/' [reduce using rule 3 (exp)]
1044 $default reduce using rule 3 (exp)
1045
1046
1047
1048 state 10
1049
1050 exp -> exp . '+' exp (rule 1)
1051 exp -> exp . '-' exp (rule 2)
1052 exp -> exp . '*' exp (rule 3)
1053 exp -> exp . '/' exp (rule 4)
1054 exp -> exp '/' exp . (rule 4)
1055
1056 '+' shift, and go to state 3
1057 '-' shift, and go to state 4
1058 '*' shift, and go to state 5
1059 '/' shift, and go to state 6
1060
1061 '+' [reduce using rule 4 (exp)]
1062 '-' [reduce using rule 4 (exp)]
1063 '*' [reduce using rule 4 (exp)]
1064 '/' [reduce using rule 4 (exp)]
1065 $default reduce using rule 4 (exp)
1066 @end group
1067 @end example
1068
1069 Observe that state 10 contains conflicts due to the lack of precedence
1070 of @samp{/} wrt @samp{+}, @samp{-}, and @samp{*}, but also because the
1071 associativity of @samp{/} is not specified.
1072
1073 Finally, the state 11 (plus 12) is named the @dfn{final state}, or the
1074 @dfn{accepting state}:
1075
1076 @example
1077 @group
1078 state 11
1079
1080 $EOI shift, and go to state 12
1081
1082
1083
1084 state 12
1085
1086 $default accept
1087 @end group
1088 @end example
1089
1090 The end of input is shifted @samp{$EOI shift,} and the parser exits
1091 successfully (@samp{go to state 12}, that terminates).
1092
1093 @node Wisent Parsing
1094 @chapter Wisent Parsing
1095
1096 @cindex bottom-up parser
1097 @cindex shift-reduce parser
1098 The Wisent's parser is what is called a @dfn{bottom-up} or
1099 @dfn{shift-reduce} parser which repeatedly:
1100
1101 @table @dfn
1102 @cindex shift
1103 @item shift
1104 That is pushes the value of the last lexical token read (the
1105 look-ahead token) into a value stack, and reads a new one.
1106
1107 @cindex reduce
1108 @item reduce
1109 That is replaces a nonterminal by its semantic value. The values of
1110 the components which form the right hand side of a rule are popped
1111 from the value stack and reduced by the semantic action of this rule.
1112 The result is pushed back on top of value stack.
1113 @end table
1114
1115 The parser will stop on:
1116
1117 @table @dfn
1118 @cindex accept
1119 @item accept
1120 When all input has been successfully parsed. The semantic value of
1121 the start nonterminal is on top of the value stack.
1122
1123 @cindex syntax error
1124 @item error
1125 When a syntax error (an unexpected token in input) has been detected.
1126 At this point the parser issues an error message and either stops or
1127 calls a recovery routine to try to resume parsing.
1128 @end table
1129
1130 @cindex table-driven parser
1131 The above elementary actions are driven by the @acronym{LALR(1)}
1132 automaton built by @code{wisent-compile-grammar} from a context-free
1133 grammar.
1134
1135 The Wisent's parser is entered by calling the function:
1136
1137 @findex wisent-parse
1138 @defun wisent-parse automaton lexer &optional error start
1139 Parse input using the automaton specified in @var{automaton}.
1140
1141 @table @var
1142 @item automaton
1143 Is an @acronym{LALR(1)} automaton generated by
1144 @code{wisent-compile-grammar} (@pxref{Wisent Grammar}).
1145
1146 @item lexer
1147 Is a function with no argument called by the parser to obtain the next
1148 terminal (token) in input (@pxref{Writing a lexer}).
1149
1150 @item error
1151 Is an optional reporting function called when a parse error occurs.
1152 It receives a message string to report. It defaults to the function
1153 @code{wisent-message} (@pxref{Report errors}).
1154
1155 @item start
1156 Specify the start symbol (nonterminal) used by the parser as its goal.
1157 It defaults to the start symbol defined in the grammar
1158 (@pxref{Wisent Grammar}).
1159 @end table
1160 @end defun
1161
1162 The following two normal hooks permit to do some useful processing
1163 respectively before to start parsing, and after the parser terminated.
1164
1165 @vindex wisent-pre-parse-hook
1166 @defvar wisent-pre-parse-hook
1167 Normal hook run just before entering the @var{LR} parser engine.
1168 @end defvar
1169
1170 @vindex wisent-post-parse-hook
1171 @defvar wisent-post-parse-hook
1172 Normal hook run just after the @var{LR} parser engine terminated.
1173 @end defvar
1174
1175 @menu
1176 * Writing a lexer::
1177 * Actions goodies::
1178 * Report errors::
1179 * Error recovery::
1180 * Debugging actions::
1181 @end menu
1182
1183 @node Writing a lexer
1184 @section What the parser must receive
1185
1186 It is important to understand that the parser does not parse
1187 characters, but lexical tokens, and does not know anything about
1188 characters in text streams!
1189
1190 @cindex lexical analysis
1191 @cindex lexer
1192 @cindex scanner
1193 Reading input data to produce lexical tokens is performed by a lexer
1194 (also called a scanner) in a lexical analysis step, before the syntax
1195 analysis step performed by the parser. The parser automatically calls
1196 the lexer when it needs the next token to parse.
1197
1198 @cindex lexical tokens
1199 A Wisent's lexer is an Emacs Lisp function with no argument. It must
1200 return a valid lexical token of the form:
1201
1202 @code{(@var{token-class value} [@var{start} . @var{end}])}
1203
1204 @table @var
1205 @item token-class
1206 Is a category of lexical token identifying a terminal as specified in
1207 the grammar (@pxref{Wisent Grammar}). It can be a symbol or a character
1208 literal.
1209
1210 @item value
1211 Is the value of the lexical token. It can be of any valid Emacs Lisp
1212 data type.
1213
1214 @item start
1215 @itemx end
1216 Are the optional beginning and ending positions of @var{value} in the
1217 input stream.
1218 @end table
1219
1220 When there are no more tokens to read the lexer must return the token
1221 @code{(list wisent-eoi-term)} to each request.
1222
1223 @vindex wisent-eoi-term
1224 @defvar wisent-eoi-term
1225 Predefined constant, End-Of-Input terminal symbol.
1226 @end defvar
1227
1228 @code{wisent-lex} is an example of a lexer that reads lexical tokens
1229 produced by a @semantic{} lexer, and translates them into lexical tokens
1230 suitable to the Wisent parser. See also @ref{Wisent Lex}.
1231
1232 To call the lexer in a semantic action use the function
1233 @code{wisent-lexer}. See also @ref{Actions goodies}.
1234
1235 @node Actions goodies
1236 @section Variables and macros useful in grammar actions.
1237
1238 @vindex wisent-input
1239 @defvar wisent-input
1240 The last token read.
1241 This variable only has meaning in the scope of @code{wisent-parse}.
1242 @end defvar
1243
1244 @findex wisent-lexer
1245 @defun wisent-lexer
1246 Obtain the next terminal in input.
1247 @end defun
1248
1249 @findex wisent-region
1250 @defun wisent-region &rest positions
1251 Return the start/end positions of the region including
1252 @var{positions}. Each element of @var{positions} is a pair
1253 @w{@code{(@var{start-pos} . @var{end-pos})}} or @code{nil}. The
1254 returned value is the pair @w{@code{(@var{min-start-pos} .
1255 @var{max-end-pos})}} or @code{nil} if no @var{positions} are
1256 available.
1257 @end defun
1258
1259 @node Report errors
1260 @section The error reporting function
1261
1262 @cindex error reporting
1263 When the parser encounters a syntax error it calls a user-defined
1264 function. It must be an Emacs Lisp function with one argument: a
1265 string containing the message to report.
1266
1267 By default the parser uses this function to report error messages:
1268
1269 @findex wisent-message
1270 @defun wisent-message string &rest args
1271 Print a one-line message if @code{wisent-parse-verbose-flag} is set.
1272 Pass @var{string} and @var{args} arguments to @dfn{message}.
1273 @end defun
1274
1275 @table @strong
1276 @item Please Note:
1277 @code{wisent-message} uses the following function to print lexical
1278 tokens:
1279
1280 @defun wisent-token-to-string token
1281 Return a printed representation of lexical token @var{token}.
1282 @end defun
1283
1284 The general printed form of a lexical token is:
1285
1286 @w{@code{@var{token}(@var{value})@@@var{location}}}
1287 @end table
1288
1289 To control the verbosity of the parser you can set to non-@code{nil}
1290 this variable:
1291
1292 @vindex wisent-parse-verbose-flag
1293 @deffn Option wisent-parse-verbose-flag
1294 non-@code{nil} means to issue more messages while parsing.
1295 @end deffn
1296
1297 Or interactively use the command:
1298
1299 @findex wisent-parse-toggle-verbose-flag
1300 @deffn Command wisent-parse-toggle-verbose-flag
1301 Toggle whether to issue more messages while parsing.
1302 @end deffn
1303
1304 When the error reporting function is entered the variable
1305 @code{wisent-input} contains the unexpected token as returned by the
1306 lexer.
1307
1308 The error reporting function can be called from a semantic action too
1309 using the special macro @code{wisent-error}. When called from a
1310 semantic action entered by error recovery (@pxref{Error recovery}) the
1311 value of the variable @code{wisent-recovering} is non-@code{nil}.
1312
1313 @node Error recovery
1314 @section Error recovery
1315
1316 @cindex error recovery
1317 The error recovery mechanism of the Wisent's parser conforms to the
1318 one Bison uses. See @ref{Error Recovery, , , bison}, in the Bison
1319 manual for details.
1320
1321 @cindex error token
1322 To recover from a syntax error you must write rules to recognize the
1323 special token @code{error}. This is a terminal symbol that is
1324 automatically defined and reserved for error handling.
1325
1326 When the parser encounters a syntax error, it pops the state stack
1327 until it finds a state that allows shifting the @code{error} token.
1328 After it has been shifted, if the old look-ahead token is not
1329 acceptable to be shifted next, the parser reads tokens and discards
1330 them until it finds a token which is acceptable.
1331
1332 @cindex error recovery strategy
1333 Strategies for error recovery depend on the choice of error rules in
1334 the grammar. A simple and useful strategy is simply to skip the rest
1335 of the current statement if an error is detected:
1336
1337 @example
1338 @group
1339 (statement (( error ?; )) ;; on error, skip until ';' is read
1340 )
1341 @end group
1342 @end example
1343
1344 It is also useful to recover to the matching close-delimiter of an
1345 opening-delimiter that has already been parsed:
1346
1347 @example
1348 @group
1349 (primary (( ?@{ expr ?@} ))
1350 (( ?@{ error ?@} ))
1351 @dots{}
1352 )
1353 @end group
1354 @end example
1355
1356 @cindex error recovery actions
1357 Note that error recovery rules may have actions, just as any other
1358 rules can. Here are some predefined hooks, variables, functions or
1359 macros, useful in such actions:
1360
1361 @vindex wisent-nerrs
1362 @defvar wisent-nerrs
1363 The number of parse errors encountered so far.
1364 @end defvar
1365
1366 @vindex wisent-recovering
1367 @defvar wisent-recovering
1368 non-@code{nil} means that the parser is recovering.
1369 This variable only has meaning in the scope of @code{wisent-parse}.
1370 @end defvar
1371
1372 @findex wisent-error
1373 @defun wisent-error msg
1374 Call the user supplied error reporting function with message
1375 @var{msg} (@pxref{Report errors}).
1376
1377 For an example of use, @xref{wisent-skip-token}.
1378 @end defun
1379
1380 @findex wisent-errok
1381 @defun wisent-errok
1382 Resume generating error messages immediately for subsequent syntax
1383 errors.
1384
1385 The parser suppress error message for syntax errors that happens
1386 shortly after the first, until three consecutive input tokens have
1387 been successfully shifted.
1388
1389 Calling @code{wisent-errok} in an action, make error messages resume
1390 immediately. No error messages will be suppressed if you call it in
1391 an error rule's action.
1392
1393 For an example of use, @xref{wisent-skip-token}.
1394 @end defun
1395
1396 @findex wisent-clearin
1397 @defun wisent-clearin
1398 Discard the current lookahead token.
1399 This will cause a new lexical token to be read.
1400
1401 In an error rule's action the previous lookahead token is reanalyzed
1402 immediately. @code{wisent-clearin} may be called to clear this token.
1403
1404 For example, suppose that on a parse error, an error handling routine
1405 is called that advances the input stream to some point where parsing
1406 should once again commence. The next symbol returned by the lexical
1407 scanner is probably correct. The previous lookahead token ought to
1408 be discarded with @code{wisent-clearin}.
1409
1410 For an example of use, @xref{wisent-skip-token}.
1411 @end defun
1412
1413 @findex wisent-abort
1414 @defun wisent-abort
1415 Abort parsing and save the lookahead token.
1416 @end defun
1417
1418 @findex wisent-set-region
1419 @defun wisent-set-region start end
1420 Change the region of text matched by the current nonterminal.
1421 @var{start} and @var{end} are respectively the beginning and end
1422 positions of the region occupied by the group of components associated
1423 to this nonterminal. If @var{start} or @var{end} values are not a
1424 valid positions the region is set to @code{nil}.
1425
1426 For an example of use, @xref{wisent-skip-token}.
1427 @end defun
1428
1429 @vindex wisent-discarding-token-functions
1430 @defvar wisent-discarding-token-functions
1431 List of functions to be called when discarding a lexical token.
1432 These functions receive the lexical token discarded.
1433 When the parser encounters unexpected tokens, it can discards them,
1434 based on what directed by error recovery rules. Either when the
1435 parser reads tokens until one is found that can be shifted, or when an
1436 semantic action calls the function @code{wisent-skip-token} or
1437 @code{wisent-skip-block}.
1438 For language specific hooks, make sure you define this as a local
1439 hook.
1440
1441 For example, in @semantic{}, this hook is set to the function
1442 @code{wisent-collect-unmatched-syntax} to collect unmatched lexical
1443 tokens (@pxref{Useful functions}).
1444 @end defvar
1445
1446 @findex wisent-skip-token
1447 @defun wisent-skip-token
1448 @anchor{wisent-skip-token}
1449 Skip the lookahead token in order to resume parsing.
1450 Return nil.
1451 Must be used in error recovery semantic actions.
1452
1453 It typically looks like this:
1454
1455 @lisp
1456 @group
1457 (wisent-message "%s: skip %s" $action
1458 (wisent-token-to-string wisent-input))
1459 (run-hook-with-args
1460 'wisent-discarding-token-functions wisent-input)
1461 (wisent-clearin)
1462 (wisent-errok)))
1463 @end group
1464 @end lisp
1465 @end defun
1466
1467 @findex wisent-skip-block
1468 @defun wisent-skip-block
1469 Safely skip a block in order to resume parsing.
1470 Return nil.
1471 Must be used in error recovery semantic actions.
1472
1473 A block is data between an open-delimiter (syntax class @code{(}) and
1474 a matching close-delimiter (syntax class @code{)}):
1475
1476 @example
1477 @group
1478 (a parenthesized block)
1479 [a block between brackets]
1480 @{a block between braces@}
1481 @end group
1482 @end example
1483
1484 The following example uses @code{wisent-skip-block} to safely skip a
1485 block delimited by @samp{LBRACE} (@code{@{}) and @samp{RBRACE}
1486 (@code{@}}) tokens, when a syntax error occurs in
1487 @samp{other-components}:
1488
1489 @example
1490 @group
1491 (block ((LBRACE other-components RBRACE))
1492 ((LBRACE RBRACE))
1493 ((LBRACE error)
1494 (wisent-skip-block))
1495 )
1496 @end group
1497 @end example
1498 @end defun
1499
1500 @node Debugging actions
1501 @section Debugging semantic actions
1502
1503 @cindex semantic action symbols
1504 Each semantic action is represented by a symbol interned in an
1505 @dfn{obarray} that is part of the @acronym{LALR(1)} automaton
1506 (@pxref{Compiling a grammar}). @code{symbol-function} on a semantic
1507 action symbol return the semantic action lambda expression.
1508
1509 A semantic action symbol name has the form
1510 @code{@var{nonterminal}:@var{index}}, where @var{nonterminal} is the
1511 name of the nonterminal symbol the action belongs to, and @var{index}
1512 is an action sequence number within the scope of @var{nonterminal}.
1513 For example, this nonterminal definition:
1514
1515 @example
1516 @group
1517 input:
1518 line [@code{input:0}]
1519 | input line
1520 (format "%s %s" $1 $2) [@code{input:1}]
1521 ;
1522 @end group
1523 @end example
1524
1525 Will produce two semantic actions, and associated symbols:
1526
1527 @table @code
1528 @item input:0
1529 A default action that returns @code{$1}.
1530
1531 @item input:1
1532 That returns @code{(format "%s %s" $1 $2)}.
1533 @end table
1534
1535 @cindex debugging semantic actions
1536 Debugging uses the Lisp debugger to investigate what is happening
1537 during execution of semantic actions.
1538 Three commands are available to debug semantic actions. They receive
1539 two arguments:
1540
1541 @itemize @bullet
1542 @item The automaton that contains the semantic action.
1543
1544 @item The semantic action symbol.
1545 @end itemize
1546
1547 @findex wisent-debug-on-entry
1548 @deffn Command wisent-debug-on-entry automaton function
1549 Request @var{automaton}'s @var{function} to invoke debugger each time it is called.
1550 @var{function} must be a semantic action symbol that exists in @var{automaton}.
1551 @end deffn
1552
1553 @findex wisent-cancel-debug-on-entry
1554 @deffn Command wisent-cancel-debug-on-entry automaton function
1555 Undo effect of @code{wisent-debug-on-entry} on @var{automaton}'s @var{function}.
1556 @var{function} must be a semantic action symbol that exists in @var{automaton}.
1557 @end deffn
1558
1559 @findex wisent-debug-show-entry
1560 @deffn Command wisent-debug-show-entry automaton function
1561 Show the source of @var{automaton}'s semantic action @var{function}.
1562 @var{function} must be a semantic action symbol that exists in @var{automaton}.
1563 @end deffn
1564
1565 @node Wisent Semantic
1566 @chapter How to use Wisent with Semantic
1567
1568 @cindex tags
1569 This section presents how the Wisent's parser can be used to produce
1570 @dfn{tags} for the @semantic{} tool set.
1571
1572 @semantic{} tags form a hierarchy of Emacs Lisp data structures that
1573 describes a program in a way independent of programming languages.
1574 Tags map program declarations, like functions, methods, variables,
1575 data types, classes, includes, grammar rules, etc..
1576
1577 @cindex WY grammar format
1578 To use the Wisent parser with @semantic{} you have to define
1579 your grammar in @dfn{WY} form, a grammar format very close
1580 to the one used by Bison.
1581
1582 Please @inforef{top, Semantic Grammar Framework Manual, grammar-fw}
1583 for more information on @semantic{} grammars.
1584
1585 @menu
1586 * Grammar styles::
1587 * Wisent Lex::
1588 @end menu
1589
1590 @node Grammar styles
1591 @section Grammar styles
1592
1593 @cindex grammar styles
1594 @semantic{} parsing heavily depends on how you wrote the grammar.
1595 There are mainly two styles to write a Wisent's grammar intended to be
1596 used with the @semantic{} tool set: the @dfn{Iterative style} and the
1597 @dfn{Bison style}. Each one has pros and cons, and in certain cases
1598 it can be worth a mix of the two styles!
1599
1600 @menu
1601 * Iterative style::
1602 * Bison style::
1603 * Mixed style::
1604 * Start nonterminals::
1605 * Useful functions::
1606 @end menu
1607
1608 @node Iterative style
1609 @subsection Iterative style
1610
1611 @cindex grammar iterative style
1612 The @dfn{iterative style} is the preferred style to use with @semantic{}.
1613 It relies on an iterative parser back-end mechanism which parses start
1614 nonterminals one at a time and automagically skips unexpected lexical
1615 tokens in input.
1616
1617 Compared to rule-based iterative functions (@pxref{Bison style}),
1618 iterative parsers are better in that they can handle obscure errors
1619 more cleanly.
1620
1621 @cindex raw tag
1622 Each start nonterminal must produces a @dfn{raw tag} by calling a
1623 @code{TAG}-like grammar macro with appropriate parameters. See also
1624 @ref{Start nonterminals}.
1625
1626 @cindex expanded tag
1627 Then, each parsing iteration automatically translates a raw tag into
1628 @dfn{expanded tags}, updating the raw tag structure with internal
1629 properties and buffer related data.
1630
1631 After parsing completes, it results in a tree of expanded tags.
1632
1633 The following example is a snippet of the iterative style Java grammar
1634 provided in the @semantic{} distribution in the file
1635 @file{semantic/wisent/java-tags.wy}.
1636
1637 @example
1638 @group
1639 @dots{}
1640 ;; Alternate entry points
1641 ;; - Needed by partial re-parse
1642 %start formal_parameter
1643 @dots{}
1644 ;; - Needed by EXPANDFULL clauses
1645 %start formal_parameters
1646 @dots{}
1647
1648 formal_parameter_list
1649 : PAREN_BLOCK
1650 (EXPANDFULL $1 formal_parameters)
1651 ;
1652
1653 formal_parameters
1654 : LPAREN
1655 ()
1656 | RPAREN
1657 ()
1658 | formal_parameter COMMA
1659 | formal_parameter RPAREN
1660 ;
1661
1662 formal_parameter
1663 : formal_parameter_modifier_opt type variable_declarator_id
1664 (VARIABLE-TAG $3 $2 nil :typemodifiers $1)
1665 ;
1666 @end group
1667 @end example
1668
1669 @findex EXPANDFULL
1670 It shows the use of the @code{EXPANDFULL} grammar macro to parse a
1671 @samp{PAREN_BLOCK} which contains a @samp{formal_parameter_list}.
1672 @code{EXPANDFULL} tells to recursively parse @samp{formal_parameters}
1673 inside @samp{PAREN_BLOCK}. The parser iterates until it digested all
1674 available input data inside the @samp{PAREN_BLOCK}, trying to match
1675 any of the @samp{formal_parameters} rules:
1676
1677 @itemize
1678 @item @samp{LPAREN}
1679
1680 @item @samp{RPAREN}
1681
1682 @item @samp{formal_parameter COMMA}
1683
1684 @item @samp{formal_parameter RPAREN}
1685 @end itemize
1686
1687 At each iteration it will return a @samp{formal_parameter} raw tag,
1688 or @code{nil} to skip unwanted (single @samp{LPAREN} or @samp{RPAREN}
1689 for example) or unexpected input data. Those raw tags will be
1690 automatically expanded by the iterative back-end parser.
1691
1692 @node Bison style
1693 @subsection Bison style
1694
1695 @cindex grammar bison style
1696 What we call the @dfn{Bison style} is the traditional style of Bison's
1697 grammars. Compared to iterative style, it is not straightforward to
1698 use grammars written in Bison style in @semantic{}. Mainly because such
1699 grammars are designed to parse the whole input data in one pass, and
1700 don't use the iterative parser back-end mechanism (@pxref{Iterative
1701 style}). With Bison style the parser is called once to parse the
1702 grammar start nonterminal.
1703
1704 The following example is a snippet of the Bison style Java grammar
1705 provided in the @semantic{} distribution in the file
1706 @file{semantic/wisent/java.wy}.
1707
1708 @example
1709 @group
1710 %start formal_parameter
1711 @dots{}
1712
1713 formal_parameter_list
1714 : formal_parameter_list COMMA formal_parameter
1715 (cons $3 $1)
1716 | formal_parameter
1717 (list $1)
1718 ;
1719
1720 formal_parameter
1721 : formal_parameter_modifier_opt type variable_declarator_id
1722 (EXPANDTAG
1723 (VARIABLE-TAG $3 $2 :typemodifiers $1)
1724 )
1725 ;
1726 @end group
1727 @end example
1728
1729 The first consequence is that syntax errors are not automatically
1730 handled by @semantic{}. Thus, it is necessary to explicitly handle
1731 them at the grammar level, providing error recovery rules to skip
1732 unexpected input data.
1733
1734 The second consequence is that the iterative parser can't do automatic
1735 tag expansion, except for the start nonterminal value. It is
1736 necessary to explicitly expand tags from concerned semantic actions by
1737 calling the grammar macro @code{EXPANDTAG} with a raw tag as
1738 parameter. See also @ref{Start nonterminals}, for incremental
1739 re-parse considerations.
1740
1741 @node Mixed style
1742 @subsection Mixed style
1743
1744 @cindex grammar mixed style
1745 @example
1746 @group
1747 %start grammar
1748 ;; Reparse
1749 %start prologue epilogue declaration nonterminal rule
1750 @dots{}
1751
1752 %%
1753
1754 grammar:
1755 prologue
1756 | epilogue
1757 | declaration
1758 | nonterminal
1759 | PERCENT_PERCENT
1760 ;
1761 @dots{}
1762
1763 nonterminal:
1764 SYMBOL COLON rules SEMI
1765 (TAG $1 'nonterminal :children $3)
1766 ;
1767
1768 rules:
1769 lifo_rules
1770 (apply 'nconc (nreverse $1))
1771 ;
1772
1773 lifo_rules:
1774 lifo_rules OR rule
1775 (cons $3 $1)
1776 | rule
1777 (list $1)
1778 ;
1779
1780 rule:
1781 rhs
1782 (let* ((rhs $1)
1783 name type comps prec action elt)
1784 @dots{}
1785 (EXPANDTAG
1786 (TAG name 'rule :type type :value comps :prec prec :expr action)
1787 ))
1788 ;
1789 @end group
1790 @end example
1791
1792 This example shows how iterative and Bison styles can be combined in
1793 the same grammar to obtain a good compromise between grammar
1794 complexity and an efficient parsing strategy in an interactive
1795 environment.
1796
1797 @samp{nonterminal} is parsed using iterative style via the main
1798 @samp{grammar} rule. The semantic action uses the @code{TAG} macro to
1799 produce a raw tag, automagically expanded by @semantic{}.
1800
1801 But @samp{rules} part is parsed in Bison style! Why?
1802
1803 Rule delimiters are the colon (@code{:}), that follows the nonterminal
1804 name, and a final semicolon (@code{;}). Unfortunately these
1805 delimiters are not @code{open-paren}/@code{close-paren} type, and the
1806 Emacs' syntactic analyzer can't easily isolate data between them to
1807 produce a @samp{RULES_PART} parenthesis-block-like lexical token.
1808 Consequently it is not possible to use @code{EXPANDFULL} to iterate in
1809 @samp{RULES_PART}, like this:
1810
1811 @example
1812 @group
1813 nonterminal:
1814 SYMBOL COLON rules SEMI
1815 (TAG $1 'nonterminal :children $3)
1816 ;
1817
1818 rules:
1819 RULES_PART ;; @strong{Map a parenthesis-block-like lexical token}
1820 (EXPANDFULL $1 'rules)
1821 ;
1822
1823 rules:
1824 COLON
1825 ()
1826 OR
1827 ()
1828 SEMI
1829 ()
1830 rhs
1831 rhs
1832 (let* ((rhs $1)
1833 name type comps prec action elt)
1834 @dots{}
1835 (TAG name 'rule :type type :value comps :prec prec :expr action)
1836 )
1837 ;
1838 @end group
1839 @end example
1840
1841 In such cases, when it is difficult for Emacs to obtain
1842 parenthesis-block-like lexical tokens, the best solution is to use the
1843 traditional Bison style with error recovery!
1844
1845 In some extreme cases, it can also be convenient to extend the lexer,
1846 to deliver new lexical tokens, to simplify the grammar.
1847
1848 @node Start nonterminals
1849 @subsection Start nonterminals
1850
1851 @cindex start nonterminals
1852 @cindex @code{reparse-symbol} property
1853 When you write a grammar for @semantic{}, it is important to carefully
1854 indicate the start nonterminals. Each one defines an entry point in
1855 the grammar, and after parsing its semantic value is returned to the
1856 back-end iterative engine. Consequently:
1857
1858 @strong{The semantic value of a start nonterminal must be a produced
1859 by a TAG like grammar macro}.
1860
1861 Start nonterminals are declared by @code{%start} statements. When
1862 nothing is specified the first nonterminal that appears in the grammar
1863 is the start nonterminal.
1864
1865 Generally, the following nonterminals must be declared as start
1866 symbols:
1867
1868 @itemize @bullet
1869 @item The main grammar entry point
1870 @quotation
1871 Of course!
1872 @end quotation
1873
1874 @item nonterminals passed to @code{EXPAND}/@code{EXPANDFULL}
1875 @quotation
1876 These grammar macros recursively parse a part of input data, based on
1877 rules of the given nonterminal.
1878
1879 For example, the following will parse @samp{PAREN_BLOCK} data using
1880 the @samp{formal_parameters} rules:
1881
1882 @example
1883 @group
1884 formal_parameter_list
1885 : PAREN_BLOCK
1886 (EXPANDFULL $1 formal_parameters)
1887 ;
1888 @end group
1889 @end example
1890
1891 The semantic value of @samp{formal_parameters} becomes the value of
1892 the @code{EXPANDFULL} expression. It is a list of @semantic{} tags
1893 spliced in the tags tree.
1894
1895 Because the automaton must know that @samp{formal_parameters} is a
1896 start symbol, you must declare it like this:
1897
1898 @example
1899 @group
1900 %start formal_parameters
1901 @end group
1902 @end example
1903 @end quotation
1904 @end itemize
1905
1906 @cindex incremental re-parse
1907 @cindex reparse-symbol
1908 The @code{EXPANDFULL} macro has a side effect it is important to know,
1909 related to the incremental re-parse mechanism of @semantic{}: the
1910 nonterminal symbol parameter passed to @code{EXPANDFULL} also becomes
1911 the @code{reparse-symbol} property of the tag returned by the
1912 @code{EXPANDFULL} expression.
1913
1914 When buffer's data mapped by a tag is modified, @semantic{}
1915 schedules an incremental re-parse of that data, using the tag's
1916 @code{reparse-symbol} property as start nonterminal.
1917
1918 @strong{The rules associated to such start symbols must be carefully
1919 reviewed to ensure that the incremental parser will work!}
1920
1921 Things are a little bit different when the grammar is written in Bison
1922 style.
1923
1924 @strong{The @code{reparse-symbol} property is set to the nonterminal
1925 symbol the rule that explicitly uses @code{EXPANDTAG} belongs to.}
1926
1927 For example:
1928
1929 @example
1930 @group
1931 rule:
1932 rhs
1933 (let* ((rhs $1)
1934 name type comps prec action elt)
1935 @dots{}
1936 (EXPANDTAG
1937 (TAG name 'rule :type type :value comps :prec prec :expr action)
1938 ))
1939 ;
1940 @end group
1941 @end example
1942
1943 Set the @code{reparse-symbol} property of the expanded tag to
1944 @samp{rule}. A important consequence is that:
1945
1946 @strong{Every nonterminal having any rule that calls @code{EXPANDTAG}
1947 in a semantic action, should be declared as a start symbol!}
1948
1949 @node Useful functions
1950 @subsection Useful functions
1951
1952 Here is a description of some predefined functions it might be useful
1953 to know when writing new code to use Wisent in @semantic{}:
1954
1955 @findex wisent-collect-unmatched-syntax
1956 @defun wisent-collect-unmatched-syntax input
1957 Add @var{input} lexical token to the cache of unmatched tokens, in
1958 variable @code{semantic-unmatched-syntax-cache}.
1959
1960 See implementation of the function @code{wisent-skip-token} in
1961 @ref{Error recovery}, for an example of use.
1962 @end defun
1963
1964 @node Wisent Lex
1965 @section The Wisent Lex lexer
1966
1967 @findex semantic-lex
1968 The lexical analysis step of @semantic{} is performed by the general
1969 function @code{semantic-lex}. For more information, @inforef{Writing
1970 Lexers, ,semantic-langdev}.
1971
1972 @code{semantic-lex} produces lexical tokens of the form:
1973
1974 @example
1975 @group
1976 @code{(@var{token-class start} . @var{end})}
1977 @end group
1978 @end example
1979
1980 @table @var
1981 @item token-class
1982 Is a symbol that identifies a lexical token class, like @code{symbol},
1983 @code{string}, @code{number}, or @code{PAREN_BLOCK}.
1984
1985 @item start
1986 @itemx end
1987 Are the start and end positions of mapped data in the input buffer.
1988 @end table
1989
1990 The Wisent's parser doesn't depend on the nature of analyzed input
1991 stream (buffer, string, etc.), and requires that lexical tokens have a
1992 different form (@pxref{Writing a lexer}):
1993
1994 @example
1995 @group
1996 @code{(@var{token-class value} [@var{start} . @var{end}])}
1997 @end group
1998 @end example
1999
2000 @cindex lexical token mapping
2001 @code{wisent-lex} is the default Wisent's lexer used in @semantic{}.
2002
2003 @vindex wisent-lex-istream
2004 @findex wisent-lex
2005 @defun wisent-lex
2006 Return the next available lexical token in Wisent's form.
2007
2008 The variable @code{wisent-lex-istream} contains the list of lexical
2009 tokens produced by @code{semantic-lex}. Pop the next token available
2010 and convert it to a form suitable for the Wisent's parser.
2011 @end defun
2012
2013 Mapping of lexical tokens as produced by @code{semantic-lex} into
2014 equivalent Wisent lexical tokens is straightforward:
2015
2016 @example
2017 @group
2018 (@var{token-class start} . @var{end})
2019 @result{} (@var{token-class value start} . @var{end})
2020 @end group
2021 @end example
2022
2023 @var{value} is the input @code{buffer-substring} from @var{start} to
2024 @var{end}.
2025
2026 @node GNU Free Documentation License
2027 @appendix GNU Free Documentation License
2028
2029 @include doclicense.texi
2030
2031 @node Index
2032 @unnumbered Index
2033 @printindex cp
2034
2035 @iftex
2036 @contents
2037 @summarycontents
2038 @end iftex
2039
2040 @bye
2041
2042 @c Following comments are for the benefit of ispell.
2043
2044 @c LocalWords: Wisent automagically wisent Wisent's LALR obarray