lexer.scm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. ;;; Guile Emacs Lisp
  2. ;;; Copyright (C) 2009, 2010, 2013 Free Software Foundation, Inc.
  3. ;;;
  4. ;;; This library is free software; you can redistribute it and/or
  5. ;;; modify it under the terms of the GNU Lesser General Public
  6. ;;; License as published by the Free Software Foundation; either
  7. ;;; version 3 of the License, or (at your option) any later version.
  8. ;;;
  9. ;;; This library is distributed in the hope that it will be useful,
  10. ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ;;; Lesser General Public License for more details.
  13. ;;;
  14. ;;; You should have received a copy of the GNU Lesser General Public
  15. ;;; License along with this library; if not, write to the Free Software
  16. ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. ;;; Code:
  18. (define-module (language elisp lexer)
  19. #:use-module (ice-9 regex)
  20. #:use-module (language elisp runtime)
  21. #:export (get-lexer get-lexer/1))
  22. ;;; This is the lexical analyzer for the elisp reader. It is
  23. ;;; hand-written instead of using some generator. I think this is the
  24. ;;; best solution because of all that fancy escape sequence handling and
  25. ;;; the like.
  26. ;;;
  27. ;;; Characters are handled internally as integers representing their
  28. ;;; code value. This is necessary because elisp allows a lot of fancy
  29. ;;; modifiers that set certain high-range bits and the resulting values
  30. ;;; would not fit into a real Scheme character range. Additionally,
  31. ;;; elisp wants characters as integers, so we just do the right thing...
  32. ;;;
  33. ;;; TODO: #@count comments
  34. ;;; Report an error from the lexer (that is, invalid input given).
  35. (define (lexer-error port msg . args)
  36. (apply error msg args))
  37. ;;; In a character, set a given bit. This is just some bit-wise or'ing
  38. ;;; on the characters integer code and converting back to character.
  39. (define (set-char-bit chr bit)
  40. (logior chr (ash 1 bit)))
  41. ;;; Check if a character equals some other. This is just like char=?
  42. ;;; except that the tested one could be EOF in which case it simply
  43. ;;; isn't equal.
  44. (define (is-char? tested should-be)
  45. (and (not (eof-object? tested))
  46. (char=? tested should-be)))
  47. ;;; For a character (as integer code), find the real character it
  48. ;;; represents or #\nul if out of range. This is used to work with
  49. ;;; Scheme character functions like char-numeric?.
  50. (define (real-character chr)
  51. (if (< chr 256)
  52. (integer->char chr)
  53. #\nul))
  54. ;;; Return the control modified version of a character. This is not
  55. ;;; just setting a modifier bit, because ASCII conrol characters must be
  56. ;;; handled as such, and in elisp C-? is the delete character for
  57. ;;; historical reasons. Otherwise, we set bit 26.
  58. (define (add-control chr)
  59. (let ((real (real-character chr)))
  60. (if (char-alphabetic? real)
  61. (- (char->integer (char-upcase real)) (char->integer #\@))
  62. (case real
  63. ((#\?) 127)
  64. ((#\@) 0)
  65. (else (set-char-bit chr 26))))))
  66. ;;; Parse a charcode given in some base, basically octal or hexadecimal
  67. ;;; are needed. A requested number of digits can be given (#f means it
  68. ;;; does not matter and arbitrary many are allowed), and additionally
  69. ;;; early return allowed (if fewer valid digits are found). These
  70. ;;; options are all we need to handle the \u, \U, \x and \ddd (octal
  71. ;;; digits) escape sequences.
  72. (define (charcode-escape port base digits early-return)
  73. (let iterate ((result 0)
  74. (procdigs 0))
  75. (if (and digits (>= procdigs digits))
  76. result
  77. (let* ((cur (read-char port))
  78. (value (cond
  79. ((char-numeric? cur)
  80. (- (char->integer cur) (char->integer #\0)))
  81. ((char-alphabetic? cur)
  82. (let ((code (- (char->integer (char-upcase cur))
  83. (char->integer #\A))))
  84. (if (< code 0)
  85. #f
  86. (+ code 10))))
  87. (else #f)))
  88. (valid (and value (< value base))))
  89. (if (not valid)
  90. (if (or (not digits) early-return)
  91. (begin
  92. (unread-char cur port)
  93. result)
  94. (lexer-error port
  95. "invalid digit in escape-code"
  96. base
  97. cur))
  98. (iterate (+ (* result base) value) (1+ procdigs)))))))
  99. ;;; Read a character and process escape-sequences when necessary. The
  100. ;;; special in-string argument defines if this character is part of a
  101. ;;; string literal or a single character literal, the difference being
  102. ;;; that in strings the meta modifier sets bit 7, while it is bit 27 for
  103. ;;; characters.
  104. (define basic-escape-codes
  105. '((#\a . 7)
  106. (#\b . 8)
  107. (#\t . 9)
  108. (#\n . 10)
  109. (#\v . 11)
  110. (#\f . 12)
  111. (#\r . 13)
  112. (#\e . 27)
  113. (#\s . 32)
  114. (#\d . 127)))
  115. (define (get-character port in-string)
  116. (let ((meta-bits `((#\A . 22)
  117. (#\s . 23)
  118. (#\H . 24)
  119. (#\S . 25)
  120. (#\M . ,(if in-string 7 27))))
  121. (cur (read-char port)))
  122. (if (char=? cur #\\)
  123. ;; Handle an escape-sequence.
  124. (let* ((escaped (read-char port))
  125. (esc-code (assq-ref basic-escape-codes escaped))
  126. (meta (assq-ref meta-bits escaped)))
  127. (cond
  128. ;; Meta-check must be before esc-code check because \s- must
  129. ;; be recognized as the super-meta modifier if a - follows.
  130. ;; If not, it will be caught as \s -> space escape code.
  131. ((and meta (is-char? (peek-char port) #\-))
  132. (if (not (char=? (read-char port) #\-))
  133. (error "expected - after control sequence"))
  134. (set-char-bit (get-character port in-string) meta))
  135. ;; One of the basic control character escape names?
  136. (esc-code esc-code)
  137. ;; Handle \ddd octal code if it is one.
  138. ((and (char>=? escaped #\0) (char<? escaped #\8))
  139. (begin
  140. (unread-char escaped port)
  141. (charcode-escape port 8 3 #t)))
  142. ;; Check for some escape-codes directly or otherwise use the
  143. ;; escaped character literally.
  144. (else
  145. (case escaped
  146. ((#\^) (add-control (get-character port in-string)))
  147. ((#\C)
  148. (if (is-char? (peek-char port) #\-)
  149. (begin
  150. (if (not (char=? (read-char port) #\-))
  151. (error "expected - after control sequence"))
  152. (add-control (get-character port in-string)))
  153. escaped))
  154. ((#\x) (charcode-escape port 16 #f #t))
  155. ((#\u) (charcode-escape port 16 4 #f))
  156. ((#\U) (charcode-escape port 16 8 #f))
  157. (else (char->integer escaped))))))
  158. ;; No escape-sequence, just the literal character. But remember
  159. ;; to get the code instead!
  160. (char->integer cur))))
  161. ;;; Read a symbol or number from a port until something follows that
  162. ;;; marks the start of a new token (like whitespace or parentheses).
  163. ;;; The data read is returned as a string for further conversion to the
  164. ;;; correct type, but we also return what this is
  165. ;;; (integer/float/symbol). If any escaped character is found, it must
  166. ;;; be a symbol. Otherwise we at the end check the result-string
  167. ;;; against regular expressions to determine if it is possibly an
  168. ;;; integer or a float.
  169. (define integer-regex (make-regexp "^[+-]?[0-9]+\\.?$"))
  170. (define float-regex
  171. (make-regexp
  172. "^[+-]?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)(e[+-]?[0-9]+)?$"))
  173. ;;; A dot is also allowed literally, only a single dort alone is parsed
  174. ;;; as the 'dot' terminal for dotted lists.
  175. (define no-escape-punctuation (string->char-set "-+=*/_~!@$%^&:<>{}?."))
  176. (define (get-symbol-or-number port)
  177. (let iterate ((result-chars '())
  178. (had-escape #f))
  179. (let* ((c (read-char port))
  180. (finish (lambda ()
  181. (let ((result (list->string
  182. (reverse result-chars))))
  183. (values
  184. (cond
  185. ((and (not had-escape)
  186. (regexp-exec integer-regex result))
  187. 'integer)
  188. ((and (not had-escape)
  189. (regexp-exec float-regex result))
  190. 'float)
  191. (else 'symbol))
  192. result))))
  193. (need-no-escape? (lambda (c)
  194. (or (char-numeric? c)
  195. (char-alphabetic? c)
  196. (char-set-contains?
  197. no-escape-punctuation
  198. c)))))
  199. (cond
  200. ((eof-object? c) (finish))
  201. ((need-no-escape? c) (iterate (cons c result-chars) had-escape))
  202. ((char=? c #\\) (iterate (cons (read-char port) result-chars) #t))
  203. (else
  204. (unread-char c port)
  205. (finish))))))
  206. ;;; Parse a circular structure marker without the leading # (which was
  207. ;;; already read and recognized), that is, a number as identifier and
  208. ;;; then either = or #.
  209. (define (get-circular-marker port)
  210. (call-with-values
  211. (lambda ()
  212. (let iterate ((result 0))
  213. (let ((cur (read-char port)))
  214. (if (char-numeric? cur)
  215. (let ((val (- (char->integer cur) (char->integer #\0))))
  216. (iterate (+ (* result 10) val)))
  217. (values result cur)))))
  218. (lambda (id type)
  219. (case type
  220. ((#\#) `(circular-ref . ,id))
  221. ((#\=) `(circular-def . ,id))
  222. (else (lexer-error port
  223. "invalid circular marker character"
  224. type))))))
  225. ;;; Main lexer routine, which is given a port and does look for the next
  226. ;;; token.
  227. (define lexical-binding-regexp
  228. (make-regexp
  229. "-\\*-(|.*;)[ \t]*lexical-binding:[ \t]*([^;]*[^ \t;]).*-\\*-"))
  230. (define (lex port)
  231. (define (lexical-binding-value string)
  232. (and=> (regexp-exec lexical-binding-regexp string)
  233. (lambda (match)
  234. (not (member (match:substring match 2) '("nil" "()"))))))
  235. (let* ((return (let ((file (if (file-port? port)
  236. (port-filename port)
  237. #f))
  238. (line (1+ (port-line port)))
  239. (column (1+ (port-column port))))
  240. (lambda (token value)
  241. (let ((obj (cons token value)))
  242. (set-source-property! obj 'filename file)
  243. (set-source-property! obj 'line line)
  244. (set-source-property! obj 'column column)
  245. obj))))
  246. ;; Read afterwards so the source-properties are correct above
  247. ;; and actually point to the very character to be read.
  248. (c (read-char port)))
  249. (cond
  250. ;; End of input must be specially marked to the parser.
  251. ((eof-object? c) (return 'eof c))
  252. ;; Whitespace, just skip it.
  253. ((char-whitespace? c) (lex port))
  254. ;; The dot is only the one for dotted lists if followed by
  255. ;; whitespace. Otherwise it is considered part of a number of
  256. ;; symbol.
  257. ((and (char=? c #\.)
  258. (char-whitespace? (peek-char port)))
  259. (return 'dot #f))
  260. ;; Continue checking for literal character values.
  261. (else
  262. (case c
  263. ;; A line comment, skip until end-of-line is found.
  264. ((#\;)
  265. (if (= (port-line port) 0)
  266. (let iterate ((chars '()))
  267. (let ((cur (read-char port)))
  268. (if (or (eof-object? cur) (char=? cur #\newline))
  269. (let ((string (list->string (reverse chars))))
  270. (return 'set-lexical-binding-mode!
  271. (lexical-binding-value string)))
  272. (iterate (cons cur chars)))))
  273. (let iterate ()
  274. (let ((cur (read-char port)))
  275. (if (or (eof-object? cur) (char=? cur #\newline))
  276. (lex port)
  277. (iterate))))))
  278. ;; A character literal.
  279. ((#\?)
  280. (return 'character (get-character port #f)))
  281. ;; A literal string. This is mainly a sequence of characters
  282. ;; just as in the character literals, the only difference is
  283. ;; that escaped newline and space are to be completely ignored
  284. ;; and that meta-escapes set bit 7 rather than bit 27.
  285. ((#\")
  286. (let iterate ((result-chars '()))
  287. (let ((cur (read-char port)))
  288. (case cur
  289. ((#\")
  290. (return 'string
  291. (make-lisp-string
  292. (list->string (reverse result-chars)))))
  293. ((#\\)
  294. (let ((escaped (read-char port)))
  295. (case escaped
  296. ((#\newline #\space)
  297. (iterate result-chars))
  298. (else
  299. (unread-char escaped port)
  300. (unread-char cur port)
  301. (iterate
  302. (cons (integer->char (get-character port #t))
  303. result-chars))))))
  304. (else (iterate (cons cur result-chars)))))))
  305. ((#\#)
  306. (let ((c (read-char port)))
  307. (case c
  308. ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
  309. (unread-char c port)
  310. (let ((mark (get-circular-marker port)))
  311. (return (car mark) (cdr mark))))
  312. ((#\')
  313. (return 'function #f))
  314. ((#\:)
  315. (call-with-values
  316. (lambda () (get-symbol-or-number port))
  317. (lambda (type str)
  318. (return 'symbol (make-symbol str))))))))
  319. ;; Parentheses and other special-meaning single characters.
  320. ((#\() (return 'paren-open #f))
  321. ((#\)) (return 'paren-close #f))
  322. ((#\[) (return 'square-open #f))
  323. ((#\]) (return 'square-close #f))
  324. ((#\') (return 'quote #f))
  325. ((#\`) (return 'backquote #f))
  326. ;; Unquote and unquote-splicing.
  327. ((#\,)
  328. (if (is-char? (peek-char port) #\@)
  329. (if (not (char=? (read-char port) #\@))
  330. (error "expected @ in unquote-splicing")
  331. (return 'unquote-splicing #f))
  332. (return 'unquote #f)))
  333. ;; Remaining are numbers and symbols. Process input until next
  334. ;; whitespace is found, and see if it looks like a number
  335. ;; (float/integer) or symbol and return accordingly.
  336. (else
  337. (unread-char c port)
  338. (call-with-values
  339. (lambda () (get-symbol-or-number port))
  340. (lambda (type str)
  341. (case type
  342. ((symbol)
  343. (cond
  344. ((equal? str "nil")
  345. (return 'symbol #nil))
  346. ((equal? str "t")
  347. (return 'symbol #t))
  348. (else
  349. ;; str could be empty if the first character is already
  350. ;; something not allowed in a symbol (and not escaped)!
  351. ;; Take care about that, it is an error because that
  352. ;; character should have been handled elsewhere or is
  353. ;; invalid in the input.
  354. (if (zero? (string-length str))
  355. (begin
  356. ;; Take it out so the REPL might not get into an
  357. ;; infinite loop with further reading attempts.
  358. (read-char port)
  359. (error "invalid character in input" c))
  360. (return 'symbol (string->symbol str))))))
  361. ((integer)
  362. ;; In elisp, something like "1." is an integer, while
  363. ;; string->number returns an inexact real. Thus we need
  364. ;; a conversion here, but it should always result in an
  365. ;; integer!
  366. (return
  367. 'integer
  368. (let ((num (inexact->exact (string->number str))))
  369. (if (not (integer? num))
  370. (error "expected integer" str num))
  371. num)))
  372. ((float)
  373. (return 'float (let ((num (string->number str)))
  374. (if (exact? num)
  375. (error "expected inexact float"
  376. str
  377. num))
  378. num)))
  379. (else (error "wrong number/symbol type" type)))))))))))
  380. ;;; Build a lexer thunk for a port. This is the exported routine which
  381. ;;; can be used to create a lexer for the parser to use.
  382. (define (get-lexer port)
  383. (lambda () (lex port)))
  384. ;;; Build a special lexer that will only read enough for one expression
  385. ;;; and then always return end-of-input. If we find one of the quotation
  386. ;;; stuff, one more expression is needed in any case.
  387. (define (get-lexer/1 port)
  388. (let ((lex (get-lexer port))
  389. (finished #f)
  390. (paren-level 0))
  391. (lambda ()
  392. (if finished
  393. (cons 'eof ((@ (ice-9 binary-ports) eof-object)))
  394. (let ((next (lex))
  395. (quotation #f))
  396. (case (car next)
  397. ((paren-open square-open)
  398. (set! paren-level (1+ paren-level)))
  399. ((paren-close square-close)
  400. (set! paren-level (1- paren-level)))
  401. ((quote backquote unquote unquote-splicing circular-def)
  402. (set! quotation #t)))
  403. (if (and (not quotation) (<= paren-level 0))
  404. (set! finished #t))
  405. next)))))