This is wisent.info, produced by makeinfo version 4.3 from wisent.texi. This manual documents the Wisent parser generator. Copyright (C) 2001, 2002, 2003, 2004, 2007 David Ponce Some texts are borrowed or adapted from the manual of Bison version 1.35. The text in section entitled "Understanding the automaton" is adapted from the section "Understanding Your Parser" in the manual of Bison version 1.49. Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1995, 1998, 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with the Invariant Sections being list their titles, with the Front-Cover Texts being list, and with the Back-Cover Texts being list. A copy of the license is included in the section entitled "GNU Free Documentation License". INFO-DIR-SECTION Emacs START-INFO-DIR-ENTRY * Semantic Wisent parser development: (wisent). END-INFO-DIR-ENTRY This file documents Application Development with Semantic. _Infrastructure for parser based text analysis in Emacs_ Copyright (C) 2001, 2002, 2003, 2004 Eric M. Ludlam, David Ponce, and Richard Y. Kim  File: wisent.info, Node: Top, Next: Wisent Overview, Up: (dir) Wisent Parser Development ************************* Wisent (the European Bison ;-) is an Emacs Lisp implementation of the GNU Compiler Compiler Bison. This manual describes how to use Wisent to develop grammars for programming languages, and how to use grammars to parse language source in Emacs buffers. It also describes how Wisent is used with the semantic tool set described in the *Note Semantic Manual: (semantic)Top. * Menu: * Wisent Overview:: * Wisent Grammar:: * Wisent Parsing:: * Wisent Semantic:: * GNU Free Documentation License:: * Index::  File: wisent.info, Node: Wisent Overview, Next: Wisent Grammar, Prev: Top, Up: Top Wisent Overview *************** "Wisent" (the European Bison) is an implementation in Emacs Lisp of the GNU Compiler Compiler Bison. Its code is a port of the C code of GNU Bison 1.28 & 1.31. For more details on the basic concepts for understanding Wisent, it is worthwhile to read the *Note Bison Manual: Top. Wisent can generate compilers compatible with the semantic tool set. See the *Note Semantic Manual: (semantic)Top. It benefits from these Bison features: * It uses a fast but not so space-efficient encoding for the parse tables, described in Corbett's PhD thesis from Berkeley: `Static Semantics in Compiler Error Recovery' June 1985, Report No. UCB/CSD 85/251. * For generating the lookahead sets, Wisent uses the well-known technique of F. DeRemer and A. Pennello they described in: `Efficient Construction of LALR(1) Lookahead Sets' October 1982, ACM TOPLS Vol 4 No 4. * Wisent resolves shift/reduce conflicts using operator precedence and associativity. * Parser error recovery is accomplished using rules which match the special token `error'. Nevertheless there are some fundamental differences between Bison and Wisent. * Wisent is intended to be used in Emacs. It reads and produces Emacs Lisp data structures. All the additional code used in grammars is Emacs Lisp code. * Contrary to Bison, Wisent does not generate a parser which combines Emacs Lisp code and grammar constructs. They exist separately. Wisent reads the grammar from a Lisp data structure and then generates grammar constructs as tables. Afterward, the derived tables can be included and byte-compiled in separate Emacs Lisp files, and be used at a later time by the Wisent's parser engine. * Wisent allows multiple start nonterminals and allows a call to the parsing function to be made for a particular start nonterminal. For example, this is particularly useful to parse a region of an Emacs buffer. semantic heavily depends on the availability of this feature.  File: wisent.info, Node: Wisent Grammar, Next: Wisent Parsing, Prev: Wisent Overview, Up: Top Wisent Grammar ************** In order for Wisent to parse a language, it must be described by a "context-free grammar". That is a grammar specified as rules that can be applied regardless of context. For more information, see *Note Language and Grammar: (bison)Language and Grammar, in the Bison manual. The formal grammar is formulated using "terminal" and "nonterminal" items. Terminals can be Emacs Lisp symbols or characters, and nonterminals are symbols only. Terminals (also known as "tokens") represent the lexical elements of the language like numbers, strings, etc.. For example `PLUS' can represent the operator `+'. Nonterminal symbols are described by rules: RESULT == COMPONENTS... `RESULT' is a nonterminal that this rule describes and `COMPONENTS' are various terminals and nonterminals that are put together by this rule. For example, this rule: exp == exp PLUS exp Says that two groupings of type `exp', with a `PLUS' token in between, can be combined into a larger grouping of type `exp'. * Menu: * Grammar format:: * Example:: * Compiling a grammar:: * Conflicts::  File: wisent.info, Node: Grammar format, Next: Example, Prev: Wisent Grammar, Up: Wisent Grammar Grammar format ============== To be acceptable by Wisent a context-free grammar must respect a particular format. That is, must be represented as an Emacs Lisp list of the form: `(TERMINALS ASSOCS . NON-TERMINALS)' TERMINALS Is the list of terminal symbols used in the grammar. ASSOCS Specify the associativity of TERMINALS. It is `nil' when there is no associativity defined, or an alist of `(ASSOC-TYPE . ASSOC-VALUE)' elements. ASSOC-TYPE must be one of the `default-prec', `nonassoc', `left' or `right' symbols. When ASSOC-TYPE is `default-prec', ASSOC-VALUE must be `nil' or `t' (the default). Otherwise it is a list of tokens which must have been previously declared in TERMINALS. For details, see *Note Contextual Precedence: (bison)Contextual Precedence, in the Bison manual. NON-TERMINALS Is the list of nonterminal definitions. Each definition has the form: `(NONTERM . RULES)' Where NONTERM is the nonterminal symbol defined and RULES the list of rules that describe this nonterminal. Each rule is a list: `(COMPONENTS [PRECEDENCE] [ACTION])' Where: COMPONENTS Is a list of various terminals and nonterminals that are put together by this rule. For example, (exp ((exp ?+ exp)) ;; exp: exp '+' exp ) ;; ; Says that two groupings of type `exp', with a `+' token in between, can be combined into a larger grouping of type `exp'. By convention, a nonterminal symbol should be in lower case, such as `exp', `stmt' or `declaration'. Terminal symbols should be upper case to distinguish them from nonterminals: for example, `INTEGER', `IDENTIFIER', `IF' or `RETURN'. A terminal symbol that represents a particular keyword in the language is conventionally the same as that keyword converted to upper case. The terminal symbol `error' is reserved for error recovery. Scattered among the components can be "middle-rule" actions. Usually only ACTION is provided (*note action::). If COMPONENTS in a rule is `nil', it means that the rule can match the empty string. For example, here is how to define a comma-separated sequence of zero or more `exp' groupings: (expseq (nil) ;; expseq: ;; empty ((expseq1)) ;; | expseq1 ) ;; ; (expseq1 ((exp)) ;; expseq1: exp ((expseq1 ?, exp)) ;; | expseq1 ',' exp ) ;; ; PRECEDENCE Assign the rule the precedence of the given terminal item, overriding the precedence that would be deduced for it, that is the one of the last terminal in it. Notice that only terminals declared in ASSOCS have a precedence level. The altered rule precedence then affects how conflicts involving that rule are resolved. PRECEDENCE is an optional vector of one terminal item. Here is how PRECEDENCE solves the problem of unary minus. First, declare a precedence for a fictitious terminal symbol named `UMINUS'. There are no tokens of this type, but the symbol serves to stand for its precedence: ... ((default-prec t) ;; This is the default (left '+' '-') (left '*') (left UMINUS)) Now the precedence of `UMINUS' can be used in specific rules: (exp ... ;; exp: ... ((exp ?- exp)) ;; | exp '-' exp ... ;; ... ((?- exp) [UMINUS]) ;; | '-' exp %prec UMINUS ... ;; ... ) ;; ; If you forget to append `[UMINUS]' to the rule for unary minus, Wisent silently assumes that minus has its usual precedence. This kind of problem can be tricky to debug, since one typically discovers the mistake only by testing the code. Using `(default-prec nil)' declaration makes it easier to discover this kind of problem systematically. It causes rules that lack a PRECEDENCE modifier to have no precedence, even if the last terminal symbol mentioned in their components has a declared precedence. If `(default-prec nil)' is in effect, you must specify PRECEDENCE for all rules that participate in precedence conflict resolution. Then you will see any shift/reduce conflict until you tell Wisent how to resolve it, either by changing your grammar or by adding an explicit precedence. This will probably add declarations to the grammar, but it helps to protect against incorrect rule precedences. The effect of `(default-prec nil)' can be reversed by giving `(default-prec t)', which is the default. For more details, see *Note Contextual Precedence: (bison)Contextual Precedence, in the Bison manual. It is important to understand that ASSOCS declarations defines associativity but also assign a precedence level to terminals. All terminals declared in the same `left', `right' or `nonassoc' association get the same precedence level. The precedence level is increased at each new association. On the other hand, PRECEDENCE explicitly assign the precedence level of the given terminal to a rule. ACTION An action is an optional Emacs Lisp function call, like this: `(identity $1)' The result of an action determines the semantic value of a rule. From an implementation standpoint, the function call will be embedded in a lambda expression, and several useful local variables will be defined: `$N' Where N is a positive integer. Like in Bison, the value of `$N' is the semantic value of the Nth element of COMPONENTS, starting from 1. It can be of any Lisp data type. `$regionN' Where N is a positive integer. For each `$N' variable defined there is a corresponding `$regionN' variable. Its value is a pair `(START-POS . END-POS)' that represent the start and end positions (in the lexical input stream) of the `$N' value. It can be `nil' when the component positions are not available, like for an empty string component for example. `$region' Its value is the leftmost and rightmost positions of input data matched by all COMPONENTS in the rule. This is a pair `(LEFTMOST-POS . RIGHTMOST-POS)'. It can be `nil' when components positions are not available. `$nterm' This variable is initialized with the nonterminal symbol (NONTERM) the rule belongs to. It could be useful to improve error reporting or debugging. It is also used to automatically provide incremental re-parse entry points for semantic tags (*note Wisent Semantic::). `$action' The value of `$action' is the symbolic name of the current semantic action (*note Debugging actions::). When an action is not specified a default value is supplied, it is `(identity $1)'. This means that the default semantic value of a rule is the value of its first component. Excepted for a rule matching the empty string, for which the default action is to return `nil'.  File: wisent.info, Node: Example, Next: Compiling a grammar, Prev: Grammar format, Up: Wisent Grammar Example ======= Here is an example to parse simple infix arithmetic expressions. See *Note Infix Calc: (bison)Infix Calc, in the Bison manual for details. '( ;; Terminals (NUM) ;; Terminal associativity & precedence ((nonassoc ?=) (left ?- ?+) (left ?* ?/) (left NEG) (right ?^)) ;; Rules (input ((line)) ((input line) (format "%s %s" $1 $2)) ) (line ((?;) (progn ";")) ((exp ?;) (format "%s;" $1)) ((error ?;) (progn "Error;"))) ) (exp ((NUM) (string-to-number $1)) ((exp ?= exp) (= $1 $3)) ((exp ?+ exp) (+ $1 $3)) ((exp ?- exp) (- $1 $3)) ((exp ?* exp) (* $1 $3)) ((exp ?/ exp) (/ $1 $3)) ((?- exp) [NEG] (- $2)) ((exp ?^ exp) (expt $1 $3)) ((?\( exp ?\)) (progn $2)) ) ) In the bison-like "WY" format (*note Wisent Semantic::) the grammar looks like this: %token NUM %nonassoc '=' ;; comparison %left '-' '+' %left '*' '/' %left NEG ;; negation--unary minus %right '^' ;; exponentiation %% input: line | input line (format "%s %s" $1 $2) ; line: ';' {";"} | exp ';' (format "%s;" $1) | error ';' {"Error;"} ; exp: NUM (string-to-number $1) | exp '=' exp (= $1 $3) | exp '+' exp (+ $1 $3) | exp '-' exp (- $1 $3) | exp '*' exp (* $1 $3) | exp '/' exp (/ $1 $3) | '-' exp %prec NEG (- $2) | exp '^' exp (expt $1 $3) | '(' exp ')' {$2} ; %%  File: wisent.info, Node: Compiling a grammar, Next: Conflicts, Prev: Example, Up: Wisent Grammar Compiling a grammar =================== After providing a context-free grammar in a suitable format, it must be translated into a set of tables (an "automaton") that will be used to derive the parser. Like Bison, Wisent translates grammars that must be "LALR(1)". A grammar is LALR(1) if it is possible to tell how to parse any portion of an input string with just a single token of look-ahead: the "look-ahead token". See *Note Language and Grammar: (bison)Language and Grammar, in the Bison manual for more information. Grammar translation (compilation) is achieved by the function: - Function: wisent-compile-grammar grammar &optional start-list Compile GRAMMAR and return an LALR(1) automaton. Optional argument START-LIST is a list of start symbols (nonterminals). If `nil' the first nonterminal defined in the grammar is the default start symbol. If START-LIST contains only one element, it defines the start symbol. If START-LIST contains more than one element, all are defined as potential start symbols, unless `wisent-single-start-flag' is non-`nil'. In that case the first element of START-LIST defines the start symbol and others are ignored. The LALR(1) automaton is a vector of the form: `[ACTIONS GOTOS STARTS FUNCTIONS]' ACTIONS A state/token matrix telling the parser what to do at every state based on the current look-ahead token. That is shift, reduce, accept or error. See also *Note Wisent Parsing::. GOTOS A state/nonterminal matrix telling the parser the next state to go to after reducing with each rule. STARTS An alist which maps the allowed start symbols (nonterminals) to lexical tokens that will be first shifted into the parser stack. FUNCTIONS An obarray of semantic action symbols. A semantic action is actually an Emacs Lisp function (lambda expression).  File: wisent.info, Node: Conflicts, Prev: Compiling a grammar, Up: Wisent Grammar Conflicts ========= Normally, a grammar should produce an automaton where at each state the parser has only one action to do (*note Wisent Parsing::). In certain cases, a grammar can produce an automaton where, at some states, there are more than one action possible. Such a grammar is "ambiguous", and generates "conflicts". The parser can't be driven by an automaton which isn't completely "deterministic", that is which contains conflicts. It is necessary to resolve the conflicts to eliminate them. Wisent resolves conflicts like Bison does. There are two sorts of conflicts: "shift/reduce conflicts" When either a shift or a reduction would be valid at the same state. Such conflicts are resolved by choosing to shift, unless otherwise directed by operator precedence declarations. See *Note Shift/Reduce: (bison)Shift/Reduce, in the Bison manual for more information. "reduce/reduce conflicts" That occurs if there are two or more rules that apply to the same sequence of input. This usually indicates a serious error in the grammar. Such conflicts are resolved by choosing to use the rule that appears first in the grammar, but it is very risky to rely on this. Every reduce/reduce conflict must be studied and usually eliminated. See *Note Reduce/Reduce: (bison)Reduce/Reduce, in the Bison manual for more information. * Menu: * Grammar Debugging:: * Understanding the automaton::  File: wisent.info, Node: Grammar Debugging, Next: Understanding the automaton, Up: Conflicts Grammar debugging ----------------- To help writing a new grammar, `wisent-compile-grammar' can produce a verbose report containing a detailed description of the grammar and parser (equivalent to what Bison reports with the `--verbose' option). To enable the verbose report you can set to non-`nil' the variable: - Option: wisent-verbose-flag non-`nil' means to report verbose information on generated parser. Or interactively use the command: - Command: wisent-toggle-verbose-flag Toggle whether to report verbose information on generated parser. The verbose report is printed in the temporary buffer `*wisent-log*' when running interactively, or in file `wisent.output' when running in batch mode. Different reports are separated from each other by a line like this: *** Wisent SOURCE-FILE - 2002-06-27 17:33 where SOURCE-FILE is the name of the Emacs Lisp file from which the grammar was read. See *Note Understanding the automaton::, for details on the verbose report. *Please Note* To help debugging the grammar compiler itself, you can set this variable to print the content of some internal data structures: - Variable: wisent-debug-flag non-`nil' means enable some debug stuff.  File: wisent.info, Node: Understanding the automaton, Prev: Grammar Debugging, Up: Conflicts Understanding the automaton --------------------------- This section (took from the manual of Bison 1.49) describes how to use the verbose report printed by `wisent-compile-grammar' to understand the generated automaton, to tune or fix a grammar. We will use the following example: (let ((wisent-verbose-flag t)) ;; Print a verbose report! (wisent-compile-grammar '((NUM STR) ; %token NUM STR ((left ?+ ?-) ; %left '+' '-'; (left ?*)) ; %left '*' (exp ; exp: ((exp ?+ exp)) ; exp '+' exp ((exp ?- exp)) ; | exp '-' exp ((exp ?* exp)) ; | exp '*' exp ((exp ?/ exp)) ; | exp '/' exp ((NUM)) ; | NUM ) ; ; (useless ; useless: ((STR)) ; STR ) ; ; ) 'nil) ; no %start declarations ) When evaluating the above expression, grammar compilation first issues the following two clear messages: Grammar contains 1 useless nonterminals and 1 useless rules Grammar contains 7 shift/reduce conflicts The `*wisent-log*' buffer details things! The first section reports conflicts that were solved using precedence and/or associativity: Conflict in state 7 between rule 1 and token '+' resolved as reduce. Conflict in state 7 between rule 1 and token '-' resolved as reduce. Conflict in state 7 between rule 1 and token '*' resolved as shift. Conflict in state 8 between rule 2 and token '+' resolved as reduce. Conflict in state 8 between rule 2 and token '-' resolved as reduce. Conflict in state 8 between rule 2 and token '*' resolved as shift. Conflict in state 9 between rule 3 and token '+' resolved as reduce. Conflict in state 9 between rule 3 and token '-' resolved as reduce. Conflict in state 9 between rule 3 and token '*' resolved as reduce. The next section reports useless tokens, nonterminal and rules (note that useless tokens might be used by the scanner): Useless nonterminals: useless Terminals which are not used: STR Useless rules: #6 useless: STR; The next section lists states that still have conflicts: State 7 contains 1 shift/reduce conflict. State 8 contains 1 shift/reduce conflict. State 9 contains 1 shift/reduce conflict. State 10 contains 4 shift/reduce conflicts. The next section reproduces the grammar used: Grammar Number, Rule 1 exp -> exp '+' exp 2 exp -> exp '-' exp 3 exp -> exp '*' exp 4 exp -> exp '/' exp 5 exp -> NUM And reports the uses of the symbols: Terminals, with rules where they appear $EOI (-1) error (1) NUM (2) 5 STR (3) 6 '+' (4) 1 '-' (5) 2 '*' (6) 3 '/' (7) 4 Nonterminals, with rules where they appear exp (8) on left: 1 2 3 4 5, on right: 1 2 3 4 The report then details the automaton itself, describing each state with it set of "items", also known as "pointed rules". Each item is a production rule together with a point (marked by `.') that the input cursor. state 0 NUM shift, and go to state 1 exp go to state 2 State 0 corresponds to being at the very beginning of the parsing, in the initial rule, right before the start symbol (`exp'). When the parser returns to this state right after having reduced a rule that produced an `exp', it jumps to state 2. If there is no such transition on a nonterminal symbol, and the lookahead is a `NUM', then this token is shifted on the parse stack, and the control flow jumps to state 1. Any other lookahead triggers a parse error. In the state 1... state 1 exp -> NUM . (rule 5) $default reduce using rule 5 (exp) the rule 5, `exp: NUM;', is completed. Whatever the lookahead (`$default'), the parser will reduce it. If it was coming from state 0, then, after this reduction it will return to state 0, and will jump to state 2 (`exp: go to state 2'). state 2 exp -> exp . '+' exp (rule 1) exp -> exp . '-' exp (rule 2) exp -> exp . '*' exp (rule 3) exp -> exp . '/' exp (rule 4) $EOI shift, and go to state 11 '+' shift, and go to state 3 '-' shift, and go to state 4 '*' shift, and go to state 5 '/' shift, and go to state 6 In state 2, the automaton can only shift a symbol. For instance, because of the item `exp -> exp . '+' exp', if the lookahead if `+', it will be shifted on the parse stack, and the automaton control will jump to state 3, corresponding to the item `exp -> exp . '+' exp': state 3 exp -> exp '+' . exp (rule 1) NUM shift, and go to state 1 exp go to state 7 Since there is no default action, any other token than those listed above will trigger a parse error. The interpretation of states 4 to 6 is straightforward: state 4 exp -> exp '-' . exp (rule 2) NUM shift, and go to state 1 exp go to state 8 state 5 exp -> exp '*' . exp (rule 3) NUM shift, and go to state 1 exp go to state 9 state 6 exp -> exp '/' . exp (rule 4) NUM shift, and go to state 1 exp go to state 10 As was announced in beginning of the report, `State 7 contains 1 shift/reduce conflict.': state 7 exp -> exp . '+' exp (rule 1) exp -> exp '+' exp . (rule 1) exp -> exp . '-' exp (rule 2) exp -> exp . '*' exp (rule 3) exp -> exp . '/' exp (rule 4) '*' shift, and go to state 5 '/' shift, and go to state 6 '/' [reduce using rule 1 (exp)] $default reduce using rule 1 (exp) Indeed, there are two actions associated to the lookahead `/': either shifting (and going to state 6), or reducing rule 1. The conflict means that either the grammar is ambiguous, or the parser lacks information to make the right decision. Indeed the grammar is ambiguous, as, since we did not specify the precedence of `/', the sentence `NUM + NUM / NUM' can be parsed as `NUM + (NUM / NUM)', which corresponds to shifting `/', or as `(NUM + NUM) / NUM', which corresponds to reducing rule 1. Because in LALR(1) parsing a single decision can be made, Wisent arbitrarily chose to disable the reduction, see *Note Conflicts::. Discarded actions are reported in between square brackets. Note that all the previous states had a single possible action: either shifting the next token and going to the corresponding state, or reducing a single rule. In the other cases, i.e., when shifting _and_ reducing is possible or when _several_ reductions are possible, the lookahead is required to select the action. State 7 is one such state: if the lookahead is `*' or `/' then the action is shifting, otherwise the action is reducing rule 1. In other words, the first two items, corresponding to rule 1, are not eligible when the lookahead is `*', since we specified that `*' has higher precedence that `+'. More generally, some items are eligible only with some set of possible lookaheads. States 8 to 10 are similar: state 8 exp -> exp . '+' exp (rule 1) exp -> exp . '-' exp (rule 2) exp -> exp '-' exp . (rule 2) exp -> exp . '*' exp (rule 3) exp -> exp . '/' exp (rule 4) '*' shift, and go to state 5 '/' shift, and go to state 6 '/' [reduce using rule 2 (exp)] $default reduce using rule 2 (exp) state 9 exp -> exp . '+' exp (rule 1) exp -> exp . '-' exp (rule 2) exp -> exp . '*' exp (rule 3) exp -> exp '*' exp . (rule 3) exp -> exp . '/' exp (rule 4) '/' shift, and go to state 6 '/' [reduce using rule 3 (exp)] $default reduce using rule 3 (exp) state 10 exp -> exp . '+' exp (rule 1) exp -> exp . '-' exp (rule 2) exp -> exp . '*' exp (rule 3) exp -> exp . '/' exp (rule 4) exp -> exp '/' exp . (rule 4) '+' shift, and go to state 3 '-' shift, and go to state 4 '*' shift, and go to state 5 '/' shift, and go to state 6 '+' [reduce using rule 4 (exp)] '-' [reduce using rule 4 (exp)] '*' [reduce using rule 4 (exp)] '/' [reduce using rule 4 (exp)] $default reduce using rule 4 (exp) Observe that state 10 contains conflicts due to the lack of precedence of `/' wrt `+', `-', and `*', but also because the associativity of `/' is not specified. Finally, the state 11 (plus 12) is named the "final state", or the "accepting state": state 11 $EOI shift, and go to state 12 state 12 $default accept The end of input is shifted `$EOI shift,' and the parser exits successfully (`go to state 12', that terminates).  File: wisent.info, Node: Wisent Parsing, Next: Wisent Semantic, Prev: Wisent Grammar, Up: Top Wisent Parsing ************** The Wisent's parser is what is called a "bottom-up" or "shift-reduce" parser which repeatedly: "shift" That is pushes the value of the last lexical token read (the look-ahead token) into a value stack, and reads a new one. "reduce" That is replaces a nonterminal by its semantic value. The values of the components which form the right hand side of a rule are popped from the value stack and reduced by the semantic action of this rule. The result is pushed back on top of value stack. The parser will stop on: "accept" When all input has been successfully parsed. The semantic value of the start nonterminal is on top of the value stack. "error" When a syntax error (an unexpected token in input) has been detected. At this point the parser issues an error message and either stops or calls a recovery routine to try to resume parsing. The above elementary actions are driven by the LALR(1) automaton built by `wisent-compile-grammar' from a context-free grammar. The Wisent's parser is entered by calling the function: - Function: wisent-parse automaton lexer &optional error start Parse input using the automaton specified in AUTOMATON. AUTOMATON Is an LALR(1) automaton generated by `wisent-compile-grammar' (*note Wisent Grammar::). LEXER Is a function with no argument called by the parser to obtain the next terminal (token) in input (*note Writing a lexer::). ERROR Is an optional reporting function called when a parse error occurs. It receives a message string to report. It defaults to the function `wisent-message' (*note Report errors::). START Specify the start symbol (nonterminal) used by the parser as its goal. It defaults to the start symbol defined in the grammar (*note Wisent Grammar::). The following two normal hooks permit to do some useful processing respectively before to start parsing, and after the parser terminated. - Variable: wisent-pre-parse-hook Normal hook run just before entering the LR parser engine. - Variable: wisent-post-parse-hook Normal hook run just after the LR parser engine terminated. * Menu: * Writing a lexer:: * Actions goodies:: * Report errors:: * Error recovery:: * Debugging actions::  File: wisent.info, Node: Writing a lexer, Next: Actions goodies, Up: Wisent Parsing What the parser must receive ============================ It is important to understand that the parser does not parse characters, but lexical tokens, and does not know anything about characters in text streams! Reading input data to produce lexical tokens is performed by a lexer (also called a scanner) in a lexical analysis step, before the syntax analysis step performed by the parser. The parser automatically calls the lexer when it needs the next token to parse. A Wisent's lexer is an Emacs Lisp function with no argument. It must return a valid lexical token of the form: `(TOKEN-CLASS VALUE [START . END])' TOKEN-CLASS Is a category of lexical token identifying a terminal as specified in the grammar (*note Wisent Grammar::). It can be a symbol or a character literal. VALUE Is the value of the lexical token. It can be of any valid Emacs Lisp data type. START END Are the optionals beginning and end positions of VALUE in the input stream. When there are no more tokens to read the lexer must return the token `(list wisent-eoi-term)' to each request. - Variable: wisent-eoi-term Predefined constant, End-Of-Input terminal symbol. `wisent-lex' is an example of a lexer that reads lexical tokens produced by a semantic lexer, and translates them into lexical tokens suitable to the Wisent parser. See also *Note Wisent Lex::. To call the lexer in a semantic action use the function `wisent-lexer'. See also *Note Actions goodies::.  File: wisent.info, Node: Actions goodies, Next: Report errors, Prev: Writing a lexer, Up: Wisent Parsing Variables and macros useful in grammar actions. =============================================== - Variable: wisent-input The last token read. This variable only has meaning in the scope of `wisent-parse'. - Function: wisent-lexer Obtain the next terminal in input. - Function: wisent-region &rest positions Return the start/end positions of the region including POSITIONS. Each element of POSITIONS is a pair `(START-POS . END-POS)' or `nil'. The returned value is the pair `(MIN-START-POS . MAX-END-POS)' or `nil' if no POSITIONS are available.  File: wisent.info, Node: Report errors, Next: Error recovery, Prev: Actions goodies, Up: Wisent Parsing The error reporting function ============================ When the parser encounters a syntax error it calls a user-defined function. It must be an Emacs Lisp function with one argument: a string containing the message to report. By default the parser uses this function to report error messages: - Function: wisent-message string &rest args Print a one-line message if `wisent-parse-verbose-flag' is set. Pass STRING and ARGS arguments to "message". *Please Note:* `wisent-message' uses the following function to print lexical tokens: - Function: wisent-token-to-string token Return a printed representation of lexical token TOKEN. The general printed form of a lexical token is: `TOKEN(VALUE)@LOCATION' To control the verbosity of the parser you can set to non-`nil' this variable: - Option: wisent-parse-verbose-flag non-`nil' means to issue more messages while parsing. Or interactively use the command: - Command: wisent-parse-toggle-verbose-flag Toggle whether to issue more messages while parsing. When the error reporting function is entered the variable `wisent-input' contains the unexpected token as returned by the lexer. The error reporting function can be called from a semantic action too using the special macro `wisent-error'. When called from a semantic action entered by error recovery (*note Error recovery::) the value of the variable `wisent-recovering' is non-`nil'.  File: wisent.info, Node: Error recovery, Next: Debugging actions, Prev: Report errors, Up: Wisent Parsing Error recovery ============== The error recovery mechanism of the Wisent's parser conforms to the one Bison uses. See *Note Error Recovery: (bison)Error Recovery, in the Bison manual for details. To recover from a syntax error you must write rules to recognize the special token `error'. This is a terminal symbol that is automatically defined and reserved for error handling. When the parser encounters a syntax error, it pops the state stack until it finds a state that allows shifting the `error' token. After it has been shifted, if the old look-ahead token is not acceptable to be shifted next, the parser reads tokens and discards them until it finds a token which is acceptable. Strategies for error recovery depend on the choice of error rules in the grammar. A simple and useful strategy is simply to skip the rest of the current statement if an error is detected: (stmnt (( error ?; )) ;; on error, skip until ';' is read ) It is also useful to recover to the matching close-delimiter of an opening-delimiter that has already been parsed: (primary (( ?{ expr ?} )) (( ?{ error ?} )) ... ) Note that error recovery rules may have actions, just as any other rules can. Here are some predefined hooks, variables, functions or macros, useful in such actions: - Variable: wisent-nerrs The number of parse errors encountered so far. - Variable: wisent-recovering non-`nil' means that the parser is recovering. This variable only has meaning in the scope of `wisent-parse'. - Function: wisent-error msg Call the user supplied error reporting function with message MSG (*note Report errors::). For an example of use, *Note wisent-skip-token::. - Function: wisent-errok Resume generating error messages immediately for subsequent syntax errors. The parser suppress error message for syntax errors that happens shortly after the first, until three consecutive input tokens have been successfully shifted. Calling `wisent-errok' in an action, make error messages resume immediately. No error messages will be suppressed if you call it in an error rule's action. For an example of use, *Note wisent-skip-token::. - Function: wisent-clearin Discard the current lookahead token. This will cause a new lexical token to be read. In an error rule's action the previous lookahead token is reanalyzed immediately. `wisent-clearin' may be called to clear this token. For example, suppose that on a parse error, an error handling routine is called that advances the input stream to some point where parsing should once again commence. The next symbol returned by the lexical scanner is probably correct. The previous lookahead token ought to be discarded with `wisent-clearin'. For an example of use, *Note wisent-skip-token::. - Function: wisent-abort Abort parsing and save the lookahead token. - Function: wisent-set-region start end Change the region of text matched by the current nonterminal. START and END are respectively the beginning and end positions of the region occupied by the group of components associated to this nonterminal. If START or END values are not a valid positions the region is set to `nil'. For an example of use, *Note wisent-skip-token::. - Variable: wisent-discarding-token-functions List of functions to be called when discarding a lexical token. These functions receive the lexical token discarded. When the parser encounters unexpected tokens, it can discards them, based on what directed by error recovery rules. Either when the parser reads tokens until one is found that can be shifted, or when an semantic action calls the function `wisent-skip-token' or `wisent-skip-block'. For language specific hooks, make sure you define this as a local hook. For example, in semantic, this hook is set to the function `wisent-collect-unmatched-syntax' to collect unmatched lexical tokens (*note Useful functions::). - Function: wisent-skip-token Skip the lookahead token in order to resume parsing. Return nil. Must be used in error recovery semantic actions. It typically looks like this: (wisent-message "%s: skip %s" $action (wisent-token-to-string wisent-input)) (run-hook-with-args 'wisent-discarding-token-functions wisent-input) (wisent-clearin) (wisent-errok))) - Function: wisent-skip-block Safely skip a block in order to resume parsing. Return nil. Must be used in error recovery semantic actions. A block is data between an open-delimiter (syntax class `(') and a matching close-delimiter (syntax class `)'): (a parenthesized block) [a block between brackets] {a block between braces} The following example uses `wisent-skip-block' to safely skip a block delimited by `LBRACE' (`{') and `RBRACE' (`}') tokens, when a syntax error occurs in `other-components': (block ((LBRACE other-components RBRACE)) ((LBRACE RBRACE)) ((LBRACE error) (wisent-skip-block)) )  File: wisent.info, Node: Debugging actions, Prev: Error recovery, Up: Wisent Parsing Debugging semantic actions ========================== Each semantic action is represented by a symbol interned in an "obarray" that is part of the LALR(1) automaton (*note Compiling a grammar::). `symbol-function' on a semantic action symbol return the semantic action lambda expression. A semantic action symbol name has the form `NONTERMINAL:INDEX', where NONTERMINAL is the name of the nonterminal symbol the action belongs to, and INDEX is an action sequence number within the scope of NONTERMINAL. For example, this nonterminal definition: input: line [`input:0'] | input line (format "%s %s" $1 $2) [`input:1'] ; Will produce two semantic actions, and associated symbols: `input:0' A default action that returns `$1'. `input:1' That returns `(format "%s %s" $1 $2)'. Debugging uses the Lisp debugger to investigate what is happening during execution of semantic actions. Three commands are available to debug semantic actions. They receive two arguments: * The automaton that contains the semantic action. * The semantic action symbol. - Command: wisent-debug-on-entry automaton function Request AUTOMATON's FUNCTION to invoke debugger each time it is called. FUNCTION must be a semantic action symbol that exists in AUTOMATON. - Command: wisent-cancel-debug-on-entry automaton function Undo effect of `wisent-debug-on-entry' on AUTOMATON's FUNCTION. FUNCTION must be a semantic action symbol that exists in AUTOMATON. - Command: wisent-debug-show-entry automaton function Show the source of AUTOMATON's semantic action FUNCTION. FUNCTION must be a semantic action symbol that exists in AUTOMATON.  File: wisent.info, Node: Wisent Semantic, Next: GNU Free Documentation License, Prev: Wisent Parsing, Up: Top How to use Wisent with Semantic ******************************* This section presents how the Wisent's parser can be used to produce "tags" for the semantic tool set. semantic tags form a hierarchy of Emacs Lisp data structures that describes a program in a way independent of programming languages. Tags map program declarations, like functions, methods, variables, data types, classes, includes, grammar rules, etc.. To use the Wisent parser with semantic you have to define your grammar in "WY" form, a grammar format very close to the one used by Bison. Please *note Semantic Grammar Framework Manual: (grammar-fw)top for more information on semantic grammars. * Menu: * Grammar styles:: * Wisent Lex::  File: wisent.info, Node: Grammar styles, Next: Wisent Lex, Up: Wisent Semantic Grammar styles ============== semantic parsing heavily depends on how you wrote the grammar. There are mainly two styles to write a Wisent's grammar intended to be used with the semantic tool set: the "Iterative style" and the "Bison style". Each one has pros and cons, and in certain cases it can be worth a mix of the two styles! * Menu: * Iterative style:: * Bison style:: * Mixed style:: * Start nonterminals:: * Useful functions::  File: wisent.info, Node: Iterative style, Next: Bison style, Prev: Grammar styles, Up: Grammar styles Iterative style --------------- The "iterative style" is the preferred style to use with semantic. It relies on an iterative parser back-end mechanism which parses start nonterminals one at a time and automagically skips unexpected lexical tokens in input. Compared to rule-based iterative functions (*note Bison style::), iterative parsers are better in that they can handle obscure errors more cleanly. Each start nonterminal must produces a "raw tag" by calling a `TAG'-like grammar macro with appropriate parameters. See also *Note Start nonterminals::. Then, each parsing iteration automatically translates a raw tag into "expanded tags", updating the raw tag structure with internal properties and buffer related data. After parsing completes, it results in a tree of expanded tags. The following example is a snippet of the iterative style Java grammar provided in the semantic distribution in the file `wisent-java-tags.wy'. ... ;; Alternate entry points ;; - Needed by partial re-parse %start formal_parameter ... ;; - Needed by EXPANDFULL clauses %start formal_parameters ... formal_parameter_list : PAREN_BLOCK (EXPANDFULL $1 formal_parameters) ; formal_parameters : LPAREN () | RPAREN () | formal_parameter COMMA | formal_parameter RPAREN ; formal_parameter : formal_parameter_modifier_opt type variable_declarator_id (VARIABLE-TAG $3 $2 nil :typemodifiers $1) ; It shows the use of the `EXPANDFULL' grammar macro to parse a `PAREN_BLOCK' which contains a `formal_parameter_list'. `EXPANDFULL' tells to recursively parse `formal_parameters' inside `PAREN_BLOCK'. The parser iterates until it digested all available input data inside the `PAREN_BLOCK', trying to match any of the `formal_parameters' rules: * `LPAREN' * `RPAREN' * `formal_parameter COMMA' * `formal_parameter RPAREN' At each iteration it will return a `formal_parameter' raw tag, or `nil' to skip unwanted (single `LPAREN' or `RPAREN' for example) or unexpected input data. Those raw tags will be automatically expanded by the iterative back-end parser.  File: wisent.info, Node: Bison style, Next: Mixed style, Prev: Iterative style, Up: Grammar styles Bison style ----------- What we call the "Bison style" is the traditional style of Bison's grammars. Compared to iterative style, it is not straightforward to use grammars written in Bison style in semantic. Mainly because such grammars are designed to parse the whole input data in one pass, and don't use the iterative parser back-end mechanism (*note Iterative style::). With Bison style the parser is called once to parse the grammar start nonterminal. The following example is a snippet of the Bison style Java grammar provided in the semantic distribution in the file `wisent-java.wy'. %start formal_parameter ... formal_parameter_list : formal_parameter_list COMMA formal_parameter (cons $3 $1) | formal_parameter (list $1) ; formal_parameter : formal_parameter_modifier_opt type variable_declarator_id (EXPANDTAG (VARIABLE-TAG $3 $2 :typemodifiers $1) ) ; The first consequence is that syntax errors are not automatically handled by semantic. Thus, it is necessary to explicitly handle them at the grammar level, providing error recovery rules to skip unexpected input data. The second consequence is that the iterative parser can't do automatic tag expansion, except for the start nonterminal value. It is necessary to explicitly expand tags from concerned semantic actions by calling the grammar macro `EXPANDTAG' with a raw tag as parameter. See also *Note Start nonterminals::, for incremental re-parse considerations.