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