]> code.delx.au - gnu-emacs/blob - lisp/cedet/semantic/lex.el
Merge from origin/emacs-25
[gnu-emacs] / lisp / cedet / semantic / lex.el
1 ;;; semantic/lex.el --- Lexical Analyzer builder
2
3 ;; Copyright (C) 1999-2016 Free Software Foundation, Inc.
4
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23 ;;
24 ;; This file handles the creation of lexical analyzers for different
25 ;; languages in Emacs Lisp. The purpose of a lexical analyzer is to
26 ;; convert a buffer into a list of lexical tokens. Each token
27 ;; contains the token class (such as 'number, 'symbol, 'IF, etc) and
28 ;; the location in the buffer it was found. Optionally, a token also
29 ;; contains a string representing what is at the designated buffer
30 ;; location.
31 ;;
32 ;; Tokens are pushed onto a token stream, which is basically a list of
33 ;; all the lexical tokens from the analyzed region. The token stream
34 ;; is then handed to the grammar which parsers the file.
35 ;;
36 ;;; How it works
37 ;;
38 ;; Each analyzer specifies a condition and forms. These conditions
39 ;; and forms are assembled into a function by `define-lex' that does
40 ;; the lexical analysis.
41 ;;
42 ;; In the lexical analyzer created with `define-lex', each condition
43 ;; is tested for a given point. When the condition is true, the forms
44 ;; run.
45 ;;
46 ;; The forms can push a lexical token onto the token stream. The
47 ;; analyzer forms also must move the current analyzer point. If the
48 ;; analyzer point is moved without pushing a token, then the matched
49 ;; syntax is effectively ignored, or skipped.
50 ;;
51 ;; Thus, starting at the beginning of a region to be analyzed, each
52 ;; condition is tested. One will match, and a lexical token might be
53 ;; pushed, and the point is moved to the end of the lexical token
54 ;; identified. At the new position, the process occurs again until
55 ;; the end of the specified region is reached.
56 ;;
57 ;;; How to use semantic-lex
58 ;;
59 ;; To create a lexer for a language, use the `define-lex' macro.
60 ;;
61 ;; The `define-lex' macro accepts a list of lexical analyzers. Each
62 ;; analyzer is created with `define-lex-analyzer', or one of the
63 ;; derivative macros. A single analyzer defines a regular expression
64 ;; to match text in a buffer, and a short segment of code to create
65 ;; one lexical token.
66 ;;
67 ;; Each analyzer has a NAME, DOC, a CONDITION, and possibly some
68 ;; FORMS. The NAME is the name used in `define-lex'. The DOC
69 ;; describes what the analyzer should do.
70 ;;
71 ;; The CONDITION evaluates the text at the current point in the
72 ;; current buffer. If CONDITION is true, then the FORMS will be
73 ;; executed.
74 ;;
75 ;; The purpose of the FORMS is to push new lexical tokens onto the
76 ;; list of tokens for the current buffer, and to move point after the
77 ;; matched text.
78 ;;
79 ;; Some macros for creating one analyzer are:
80 ;;
81 ;; define-lex-analyzer - A generic analyzer associating any style of
82 ;; condition to forms.
83 ;; define-lex-regex-analyzer - Matches a regular expression.
84 ;; define-lex-simple-regex-analyzer - Matches a regular expressions,
85 ;; and pushes the match.
86 ;; define-lex-block-analyzer - Matches list syntax, and defines
87 ;; handles open/close delimiters.
88 ;;
89 ;; These macros are used by the grammar compiler when lexical
90 ;; information is specified in a grammar:
91 ;; define-lex- * -type-analyzer - Matches syntax specified in
92 ;; a grammar, and pushes one token for it. The * would
93 ;; be `sexp' for things like lists or strings, and
94 ;; `string' for things that need to match some special
95 ;; string, such as "\\." where a literal match is needed.
96 ;;
97 ;;; Lexical Tables
98 ;;
99 ;; There are tables of different symbols managed in semantic-lex.el.
100 ;; They are:
101 ;;
102 ;; Lexical keyword table - A Table of symbols declared in a grammar
103 ;; file with the %keyword declaration.
104 ;; Keywords are used by `semantic-lex-symbol-or-keyword'
105 ;; to create lexical tokens based on the keyword.
106 ;;
107 ;; Lexical type table - A table of symbols declared in a grammar
108 ;; file with the %type declaration.
109 ;; The grammar compiler uses the type table to create new
110 ;; lexical analyzers. These analyzers are then used to when
111 ;; a new lexical analyzer is made for a language.
112 ;;
113 ;;; Lexical Types
114 ;;
115 ;; A lexical type defines a kind of lexical analyzer that will be
116 ;; automatically generated from a grammar file based on some
117 ;; predetermined attributes. For now these two attributes are
118 ;; recognized :
119 ;;
120 ;; * matchdatatype : define the kind of lexical analyzer. That is :
121 ;;
122 ;; - regexp : define a regexp analyzer (see
123 ;; `define-lex-regex-type-analyzer')
124 ;;
125 ;; - string : define a string analyzer (see
126 ;; `define-lex-string-type-analyzer')
127 ;;
128 ;; - block : define a block type analyzer (see
129 ;; `define-lex-block-type-analyzer')
130 ;;
131 ;; - sexp : define a sexp analyzer (see
132 ;; `define-lex-sexp-type-analyzer')
133 ;;
134 ;; - keyword : define a keyword analyzer (see
135 ;; `define-lex-keyword-type-analyzer')
136 ;;
137 ;; * syntax : define the syntax that matches a syntactic
138 ;; expression. When syntax is matched the corresponding type
139 ;; analyzer is entered and the resulting match data will be
140 ;; interpreted based on the kind of analyzer (see matchdatatype
141 ;; above).
142 ;;
143 ;; The following lexical types are predefined :
144 ;;
145 ;; +-------------+---------------+--------------------------------+
146 ;; | type | matchdatatype | syntax |
147 ;; +-------------+---------------+--------------------------------+
148 ;; | punctuation | string | "\\(\\s.\\|\\s$\\|\\s'\\)+" |
149 ;; | keyword | keyword | "\\(\\sw\\|\\s_\\)+" |
150 ;; | symbol | regexp | "\\(\\sw\\|\\s_\\)+" |
151 ;; | string | sexp | "\\s\"" |
152 ;; | number | regexp | semantic-lex-number-expression |
153 ;; | block | block | "\\s(\\|\\s)" |
154 ;; +-------------+---------------+--------------------------------+
155 ;;
156 ;; In a grammar you must use a %type expression to automatically generate
157 ;; the corresponding analyzers of that type.
158 ;;
159 ;; Here is an example to auto-generate punctuation analyzers
160 ;; with 'matchdatatype and 'syntax predefined (see table above)
161 ;;
162 ;; %type <punctuation> ;; will auto-generate this kind of analyzers
163 ;;
164 ;; It is equivalent to write :
165 ;;
166 ;; %type <punctuation> syntax "\\(\\s.\\|\\s$\\|\\s'\\)+" matchdatatype string
167 ;;
168 ;; ;; Some punctuation based on the type defines above
169 ;;
170 ;; %token <punctuation> NOT "!"
171 ;; %token <punctuation> NOTEQ "!="
172 ;; %token <punctuation> MOD "%"
173 ;; %token <punctuation> MODEQ "%="
174 ;;
175
176 ;;; On the Semantic 1.x lexer
177 ;;
178 ;; In semantic 1.x, the lexical analyzer was an all purpose routine.
179 ;; To boost efficiency, the analyzer is now a series of routines that
180 ;; are constructed at build time into a single routine. This will
181 ;; eliminate unneeded if statements to speed the lexer.
182
183 (require 'semantic/fw)
184
185 ;;; Code:
186
187 ;;; Semantic 2.x lexical analysis
188 ;;
189 (defun semantic-lex-map-symbols (fun table &optional property)
190 "Call function FUN on every symbol in TABLE.
191 If optional PROPERTY is non-nil, call FUN only on every symbol which
192 as a PROPERTY value. FUN receives a symbol as argument."
193 (if (arrayp table)
194 (mapatoms
195 #'(lambda (symbol)
196 (if (or (null property) (get symbol property))
197 (funcall fun symbol)))
198 table)))
199
200 ;;; Lexical keyword table handling.
201 ;;
202 ;; These keywords are keywords defined for using in a grammar with the
203 ;; %keyword declaration, and are not keywords used in Emacs Lisp.
204
205 (defvar semantic-flex-keywords-obarray nil
206 "Buffer local keyword obarray for the lexical analyzer.
207 These keywords are matched explicitly, and converted into special symbols.")
208 (make-variable-buffer-local 'semantic-flex-keywords-obarray)
209
210 (defmacro semantic-lex-keyword-invalid (name)
211 "Signal that NAME is an invalid keyword name."
212 `(signal 'wrong-type-argument '(semantic-lex-keyword-p ,name)))
213
214 (defsubst semantic-lex-keyword-symbol (name)
215 "Return keyword symbol with NAME or nil if not found."
216 (and (arrayp semantic-flex-keywords-obarray)
217 (stringp name)
218 (intern-soft name semantic-flex-keywords-obarray)))
219
220 (defsubst semantic-lex-keyword-p (name)
221 "Return non-nil if a keyword with NAME exists in the keyword table.
222 Return nil otherwise."
223 (and (setq name (semantic-lex-keyword-symbol name))
224 (symbol-value name)))
225
226 (defsubst semantic-lex-keyword-set (name value)
227 "Set value of keyword with NAME to VALUE and return VALUE."
228 (set (intern name semantic-flex-keywords-obarray) value))
229
230 (defsubst semantic-lex-keyword-value (name)
231 "Return value of keyword with NAME.
232 Signal an error if a keyword with NAME does not exist."
233 (let ((keyword (semantic-lex-keyword-symbol name)))
234 (if keyword
235 (symbol-value keyword)
236 (semantic-lex-keyword-invalid name))))
237
238 (defsubst semantic-lex-keyword-put (name property value)
239 "For keyword with NAME, set its PROPERTY to VALUE."
240 (let ((keyword (semantic-lex-keyword-symbol name)))
241 (if keyword
242 (put keyword property value)
243 (semantic-lex-keyword-invalid name))))
244
245 (defsubst semantic-lex-keyword-get (name property)
246 "For keyword with NAME, return its PROPERTY value."
247 (let ((keyword (semantic-lex-keyword-symbol name)))
248 (if keyword
249 (get keyword property)
250 (semantic-lex-keyword-invalid name))))
251
252 (defun semantic-lex-make-keyword-table (specs &optional propspecs)
253 "Convert keyword SPECS into an obarray and return it.
254 SPECS must be a list of (NAME . TOKSYM) elements, where:
255
256 NAME is the name of the keyword symbol to define.
257 TOKSYM is the lexical token symbol of that keyword.
258
259 If optional argument PROPSPECS is non nil, then interpret it, and
260 apply those properties.
261 PROPSPECS must be a list of (NAME PROPERTY VALUE) elements."
262 ;; Create the symbol hash table
263 (let ((semantic-flex-keywords-obarray (make-vector 13 0))
264 spec)
265 ;; fill it with stuff
266 (while specs
267 (setq spec (car specs)
268 specs (cdr specs))
269 (semantic-lex-keyword-set (car spec) (cdr spec)))
270 ;; Apply all properties
271 (while propspecs
272 (setq spec (car propspecs)
273 propspecs (cdr propspecs))
274 (semantic-lex-keyword-put (car spec) (nth 1 spec) (nth 2 spec)))
275 semantic-flex-keywords-obarray))
276
277 (defsubst semantic-lex-map-keywords (fun &optional property)
278 "Call function FUN on every lexical keyword.
279 If optional PROPERTY is non-nil, call FUN only on every keyword which
280 as a PROPERTY value. FUN receives a lexical keyword as argument."
281 (semantic-lex-map-symbols
282 fun semantic-flex-keywords-obarray property))
283
284 (defun semantic-lex-keywords (&optional property)
285 "Return a list of lexical keywords.
286 If optional PROPERTY is non-nil, return only keywords which have a
287 PROPERTY set."
288 (let (keywords)
289 (semantic-lex-map-keywords
290 #'(lambda (symbol) (setq keywords (cons symbol keywords)))
291 property)
292 keywords))
293
294 ;;; Inline functions:
295
296 (defvar semantic-lex-unterminated-syntax-end-function)
297 (defvar semantic-lex-analysis-bounds)
298 (defvar semantic-lex-end-point)
299
300 (defsubst semantic-lex-token-bounds (token)
301 "Fetch the start and end locations of the lexical token TOKEN.
302 Return a pair (START . END)."
303 (if (not (numberp (car (cdr token))))
304 (cdr (cdr token))
305 (cdr token)))
306
307 (defsubst semantic-lex-token-start (token)
308 "Fetch the start position of the lexical token TOKEN.
309 See also the function `semantic-lex-token'."
310 (car (semantic-lex-token-bounds token)))
311
312 (defsubst semantic-lex-token-end (token)
313 "Fetch the end position of the lexical token TOKEN.
314 See also the function `semantic-lex-token'."
315 (cdr (semantic-lex-token-bounds token)))
316
317 (defsubst semantic-lex-unterminated-syntax-detected (syntax)
318 "Inside a lexical analyzer, use this when unterminated syntax was found.
319 Argument SYNTAX indicates the type of syntax that is unterminated.
320 The job of this function is to move (point) to a new logical location
321 so that analysis can continue, if possible."
322 (goto-char
323 (funcall semantic-lex-unterminated-syntax-end-function
324 syntax
325 (car semantic-lex-analysis-bounds)
326 (cdr semantic-lex-analysis-bounds)
327 ))
328 (setq semantic-lex-end-point (point)))
329 \f
330 ;;; Type table handling.
331 ;;
332 ;; The lexical type table manages types that occur in a grammar file
333 ;; with the %type declaration. Types represent different syntaxes.
334 ;; See code for `semantic-lex-preset-default-types' for the classic
335 ;; types of syntax.
336 (defvar semantic-lex-types-obarray nil
337 "Buffer local types obarray for the lexical analyzer.")
338 (make-variable-buffer-local 'semantic-lex-types-obarray)
339
340 (defmacro semantic-lex-type-invalid (type)
341 "Signal that TYPE is an invalid lexical type name."
342 `(signal 'wrong-type-argument '(semantic-lex-type-p ,type)))
343
344 (defsubst semantic-lex-type-symbol (type)
345 "Return symbol with TYPE or nil if not found."
346 (and (arrayp semantic-lex-types-obarray)
347 (stringp type)
348 (intern-soft type semantic-lex-types-obarray)))
349
350 (defsubst semantic-lex-type-p (type)
351 "Return non-nil if a symbol with TYPE name exists."
352 (and (setq type (semantic-lex-type-symbol type))
353 (symbol-value type)))
354
355 (defsubst semantic-lex-type-set (type value)
356 "Set value of symbol with TYPE name to VALUE and return VALUE."
357 (set (intern type semantic-lex-types-obarray) value))
358
359 (defsubst semantic-lex-type-value (type &optional noerror)
360 "Return value of symbol with TYPE name.
361 If optional argument NOERROR is non-nil return nil if a symbol with
362 TYPE name does not exist. Otherwise signal an error."
363 (let ((sym (semantic-lex-type-symbol type)))
364 (if sym
365 (symbol-value sym)
366 (unless noerror
367 (semantic-lex-type-invalid type)))))
368
369 (defsubst semantic-lex-type-put (type property value &optional add)
370 "For symbol with TYPE name, set its PROPERTY to VALUE.
371 If optional argument ADD is non-nil, create a new symbol with TYPE
372 name if it does not already exist. Otherwise signal an error."
373 (let ((sym (semantic-lex-type-symbol type)))
374 (unless sym
375 (or add (semantic-lex-type-invalid type))
376 (semantic-lex-type-set type nil)
377 (setq sym (semantic-lex-type-symbol type)))
378 (put sym property value)))
379
380 (defsubst semantic-lex-type-get (type property &optional noerror)
381 "For symbol with TYPE name, return its PROPERTY value.
382 If optional argument NOERROR is non-nil return nil if a symbol with
383 TYPE name does not exist. Otherwise signal an error."
384 (let ((sym (semantic-lex-type-symbol type)))
385 (if sym
386 (get sym property)
387 (unless noerror
388 (semantic-lex-type-invalid type)))))
389
390 (defun semantic-lex-preset-default-types ()
391 "Install useful default properties for well known types."
392 (semantic-lex-type-put "punctuation" 'matchdatatype 'string t)
393 (semantic-lex-type-put "punctuation" 'syntax "\\(\\s.\\|\\s$\\|\\s'\\)+")
394 (semantic-lex-type-put "keyword" 'matchdatatype 'keyword t)
395 (semantic-lex-type-put "keyword" 'syntax "\\(\\sw\\|\\s_\\)+")
396 (semantic-lex-type-put "symbol" 'matchdatatype 'regexp t)
397 (semantic-lex-type-put "symbol" 'syntax "\\(\\sw\\|\\s_\\)+")
398 (semantic-lex-type-put "string" 'matchdatatype 'sexp t)
399 (semantic-lex-type-put "string" 'syntax "\\s\"")
400 (semantic-lex-type-put "number" 'matchdatatype 'regexp t)
401 (semantic-lex-type-put "number" 'syntax 'semantic-lex-number-expression)
402 (semantic-lex-type-put "block" 'matchdatatype 'block t)
403 (semantic-lex-type-put "block" 'syntax "\\s(\\|\\s)")
404 )
405
406 (defun semantic-lex-make-type-table (specs &optional propspecs)
407 "Convert type SPECS into an obarray and return it.
408 SPECS must be a list of (TYPE . TOKENS) elements, where:
409
410 TYPE is the name of the type symbol to define.
411 TOKENS is an list of (TOKSYM . MATCHER) elements, where:
412
413 TOKSYM is any lexical token symbol.
414 MATCHER is a string or regexp a text must match to be a such
415 lexical token.
416
417 If optional argument PROPSPECS is non nil, then interpret it, and
418 apply those properties.
419 PROPSPECS must be a list of (TYPE PROPERTY VALUE)."
420 ;; Create the symbol hash table
421 (let* ((semantic-lex-types-obarray (make-vector 13 0))
422 spec type tokens token alist default)
423 ;; fill it with stuff
424 (while specs
425 (setq spec (car specs)
426 specs (cdr specs)
427 type (car spec)
428 tokens (cdr spec)
429 default nil
430 alist nil)
431 (while tokens
432 (setq token (car tokens)
433 tokens (cdr tokens))
434 (if (cdr token)
435 (setq alist (cons token alist))
436 (setq token (car token))
437 (if default
438 (message
439 "*Warning* default value of <%s> tokens changed to %S, was %S"
440 type token default))
441 (setq default token)))
442 ;; Ensure the default matching spec is the first one.
443 (semantic-lex-type-set type (cons default (nreverse alist))))
444 ;; Install useful default types & properties
445 (semantic-lex-preset-default-types)
446 ;; Apply all properties
447 (while propspecs
448 (setq spec (car propspecs)
449 propspecs (cdr propspecs))
450 ;; Create the type if necessary.
451 (semantic-lex-type-put (car spec) (nth 1 spec) (nth 2 spec) t))
452 semantic-lex-types-obarray))
453
454 (defsubst semantic-lex-map-types (fun &optional property)
455 "Call function FUN on every lexical type.
456 If optional PROPERTY is non-nil, call FUN only on every type symbol
457 which as a PROPERTY value. FUN receives a type symbol as argument."
458 (semantic-lex-map-symbols
459 fun semantic-lex-types-obarray property))
460
461 (defun semantic-lex-types (&optional property)
462 "Return a list of lexical type symbols.
463 If optional PROPERTY is non-nil, return only type symbols which have
464 PROPERTY set."
465 (let (types)
466 (semantic-lex-map-types
467 #'(lambda (symbol) (setq types (cons symbol types)))
468 property)
469 types))
470 \f
471 ;;; Lexical Analyzer framework settings
472 ;;
473
474 (defvar semantic-lex-analyzer 'semantic-flex
475 "The lexical analyzer used for a given buffer.
476 See `semantic-lex' for documentation.
477 For compatibility with Semantic 1.x it defaults to `semantic-flex'.")
478 (make-variable-buffer-local 'semantic-lex-analyzer)
479
480 (defvar semantic-lex-tokens
481 '(
482 (bol)
483 (charquote)
484 (close-paren)
485 (comment)
486 (newline)
487 (open-paren)
488 (punctuation)
489 (semantic-list)
490 (string)
491 (symbol)
492 (whitespace)
493 )
494 "An alist of semantic token types.
495 As of December 2001 (semantic 1.4beta13), this variable is not used in
496 any code. The only use is to refer to the doc-string from elsewhere.
497
498 The key to this alist is the symbol representing token type that
499 \\[semantic-flex] returns. These are
500
501 - bol: Empty string matching a beginning of line.
502 This token is produced with
503 `semantic-lex-beginning-of-line'.
504
505 - charquote: String sequences that match `\\s\\+' regexp.
506 This token is produced with `semantic-lex-charquote'.
507
508 - close-paren: Characters that match `\\s)' regexp.
509 These are typically `)', `}', `]', etc.
510 This token is produced with
511 `semantic-lex-close-paren'.
512
513 - comment: A comment chunk. These token types are not
514 produced by default.
515 This token is produced with `semantic-lex-comments'.
516 Comments are ignored with `semantic-lex-ignore-comments'.
517 Comments are treated as whitespace with
518 `semantic-lex-comments-as-whitespace'.
519
520 - newline Characters matching `\\s-*\\(\n\\|\\s>\\)' regexp.
521 This token is produced with `semantic-lex-newline'.
522
523 - open-paren: Characters that match `\\s(' regexp.
524 These are typically `(', `{', `[', etc.
525 If `semantic-lex-paren-or-list' is used,
526 then `open-paren' is not usually generated unless
527 the `depth' argument to \\[semantic-lex] is
528 greater than 0.
529 This token is always produced if the analyzer
530 `semantic-lex-open-paren' is used.
531
532 - punctuation: Characters matching `{\\(\\s.\\|\\s$\\|\\s'\\)'
533 regexp.
534 This token is produced with `semantic-lex-punctuation'.
535 Always specify this analyzer after the comment
536 analyzer.
537
538 - semantic-list: String delimited by matching parenthesis, braces,
539 etc. that the lexer skipped over, because the
540 `depth' parameter to \\[semantic-flex] was not high
541 enough.
542 This token is produced with `semantic-lex-paren-or-list'.
543
544 - string: Quoted strings, i.e., string sequences that start
545 and end with characters matching `\\s\"'
546 regexp. The lexer relies on @code{forward-sexp} to
547 find the matching end.
548 This token is produced with `semantic-lex-string'.
549
550 - symbol: String sequences that match `\\(\\sw\\|\\s_\\)+'
551 regexp.
552 This token is produced with
553 `semantic-lex-symbol-or-keyword'. Always add this analyzer
554 after `semantic-lex-number', or other analyzers that
555 match its regular expression.
556
557 - whitespace: Characters that match `\\s-+' regexp.
558 This token is produced with `semantic-lex-whitespace'.")
559
560 (defvar semantic-lex-syntax-modifications nil
561 "Changes to the syntax table for this buffer.
562 These changes are active only while the buffer is being flexed.
563 This is a list where each element has the form:
564 (CHAR CLASS)
565 CHAR is the char passed to `modify-syntax-entry',
566 and CLASS is the string also passed to `modify-syntax-entry' to define
567 what syntax class CHAR has.")
568 (make-variable-buffer-local 'semantic-lex-syntax-modifications)
569
570 (defvar semantic-lex-syntax-table nil
571 "Syntax table used by lexical analysis.
572 See also `semantic-lex-syntax-modifications'.")
573 (make-variable-buffer-local 'semantic-lex-syntax-table)
574
575 (defvar semantic-lex-comment-regex nil
576 "Regular expression for identifying comment start during lexical analysis.
577 This may be automatically set when semantic initializes in a mode, but
578 may need to be overridden for some special languages.")
579 (make-variable-buffer-local 'semantic-lex-comment-regex)
580
581 (defvar semantic-lex-number-expression
582 ;; This expression was written by David Ponce for Java, and copied
583 ;; here for C and any other similar language.
584 (eval-when-compile
585 (concat "\\("
586 "\\<[0-9]+[.][0-9]+\\([eE][-+]?[0-9]+\\)?[fFdD]?\\>"
587 "\\|"
588 "\\<[0-9]+[.][eE][-+]?[0-9]+[fFdD]?\\>"
589 "\\|"
590 "\\<[0-9]+[.][fFdD]\\>"
591 "\\|"
592 "\\<[0-9]+[.]"
593 "\\|"
594 "[.][0-9]+\\([eE][-+]?[0-9]+\\)?[fFdD]?\\>"
595 "\\|"
596 "\\<[0-9]+[eE][-+]?[0-9]+[fFdD]?\\>"
597 "\\|"
598 "\\<0[xX][0-9a-fA-F]+[lL]?\\>"
599 "\\|"
600 "\\<[0-9]+[lLfFdD]?\\>"
601 "\\)"
602 ))
603 "Regular expression for matching a number.
604 If this value is nil, no number extraction is done during lex.
605 This expression tries to match C and Java like numbers.
606
607 DECIMAL_LITERAL:
608 [1-9][0-9]*
609 ;
610 HEX_LITERAL:
611 0[xX][0-9a-fA-F]+
612 ;
613 OCTAL_LITERAL:
614 0[0-7]*
615 ;
616 INTEGER_LITERAL:
617 <DECIMAL_LITERAL>[lL]?
618 | <HEX_LITERAL>[lL]?
619 | <OCTAL_LITERAL>[lL]?
620 ;
621 EXPONENT:
622 [eE][+-]?[09]+
623 ;
624 FLOATING_POINT_LITERAL:
625 [0-9]+[.][0-9]*<EXPONENT>?[fFdD]?
626 | [.][0-9]+<EXPONENT>?[fFdD]?
627 | [0-9]+<EXPONENT>[fFdD]?
628 | [0-9]+<EXPONENT>?[fFdD]
629 ;")
630 (make-variable-buffer-local 'semantic-lex-number-expression)
631
632 (defvar semantic-lex-depth 0
633 "Default lexing depth.
634 This specifies how many lists to create tokens in.")
635 (make-variable-buffer-local 'semantic-lex-depth)
636
637 (defvar semantic-lex-unterminated-syntax-end-function
638 (lambda (syntax syntax-start lex-end) lex-end)
639 "Function called when unterminated syntax is encountered.
640 This should be set to one function. That function should take three
641 parameters. The SYNTAX, or type of syntax which is unterminated.
642 SYNTAX-START where the broken syntax begins.
643 LEX-END is where the lexical analysis was asked to end.
644 This function can be used for languages that can intelligently fix up
645 broken syntax, or the exit lexical analysis via `throw' or `signal'
646 when finding unterminated syntax.")
647
648 ;;; Interactive testing commands
649
650 (declare-function semantic-elapsed-time "semantic")
651
652 (defun semantic-lex-test (arg)
653 "Test the semantic lexer in the current buffer.
654 If universal argument ARG, then try the whole buffer."
655 (interactive "P")
656 (require 'semantic)
657 (let* ((start (current-time))
658 (result (semantic-lex
659 (if arg (point-min) (point))
660 (point-max)))
661 (end (current-time)))
662 (message "Elapsed Time: %.2f seconds."
663 (semantic-elapsed-time start end))
664 (pop-to-buffer "*Lexer Output*")
665 (require 'pp)
666 (erase-buffer)
667 (insert (pp-to-string result))
668 (goto-char (point-min))
669 ))
670
671 (defvar semantic-lex-debug nil
672 "When non-nil, debug the local lexical analyzer.")
673
674 (defun semantic-lex-debug (arg)
675 "Debug the semantic lexer in the current buffer.
676 Argument ARG specifies of the analyze the whole buffer, or start at point.
677 While engaged, each token identified by the lexer will be highlighted
678 in the target buffer A description of the current token will be
679 displayed in the minibuffer. Press SPC to move to the next lexical token."
680 (interactive "P")
681 (require 'semantic/debug)
682 (let ((semantic-lex-debug t))
683 (semantic-lex-test arg)))
684
685 (defun semantic-lex-highlight-token (token)
686 "Highlight the lexical TOKEN.
687 TOKEN is a lexical token with a START And END position.
688 Return the overlay."
689 (let ((o (semantic-make-overlay (semantic-lex-token-start token)
690 (semantic-lex-token-end token))))
691 (semantic-overlay-put o 'face 'highlight)
692 o))
693
694 ;;; Lexical analyzer creation
695 ;;
696 ;; Code for creating a lex function from lists of analyzers.
697 ;;
698 ;; A lexical analyzer is created from a list of individual analyzers.
699 ;; Each individual analyzer specifies a single match, and code that
700 ;; goes with it.
701 ;;
702 ;; Creation of an analyzer assembles these analyzers into a new function
703 ;; with the behaviors of all the individual analyzers.
704 ;;
705 (defmacro semantic-lex-one-token (analyzers)
706 "Calculate one token from the current buffer at point.
707 Uses locally bound variables from `define-lex'.
708 Argument ANALYZERS is the list of analyzers being used."
709 (cons 'cond (mapcar #'symbol-value analyzers)))
710
711 (defvar semantic-lex-end-point nil
712 "The end point as tracked through lexical functions.")
713
714 (defvar semantic-lex-current-depth nil
715 "The current depth as tracked through lexical functions.")
716
717 (defvar semantic-lex-maximum-depth nil
718 "The maximum depth of parenthesis as tracked through lexical functions.")
719
720 (defvar semantic-lex-token-stream nil
721 "The current token stream we are collecting.")
722
723 (defvar semantic-lex-analysis-bounds nil
724 "The bounds of the current analysis.")
725
726 (defvar semantic-lex-block-streams nil
727 "Streams of tokens inside collapsed blocks.
728 This is an alist of (ANCHOR . STREAM) elements where ANCHOR is the
729 start position of the block, and STREAM is the list of tokens in that
730 block.")
731
732 (define-obsolete-variable-alias 'semantic-lex-reset-hooks
733 'semantic-lex-reset-functions "24.3")
734 (defvar semantic-lex-reset-functions nil
735 "Abnormal hook used by major-modes to reset lexical analyzers.
736 Hook functions are called with START and END values for the
737 current lexical pass. Should be set with `add-hook', specifying
738 a LOCAL option.")
739
740 ;; Stack of nested blocks.
741 (defvar semantic-lex-block-stack nil)
742 ;;(defcustom semantic-lex-timeout 5
743 ;; "Number of sections of lexing before giving up."
744 ;; :type 'integer
745 ;; :group 'semantic)
746
747 (defsubst semantic-lex-debug-break (token)
748 "Break during lexical analysis at TOKEN."
749 (when semantic-lex-debug
750 (let ((o nil))
751 (unwind-protect
752 (progn
753 (when token
754 (setq o (semantic-lex-highlight-token token)))
755 (semantic-read-event
756 (format "%S :: Depth: %d :: SPC - continue" token semantic-lex-current-depth))
757 )
758 (when o
759 (semantic-overlay-delete o))))))
760
761 (defmacro define-lex (name doc &rest analyzers)
762 "Create a new lexical analyzer with NAME.
763 DOC is a documentation string describing this analyzer.
764 ANALYZERS are small code snippets of analyzers to use when
765 building the new NAMED analyzer. Only use analyzers which
766 are written to be used in `define-lex'.
767 Each analyzer should be an analyzer created with `define-lex-analyzer'.
768 Note: The order in which analyzers are listed is important.
769 If two analyzers can match the same text, it is important to order the
770 analyzers so that the one you want to match first occurs first. For
771 example, it is good to put a number analyzer in front of a symbol
772 analyzer which might mistake a number for as a symbol."
773 `(defun ,name (start end &optional depth length)
774 ,(concat doc "\nSee `semantic-lex' for more information.")
775 ;; Make sure the state of block parsing starts over.
776 (setq semantic-lex-block-streams nil)
777 ;; Allow specialty reset items.
778 (run-hook-with-args 'semantic-lex-reset-functions start end)
779 ;; Lexing state.
780 (let* (;(starttime (current-time))
781 (starting-position (point))
782 (semantic-lex-token-stream nil)
783 (semantic-lex-block-stack nil)
784 (tmp-start start)
785 (semantic-lex-end-point start)
786 (semantic-lex-current-depth 0)
787 ;; Use the default depth when not specified.
788 (semantic-lex-maximum-depth
789 (or depth semantic-lex-depth))
790 ;; Bounds needed for unterminated syntax
791 (semantic-lex-analysis-bounds (cons start end))
792 ;; This entry prevents text properties from
793 ;; confusing our lexical analysis. See Emacs 22 (CVS)
794 ;; version of C++ mode with template hack text properties.
795 (parse-sexp-lookup-properties nil)
796 )
797 ;; Maybe REMOVE THIS LATER.
798 ;; Trying to find incremental parser bug.
799 (when (> end (point-max))
800 (error ,(format "%s: end (%%d) > point-max (%%d)" name)
801 end (point-max)))
802 (with-syntax-table semantic-lex-syntax-table
803 (goto-char start)
804 (while (and (< (point) end)
805 (or (not length)
806 (<= (length semantic-lex-token-stream) length)))
807 (semantic-lex-one-token ,analyzers)
808 (when (eq semantic-lex-end-point tmp-start)
809 (error ,(format "%s: endless loop at %%d, after %%S" name)
810 tmp-start (car semantic-lex-token-stream)))
811 (setq tmp-start semantic-lex-end-point)
812 (goto-char semantic-lex-end-point)
813 ;;(when (> (semantic-elapsed-time starttime (current-time))
814 ;; semantic-lex-timeout)
815 ;; (error "Timeout during lex at char %d" (point)))
816 (semantic-throw-on-input 'lex)
817 (semantic-lex-debug-break (car semantic-lex-token-stream))
818 ))
819 ;; Check that there is no unterminated block.
820 (when semantic-lex-block-stack
821 (let* ((last (pop semantic-lex-block-stack))
822 (blk last))
823 (while blk
824 (message
825 ,(format "%s: `%%s' block from %%S is unterminated" name)
826 (car blk) (cadr blk))
827 (setq blk (pop semantic-lex-block-stack)))
828 (semantic-lex-unterminated-syntax-detected (car last))))
829 ;; Return to where we started.
830 ;; Do not wrap in protective stuff so that if there is an error
831 ;; thrown, the user knows where.
832 (goto-char starting-position)
833 ;; Return the token stream
834 (nreverse semantic-lex-token-stream))))
835 \f
836 ;;; Lexical token API
837 ;;
838 ;; Functions for accessing parts of a token. Use these functions
839 ;; instead of accessing the list structure directly because the
840 ;; contents of the lexical may change.
841 ;;
842 (defmacro semantic-lex-token (symbol start end &optional str)
843 "Create a lexical token.
844 SYMBOL is a symbol representing the class of syntax found.
845 START and END define the bounds of the token in the current buffer.
846 Optional STR is the string for the token only if the bounds in
847 the buffer do not cover the string they represent. (As from
848 macro expansion.)"
849 ;; This if statement checks the existence of a STR argument at
850 ;; compile time, where STR is some symbol or constant. If the
851 ;; variable STr (runtime) is nil, this will make an incorrect decision.
852 ;;
853 ;; It is like this to maintain the original speed of the compiled
854 ;; code.
855 (if str
856 `(cons ,symbol (cons ,str (cons ,start ,end)))
857 `(cons ,symbol (cons ,start ,end))))
858
859 (defun semantic-lex-token-p (thing)
860 "Return non-nil if THING is a semantic lex token.
861 This is an exhaustively robust check."
862 (and (consp thing)
863 (symbolp (car thing))
864 (or (and (numberp (nth 1 thing))
865 (numberp (nthcdr 2 thing)))
866 (and (stringp (nth 1 thing))
867 (numberp (nth 2 thing))
868 (numberp (nthcdr 3 thing)))
869 ))
870 )
871
872 (defun semantic-lex-token-with-text-p (thing)
873 "Return non-nil if THING is a semantic lex token.
874 This is an exhaustively robust check."
875 (and (consp thing)
876 (symbolp (car thing))
877 (= (length thing) 4)
878 (stringp (nth 1 thing))
879 (numberp (nth 2 thing))
880 (numberp (nth 3 thing)))
881 )
882
883 (defun semantic-lex-token-without-text-p (thing)
884 "Return non-nil if THING is a semantic lex token.
885 This is an exhaustively robust check."
886 (and (consp thing)
887 (symbolp (car thing))
888 (= (length thing) 3)
889 (numberp (nth 1 thing))
890 (numberp (nth 2 thing)))
891 )
892
893 (eval-and-compile
894
895 (defun semantic-lex-expand-block-specs (specs)
896 "Expand block specifications SPECS into a Lisp form.
897 SPECS is a list of (BLOCK BEGIN END) elements where BLOCK, BEGIN, and
898 END are token class symbols that indicate to produce one collapsed
899 BLOCK token from tokens found between BEGIN and END ones.
900 BLOCK must be a non-nil symbol, and at least one of the BEGIN or END
901 symbols must be non-nil too.
902 When BEGIN is non-nil, generate a call to `semantic-lex-start-block'
903 when a BEGIN token class is encountered.
904 When END is non-nil, generate a call to `semantic-lex-end-block' when
905 an END token class is encountered."
906 (let ((class (make-symbol "class"))
907 (form nil))
908 (dolist (spec specs)
909 (when (car spec)
910 (when (nth 1 spec)
911 (push `((eq ',(nth 1 spec) ,class)
912 (semantic-lex-start-block ',(car spec)))
913 form))
914 (when (nth 2 spec)
915 (push `((eq ',(nth 2 spec) ,class)
916 (semantic-lex-end-block ',(car spec)))
917 form))))
918 (when form
919 `((let ((,class (semantic-lex-token-class
920 (car semantic-lex-token-stream))))
921 (cond ,@(nreverse form))))
922 )))
923 )
924
925 (defmacro semantic-lex-push-token (token &rest blockspecs)
926 "Push TOKEN in the lexical analyzer token stream.
927 Return the lexical analysis current end point.
928 If optional arguments BLOCKSPECS is non-nil, it specifies to process
929 collapsed block tokens. See `semantic-lex-expand-block-specs' for
930 more details.
931 This macro should only be called within the bounds of
932 `define-lex-analyzer'. It changes the values of the lexical analyzer
933 variables `token-stream' and `semantic-lex-end-point'. If you need to
934 move `semantic-lex-end-point' somewhere else, just modify this
935 variable after calling `semantic-lex-push-token'."
936 `(progn
937 (push ,token semantic-lex-token-stream)
938 ,@(semantic-lex-expand-block-specs blockspecs)
939 (setq semantic-lex-end-point
940 (semantic-lex-token-end (car semantic-lex-token-stream)))
941 ))
942
943 (defsubst semantic-lex-token-class (token)
944 "Fetch the class of the lexical token TOKEN.
945 See also the function `semantic-lex-token'."
946 (car token))
947
948 (defsubst semantic-lex-token-text (token)
949 "Fetch the text associated with the lexical token TOKEN.
950 See also the function `semantic-lex-token'."
951 (if (stringp (car (cdr token)))
952 (car (cdr token))
953 (buffer-substring-no-properties
954 (semantic-lex-token-start token)
955 (semantic-lex-token-end token))))
956
957 (defun semantic-lex-init ()
958 "Initialize any lexical state for this buffer."
959 (unless semantic-lex-comment-regex
960 (setq semantic-lex-comment-regex
961 (if comment-start-skip
962 (concat "\\(\\s<\\|" comment-start-skip "\\)")
963 "\\(\\s<\\)")))
964 ;; Setup the lexer syntax-table
965 (setq semantic-lex-syntax-table (copy-syntax-table (syntax-table)))
966 (dolist (mod semantic-lex-syntax-modifications)
967 (modify-syntax-entry
968 (car mod) (nth 1 mod) semantic-lex-syntax-table)))
969
970 ;;;###autoload
971 (define-overloadable-function semantic-lex (start end &optional depth length)
972 "Lexically analyze text in the current buffer between START and END.
973 Optional argument DEPTH indicates at what level to scan over entire
974 lists. The last argument, LENGTH specifies that `semantic-lex'
975 should only return LENGTH tokens. The return value is a token stream.
976 Each element is a list, such of the form
977 (symbol start-expression . end-expression)
978 where SYMBOL denotes the token type.
979 See `semantic-lex-tokens' variable for details on token types. END
980 does not mark the end of the text scanned, only the end of the
981 beginning of text scanned. Thus, if a string extends past END, the
982 end of the return token will be larger than END. To truly restrict
983 scanning, use `narrow-to-region'."
984 (funcall semantic-lex-analyzer start end depth length))
985
986 (defsubst semantic-lex-buffer (&optional depth)
987 "Lex the current buffer.
988 Optional argument DEPTH is the depth to scan into lists."
989 (semantic-lex (point-min) (point-max) depth))
990
991 (defsubst semantic-lex-list (semlist depth)
992 "Lex the body of SEMLIST to DEPTH."
993 (semantic-lex (semantic-lex-token-start semlist)
994 (semantic-lex-token-end semlist)
995 depth))
996 \f
997 ;;; Collapsed block tokens delimited by any tokens.
998 ;;
999 (defun semantic-lex-start-block (syntax)
1000 "Mark the last read token as the beginning of a SYNTAX block."
1001 (if (or (not semantic-lex-maximum-depth)
1002 (< semantic-lex-current-depth semantic-lex-maximum-depth))
1003 (setq semantic-lex-current-depth (1+ semantic-lex-current-depth))
1004 (push (list syntax (car semantic-lex-token-stream))
1005 semantic-lex-block-stack)))
1006
1007 (defun semantic-lex-end-block (syntax)
1008 "Process the end of a previously marked SYNTAX block.
1009 That is, collapse the tokens inside that block, including the
1010 beginning and end of block tokens, into a high level block token of
1011 class SYNTAX.
1012 The token at beginning of block is the one marked by a previous call
1013 to `semantic-lex-start-block'. The current token is the end of block.
1014 The collapsed tokens are saved in `semantic-lex-block-streams'."
1015 (if (null semantic-lex-block-stack)
1016 (setq semantic-lex-current-depth (1- semantic-lex-current-depth))
1017 (let* ((stream semantic-lex-token-stream)
1018 (blk (pop semantic-lex-block-stack))
1019 (bstream (cdr blk))
1020 (first (car bstream))
1021 (last (pop stream)) ;; The current token mark the EOBLK
1022 tok)
1023 (if (not (eq (car blk) syntax))
1024 ;; SYNTAX doesn't match the syntax of the current block in
1025 ;; the stack. So we encountered the end of the SYNTAX block
1026 ;; before the end of the current one in the stack which is
1027 ;; signaled unterminated.
1028 (semantic-lex-unterminated-syntax-detected (car blk))
1029 ;; Move tokens found inside the block from the main stream
1030 ;; into a separate block stream.
1031 (while (and stream (not (eq (setq tok (pop stream)) first)))
1032 (push tok bstream))
1033 ;; The token marked as beginning of block was not encountered.
1034 ;; This should not happen!
1035 (or (eq tok first)
1036 (error "Token %S not found at beginning of block `%s'"
1037 first syntax))
1038 ;; Save the block stream for future reuse, to avoid to redo
1039 ;; the lexical analysis of the block content!
1040 ;; Anchor the block stream with its start position, so we can
1041 ;; use: (cdr (assq start semantic-lex-block-streams)) to
1042 ;; quickly retrieve the lexical stream associated to a block.
1043 (setcar blk (semantic-lex-token-start first))
1044 (setcdr blk (nreverse bstream))
1045 (push blk semantic-lex-block-streams)
1046 ;; In the main stream, replace the tokens inside the block by
1047 ;; a high level block token of class SYNTAX.
1048 (setq semantic-lex-token-stream stream)
1049 (semantic-lex-push-token
1050 (semantic-lex-token
1051 syntax (car blk) (semantic-lex-token-end last)))
1052 ))))
1053 \f
1054 ;;; Analyzer creation macros
1055 ;;
1056 ;; An individual analyzer is a condition and code that goes with it.
1057 ;;
1058 ;; Created analyzers become variables with the code associated with them
1059 ;; as the symbol value. These analyzers are assembled into a lexer
1060 ;; to create new lexical analyzers.
1061
1062 (defcustom semantic-lex-debug-analyzers nil
1063 "Non nil means to debug analyzers with syntax protection.
1064 Only in effect if `debug-on-error' is also non-nil."
1065 :group 'semantic
1066 :type 'boolean)
1067
1068 (defmacro semantic-lex-unterminated-syntax-protection (syntax &rest forms)
1069 "For SYNTAX, execute FORMS with protection for unterminated syntax.
1070 If FORMS throws an error, treat this as a syntax problem, and
1071 execute the unterminated syntax code. FORMS should return a position.
1072 Irregardless of an error, the cursor should be moved to the end of
1073 the desired syntax, and a position returned.
1074 If `debug-on-error' is set, errors are not caught, so that you can
1075 debug them.
1076 Avoid using a large FORMS since it is duplicated."
1077 `(if (and debug-on-error semantic-lex-debug-analyzers)
1078 (progn ,@forms)
1079 (condition-case nil
1080 (progn ,@forms)
1081 (error
1082 (semantic-lex-unterminated-syntax-detected ,syntax)))))
1083 (put 'semantic-lex-unterminated-syntax-protection
1084 'lisp-indent-function 1)
1085
1086 (defmacro define-lex-analyzer (name doc condition &rest forms)
1087 "Create a single lexical analyzer NAME with DOC.
1088 When an analyzer is called, the current buffer and point are
1089 positioned in a buffer at the location to be analyzed.
1090 CONDITION is an expression which returns t if FORMS should be run.
1091 Within the bounds of CONDITION and FORMS, the use of backquote
1092 can be used to evaluate expressions at compile time.
1093 While forms are running, the following variables will be locally bound:
1094 `semantic-lex-analysis-bounds' - The bounds of the current analysis.
1095 of the form (START . END)
1096 `semantic-lex-maximum-depth' - The maximum depth of semantic-list
1097 for the current analysis.
1098 `semantic-lex-current-depth' - The current depth of `semantic-list' that has
1099 been descended.
1100 `semantic-lex-end-point' - End Point after match.
1101 Analyzers should set this to a buffer location if their
1102 match string does not represent the end of the matched text.
1103 `semantic-lex-token-stream' - The token list being collected.
1104 Add new lexical tokens to this list.
1105 Proper action in FORMS is to move the value of `semantic-lex-end-point' to
1106 after the location of the analyzed entry, and to add any discovered tokens
1107 at the beginning of `semantic-lex-token-stream'.
1108 This can be done by using `semantic-lex-push-token'."
1109 `(eval-and-compile
1110 (defvar ,name nil ,doc)
1111 (defun ,name nil)
1112 ;; Do this part separately so that re-evaluation rebuilds this code.
1113 (setq ,name '(,condition ,@forms))
1114 ;; Build a single lexical analyzer function, so the doc for
1115 ;; function help is automatically provided, and perhaps the
1116 ;; function could be useful for testing and debugging one
1117 ;; analyzer.
1118 (fset ',name (lambda () ,doc
1119 (let ((semantic-lex-token-stream nil)
1120 (semantic-lex-end-point (point))
1121 (semantic-lex-analysis-bounds
1122 (cons (point) (point-max)))
1123 (semantic-lex-current-depth 0)
1124 (semantic-lex-maximum-depth
1125 semantic-lex-depth)
1126 )
1127 (when ,condition ,@forms)
1128 semantic-lex-token-stream)))
1129 ))
1130
1131 (defmacro define-lex-regex-analyzer (name doc regexp &rest forms)
1132 "Create a lexical analyzer with NAME and DOC that will match REGEXP.
1133 FORMS are evaluated upon a successful match.
1134 See `define-lex-analyzer' for more about analyzers."
1135 `(define-lex-analyzer ,name
1136 ,doc
1137 (looking-at ,regexp)
1138 ,@forms
1139 ))
1140
1141 (defmacro define-lex-simple-regex-analyzer (name doc regexp toksym
1142 &optional index
1143 &rest forms)
1144 "Create a lexical analyzer with NAME and DOC that match REGEXP.
1145 TOKSYM is the symbol to use when creating a semantic lexical token.
1146 INDEX is the index into the match that defines the bounds of the token.
1147 Index should be a plain integer, and not specified in the macro as an
1148 expression.
1149 FORMS are evaluated upon a successful match BEFORE the new token is
1150 created. It is valid to ignore FORMS.
1151 See `define-lex-analyzer' for more about analyzers."
1152 `(define-lex-analyzer ,name
1153 ,doc
1154 (looking-at ,regexp)
1155 ,@forms
1156 (semantic-lex-push-token
1157 (semantic-lex-token ,toksym
1158 (match-beginning ,(or index 0))
1159 (match-end ,(or index 0))))
1160 ))
1161
1162 (defmacro define-lex-block-analyzer (name doc spec1 &rest specs)
1163 "Create a lexical analyzer NAME for paired delimiters blocks.
1164 It detects a paired delimiters block or the corresponding open or
1165 close delimiter depending on the value of the variable
1166 `semantic-lex-current-depth'. DOC is the documentation string of the lexical
1167 analyzer. SPEC1 and SPECS specify the token symbols and open, close
1168 delimiters used. Each SPEC has the form:
1169
1170 \(BLOCK-SYM (OPEN-DELIM OPEN-SYM) (CLOSE-DELIM CLOSE-SYM))
1171
1172 where BLOCK-SYM is the symbol returned in a block token. OPEN-DELIM
1173 and CLOSE-DELIM are respectively the open and close delimiters
1174 identifying a block. OPEN-SYM and CLOSE-SYM are respectively the
1175 symbols returned in open and close tokens."
1176 (let ((specs (cons spec1 specs))
1177 spec open olist clist)
1178 (while specs
1179 (setq spec (car specs)
1180 specs (cdr specs)
1181 open (nth 1 spec)
1182 ;; build alist ((OPEN-DELIM OPEN-SYM BLOCK-SYM) ...)
1183 olist (cons (list (car open) (cadr open) (car spec)) olist)
1184 ;; build alist ((CLOSE-DELIM CLOSE-SYM) ...)
1185 clist (cons (nth 2 spec) clist)))
1186 `(define-lex-analyzer ,name
1187 ,doc
1188 (and
1189 (looking-at "\\(\\s(\\|\\s)\\)")
1190 (let ((text (match-string 0)) match)
1191 (cond
1192 ((setq match (assoc text ',olist))
1193 (if (or (not semantic-lex-maximum-depth)
1194 (< semantic-lex-current-depth semantic-lex-maximum-depth))
1195 (progn
1196 (setq semantic-lex-current-depth (1+ semantic-lex-current-depth))
1197 (semantic-lex-push-token
1198 (semantic-lex-token
1199 (nth 1 match)
1200 (match-beginning 0) (match-end 0))))
1201 (semantic-lex-push-token
1202 (semantic-lex-token
1203 (nth 2 match)
1204 (match-beginning 0)
1205 (save-excursion
1206 (semantic-lex-unterminated-syntax-protection (nth 2 match)
1207 (forward-list 1)
1208 (point)))
1209 ))
1210 ))
1211 ((setq match (assoc text ',clist))
1212 (if (> semantic-lex-current-depth 0)
1213 (progn
1214 (setq semantic-lex-current-depth (1- semantic-lex-current-depth))
1215 (semantic-lex-push-token
1216 (semantic-lex-token
1217 (nth 1 match)
1218 (match-beginning 0) (match-end 0)))))))))
1219 )))
1220 \f
1221 ;;; Analyzers
1222 ;;
1223 ;; Pre-defined common analyzers.
1224 ;;
1225 (define-lex-analyzer semantic-lex-default-action
1226 "The default action when no other lexical actions match text.
1227 This action will just throw an error."
1228 t
1229 (error "Unmatched Text during Lexical Analysis"))
1230
1231 (define-lex-analyzer semantic-lex-beginning-of-line
1232 "Detect and create a beginning of line token (BOL)."
1233 (and (bolp)
1234 ;; Just insert a (bol N . N) token in the token stream,
1235 ;; without moving the point. N is the point at the
1236 ;; beginning of line.
1237 (semantic-lex-push-token (semantic-lex-token 'bol (point) (point)))
1238 nil) ;; CONTINUE
1239 ;; We identify and add the BOL token onto the stream, but since
1240 ;; semantic-lex-end-point doesn't move, we always fail CONDITION, and have no
1241 ;; FORMS body.
1242 nil)
1243
1244 (define-lex-simple-regex-analyzer semantic-lex-newline
1245 "Detect and create newline tokens."
1246 "\\s-*\\(\n\\|\\s>\\)" 'newline 1)
1247
1248 (define-lex-regex-analyzer semantic-lex-newline-as-whitespace
1249 "Detect and create newline tokens.
1250 Use this ONLY if newlines are not whitespace characters (such as when
1251 they are comment end characters) AND when you want whitespace tokens."
1252 "\\s-*\\(\n\\|\\s>\\)"
1253 ;; Language wants whitespaces. Create a token for it.
1254 (if (eq (semantic-lex-token-class (car semantic-lex-token-stream))
1255 'whitespace)
1256 ;; Merge whitespace tokens together if they are adjacent. Two
1257 ;; whitespace tokens may be separated by a comment which is not in
1258 ;; the token stream.
1259 (setcdr (semantic-lex-token-bounds (car semantic-lex-token-stream))
1260 (match-end 0))
1261 (semantic-lex-push-token
1262 (semantic-lex-token
1263 'whitespace (match-beginning 0) (match-end 0)))))
1264
1265 (define-lex-regex-analyzer semantic-lex-ignore-newline
1266 "Detect and ignore newline tokens.
1267 Use this ONLY if newlines are not whitespace characters (such as when
1268 they are comment end characters)."
1269 "\\s-*\\(\n\\|\\s>\\)"
1270 (setq semantic-lex-end-point (match-end 0)))
1271
1272 (define-lex-regex-analyzer semantic-lex-whitespace
1273 "Detect and create whitespace tokens."
1274 ;; catch whitespace when needed
1275 "\\s-+"
1276 ;; Language wants whitespaces. Create a token for it.
1277 (if (eq (semantic-lex-token-class (car semantic-lex-token-stream))
1278 'whitespace)
1279 ;; Merge whitespace tokens together if they are adjacent. Two
1280 ;; whitespace tokens may be separated by a comment which is not in
1281 ;; the token stream.
1282 (progn
1283 (setq semantic-lex-end-point (match-end 0))
1284 (setcdr (semantic-lex-token-bounds (car semantic-lex-token-stream))
1285 semantic-lex-end-point))
1286 (semantic-lex-push-token
1287 (semantic-lex-token
1288 'whitespace (match-beginning 0) (match-end 0)))))
1289
1290 (define-lex-regex-analyzer semantic-lex-ignore-whitespace
1291 "Detect and skip over whitespace tokens."
1292 ;; catch whitespace when needed
1293 "\\s-+"
1294 ;; Skip over the detected whitespace, do not create a token for it.
1295 (setq semantic-lex-end-point (match-end 0)))
1296
1297 (define-lex-simple-regex-analyzer semantic-lex-number
1298 "Detect and create number tokens.
1299 See `semantic-lex-number-expression' for details on matching numbers,
1300 and number formats."
1301 semantic-lex-number-expression 'number)
1302
1303 (define-lex-regex-analyzer semantic-lex-symbol-or-keyword
1304 "Detect and create symbol and keyword tokens."
1305 "\\(\\sw\\|\\s_\\)+"
1306 (semantic-lex-push-token
1307 (semantic-lex-token
1308 (or (semantic-lex-keyword-p (match-string 0)) 'symbol)
1309 (match-beginning 0) (match-end 0))))
1310
1311 (define-lex-simple-regex-analyzer semantic-lex-charquote
1312 "Detect and create charquote tokens."
1313 ;; Character quoting characters (ie, \n as newline)
1314 "\\s\\+" 'charquote)
1315
1316 (define-lex-simple-regex-analyzer semantic-lex-punctuation
1317 "Detect and create punctuation tokens."
1318 "\\(\\s.\\|\\s$\\|\\s'\\)" 'punctuation)
1319
1320 (define-lex-analyzer semantic-lex-punctuation-type
1321 "Detect and create a punctuation type token.
1322 Recognized punctuation is defined in the current table of lexical
1323 types, as the value of the `punctuation' token type."
1324 (and (looking-at "\\(\\s.\\|\\s$\\|\\s'\\)+")
1325 (let* ((key (match-string 0))
1326 (pos (match-beginning 0))
1327 (end (match-end 0))
1328 (len (- end pos))
1329 (lst (semantic-lex-type-value "punctuation" t))
1330 (def (car lst)) ;; default lexical symbol or nil
1331 (lst (cdr lst)) ;; alist of (LEX-SYM . PUNCT-STRING)
1332 (elt nil))
1333 (if lst
1334 ;; Starting with the longest one, search if the
1335 ;; punctuation string is defined for this language.
1336 (while (and (> len 0) (not (setq elt (rassoc key lst))))
1337 (setq len (1- len)
1338 key (substring key 0 len))))
1339 (if elt ;; Return the punctuation token found
1340 (semantic-lex-push-token
1341 (semantic-lex-token (car elt) pos (+ pos len)))
1342 (if def ;; Return a default generic token
1343 (semantic-lex-push-token
1344 (semantic-lex-token def pos end))
1345 ;; Nothing match
1346 )))))
1347
1348 (define-lex-regex-analyzer semantic-lex-paren-or-list
1349 "Detect open parenthesis.
1350 Return either a paren token or a semantic list token depending on
1351 `semantic-lex-current-depth'."
1352 "\\s("
1353 (if (or (not semantic-lex-maximum-depth)
1354 (< semantic-lex-current-depth semantic-lex-maximum-depth))
1355 (progn
1356 (setq semantic-lex-current-depth (1+ semantic-lex-current-depth))
1357 (semantic-lex-push-token
1358 (semantic-lex-token
1359 'open-paren (match-beginning 0) (match-end 0))))
1360 (semantic-lex-push-token
1361 (semantic-lex-token
1362 'semantic-list (match-beginning 0)
1363 (save-excursion
1364 (semantic-lex-unterminated-syntax-protection 'semantic-list
1365 (forward-list 1)
1366 (point))
1367 )))
1368 ))
1369
1370 (define-lex-simple-regex-analyzer semantic-lex-open-paren
1371 "Detect and create an open parenthesis token."
1372 "\\s(" 'open-paren 0 (setq semantic-lex-current-depth (1+ semantic-lex-current-depth)))
1373
1374 (define-lex-simple-regex-analyzer semantic-lex-close-paren
1375 "Detect and create a close parenthesis token."
1376 "\\s)" 'close-paren 0 (setq semantic-lex-current-depth (1- semantic-lex-current-depth)))
1377
1378 (define-lex-regex-analyzer semantic-lex-string
1379 "Detect and create a string token."
1380 "\\s\""
1381 ;; Zing to the end of this string.
1382 (semantic-lex-push-token
1383 (semantic-lex-token
1384 'string (point)
1385 (save-excursion
1386 (semantic-lex-unterminated-syntax-protection 'string
1387 (forward-sexp 1)
1388 (point))
1389 ))))
1390
1391 (define-lex-regex-analyzer semantic-lex-comments
1392 "Detect and create a comment token."
1393 semantic-lex-comment-regex
1394 (save-excursion
1395 (forward-comment 1)
1396 ;; Generate newline token if enabled
1397 (if (bolp) (backward-char 1))
1398 (setq semantic-lex-end-point (point))
1399 ;; Language wants comments or want them as whitespaces,
1400 ;; link them together.
1401 (if (eq (semantic-lex-token-class (car semantic-lex-token-stream)) 'comment)
1402 (setcdr (semantic-lex-token-bounds (car semantic-lex-token-stream))
1403 semantic-lex-end-point)
1404 (semantic-lex-push-token
1405 (semantic-lex-token
1406 'comment (match-beginning 0) semantic-lex-end-point)))))
1407
1408 (define-lex-regex-analyzer semantic-lex-comments-as-whitespace
1409 "Detect comments and create a whitespace token."
1410 semantic-lex-comment-regex
1411 (save-excursion
1412 (forward-comment 1)
1413 ;; Generate newline token if enabled
1414 (if (bolp) (backward-char 1))
1415 (setq semantic-lex-end-point (point))
1416 ;; Language wants comments or want them as whitespaces,
1417 ;; link them together.
1418 (if (eq (semantic-lex-token-class (car semantic-lex-token-stream)) 'whitespace)
1419 (setcdr (semantic-lex-token-bounds (car semantic-lex-token-stream))
1420 semantic-lex-end-point)
1421 (semantic-lex-push-token
1422 (semantic-lex-token
1423 'whitespace (match-beginning 0) semantic-lex-end-point)))))
1424
1425 (define-lex-regex-analyzer semantic-lex-ignore-comments
1426 "Detect and create a comment token."
1427 semantic-lex-comment-regex
1428 (let ((comment-start-point (point)))
1429 (forward-comment 1)
1430 (if (eq (point) comment-start-point)
1431 ;; In this case our start-skip string failed
1432 ;; to work properly. Lets try and move over
1433 ;; whatever white space we matched to begin
1434 ;; with.
1435 (skip-syntax-forward "-.'" (point-at-eol))
1436 ;; We may need to back up so newlines or whitespace is generated.
1437 (if (bolp)
1438 (backward-char 1)))
1439 (if (eq (point) comment-start-point)
1440 (error "Strange comment syntax prevents lexical analysis"))
1441 (setq semantic-lex-end-point (point))))
1442 \f
1443 ;;; Comment lexer
1444 ;;
1445 ;; Predefined lexers that could be used instead of creating new
1446 ;; analyzers.
1447
1448 (define-lex semantic-comment-lexer
1449 "A simple lexical analyzer that handles comments.
1450 This lexer will only return comment tokens. It is the default lexer
1451 used by `semantic-find-doc-snarf-comment' to snarf up the comment at
1452 point."
1453 semantic-lex-ignore-whitespace
1454 semantic-lex-ignore-newline
1455 semantic-lex-comments
1456 semantic-lex-default-action)
1457
1458 ;;; Test Lexer
1459 ;;
1460 (define-lex semantic-simple-lexer
1461 "A simple lexical analyzer that handles simple buffers.
1462 This lexer ignores comments and whitespace, and will return
1463 syntax as specified by the syntax table."
1464 semantic-lex-ignore-whitespace
1465 semantic-lex-ignore-newline
1466 semantic-lex-number
1467 semantic-lex-symbol-or-keyword
1468 semantic-lex-charquote
1469 semantic-lex-paren-or-list
1470 semantic-lex-close-paren
1471 semantic-lex-string
1472 semantic-lex-ignore-comments
1473 semantic-lex-punctuation
1474 semantic-lex-default-action)
1475 \f
1476 ;;; Analyzers generated from grammar.
1477 ;;
1478 ;; Some analyzers are hand written. Analyzers created with these
1479 ;; functions are generated from the grammar files.
1480
1481 (defmacro define-lex-keyword-type-analyzer (name doc syntax)
1482 "Define a keyword type analyzer NAME with DOC string.
1483 SYNTAX is the regexp that matches a keyword syntactic expression."
1484 (let ((key (make-symbol "key")))
1485 `(define-lex-analyzer ,name
1486 ,doc
1487 (and (looking-at ,syntax)
1488 (let ((,key (semantic-lex-keyword-p (match-string 0))))
1489 (when ,key
1490 (semantic-lex-push-token
1491 (semantic-lex-token
1492 ,key (match-beginning 0) (match-end 0)))))))
1493 ))
1494
1495 (defmacro define-lex-sexp-type-analyzer (name doc syntax token)
1496 "Define a sexp type analyzer NAME with DOC string.
1497 SYNTAX is the regexp that matches the beginning of the s-expression.
1498 TOKEN is the lexical token returned when SYNTAX matches."
1499 `(define-lex-regex-analyzer ,name
1500 ,doc
1501 ,syntax
1502 (semantic-lex-push-token
1503 (semantic-lex-token
1504 ,token (point)
1505 (save-excursion
1506 (semantic-lex-unterminated-syntax-protection ,token
1507 (forward-sexp 1)
1508 (point))))))
1509 )
1510
1511 (defmacro define-lex-regex-type-analyzer (name doc syntax matches default)
1512 "Define a regexp type analyzer NAME with DOC string.
1513 SYNTAX is the regexp that matches a syntactic expression.
1514 MATCHES is an alist of lexical elements used to refine the syntactic
1515 expression.
1516 DEFAULT is the default lexical token returned when no MATCHES."
1517 (if matches
1518 (let* ((val (make-symbol "val"))
1519 (lst (make-symbol "lst"))
1520 (elt (make-symbol "elt"))
1521 (pos (make-symbol "pos"))
1522 (end (make-symbol "end")))
1523 `(define-lex-analyzer ,name
1524 ,doc
1525 (and (looking-at ,syntax)
1526 (let* ((,val (match-string 0))
1527 (,pos (match-beginning 0))
1528 (,end (match-end 0))
1529 (,lst ,matches)
1530 ,elt)
1531 (while (and ,lst (not ,elt))
1532 (if (string-match (cdar ,lst) ,val)
1533 (setq ,elt (caar ,lst))
1534 (setq ,lst (cdr ,lst))))
1535 (semantic-lex-push-token
1536 (semantic-lex-token (or ,elt ,default) ,pos ,end))))
1537 ))
1538 `(define-lex-simple-regex-analyzer ,name
1539 ,doc
1540 ,syntax ,default)
1541 ))
1542
1543 (defmacro define-lex-string-type-analyzer (name doc syntax matches default)
1544 "Define a string type analyzer NAME with DOC string.
1545 SYNTAX is the regexp that matches a syntactic expression.
1546 MATCHES is an alist of lexical elements used to refine the syntactic
1547 expression.
1548 DEFAULT is the default lexical token returned when no MATCHES."
1549 (if matches
1550 (let* ((val (make-symbol "val"))
1551 (lst (make-symbol "lst"))
1552 (elt (make-symbol "elt"))
1553 (pos (make-symbol "pos"))
1554 (end (make-symbol "end"))
1555 (len (make-symbol "len")))
1556 `(define-lex-analyzer ,name
1557 ,doc
1558 (and (looking-at ,syntax)
1559 (let* ((,val (match-string 0))
1560 (,pos (match-beginning 0))
1561 (,end (match-end 0))
1562 (,len (- ,end ,pos))
1563 (,lst ,matches)
1564 ,elt)
1565 ;; Starting with the longest one, search if a lexical
1566 ;; value match a token defined for this language.
1567 (while (and (> ,len 0) (not (setq ,elt (rassoc ,val ,lst))))
1568 (setq ,len (1- ,len)
1569 ,val (substring ,val 0 ,len)))
1570 (when ,elt ;; Adjust token end position.
1571 (setq ,elt (car ,elt)
1572 ,end (+ ,pos ,len)))
1573 (semantic-lex-push-token
1574 (semantic-lex-token (or ,elt ,default) ,pos ,end))))
1575 ))
1576 `(define-lex-simple-regex-analyzer ,name
1577 ,doc
1578 ,syntax ,default)
1579 ))
1580
1581 (defmacro define-lex-block-type-analyzer (name doc syntax matches)
1582 "Define a block type analyzer NAME with DOC string.
1583
1584 SYNTAX is the regexp that matches block delimiters, typically the
1585 open (`\\\\s(') and close (`\\\\s)') parenthesis syntax classes.
1586
1587 MATCHES is a pair (OPEN-SPECS . CLOSE-SPECS) that defines blocks.
1588
1589 OPEN-SPECS is a list of (OPEN-DELIM OPEN-TOKEN BLOCK-TOKEN) elements
1590 where:
1591
1592 OPEN-DELIM is a string: the block open delimiter character.
1593
1594 OPEN-TOKEN is the lexical token class associated to the OPEN-DELIM
1595 delimiter.
1596
1597 BLOCK-TOKEN is the lexical token class associated to the block
1598 that starts at the OPEN-DELIM delimiter.
1599
1600 CLOSE-SPECS is a list of (CLOSE-DELIM CLOSE-TOKEN) elements where:
1601
1602 CLOSE-DELIM is a string: the block end delimiter character.
1603
1604 CLOSE-TOKEN is the lexical token class associated to the
1605 CLOSE-DELIM delimiter.
1606
1607 Each element in OPEN-SPECS must have a corresponding element in
1608 CLOSE-SPECS.
1609
1610 The lexer will return a BLOCK-TOKEN token when the value of
1611 `semantic-lex-current-depth' is greater than or equal to the maximum
1612 depth of parenthesis tracking (see also the function `semantic-lex').
1613 Otherwise it will return OPEN-TOKEN and CLOSE-TOKEN tokens.
1614
1615 TO DO: Put the following in the developer's guide and just put a
1616 reference here.
1617
1618 In the grammar:
1619
1620 The value of a block token must be a string that contains a readable
1621 sexp of the form:
1622
1623 \"(OPEN-TOKEN CLOSE-TOKEN)\"
1624
1625 OPEN-TOKEN and CLOSE-TOKEN represent the block delimiters, and must be
1626 lexical tokens of respectively `open-paren' and `close-paren' types.
1627 Their value is the corresponding delimiter character as a string.
1628
1629 Here is a small example to analyze a parenthesis block:
1630
1631 %token <block> PAREN_BLOCK \"(LPAREN RPAREN)\"
1632 %token <open-paren> LPAREN \"(\"
1633 %token <close-paren> RPAREN \")\"
1634
1635 When the lexer encounters the open-paren delimiter \"(\":
1636
1637 - If the maximum depth of parenthesis tracking is not reached (that
1638 is, current depth < max depth), it returns a (LPAREN start . end)
1639 token, then continue analysis inside the block. Later, when the
1640 corresponding close-paren delimiter \")\" will be encountered, it
1641 will return a (RPAREN start . end) token.
1642
1643 - If the maximum depth of parenthesis tracking is reached (current
1644 depth >= max depth), it returns the whole parenthesis block as
1645 a (PAREN_BLOCK start . end) token."
1646 (let* ((val (make-symbol "val"))
1647 (lst (make-symbol "lst"))
1648 (elt (make-symbol "elt")))
1649 `(define-lex-analyzer ,name
1650 ,doc
1651 (and
1652 (looking-at ,syntax) ;; "\\(\\s(\\|\\s)\\)"
1653 (let ((,val (match-string 0))
1654 (,lst ,matches)
1655 ,elt)
1656 (cond
1657 ((setq ,elt (assoc ,val (car ,lst)))
1658 (if (or (not semantic-lex-maximum-depth)
1659 (< semantic-lex-current-depth semantic-lex-maximum-depth))
1660 (progn
1661 (setq semantic-lex-current-depth (1+ semantic-lex-current-depth))
1662 (semantic-lex-push-token
1663 (semantic-lex-token
1664 (nth 1 ,elt)
1665 (match-beginning 0) (match-end 0))))
1666 (semantic-lex-push-token
1667 (semantic-lex-token
1668 (nth 2 ,elt)
1669 (match-beginning 0)
1670 (save-excursion
1671 (semantic-lex-unterminated-syntax-protection (nth 2 ,elt)
1672 (forward-list 1)
1673 (point)))))))
1674 ((setq ,elt (assoc ,val (cdr ,lst)))
1675 (setq semantic-lex-current-depth (1- semantic-lex-current-depth))
1676 (semantic-lex-push-token
1677 (semantic-lex-token
1678 (nth 1 ,elt)
1679 (match-beginning 0) (match-end 0))))
1680 ))))
1681 ))
1682 \f
1683 ;;; Lexical Safety
1684 ;;
1685 ;; The semantic lexers, unlike other lexers, can throw errors on
1686 ;; unbalanced syntax. Since editing is all about changing text
1687 ;; we need to provide a convenient way to protect against syntactic
1688 ;; inequalities.
1689
1690 (defmacro semantic-lex-catch-errors (symbol &rest forms)
1691 "Using SYMBOL, execute FORMS catching lexical errors.
1692 If FORMS results in a call to the parser that throws a lexical error,
1693 the error will be caught here without the buffer's cache being thrown
1694 out of date.
1695 If there is an error, the syntax that failed is returned.
1696 If there is no error, then the last value of FORMS is returned."
1697 (let ((ret (make-symbol "ret"))
1698 (syntax (make-symbol "syntax"))
1699 (start (make-symbol "start"))
1700 (end (make-symbol "end")))
1701 `(let* ((semantic-lex-unterminated-syntax-end-function
1702 (lambda (,syntax ,start ,end)
1703 (throw ',symbol ,syntax)))
1704 ;; Delete the below when semantic-flex is fully retired.
1705 (semantic-flex-unterminated-syntax-end-function
1706 semantic-lex-unterminated-syntax-end-function)
1707 (,ret (catch ',symbol
1708 (save-excursion
1709 ,@forms
1710 nil))))
1711 ;; Great Sadness. Assume that FORMS execute within the
1712 ;; confines of the current buffer only! Mark this thing
1713 ;; unparsable iff the special symbol was thrown. This
1714 ;; will prevent future calls from parsing, but will allow
1715 ;; then to still return the cache.
1716 (when ,ret
1717 ;; Leave this message off. If an APP using this fcn wants
1718 ;; a message, they can do it themselves. This cleans up
1719 ;; problems with the idle scheduler obscuring useful data.
1720 ;;(message "Buffer not currently parsable (%S)." ,ret)
1721 (semantic-parse-tree-unparseable))
1722 ,ret)))
1723 (put 'semantic-lex-catch-errors 'lisp-indent-function 1)
1724
1725 \f
1726 ;;; Interfacing with edebug
1727 ;;
1728 (add-hook
1729 'edebug-setup-hook
1730 #'(lambda ()
1731
1732 (def-edebug-spec define-lex
1733 (&define name stringp (&rest symbolp))
1734 )
1735 (def-edebug-spec define-lex-analyzer
1736 (&define name stringp form def-body)
1737 )
1738 (def-edebug-spec define-lex-regex-analyzer
1739 (&define name stringp form def-body)
1740 )
1741 (def-edebug-spec define-lex-simple-regex-analyzer
1742 (&define name stringp form symbolp [ &optional form ] def-body)
1743 )
1744 (def-edebug-spec define-lex-block-analyzer
1745 (&define name stringp form (&rest form))
1746 )
1747 (def-edebug-spec semantic-lex-catch-errors
1748 (symbolp def-body)
1749 )
1750
1751 ))
1752 \f
1753 ;;; Compatibility with Semantic 1.x lexical analysis
1754 ;;
1755 ;; NOTE: DELETE THIS SOMEDAY SOON
1756
1757 (semantic-alias-obsolete 'semantic-flex-start 'semantic-lex-token-start "23.2")
1758 (semantic-alias-obsolete 'semantic-flex-end 'semantic-lex-token-end "23.2")
1759 (semantic-alias-obsolete 'semantic-flex-text 'semantic-lex-token-text "23.2")
1760 (semantic-alias-obsolete 'semantic-flex-make-keyword-table 'semantic-lex-make-keyword-table "23.2")
1761 (semantic-alias-obsolete 'semantic-flex-keyword-p 'semantic-lex-keyword-p "23.2")
1762 (semantic-alias-obsolete 'semantic-flex-keyword-put 'semantic-lex-keyword-put "23.2")
1763 (semantic-alias-obsolete 'semantic-flex-keyword-get 'semantic-lex-keyword-get "23.2")
1764 (semantic-alias-obsolete 'semantic-flex-map-keywords 'semantic-lex-map-keywords "23.2")
1765 (semantic-alias-obsolete 'semantic-flex-keywords 'semantic-lex-keywords "23.2")
1766 (semantic-alias-obsolete 'semantic-flex-buffer 'semantic-lex-buffer "23.2")
1767 (semantic-alias-obsolete 'semantic-flex-list 'semantic-lex-list "23.2")
1768
1769 ;; This simple scanner uses the syntax table to generate a stream of
1770 ;; simple tokens of the form:
1771 ;;
1772 ;; (SYMBOL START . END)
1773 ;;
1774 ;; Where symbol is the type of thing it is. START and END mark that
1775 ;; objects boundary.
1776
1777 (defvar semantic-flex-tokens semantic-lex-tokens
1778 "An alist of semantic token types.
1779 See variable `semantic-lex-tokens'.")
1780
1781 (defvar semantic-flex-unterminated-syntax-end-function
1782 (lambda (syntax syntax-start flex-end) flex-end)
1783 "Function called when unterminated syntax is encountered.
1784 This should be set to one function. That function should take three
1785 parameters. The SYNTAX, or type of syntax which is unterminated.
1786 SYNTAX-START where the broken syntax begins.
1787 FLEX-END is where the lexical analysis was asked to end.
1788 This function can be used for languages that can intelligently fix up
1789 broken syntax, or the exit lexical analysis via `throw' or `signal'
1790 when finding unterminated syntax.")
1791
1792 (defvar semantic-flex-extensions nil
1793 "Buffer local extensions to the lexical analyzer.
1794 This should contain an alist with a key of a regex and a data element of
1795 a function. The function should both move point, and return a lexical
1796 token of the form:
1797 ( TYPE START . END)
1798 nil is also a valid return value.
1799 TYPE can be any type of symbol, as long as it doesn't occur as a
1800 nonterminal in the language definition.")
1801 (make-variable-buffer-local 'semantic-flex-extensions)
1802
1803 (defvar semantic-flex-syntax-modifications nil
1804 "Changes to the syntax table for this buffer.
1805 These changes are active only while the buffer is being flexed.
1806 This is a list where each element has the form:
1807 (CHAR CLASS)
1808 CHAR is the char passed to `modify-syntax-entry',
1809 and CLASS is the string also passed to `modify-syntax-entry' to define
1810 what syntax class CHAR has.")
1811 (make-variable-buffer-local 'semantic-flex-syntax-modifications)
1812
1813 (defvar semantic-ignore-comments t
1814 "Default comment handling.
1815 The value t means to strip comments when flexing; nil means
1816 to keep comments as part of the token stream.")
1817 (make-variable-buffer-local 'semantic-ignore-comments)
1818
1819 (defvar semantic-flex-enable-newlines nil
1820 "When flexing, report newlines as syntactic elements.
1821 Useful for languages where the newline is a special case terminator.
1822 Only set this on a per mode basis, not globally.")
1823 (make-variable-buffer-local 'semantic-flex-enable-newlines)
1824
1825 (defvar semantic-flex-enable-whitespace nil
1826 "When flexing, report whitespace as syntactic elements.
1827 Useful for languages where the syntax is whitespace dependent.
1828 Only set this on a per mode basis, not globally.")
1829 (make-variable-buffer-local 'semantic-flex-enable-whitespace)
1830
1831 (defvar semantic-flex-enable-bol nil
1832 "When flexing, report beginning of lines as syntactic elements.
1833 Useful for languages like python which are indentation sensitive.
1834 Only set this on a per mode basis, not globally.")
1835 (make-variable-buffer-local 'semantic-flex-enable-bol)
1836
1837 (defvar semantic-number-expression semantic-lex-number-expression
1838 "See variable `semantic-lex-number-expression'.")
1839 (make-variable-buffer-local 'semantic-number-expression)
1840
1841 (defvar semantic-flex-depth 0
1842 "Default flexing depth.
1843 This specifies how many lists to create tokens in.")
1844 (make-variable-buffer-local 'semantic-flex-depth)
1845
1846 (defun semantic-flex (start end &optional depth length)
1847 "Using the syntax table, do something roughly equivalent to flex.
1848 Semantically check between START and END. Optional argument DEPTH
1849 indicates at what level to scan over entire lists.
1850 The return value is a token stream. Each element is a list, such of
1851 the form (symbol start-expression . end-expression) where SYMBOL
1852 denotes the token type.
1853 See `semantic-flex-tokens' variable for details on token types.
1854 END does not mark the end of the text scanned, only the end of the
1855 beginning of text scanned. Thus, if a string extends past END, the
1856 end of the return token will be larger than END. To truly restrict
1857 scanning, use `narrow-to-region'.
1858 The last argument, LENGTH specifies that `semantic-flex' should only
1859 return LENGTH tokens."
1860 (message "`semantic-flex' is an obsolete function. Use `define-lex' to create lexers.")
1861 (if (not semantic-flex-keywords-obarray)
1862 (setq semantic-flex-keywords-obarray [ nil ]))
1863 (let ((ts nil)
1864 (pos (point))
1865 (ep nil)
1866 (curdepth 0)
1867 (cs (if comment-start-skip
1868 (concat "\\(\\s<\\|" comment-start-skip "\\)")
1869 (concat "\\(\\s<\\)")))
1870 (newsyntax (copy-syntax-table (syntax-table)))
1871 (mods semantic-flex-syntax-modifications)
1872 ;; Use the default depth if it is not specified.
1873 (depth (or depth semantic-flex-depth)))
1874 ;; Update the syntax table
1875 (while mods
1876 (modify-syntax-entry (car (car mods)) (car (cdr (car mods))) newsyntax)
1877 (setq mods (cdr mods)))
1878 (with-syntax-table newsyntax
1879 (goto-char start)
1880 (while (and (< (point) end) (or (not length) (<= (length ts) length)))
1881 (cond
1882 ;; catch beginning of lines when needed.
1883 ;; Must be done before catching any other tokens!
1884 ((and semantic-flex-enable-bol
1885 (bolp)
1886 ;; Just insert a (bol N . N) token in the token stream,
1887 ;; without moving the point. N is the point at the
1888 ;; beginning of line.
1889 (setq ts (cons (cons 'bol (cons (point) (point))) ts))
1890 nil)) ;; CONTINUE
1891 ;; special extensions, includes whitespace, nl, etc.
1892 ((and semantic-flex-extensions
1893 (let ((fe semantic-flex-extensions)
1894 (r nil))
1895 (while fe
1896 (if (looking-at (car (car fe)))
1897 (setq ts (cons (funcall (cdr (car fe))) ts)
1898 r t
1899 fe nil
1900 ep (point)))
1901 (setq fe (cdr fe)))
1902 (if (and r (not (car ts))) (setq ts (cdr ts)))
1903 r)))
1904 ;; catch newlines when needed
1905 ((looking-at "\\s-*\\(\n\\|\\s>\\)")
1906 (if semantic-flex-enable-newlines
1907 (setq ep (match-end 1)
1908 ts (cons (cons 'newline
1909 (cons (match-beginning 1) ep))
1910 ts))))
1911 ;; catch whitespace when needed
1912 ((looking-at "\\s-+")
1913 (if semantic-flex-enable-whitespace
1914 ;; Language wants whitespaces, link them together.
1915 (if (eq (car (car ts)) 'whitespace)
1916 (setcdr (cdr (car ts)) (match-end 0))
1917 (setq ts (cons (cons 'whitespace
1918 (cons (match-beginning 0)
1919 (match-end 0)))
1920 ts)))))
1921 ;; numbers
1922 ((and semantic-number-expression
1923 (looking-at semantic-number-expression))
1924 (setq ts (cons (cons 'number
1925 (cons (match-beginning 0)
1926 (match-end 0)))
1927 ts)))
1928 ;; symbols
1929 ((looking-at "\\(\\sw\\|\\s_\\)+")
1930 (setq ts (cons (cons
1931 ;; Get info on if this is a keyword or not
1932 (or (semantic-lex-keyword-p (match-string 0))
1933 'symbol)
1934 (cons (match-beginning 0) (match-end 0)))
1935 ts)))
1936 ;; Character quoting characters (ie, \n as newline)
1937 ((looking-at "\\s\\+")
1938 (setq ts (cons (cons 'charquote
1939 (cons (match-beginning 0) (match-end 0)))
1940 ts)))
1941 ;; Open parens, or semantic-lists.
1942 ((looking-at "\\s(")
1943 (if (or (not depth) (< curdepth depth))
1944 (progn
1945 (setq curdepth (1+ curdepth))
1946 (setq ts (cons (cons 'open-paren
1947 (cons (match-beginning 0) (match-end 0)))
1948 ts)))
1949 (setq ts (cons
1950 (cons 'semantic-list
1951 (cons (match-beginning 0)
1952 (save-excursion
1953 (condition-case nil
1954 (forward-list 1)
1955 ;; This case makes flex robust
1956 ;; to broken lists.
1957 (error
1958 (goto-char
1959 (funcall
1960 semantic-flex-unterminated-syntax-end-function
1961 'semantic-list
1962 start end))))
1963 (setq ep (point)))))
1964 ts))))
1965 ;; Close parens
1966 ((looking-at "\\s)")
1967 (setq ts (cons (cons 'close-paren
1968 (cons (match-beginning 0) (match-end 0)))
1969 ts))
1970 (setq curdepth (1- curdepth)))
1971 ;; String initiators
1972 ((looking-at "\\s\"")
1973 ;; Zing to the end of this string.
1974 (setq ts (cons (cons 'string
1975 (cons (match-beginning 0)
1976 (save-excursion
1977 (condition-case nil
1978 (forward-sexp 1)
1979 ;; This case makes flex
1980 ;; robust to broken strings.
1981 (error
1982 (goto-char
1983 (funcall
1984 semantic-flex-unterminated-syntax-end-function
1985 'string
1986 start end))))
1987 (setq ep (point)))))
1988 ts)))
1989 ;; comments
1990 ((looking-at cs)
1991 (if (and semantic-ignore-comments
1992 (not semantic-flex-enable-whitespace))
1993 ;; If the language doesn't deal with comments nor
1994 ;; whitespaces, ignore them here.
1995 (let ((comment-start-point (point)))
1996 (forward-comment 1)
1997 (if (eq (point) comment-start-point)
1998 ;; In this case our start-skip string failed
1999 ;; to work properly. Lets try and move over
2000 ;; whatever white space we matched to begin
2001 ;; with.
2002 (skip-syntax-forward "-.'" (point-at-eol))
2003 ;;(forward-comment 1)
2004 ;; Generate newline token if enabled
2005 (if (and semantic-flex-enable-newlines
2006 (bolp))
2007 (backward-char 1)))
2008 (if (eq (point) comment-start-point)
2009 (error "Strange comment syntax prevents lexical analysis"))
2010 (setq ep (point)))
2011 (let ((tk (if semantic-ignore-comments 'whitespace 'comment)))
2012 (save-excursion
2013 (forward-comment 1)
2014 ;; Generate newline token if enabled
2015 (if (and semantic-flex-enable-newlines
2016 (bolp))
2017 (backward-char 1))
2018 (setq ep (point)))
2019 ;; Language wants comments or want them as whitespaces,
2020 ;; link them together.
2021 (if (eq (car (car ts)) tk)
2022 (setcdr (cdr (car ts)) ep)
2023 (setq ts (cons (cons tk (cons (match-beginning 0) ep))
2024 ts))))))
2025 ;; punctuation
2026 ((looking-at "\\(\\s.\\|\\s$\\|\\s'\\)")
2027 (setq ts (cons (cons 'punctuation
2028 (cons (match-beginning 0) (match-end 0)))
2029 ts)))
2030 ;; unknown token
2031 (t
2032 (error "What is that?")))
2033 (goto-char (or ep (match-end 0)))
2034 (setq ep nil)))
2035 ;; maybe catch the last beginning of line when needed
2036 (and semantic-flex-enable-bol
2037 (= (point) end)
2038 (bolp)
2039 (setq ts (cons (cons 'bol (cons (point) (point))) ts)))
2040 (goto-char pos)
2041 ;;(message "Flexing muscles...done")
2042 (nreverse ts)))
2043
2044 (provide 'semantic/lex)
2045
2046 ;; Local variables:
2047 ;; generated-autoload-file: "loaddefs.el"
2048 ;; generated-autoload-load-name: "semantic/lex"
2049 ;; End:
2050
2051 ;;; semantic/lex.el ends here