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