1 ;;; semantic/wisent/wisent.el --- GNU Bison for Emacs - Runtime
3 ;;; Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2009
4 ;;; Free Software Foundation, Inc.
6 ;; Author: David Ponce <david@dponce.com>
7 ;; Maintainer: David Ponce <david@dponce.com>
8 ;; Created: 30 January 2002
10 ;; X-RCS: $Id: wisent.el,v 1.39 2009/01/10 00:15:49 zappo Exp $
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Parser engine and runtime of Wisent.
31 ;; Wisent (the European Bison ;-) is an Elisp implementation of the
32 ;; GNU Compiler Compiler Bison. The Elisp code is a port of the C
33 ;; code of GNU Bison 1.28 & 1.31.
35 ;; For more details on the basic concepts for understanding Wisent,
36 ;; read the Bison manual ;)
38 ;; For more details on Wisent itself read the Wisent manual.
47 /\\_.-^^^-._/\\ The GNU
49 ( `o ` (European ;-) Bison
63 (if (fboundp 'char-valid-p
)
64 (defalias 'wisent-char-p
'char-valid-p
)
65 (defalias 'wisent-char-p
'char-or-char-int-p
)))
67 ;;; Printed representation of terminals and nonterminals
68 (defconst wisent-escape-sequence-strings
71 (?
\b .
"'\\b'") ; backspace, BS, C-h
72 (?
\t .
"'\\t'") ; tab, TAB, C-i
73 (?
\n .
"'\\n'") ; newline, C-j
74 (?
\v .
"'\\v'") ; vertical tab, C-k
75 (?
\f .
"'\\f'") ; formfeed character, C-l
76 (?
\r .
"'\\r'") ; carriage return, RET, C-m
77 (?\e .
"'\\e'") ; escape character, ESC, C-[
78 (?
\\ .
"'\\'") ; backslash character, \
79 (?\d .
"'\\d'") ; delete character, DEL
81 "Printed representation of usual escape sequences.")
83 (defsubst wisent-item-to-string
(item)
84 "Return a printed representation of ITEM.
85 ITEM can be a nonterminal or terminal symbol, or a character literal."
86 (if (wisent-char-p item
)
87 (or (cdr (assq item wisent-escape-sequence-strings
))
91 (defsubst wisent-token-to-string
(token)
92 "Return a printed representation of lexical token TOKEN."
93 (format "%s%s(%S)" (wisent-item-to-string (car token
))
94 (if (nth 2 token
) (format "@%s" (nth 2 token
)) "")
98 (defconst wisent-eoi-term
'$EOI
99 "End Of Input token.")
101 (defconst wisent-error-term
'error
102 "Error recovery token.")
104 (defconst wisent-accept-tag
'accept
105 "Accept result after input successfully parsed.")
107 (defconst wisent-error-tag
'error
108 "Process a syntax error.")
110 ;;; Special functions
111 (defun wisent-automaton-p (obj)
112 "Return non-nil if OBJ is a LALR automaton.
113 If OBJ is a symbol check its value."
114 (and obj
(symbolp obj
) (boundp obj
)
115 (setq obj
(symbol-value obj
)))
116 (and (vectorp obj
) (= 4 (length obj
))
117 (vectorp (aref obj
0)) (vectorp (aref obj
1))
118 (= (length (aref obj
0)) (length (aref obj
1)))
119 (listp (aref obj
2)) (vectorp (aref obj
3))))
121 (defsubst wisent-region
(&rest positions
)
122 "Return the start/end positions of the region including POSITIONS.
123 Each element of POSITIONS is a pair (START-POS . END-POS) or nil. The
124 returned value is the pair (MIN-START-POS . MAX-END-POS) or nil if no
125 POSITIONS are available."
126 (let ((pl (delq nil positions
)))
128 (cons (apply #'min
(mapcar #'car pl
))
129 (apply #'max
(mapcar #'cdr pl
))))))
132 (defvar wisent-parse-verbose-flag nil
133 "*Non-nil means to issue more messages while parsing.")
135 (defun wisent-parse-toggle-verbose-flag ()
136 "Toggle whether to issue more messages while parsing."
138 (setq wisent-parse-verbose-flag
(not wisent-parse-verbose-flag
))
139 (when (interactive-p)
140 (message "More messages while parsing %sabled"
141 (if wisent-parse-verbose-flag
"en" "dis"))))
143 (defsubst wisent-message
(string &rest args
)
144 "Print a one-line message if `wisent-parse-verbose-flag' is set.
145 Pass STRING and ARGS arguments to `message'."
146 (and wisent-parse-verbose-flag
147 (apply 'message string args
)))
149 ;;;; --------------------
150 ;;;; The LR parser engine
151 ;;;; --------------------
153 (defcustom wisent-parse-max-stack-size
500
154 "The parser stack size."
158 (defcustom wisent-parse-max-recover
3
159 "Number of tokens to shift before turning off error status."
163 (defvar wisent-discarding-token-functions nil
164 "List of functions to be called when discarding a lexical token.
165 These functions receive the lexical token discarded.
166 When the parser encounters unexpected tokens, it can discards them,
167 based on what directed by error recovery rules. Either when the
168 parser reads tokens until one is found that can be shifted, or when an
169 semantic action calls the function `wisent-skip-token' or
171 For language specific hooks, make sure you define this as a local
174 (defvar wisent-pre-parse-hook nil
175 "Normal hook run just before entering the LR parser engine.")
177 (defvar wisent-post-parse-hook nil
178 "Normal hook run just after the LR parser engine terminated.")
180 (defvar wisent-loop nil
181 "The current parser action.
182 Stop parsing when set to nil.
183 This variable only has meaning in the scope of `wisent-parse'.")
185 (defvar wisent-nerrs nil
186 "The number of parse errors encountered so far.")
188 (defvar wisent-lookahead nil
189 "The lookahead lexical token.
190 This value is non-nil if the parser terminated because of an
191 unrecoverable error.")
193 ;; Variables and macros that are useful in semantic actions.
194 (defvar wisent-parse-lexer-function nil
195 "The user supplied lexer function.
196 This function don't have arguments.
197 This variable only has meaning in the scope of `wisent-parse'.")
199 (defvar wisent-parse-error-function nil
200 "The user supplied error function.
201 This function must accept one argument, a message string.
202 This variable only has meaning in the scope of `wisent-parse'.")
204 (defvar wisent-input nil
205 "The last token read.
206 This variable only has meaning in the scope of `wisent-parse'.")
208 (defvar wisent-recovering nil
209 "Non-nil means that the parser is recovering.
210 This variable only has meaning in the scope of `wisent-parse'.")
212 ;; Variables that only have meaning in the scope of a semantic action.
213 ;; These global definitions avoid byte-compiler warnings.
218 (defmacro wisent-lexer
()
219 "Obtain the next terminal in input."
220 '(funcall wisent-parse-lexer-function
))
222 (defmacro wisent-error
(msg)
223 "Call the user supplied error reporting function with message MSG."
224 `(funcall wisent-parse-error-function
,msg
))
226 (defmacro wisent-errok
()
227 "Resume generating error messages immediately for subsequent syntax errors.
228 This is useful primarily in error recovery semantic actions."
229 '(setq wisent-recovering nil
))
231 (defmacro wisent-clearin
()
232 "Discard the current lookahead token.
233 This will cause a new lexical token to be read.
234 This is useful primarily in error recovery semantic actions."
235 '(setq wisent-input nil
))
237 (defmacro wisent-abort
()
238 "Abort parsing and save the lookahead token.
239 This is useful primarily in error recovery semantic actions."
240 '(setq wisent-lookahead wisent-input
243 (defmacro wisent-set-region
(start end
)
244 "Change the region of text matched by the current nonterminal.
245 START and END are respectively the beginning and end positions of the
246 region. If START or END values are not a valid positions the region
248 `(setq $region
(and (number-or-marker-p ,start
)
249 (number-or-marker-p ,end
)
250 (cons ,start
,end
))))
252 (defun wisent-skip-token ()
253 "Skip the lookahead token in order to resume parsing.
255 Must be used in error recovery semantic actions."
256 (if (eq (car wisent-input
) wisent-eoi-term
)
257 ;; Does nothing at EOI to avoid infinite recovery loop.
259 (wisent-message "%s: skip %s" $action
260 (wisent-token-to-string wisent-input
))
262 'wisent-discarding-token-functions wisent-input
)
266 (defun wisent-skip-block (&optional bounds
)
267 "Safely skip a parenthesized block in order to resume parsing.
269 Must be used in error recovery semantic actions.
270 Optional argument BOUNDS is a pair (START . END) which indicates where
271 the parenthesized block starts. Typically the value of a `$regionN'
272 variable, where `N' is the the Nth element of the current rule
273 components that match the block beginning. It defaults to the value
274 of the `$region' variable."
275 (let ((start (car (or bounds $region
)))
277 (if (not (number-or-marker-p start
))
278 ;; No nonterminal region available, skip the lookahead token.
280 ;; Try to skip a block.
281 (if (not (setq end
(save-excursion
283 (and (looking-at "\\s(")
285 (1- (scan-lists (point) 1 0))
287 ;; Not actually a block, skip the lookahead token.
289 ;; OK to safely skip the block, so read input until a matching
290 ;; close paren or EOI is encountered.
291 (setq input wisent-input
)
292 (while (and (not (eq (car input
) wisent-eoi-term
))
293 (< (nth 2 input
) end
))
295 'wisent-discarding-token-functions input
)
296 (setq input
(wisent-lexer)))
297 (wisent-message "%s: in enclosing block, skip from %s to %s"
299 (wisent-token-to-string wisent-input
)
300 (wisent-token-to-string input
))
301 (if (eq (car wisent-input
) wisent-eoi-term
)
302 ;; Does nothing at EOI to avoid infinite recovery loop.
306 ;; Set end of $region to end of block.
307 (wisent-set-region (car $region
) (1+ end
))
310 ;;; Core parser engine
311 (defsubst wisent-production-bounds
(stack i j
)
312 "Determine the start and end locations of a production value.
313 Return a pair (START . END), where START is the first available start
314 location, and END the last available end location, in components
315 values of the rule currently reduced.
316 Return nil when no component location is available.
317 STACK is the parser stack.
318 I and J are the indices in STACK of respectively the value of the
319 first and last components of the current rule.
320 This function is for internal use by semantic actions' generated
322 (let ((f (cadr (aref stack i
)))
323 (l (cddr (aref stack j
))))
326 ((not f
) (setq f
(cadr (aref stack
(setq i
(+ i
2))))))
327 ((not l
) (setq l
(cddr (aref stack
(setq j
(- j
2))))))
329 (and f l
(cons f l
))))
331 (defmacro wisent-parse-action
(i al
)
332 "Return the next parser action.
333 I is a token item number and AL is the list of (item . action)
334 available at current state. The first element of AL contains the
335 default action for this state."
336 `(cdr (or (assq ,i
,al
) (car ,al
))))
338 (defsubst wisent-parse-start
(start starts
)
339 "Return the first lexical token to shift for START symbol.
340 STARTS is the table of allowed start symbols or nil if the LALR
341 automaton has only one entry point."
343 ;; Only one entry point, return the first lexical token
344 ;; available in input.
346 ;; Multiple start symbols defined, return the internal lexical
347 ;; token associated to START. By default START is the first
348 ;; nonterminal defined in STARTS.
349 (let ((token (cdr (if start
(assq start starts
) (car starts
)))))
351 (list token
(symbol-name token
))
352 (error "Invalid start symbol %s" start
)))))
354 (defun wisent-parse (automaton lexer
&optional error start
)
355 "Parse input using the automaton specified in AUTOMATON.
357 - AUTOMATON is an LALR(1) automaton generated by
358 `wisent-compile-grammar'.
360 - LEXER is a function with no argument called by the parser to obtain
361 the next terminal (token) in input.
363 - ERROR is an optional reporting function called when a parse error
364 occurs. It receives a message string to report. It defaults to the
365 function `wisent-message'.
367 - START specify the start symbol (nonterminal) used by the parser as
368 its goal. It defaults to the start symbol defined in the grammar
369 \(see also `wisent-compile-grammar')."
370 (run-hooks 'wisent-pre-parse-hook
)
371 (let* ((actions (aref automaton
0))
372 (gotos (aref automaton
1))
373 (starts (aref automaton
2))
374 (stack (make-vector wisent-parse-max-stack-size nil
))
377 (wisent-parse-error-function (or error
'wisent-message
))
378 (wisent-parse-lexer-function lexer
)
379 (wisent-recovering nil
)
380 (wisent-input (wisent-parse-start start starts
))
381 state tokid choices choice
)
382 (setq wisent-nerrs
0 ;; Reset parse error counter
383 wisent-lookahead nil
) ;; and lookahead token
384 (aset stack
0 0) ;; Initial state
386 (setq state
(aref stack sp
)
387 tokid
(car wisent-input
)
388 wisent-loop
(wisent-parse-action tokid
(aref actions state
)))
391 ;; Input successfully parsed
392 ;; -------------------------
393 ((eq wisent-loop wisent-accept-tag
)
394 (setq wisent-loop nil
))
396 ;; Syntax error in input
397 ;; ---------------------
398 ((eq wisent-loop wisent-error-tag
)
399 ;; Report this error if not already recovering from an error.
400 (setq choices
(aref actions state
))
401 (or wisent-recovering
403 (format "Syntax error, unexpected %s, expecting %s"
404 (wisent-token-to-string wisent-input
)
405 (mapconcat 'wisent-item-to-string
406 (delq wisent-error-term
407 (mapcar 'car
(cdr choices
)))
409 ;; Increment the error counter
410 (setq wisent-nerrs
(1+ wisent-nerrs
))
411 ;; If just tried and failed to reuse lookahead token after an
412 ;; error, discard it.
413 (if (eq wisent-recovering wisent-parse-max-recover
)
414 (if (eq tokid wisent-eoi-term
)
415 (wisent-abort) ;; Terminate if at end of input.
416 (wisent-message "Error recovery: skip %s"
417 (wisent-token-to-string wisent-input
))
419 'wisent-discarding-token-functions wisent-input
)
420 (setq wisent-input
(wisent-lexer)))
422 ;; Else will try to reuse lookahead token after shifting the
425 ;; Each real token shifted decrements this.
426 (setq wisent-recovering wisent-parse-max-recover
)
427 ;; Pop the value/state stack to see if an action associated
428 ;; to special terminal symbol 'error exists.
429 (while (and (>= sp
0)
430 (not (and (setq state
(aref stack sp
)
431 choices
(aref actions state
)
432 choice
(assq wisent-error-term choices
))
433 (natnump (cdr choice
)))))
437 ;; No 'error terminal was found. Just terminate.
439 ;; Try to recover and continue parsing.
440 ;; Shift the error terminal.
441 (setq state
(cdr choice
) ; new state
443 (aset stack
(1- sp
) nil
) ; push value
444 (aset stack sp state
) ; push new state
445 ;; Adjust input to error recovery state. Unless 'error
446 ;; triggers a reduction, eat the input stream until an
447 ;; expected terminal symbol is found, or EOI is reached.
448 (if (cdr (setq choices
(aref actions state
)))
449 (while (not (or (eq (car wisent-input
) wisent-eoi-term
)
450 (assq (car wisent-input
) choices
)))
451 (wisent-message "Error recovery: skip %s"
452 (wisent-token-to-string wisent-input
))
454 'wisent-discarding-token-functions wisent-input
)
455 (setq wisent-input
(wisent-lexer)))))))
457 ;; Shift current token on top of the stack
458 ;; ---------------------------------------
459 ((natnump wisent-loop
)
460 ;; Count tokens shifted since error; after
461 ;; `wisent-parse-max-recover', turn off error status.
462 (setq wisent-recovering
(and (natnump wisent-recovering
)
463 (> wisent-recovering
1)
464 (1- wisent-recovering
)))
466 (aset stack
(1- sp
) (cdr wisent-input
))
467 (aset stack sp wisent-loop
)
468 (setq wisent-input
(wisent-lexer)))
470 ;; Reduce by rule (call semantic action)
471 ;; -------------------------------------
473 (setq sp
(funcall wisent-loop stack sp gotos
))
474 (or wisent-input
(setq wisent-input
(wisent-lexer))))))
475 (run-hooks 'wisent-post-parse-hook
)
476 (car (aref stack
1))))
478 (provide 'semantic
/wisent
/wisent
)
480 ;;; semantic/wisent/wisent.el ends here