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