wisent.el 18 KB

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