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