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