Merge branch 'master' into comment-cache
[emacs.git] / lisp / progmodes / antlr-mode.el
blob2d09e431f29b66d0c22d2858259e76b8fc371d30
1 ;;; antlr-mode.el --- major mode for ANTLR grammar files
3 ;; Copyright (C) 1999-2017 Free Software Foundation, Inc.
5 ;; Author: Christoph Wedler <Christoph.Wedler@sap.com>
6 ;; Keywords: languages, ANTLR, code generator
7 ;; Version: 2.2c
8 ;; X-URL: http://antlr-mode.sourceforge.net/
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; The Emacs package ANTLR-Mode provides: syntax highlighting for ANTLR grammar
28 ;; files, automatic indentation, menus containing rule/token definitions and
29 ;; supported options and various other things like running ANTLR from within
30 ;; Emacs.
32 ;; For details, check <http://antlr-mode.sourceforge.net/> or, if you prefer
33 ;; the manual style, follow all commands mentioned in the documentation of
34 ;; `antlr-mode'. ANTLR is a LL(k)-based recognition tool which generates
35 ;; lexers, parsers and tree transformers in Java, C++ or Sather and can be
36 ;; found at <http://www.antlr.org/>.
38 ;; Bug fixes, bug reports, improvements, and suggestions for the newest version
39 ;; are strongly appreciated.
41 ;; To-do/Wish-list:
43 ;; * Next Version [C-c C-w]. Produce HTML document with syntax highlighted
44 ;; and hyper-links (using htmlize).
45 ;; * Next Version [C-c C-u]. Insert/update special comments: each rule lists
46 ;; all rules which use the current rule. With font-lock update.
47 ;; * Next Version. Make hiding much more customizable.
48 ;; * Planned [C-c C-j]. Jump to generated coding.
49 ;; * Planned. Further support for imenu, i.e., include entries for method
50 ;; definitions at beginning of grammar class.
51 ;; * Planned [C-c C-p]. Pack/unpack rule/subrule & options (one/multi-line).
53 ;; * Probably. Show rules/dependencies for ANT like for Makefile (does ANT
54 ;; support vocabularies and grammar inheritance?), I have to look at
55 ;; jde-ant.el: http://jakarta.apache.org/ant/manual/OptionalTasks/antlr.html
56 ;; * Probably. Make `indent-region' faster, especially in actions. ELP
57 ;; profiling in a class init action shows half the time is spent in
58 ;; `antlr-next-rule', the other half in `c-guess-basic-syntax'.
59 ;; * Unlikely. Sather as generated language with syntax highlighting etc/.
60 ;; Questions/problems: is sather-mode.el the standard mode for sather, is it
61 ;; still supported, what is its relationship to eiffel3.el? Requirement:
62 ;; this mode must not depend on a Sather mode.
63 ;; * Unlikely. Faster syntax highlighting: sectionize the buffer into Antlr
64 ;; and action code and run special highlighting functions on these regions.
65 ;; Problems: code size, this mode would depend on font-lock internals.
67 ;;; Installation:
69 ;; This file requires Emacs-20.3, XEmacs-20.4 or higher and package cc-mode.
71 ;; If antlr-mode is not part of your distribution, put this file into your
72 ;; load-path and the following into your init file:
73 ;; (autoload 'antlr-mode "antlr-mode" nil t)
74 ;; (setq auto-mode-alist (cons '("\\.g\\'" . antlr-mode) auto-mode-alist))
75 ;; (add-hook 'speedbar-load-hook ; would be too late in antlr-mode.el
76 ;; (lambda () (speedbar-add-supported-extension ".g")))
78 ;; I strongly recommend to use font-lock with a support mode like fast-lock,
79 ;; lazy-lock or better jit-lock (Emacs-21.1+) / lazy-shot (XEmacs).
81 ;; To customize, use menu item "Antlr" -> "Customize Antlr".
83 ;;; Code:
85 (eval-when-compile
86 (require 'cl))
88 (require 'easymenu)
89 (require 'cc-mode)
91 ;; Just to get the rid of the byte compiler warning. The code for
92 ;; this function and its friends are too complex for their own good.
93 (declare-function cond-emacs-xemacs-macfn "antlr-mode" (args &optional msg))
95 ;; General Emacs/XEmacs-compatibility compile-time macros
96 (eval-when-compile
97 (defmacro cond-emacs-xemacs (&rest args)
98 (cond-emacs-xemacs-macfn
99 args "`cond-emacs-xemacs' must return exactly one element"))
100 (defun cond-emacs-xemacs-macfn (args &optional msg)
101 (if (atom args) args
102 (and (eq (car args) :@) (null msg) ; (:@ ...spliced...)
103 (setq args (cdr args)
104 msg "(:@ ....) must return exactly one element"))
105 (let ((ignore (if (featurep 'xemacs) :EMACS :XEMACS))
106 (mode :BOTH) code)
107 (while (consp args)
108 (if (memq (car args) '(:EMACS :XEMACS :BOTH)) (setq mode (pop args)))
109 (if (atom args)
110 (or args (error "Used selector %s without elements" mode))
111 (or (eq ignore mode)
112 (push (cond-emacs-xemacs-macfn (car args)) code))
113 (pop args)))
114 (cond (msg (if (or args (cdr code)) (error msg) (car code)))
115 ((or (null args) (eq ignore mode)) (nreverse code))
116 (t (nconc (nreverse code) args))))))
117 ;; Emacs/XEmacs-compatibility `defun': remove interactive "_" for Emacs, use
118 ;; existing functions when they are `fboundp', provide shortcuts if they are
119 ;; known to be defined in a specific Emacs branch (for short .elc)
120 (defmacro defunx (name arglist &rest definition)
121 (let ((xemacsp (featurep 'xemacs)) reuses)
122 (while (memq (car definition)
123 '(:try :emacs-and-try :xemacs-and-try))
124 (if (eq (pop definition) (if xemacsp :xemacs-and-try :emacs-and-try))
125 (setq reuses (car definition)
126 definition nil)
127 (push (pop definition) reuses)))
128 (if (and reuses (symbolp reuses))
129 `(defalias ',name ',reuses)
130 (let* ((docstring (if (stringp (car definition)) (pop definition)))
131 (spec (and (not xemacsp)
132 (eq (car-safe (car definition)) 'interactive)
133 (null (cddar definition))
134 (cadar definition))))
135 (if (and (stringp spec)
136 (not (string-equal spec ""))
137 (eq (aref spec 0) ?_))
138 (setq definition
139 (cons (if (string-equal spec "_")
140 '(interactive)
141 `(interactive ,(substring spec 1)))
142 (cdr definition))))
143 (if (null reuses)
144 `(defun ,name ,arglist ,docstring
145 ,@(cond-emacs-xemacs-macfn definition))
146 ;; no dynamic docstring in this case
147 `(eval-and-compile ; no warnings in Emacs
148 (defalias ',name
149 (cond ,@(mapcar (lambda (func) `((fboundp ',func) ',func))
150 (nreverse reuses))
151 (t ,(if definition
152 `(lambda ,arglist ,docstring
153 ,@(cond-emacs-xemacs-macfn definition))
154 'ignore))))))))))
155 (defmacro ignore-errors-x (&rest body)
156 (let ((specials '((scan-sexps . 4) (scan-lists . 5)))
157 spec nils)
158 (if (and (featurep 'xemacs)
159 (null (cdr body)) (consp (car body))
160 (setq spec (assq (caar body) specials))
161 (>= (setq nils (- (cdr spec) (length (car body)))) 0))
162 `(,@(car body) ,@(make-list nils nil) t)
163 `(ignore-errors ,@body)))))
165 ;; More compile-time-macros
166 (eval-when-compile
167 (defmacro save-buffer-state-x (&rest body) ; similar to EMACS/lazy-lock.el
168 (let ((modified (with-no-warnings (gensym "save-buffer-state-x-modified-"))))
169 `(let ((,modified (buffer-modified-p)))
170 (unwind-protect
171 (let ((buffer-undo-list t) (inhibit-read-only t)
172 ,@(unless (featurep 'xemacs)
173 '((inhibit-point-motion-hooks t) deactivate-mark))
174 (inhibit-modification-hooks t)
175 buffer-file-name buffer-file-truename)
176 ,@body)
177 (and (not ,modified) (buffer-modified-p)
178 (set-buffer-modified-p nil)))))))
179 (put 'save-buffer-state-x 'lisp-indent-function 0)
181 (defvar outline-level)
182 (defvar imenu-use-markers)
183 (defvar imenu-create-index-function)
185 ;; We cannot use `c-forward-syntactic-ws' directly since it is a macro since
186 ;; cc-mode-5.30 => antlr-mode compiled with older cc-mode would fail (macro
187 ;; call) when used with newer cc-mode. Also, antlr-mode compiled with newer
188 ;; cc-mode would fail (undefined `c-forward-sws') when used with older cc-mode.
189 ;; Additional to the `defalias' below, we must set `antlr-c-forward-sws' to
190 ;; `c-forward-syntactic-ws' when `c-forward-sws' is not defined after requiring
191 ;; cc-mode.
192 (defalias 'antlr-c-forward-sws 'c-forward-sws)
195 ;;;;##########################################################################
196 ;;;; Variables
197 ;;;;##########################################################################
200 (defgroup antlr nil
201 "Major mode for ANTLR grammar files."
202 :group 'languages
203 :link '(emacs-commentary-link "antlr-mode.el")
204 :link '(url-link "http://antlr-mode.sourceforge.net/")
205 :prefix "antlr-")
207 (defconst antlr-version "2.2c"
208 "ANTLR major mode version number.
209 Check <http://antlr-mode.sourceforge.net/> for the newest.")
212 ;;;===========================================================================
213 ;;; Controlling ANTLR's code generator (language option)
214 ;;;===========================================================================
216 (defvar antlr-language nil
217 "Major mode corresponding to ANTLR's \"language\" option.
218 Set via `antlr-language-alist'. The only useful place to change this
219 buffer-local variable yourself is in `antlr-mode-hook' or in the \"local
220 variable list\" near the end of the file, see
221 `enable-local-variables'.")
223 (defcustom antlr-language-alist
224 '((java-mode "Java" nil "\"Java\"" "Java")
225 (c++-mode "C++" "\"Cpp\"" "Cpp"))
226 "List of ANTLR's supported languages.
227 Each element in this list looks like
228 (MAJOR-MODE MODELINE-STRING OPTION-VALUE...)
230 MAJOR-MODE, the major mode of the code in the grammar's actions, is the
231 value of `antlr-language' if the first group in the string matched by
232 REGEXP in `antlr-language-limit-n-regexp' is one of the OPTION-VALUEs.
233 An OPTION-VALUE of nil denotes the fallback element. MODELINE-STRING is
234 also displayed in the mode line next to \"Antlr\"."
235 :group 'antlr
236 :type '(repeat (group :value (java-mode "")
237 (function :tag "Major mode")
238 (string :tag "Mode line string")
239 (repeat :tag "ANTLR language option" :inline t
240 (choice (const :tag "Default" nil)
241 string )))))
243 (defcustom antlr-language-limit-n-regexp
244 '(8192 . "language[ \t]*=[ \t]*\\(\"?[A-Z][A-Za-z_]*\"?\\)")
245 "Used to set a reasonable value for `antlr-language'.
246 Looks like \(LIMIT . REGEXP). Search for REGEXP from the beginning of
247 the buffer to LIMIT and use the first group in the matched string to set
248 the language according to `antlr-language-alist'."
249 :group 'antlr
250 :type '(cons (choice :tag "Limit" (const :tag "No" nil) (integer :value 0))
251 regexp))
254 ;;;===========================================================================
255 ;;; Hide/Unhide, Indent/Tabs
256 ;;;===========================================================================
258 (defcustom antlr-action-visibility 3
259 "Visibility of actions when command `antlr-hide-actions' is used.
260 If nil, the actions with their surrounding braces are hidden. If a
261 number, do not hide the braces, only hide the contents if its length is
262 greater than this number."
263 :group 'antlr
264 :type '(choice (const :tag "Completely hidden" nil)
265 (integer :tag "Hidden if longer than" :value 3)))
267 (defcustom antlr-indent-comment 'tab
268 "Non-nil, if the indentation should touch lines in block comments.
269 If nil, no continuation line of a block comment is changed. If t, they
270 are changed according to `c-indentation-line'. When not nil and not t,
271 they are only changed by \\[antlr-indent-command]."
272 :group 'antlr
273 :type '(radio (const :tag "No" nil)
274 (const :tag "Always" t)
275 (sexp :tag "With TAB" :format "%t" :value tab)))
277 (defcustom antlr-tab-offset-alist
278 '((antlr-mode nil 4 nil)
279 (java-mode "antlr" 4 nil))
280 "Alist to determine whether to use ANTLR's convention for TABs.
281 Each element looks like \(MAJOR-MODE REGEXP TAB-WIDTH INDENT-TABS-MODE).
282 The first element whose MAJOR-MODE is nil or equal to `major-mode' and
283 whose REGEXP is nil or matches variable `buffer-file-name' is used to
284 set `tab-width' and `indent-tabs-mode'. This is useful to support both
285 ANTLR's and Java's indentation styles. Used by `antlr-set-tabs'."
286 :group 'antlr
287 :type '(repeat (group :value (antlr-mode nil 8 nil)
288 (choice (const :tag "All" nil)
289 (function :tag "Major mode"))
290 (choice (const :tag "All" nil) regexp)
291 (integer :tag "Tab width")
292 (boolean :tag "Indent-tabs-mode"))))
294 (defcustom antlr-indent-style "java"
295 "If non-nil, cc-mode indentation style used for `antlr-mode'.
296 See `c-set-style' and for details, where the most interesting part in
297 `c-style-alist' is the value of `c-basic-offset'."
298 :group 'antlr
299 :type '(choice (const nil) regexp))
301 (defcustom antlr-indent-item-regexp
302 "[]}):;|&]" ; & is local ANTLR extension (SGML's and-connector)
303 "Regexp matching lines which should be indented by one TAB less.
304 See `antlr-indent-line' and command \\[antlr-indent-command]."
305 :group 'antlr
306 :type 'regexp)
308 (defcustom antlr-indent-at-bol-alist
309 ;; eval-when-compile not usable with defcustom...
310 '((java-mode . "\\(package\\|import\\)\\>")
311 (c++-mode . "#\\(assert\\|cpu\\|define\\|endif\\|el\\(if\\|se\\)\\|i\\(dent\\|f\\(def\\|ndef\\)?\\|mport\\|nclude\\(_next\\)?\\)\\|line\\|machine\\|pragma\\|system\\|un\\(assert\\|def\\)\\|warning\\)\\>"))
312 "Alist of regexps matching lines are indented at column 0.
313 Each element in this list looks like (MODE . REGEXP) where MODE is a
314 function and REGEXP is a regular expression.
316 If `antlr-language' equals to a MODE, the line starting at the first
317 non-whitespace is matched by the corresponding REGEXP, and the line is
318 part of a header action, indent the line at column 0 instead according
319 to the normal rules of `antlr-indent-line'."
320 :group 'antlr
321 :type '(repeat (cons (function :tag "Major mode") regexp)))
323 ;; adopt indentation to cc-engine
324 (defvar antlr-disabling-cc-syntactic-symbols
325 '(statement-block-intro
326 defun-block-intro topmost-intro statement-case-intro member-init-intro
327 arglist-intro brace-list-intro knr-argdecl-intro inher-intro
328 objc-method-intro
329 block-close defun-close class-close brace-list-close arglist-close
330 inline-close extern-lang-close namespace-close))
333 ;;;===========================================================================
334 ;;; Options: customization
335 ;;;===========================================================================
337 (defcustom antlr-options-use-submenus t
338 "Non-nil, if the major mode menu should include option submenus.
339 If nil, the menu just includes a command to insert options. Otherwise,
340 it includes four submenus to insert file/grammar/rule/subrule options."
341 :group 'antlr
342 :type 'boolean)
344 (defcustom antlr-tool-version 20701
345 "The version number of the Antlr tool.
346 The value is an integer of the form XYYZZ which stands for vX.YY.ZZ.
347 This variable is used to warn about non-supported options and to supply
348 version correct option values when using \\[antlr-insert-option].
350 Don't use a number smaller than 20600 since the stored history of
351 Antlr's options starts with v2.06.00, see `antlr-options-alists'. You
352 can make this variable buffer-local."
353 :group 'antlr
354 :type 'integer)
356 (defcustom antlr-options-auto-colon t
357 "Non-nil, if `:' is inserted with a rule or subrule options section.
358 A `:' is only inserted if this value is non-nil, if a rule or subrule
359 option is inserted with \\[antlr-insert-option], if there was no rule or
360 subrule options section before, and if a `:' is not already present
361 after the section, ignoring whitespace, comments and the init action."
362 :group 'antlr
363 :type 'boolean)
365 (defcustom antlr-options-style nil
366 "List of symbols which determine the style of option values.
367 If a style symbol is present, the corresponding option value is put into
368 quotes, i.e., represented as a string, otherwise it is represented as an
369 identifier.
371 The only style symbol used in the default value of `antlr-options-alist'
372 is `language-as-string'. See also `antlr-read-value'."
373 :group 'antlr
374 :type '(repeat (symbol :tag "Style symbol")))
376 (defcustom antlr-options-push-mark t
377 "Non-nil, if inserting an option should set & push mark.
378 If nil, never set mark when inserting an option with command
379 \\[antlr-insert-option]. If t, always set mark via `push-mark'. If a
380 number, only set mark if point was outside the options area before and
381 the number of lines between point and the insert position is greater
382 than this value. Otherwise, only set mark if point was outside the
383 options area before."
384 :group 'antlr
385 :type '(radio (const :tag "No" nil)
386 (const :tag "Always" t)
387 (integer :tag "Lines between" :value 10)
388 (sexp :tag "If outside options" :format "%t" :value outside)))
390 (defcustom antlr-options-assign-string " = "
391 "String containing `=' to use between option name and value.
392 This string is only used if the option to insert did not exist before
393 or if there was no `=' after it. In other words, the spacing around an
394 existing `=' won't be changed when changing an option value."
395 :group 'antlr
396 :type 'string)
399 ;;;===========================================================================
400 ;;; Options: definitions
401 ;;;===========================================================================
403 (defvar antlr-options-headings '("file" "grammar" "rule" "subrule")
404 "Headings for the four different option kinds.
405 The standard value is (\"file\" \"grammar\" \"rule\" \"subrule\"). See
406 `antlr-options-alists'")
408 (defvar antlr-options-alists
409 '(;; file options ----------------------------------------------------------
410 (("language" antlr-language-option-extra
411 (20600 antlr-read-value
412 "Generated language: " language-as-string
413 (("Java") ("Cpp") ("HTML") ("Diagnostic")))
414 (20700 antlr-read-value
415 "Generated language: " language-as-string
416 (("Java") ("Cpp") ("HTML") ("Diagnostic") ("Sather"))))
417 ("mangleLiteralPrefix" nil
418 (20600 antlr-read-value
419 "Prefix for literals (default LITERAL_): " t))
420 ("namespace" antlr-c++-mode-extra
421 (20700 antlr-read-value
422 "Wrap generated C++ code in namespace: " t))
423 ("namespaceStd" antlr-c++-mode-extra
424 (20701 antlr-read-value
425 "Replace ANTLR_USE_NAMESPACE(std) by: " t))
426 ("namespaceAntlr" antlr-c++-mode-extra
427 (20701 antlr-read-value
428 "Replace ANTLR_USE_NAMESPACE(antlr) by: " t))
429 ("genHashLines" antlr-c++-mode-extra
430 (20701 antlr-read-boolean
431 "Include #line in generated C++ code? "))
433 ;; grammar options --------------------------------------------------------
434 (("k" nil
435 (20600 antlr-read-value
436 "Lookahead depth: "))
437 ("importVocab" nil
438 (20600 antlr-read-value
439 "Import vocabulary: "))
440 ("exportVocab" nil
441 (20600 antlr-read-value
442 "Export vocabulary: "))
443 ("testLiterals" nil ; lexer only
444 (20600 antlr-read-boolean
445 "Test each token against literals table? "))
446 ("defaultErrorHandler" nil ; not for lexer
447 (20600 antlr-read-boolean
448 "Generate default exception handler for each rule? "))
449 ("codeGenMakeSwitchThreshold" nil
450 (20600 antlr-read-value
451 "Min number of alternatives for `switch': "))
452 ("codeGenBitsetTestThreshold" nil
453 (20600 antlr-read-value
454 "Min size of lookahead set for bitset test: "))
455 ("analyzerDebug" nil
456 (20600 antlr-read-boolean
457 "Display debugging info during grammar analysis? "))
458 ("codeGenDebug" nil
459 (20600 antlr-read-boolean
460 "Display debugging info during code generation? "))
461 ("buildAST" nil ; not for lexer
462 (20600 antlr-read-boolean
463 "Use automatic AST construction/transformation? "))
464 ("ASTLabelType" nil ; not for lexer
465 (20600 antlr-read-value
466 "Class of user-defined AST node: " t))
467 ("charVocabulary" nil ; lexer only
468 (20600 nil
469 "Insert character vocabulary"))
470 ("interactive" nil
471 (20600 antlr-read-boolean
472 "Generate interactive lexer/parser? "))
473 ("caseSensitive" nil ; lexer only
474 (20600 antlr-read-boolean
475 "Case significant when matching characters? "))
476 ("caseSensitiveLiterals" nil ; lexer only
477 (20600 antlr-read-boolean
478 "Case significant when testing literals table? "))
479 ("classHeaderSuffix" nil
480 (20600 nil
481 "Additional string for grammar class definition"))
482 ("filter" nil ; lexer only
483 (20600 antlr-read-boolean
484 "Skip rule (the name, true or false): "
485 antlr-grammar-tokens))
486 ("namespace" antlr-c++-mode-extra
487 (20700 antlr-read-value
488 "Wrap generated C++ code for grammar in namespace: " t))
489 ("namespaceStd" antlr-c++-mode-extra
490 (20701 antlr-read-value
491 "Replace ANTLR_USE_NAMESPACE(std) by: " t))
492 ("namespaceAntlr" antlr-c++-mode-extra
493 (20701 antlr-read-value
494 "Replace ANTLR_USE_NAMESPACE(antlr) by: " t))
495 ("genHashLines" antlr-c++-mode-extra
496 (20701 antlr-read-boolean
497 "Include #line in generated C++ code? "))
498 ;;; ("autoTokenDef" nil ; parser only
499 ;;; (80000 antlr-read-boolean ; default: true
500 ;;; "Automatically define referenced token? "))
501 ;;; ("keywordsMeltTo" nil ; parser only
502 ;;; (80000 antlr-read-value
503 ;;; "Change non-matching keywords to token type: "))
505 ;; rule options ----------------------------------------------------------
506 (("testLiterals" nil ; lexer only
507 (20600 antlr-read-boolean
508 "Test this token against literals table? "))
509 ("defaultErrorHandler" nil ; not for lexer
510 (20600 antlr-read-boolean
511 "Generate default exception handler for this rule? "))
512 ("ignore" nil ; lexer only
513 (20600 antlr-read-value
514 "In this rule, ignore tokens of type: " nil
515 antlr-grammar-tokens))
516 ("paraphrase" nil ; lexer only
517 (20600 antlr-read-value
518 "In messages, replace name of this token by: " t))
520 ;; subrule options -------------------------------------------------------
521 (("warnWhenFollowAmbig" nil
522 (20600 antlr-read-boolean
523 "Display warnings for ambiguities with FOLLOW? "))
524 ("generateAmbigWarnings" nil
525 (20600 antlr-read-boolean
526 "Display warnings for ambiguities? "))
527 ("greedy" nil
528 (20700 antlr-read-boolean
529 "Make this optional/loop subrule greedy? "))
531 "Definitions for Antlr's options of all four different kinds.
533 The value looks like \(FILE GRAMMAR RULE SUBRULE) where each FILE,
534 GRAMMAR, RULE, and SUBRULE is a list of option definitions of the
535 corresponding kind, i.e., looks like \(OPTION-DEF...).
537 Each OPTION-DEF looks like \(OPTION-NAME EXTRA-FN VALUE-SPEC...) which
538 defines a file/grammar/rule/subrule option with name OPTION-NAME. The
539 OPTION-NAMEs are used for the creation of the \"Insert XXX Option\"
540 submenus, see `antlr-options-use-submenus', and to allow the insertion
541 of the option name with completion when using \\[antlr-insert-option].
543 If EXTRA-FN is a function, it is called at different phases of the
544 insertion with arguments \(PHASE OPTION-NAME). PHASE can have the
545 values `before-input' or `after-insertion', additional phases might be
546 defined in future versions of this mode. The phase `before-input'
547 occurs before the user is asked to insert a value. The phase
548 `after-insertion' occurs after the option value has been inserted.
549 EXTRA-FN might be called with additional arguments in future versions of
550 this mode.
552 Each specification VALUE-SPEC looks like \(VERSION READ-FN ARG...). The
553 last VALUE-SPEC in an OPTION-DEF whose VERSION is smaller or equal to
554 `antlr-tool-version' specifies how the user is asked for the value of
555 the option.
557 If READ-FN is nil, the only ARG is a string which is printed at the echo
558 area to guide the user what to insert at point. Otherwise, READ-FN is
559 called with arguments \(INIT-VALUE ARG...) to get the new value of the
560 option. INIT-VALUE is the old value of the option or nil.
562 The standard value contains the following functions as READ-FN:
563 `antlr-read-value' with ARGs = \(PROMPT AS-STRING TABLE) which reads a
564 general value, or `antlr-read-boolean' with ARGs = \(PROMPT TABLE) which
565 reads a boolean value or a member of TABLE. PROMPT is the prompt when
566 asking for a new value. If non-nil, TABLE is a table for completion or
567 a function evaluating to such a table. The return value is quoted if
568 AS-STRING is non-nil and is either t or a symbol which is a member of
569 `antlr-options-style'.")
572 ;;;===========================================================================
573 ;;; Run tool, create Makefile dependencies
574 ;;;===========================================================================
576 (defcustom antlr-tool-command "java antlr.Tool"
577 "Command used in \\[antlr-run-tool] to run the Antlr tool.
578 This variable should include all options passed to Antlr except the
579 option \"-glib\" which is automatically suggested if necessary."
580 :group 'antlr
581 :type 'string)
583 (defcustom antlr-ask-about-save t
584 "If not nil, \\[antlr-run-tool] asks which buffers to save.
585 Otherwise, it saves all modified buffers before running without asking."
586 :group 'antlr
587 :type 'boolean)
589 (defcustom antlr-makefile-specification
590 '("\n" ("GENS" "GENS%d" " \\\n\t") "$(ANTLR)")
591 "Variable to specify the appearance of the generated makefile rules.
592 This variable influences the output of \\[antlr-show-makefile-rules].
593 It looks like \(RULE-SEP GEN-VAR-SPEC COMMAND).
595 RULE-SEP is the string to separate different makefile rules. COMMAND is
596 a string with the command which runs the Antlr tool, it should include
597 all options except the option \"-glib\" which is automatically added
598 if necessary.
600 If GEN-VAR-SPEC is nil, each target directly consists of a list of
601 files. If GEN-VAR-SPEC looks like \(GEN-VAR GEN-VAR-FORMAT GEN-SEP), a
602 Makefile variable is created for each rule target.
604 Then, GEN-VAR is a string with the name of the variable which contains
605 the file names of all makefile rules. GEN-VAR-FORMAT is a format string
606 producing the variable of each target with substitution COUNT/%d where
607 COUNT starts with 1. GEN-SEP is used to separate long variable values."
608 :group 'antlr
609 :type '(list (string :tag "Rule separator")
610 (choice
611 (const :tag "Direct targets" nil)
612 (list :tag "Variables for targets"
613 (string :tag "Variable for all targets")
614 (string :tag "Format for each target variable")
615 (string :tag "Variable separator")))
616 (string :tag "ANTLR command")))
618 (defvar antlr-file-formats-alist
619 '((java-mode ("%sTokenTypes.java") ("%s.java"))
620 (c++-mode ("%sTokenTypes.hpp") ("%s.cpp" "%s.hpp")))
621 "Language dependent formats which specify generated files.
622 Each element in this list looks looks like
623 (MAJOR-MODE (VOCAB-FILE-FORMAT...) (CLASS-FILE-FORMAT...)).
625 The element whose MAJOR-MODE is equal to `antlr-language' is used to
626 specify the generated files which are language dependent. See variable
627 `antlr-special-file-formats' for language independent files.
629 VOCAB-FILE-FORMAT is a format string, it specifies with substitution
630 VOCAB/%s the generated file for each export vocabulary VOCAB.
631 CLASS-FILE-FORMAT is a format string, it specifies with substitution
632 CLASS/%s the generated file for each grammar class CLASS.")
634 (defvar antlr-special-file-formats '("%sTokenTypes.txt" "expanded%s.g")
635 "Language independent formats which specify generated files.
636 The value looks like \(VOCAB-FILE-FORMAT EXPANDED-GRAMMAR-FORMAT).
638 VOCAB-FILE-FORMAT is a format string, it specifies with substitution
639 VOCAB/%s the generated or input file for each export or import
640 vocabulary VOCAB, respectively. EXPANDED-GRAMMAR-FORMAT is a format
641 string, it specifies with substitution GRAMMAR/%s the constructed
642 grammar file if the file GRAMMAR.g contains a grammar class which
643 extends a class other than \"Lexer\", \"Parser\" or \"TreeParser\".
645 See variable `antlr-file-formats-alist' for language dependent
646 formats.")
648 (defvar antlr-unknown-file-formats '("?%s?.g" "?%s?")
649 "Formats which specify the names of unknown files.
650 The value looks like \(SUPER-GRAMMAR-FILE-FORMAT SUPER-EVOCAB-FORMAT).
652 SUPER-GRAMMAR-FORMAT is a format string, it specifies with substitution
653 SUPER/%s the name of a grammar file for Antlr's option \"-glib\" if no
654 grammar file in the current directory defines the class SUPER or if it
655 is defined more than once. SUPER-EVOCAB-FORMAT is a format string, it
656 specifies with substitution SUPER/%s the name for the export vocabulary
657 of above mentioned class SUPER.")
659 (defvar antlr-help-unknown-file-text
660 "## The following rules contain filenames of the form
661 ## \"?SUPERCLASS?.g\" (and \"?SUPERCLASS?TokenTypes.txt\")
662 ## where SUPERCLASS is not found to be defined in any grammar file of
663 ## the current directory or is defined more than once. Please replace
664 ## these filenames by the grammar files (and their exportVocab).\n\n"
665 "String indicating the existence of unknown files in the Makefile.
666 See \\[antlr-show-makefile-rules] and `antlr-unknown-file-formats'.")
668 (defvar antlr-help-rules-intro
669 "The following Makefile rules define the dependencies for all (non-
670 expanded) grammars in directory \"%s\".\n
671 They are stored in the kill-ring, i.e., you can insert them with C-y
672 into your Makefile. You can also invoke M-x antlr-show-makefile-rules
673 from within a Makefile to insert them directly.\n\n\n"
674 "Introduction to use with \\[antlr-show-makefile-rules].
675 It is a format string and used with substitution DIRECTORY/%s where
676 DIRECTORY is the name of the current directory.")
679 ;;;===========================================================================
680 ;;; Menu
681 ;;;===========================================================================
683 (defcustom antlr-imenu-name t ; (featurep 'xemacs) ; TODO: Emacs-21 bug?
684 "Non-nil, if a \"Index\" menu should be added to the menubar.
685 If it is a string, it is used instead \"Index\". Requires package
686 imenu."
687 :group 'antlr
688 :type '(choice (const :tag "No menu" nil)
689 (const :tag "Index menu" t)
690 (string :tag "Other menu name")))
692 (defvar antlr-mode-map
693 (let ((map (make-sparse-keymap)))
694 (define-key map "\t" 'antlr-indent-command)
695 (define-key map "\e\C-a" 'antlr-beginning-of-rule)
696 (define-key map "\e\C-e" 'antlr-end-of-rule)
697 (define-key map "\C-c\C-a" 'antlr-beginning-of-body)
698 (define-key map "\C-c\C-e" 'antlr-end-of-body)
699 (define-key map "\C-c\C-f" 'c-forward-into-nomenclature)
700 (define-key map "\C-c\C-b" 'c-backward-into-nomenclature)
701 (define-key map "\C-c\C-c" 'comment-region)
702 (define-key map "\C-c\C-v" 'antlr-hide-actions)
703 (define-key map "\C-c\C-r" 'antlr-run-tool)
704 (define-key map "\C-c\C-o" 'antlr-insert-option)
705 ;; I'm too lazy to define my own:
706 (define-key map "\ea" 'c-beginning-of-statement)
707 (define-key map "\ee" 'c-end-of-statement)
708 ;; electric keys:
709 (define-key map ":" 'antlr-electric-character)
710 (define-key map ";" 'antlr-electric-character)
711 (define-key map "|" 'antlr-electric-character)
712 (define-key map "&" 'antlr-electric-character)
713 (define-key map "(" 'antlr-electric-character)
714 (define-key map ")" 'antlr-electric-character)
715 (define-key map "{" 'antlr-electric-character)
716 (define-key map "}" 'antlr-electric-character)
717 map)
718 "Keymap used in `antlr-mode' buffers.")
720 (easy-menu-define antlr-mode-menu antlr-mode-map
721 "Major mode menu."
722 `("Antlr"
723 ,@(if (cond-emacs-xemacs
724 :EMACS (and antlr-options-use-submenus
725 (>= emacs-major-version 21))
726 :XEMACS antlr-options-use-submenus)
727 `(("Insert File Option"
728 :filter ,(lambda (x) (antlr-options-menu-filter 1 x)))
729 ("Insert Grammar Option"
730 :filter ,(lambda (x) (antlr-options-menu-filter 2 x)))
731 ("Insert Rule Option"
732 :filter ,(lambda (x) (antlr-options-menu-filter 3 x)))
733 ("Insert Subrule Option"
734 :filter ,(lambda (x) (antlr-options-menu-filter 4 x)))
735 "---")
736 '(["Insert Option" antlr-insert-option
737 :active (not buffer-read-only)]))
738 ("Forward/Backward"
739 ["Backward Rule" antlr-beginning-of-rule t]
740 ["Forward Rule" antlr-end-of-rule t]
741 ["Start of Rule Body" antlr-beginning-of-body
742 :active (antlr-inside-rule-p)]
743 ["End of Rule Body" antlr-end-of-body
744 :active (antlr-inside-rule-p)]
745 "---"
746 ["Backward Statement" c-beginning-of-statement t]
747 ["Forward Statement" c-end-of-statement t]
748 ["Backward Into Nomencl." c-backward-into-nomenclature t]
749 ["Forward Into Nomencl." c-forward-into-nomenclature t])
750 ["Indent Region" indent-region
751 :active (and (not buffer-read-only) (c-region-is-active-p))]
752 ["Comment Out Region" comment-region
753 :active (and (not buffer-read-only) (c-region-is-active-p))]
754 ["Uncomment Region"
755 (comment-region (region-beginning) (region-end) '(4))
756 :active (and (not buffer-read-only) (c-region-is-active-p))]
757 "---"
758 ["Hide Actions (incl. Args)" antlr-hide-actions t]
759 ["Hide Actions (excl. Args)" (antlr-hide-actions 2) t]
760 ["Unhide All Actions" (antlr-hide-actions 0) t]
761 "---"
762 ["Run Tool on Grammar" antlr-run-tool t]
763 ["Show Makefile Rules" antlr-show-makefile-rules t]
764 "---"
765 ["Customize Antlr" (customize-group 'antlr) t]))
768 ;;;===========================================================================
769 ;;; font-lock
770 ;;;===========================================================================
772 (defcustom antlr-font-lock-maximum-decoration 'inherit
773 "The maximum decoration level for fontifying actions.
774 Value `none' means, do not fontify actions, just normal grammar code
775 according to `antlr-font-lock-additional-keywords'. Value `inherit'
776 means, use value of `font-lock-maximum-decoration'. Any other value is
777 interpreted as in `font-lock-maximum-decoration' with no level-0
778 fontification, see `antlr-font-lock-keywords-alist'.
780 While calculating the decoration level for actions, `major-mode' is
781 bound to `antlr-language'. For example, with value
782 ((java-mode . 2) (c++-mode . 0))
783 Java actions are fontified with level 2 and C++ actions are not
784 fontified at all."
785 :group 'antlr
786 :type '(choice (const :tag "None" none)
787 (const :tag "Inherit" inherit)
788 (const :tag "Default" nil)
789 (const :tag "Maximum" t)
790 (integer :tag "Level" 1)
791 (repeat :menu-tag "Mode specific" :tag "Mode specific"
792 :value ((t . t))
793 (cons :tag "Instance"
794 (radio :tag "Mode"
795 (const :tag "All" t)
796 (symbol :tag "Name"))
797 (radio :tag "Decoration"
798 (const :tag "Default" nil)
799 (const :tag "Maximum" t)
800 (integer :tag "Level" 1))))))
802 (defconst antlr-no-action-keywords nil
803 ;; Using nil directly won't work (would use highest level, see
804 ;; `font-lock-choose-keywords'), but a non-symbol, i.e., (list), at `car'
805 ;; would break Emacs-21.0:
806 "Empty font-lock keywords for actions.
807 Do not change the value of this constant.")
809 (defvar antlr-font-lock-keywords-alist
810 '((java-mode
811 antlr-no-action-keywords
812 java-font-lock-keywords-1 java-font-lock-keywords-2
813 java-font-lock-keywords-3)
814 (c++-mode
815 antlr-no-action-keywords
816 c++-font-lock-keywords-1 c++-font-lock-keywords-2
817 c++-font-lock-keywords-3))
818 "List of font-lock keywords for actions in the grammar.
819 Each element in this list looks like
820 (MAJOR-MODE KEYWORD...)
822 If `antlr-language' is equal to MAJOR-MODE, the KEYWORDs are the
823 font-lock keywords according to `font-lock-defaults' used for the code
824 in the grammar's actions and semantic predicates, see
825 `antlr-font-lock-maximum-decoration'.")
827 (defface antlr-default '((t nil))
828 "Face to prevent strings from language dependent highlighting.
829 Do not change."
830 :group 'antlr)
832 (defface antlr-keyword
833 (cond-emacs-xemacs
834 '((((class color) (background light))
835 (:foreground "black" :EMACS :weight bold :XEMACS :bold t))
836 (t :inherit font-lock-keyword-face)))
837 "ANTLR keywords."
838 :group 'antlr)
840 (defface antlr-syntax
841 (cond-emacs-xemacs
842 '((((class color) (background light))
843 (:foreground "black" :EMACS :weight bold :XEMACS :bold t))
844 (t :inherit font-lock-constant-face)))
845 "ANTLR syntax symbols like :, |, (, ), ...."
846 :group 'antlr)
848 (defface antlr-ruledef
849 (cond-emacs-xemacs
850 '((((class color) (background light))
851 (:foreground "blue" :EMACS :weight bold :XEMACS :bold t))
852 (t :inherit font-lock-function-name-face)))
853 "ANTLR rule references (definition)."
854 :group 'antlr)
856 (defface antlr-tokendef
857 (cond-emacs-xemacs
858 '((((class color) (background light))
859 (:foreground "blue" :EMACS :weight bold :XEMACS :bold t))
860 (t :inherit font-lock-function-name-face)))
861 "ANTLR token references (definition)."
862 :group 'antlr)
864 (defface antlr-ruleref
865 '((((class color) (background light)) (:foreground "blue4"))
866 (t :inherit font-lock-type-face))
867 "ANTLR rule references (usage)."
868 :group 'antlr)
870 (defface antlr-tokenref
871 '((((class color) (background light)) (:foreground "orange4"))
872 (t :inherit font-lock-type-face))
873 "ANTLR token references (usage)."
874 :group 'antlr)
876 (defface antlr-literal
877 (cond-emacs-xemacs
878 '((((class color) (background light))
879 (:foreground "brown4" :EMACS :weight bold :XEMACS :bold t))
880 (t :inherit font-lock-string-face)))
881 "ANTLR special literal tokens.
882 It is used to highlight strings matched by the first regexp group of
883 `antlr-font-lock-literal-regexp'."
884 :group 'antlr)
886 (defcustom antlr-font-lock-literal-regexp "\"\\(\\sw\\(\\sw\\|-\\)*\\)\""
887 "Regexp matching literals with special syntax highlighting, or nil.
888 If nil, there is no special syntax highlighting for some literals.
889 Otherwise, it should be a regular expression which must contain a regexp
890 group. The string matched by the first group is highlighted with
891 `antlr-font-lock-literal-face'."
892 :group 'antlr
893 :type '(choice (const :tag "None" nil) regexp))
895 (defvar antlr-class-header-regexp
896 "\\(class\\)[ \t]+\\([A-Za-z\300-\326\330-\337]\\sw*\\)[ \t]+\\(extends\\)[ \t]+\\([A-Za-z\300-\326\330-\337]\\sw*\\)[ \t]*;"
897 "Regexp matching class headers.")
899 (defvar antlr-font-lock-additional-keywords
900 (cond-emacs-xemacs
901 `((antlr-invalidate-context-cache)
902 ("\\$setType[ \t]*(\\([A-Za-z\300-\326\330-\337]\\sw*\\))"
903 (1 'antlr-tokendef))
904 ("\\$\\sw+" (0 'antlr-keyword))
905 ;; the tokens are already fontified as string/docstrings:
906 (,(lambda (limit)
907 (if antlr-font-lock-literal-regexp
908 (antlr-re-search-forward antlr-font-lock-literal-regexp limit)))
909 (1 'antlr-literal t)
910 :XEMACS (0 nil)) ; XEmacs bug workaround
911 (,(lambda (limit)
912 (antlr-re-search-forward antlr-class-header-regexp limit))
913 (1 'antlr-keyword)
914 (2 'antlr-ruledef)
915 (3 'antlr-keyword)
916 (4 (if (member (match-string 4) '("Lexer" "Parser" "TreeParser"))
917 'antlr-keyword
918 'font-lock-type-face)))
919 (,(lambda (limit)
920 (antlr-re-search-forward
921 "\\<\\(header\\|options\\|tokens\\|exception\\|catch\\|returns\\)\\>"
922 limit))
923 (1 'antlr-keyword))
924 (,(lambda (limit)
925 (antlr-re-search-forward
926 "^\\(private\\|public\\|protected\\)\\>[ \t]*\\(\\(\\sw+[ \t]*\\(:\\)?\\)\\)?"
927 limit))
928 (1 'font-lock-type-face) ; not XEmacs's java level-3 fruit salad
929 (3 (if (antlr-upcase-p (char-after (match-beginning 3)))
930 'antlr-tokendef
931 'antlr-ruledef)
932 nil t)
933 (4 'antlr-syntax nil t))
934 (,(lambda (limit)
935 (antlr-re-search-forward "^\\(\\sw+\\)[ \t]*\\(:\\)?" limit))
936 (1 (if (antlr-upcase-p (char-after (match-beginning 0)))
937 'antlr-tokendef
938 'antlr-ruledef)
939 nil t)
940 (2 'antlr-syntax nil t))
941 (,(lambda (limit)
942 ;; v:ruleref and v:"literal" is allowed...
943 (antlr-re-search-forward "\\(\\sw+\\)[ \t]*\\([=:]\\)?" limit))
944 (1 (if (match-beginning 2)
945 (if (eq (char-after (match-beginning 2)) ?=)
946 'antlr-default
947 'font-lock-variable-name-face)
948 (if (antlr-upcase-p (char-after (match-beginning 1)))
949 'antlr-tokenref
950 'antlr-ruleref)))
951 (2 'antlr-default nil t))
952 (,(lambda (limit)
953 (antlr-re-search-forward "[|&:;(~]\\|)\\([*+?]\\|=>\\)?" limit))
954 (0 'antlr-syntax))))
955 "Font-lock keywords for ANTLR's normal grammar code.
956 See `antlr-font-lock-keywords-alist' for the keywords of actions.")
958 (defvar antlr-font-lock-defaults
959 '(antlr-font-lock-keywords
960 nil nil ((?_ . "w") (?\( . ".") (?\) . ".")) beginning-of-defun)
961 "Font-lock defaults used for ANTLR syntax highlighting.
962 The SYNTAX-ALIST element is also used to initialize
963 `antlr-action-syntax-table'.")
966 ;;;===========================================================================
967 ;;; Internal variables
968 ;;;===========================================================================
970 (defvar antlr-mode-hook nil
971 "Hook called by `antlr-mode'.")
973 (defvar antlr-mode-syntax-table
974 (let ((st (make-syntax-table)))
975 (c-populate-syntax-table st)
977 "Syntax table used in `antlr-mode' buffers.
978 If non-nil, it will be initialized in `antlr-mode'.")
980 ;; used for "in Java/C++ code" = syntactic-depth>0
981 (defvar antlr-action-syntax-table
982 (let ((st (copy-syntax-table antlr-mode-syntax-table))
983 (slist (nth 3 antlr-font-lock-defaults)))
984 (while slist
985 (modify-syntax-entry (caar slist) (cdar slist) st)
986 (setq slist (cdr slist)))
988 "Syntax table used for ANTLR action parsing.
989 Initialized by `antlr-mode-syntax-table', changed by SYNTAX-ALIST in
990 `antlr-font-lock-defaults'. This table should be selected if you use
991 `buffer-syntactic-context' and `buffer-syntactic-context-depth' in order
992 not to confuse their context_cache.")
994 (defvar antlr-mode-abbrev-table nil
995 "Abbreviation table used in `antlr-mode' buffers.")
996 (define-abbrev-table 'antlr-mode-abbrev-table ())
998 (defvar antlr-slow-cache-enabling-symbol 'loudly
999 ;; Emacs's font-lock changes buffer's tick counter, therefore this value should
1000 ;; be a parameter of a font-lock function, but not any other variable of
1001 ;; functions which call `antlr-slow-syntactic-context'.
1002 "If value is a bound symbol, cache will be used even with text changes.
1003 This is no user option. Used for `antlr-slow-syntactic-context'.")
1005 (defvar antlr-slow-cache-diff-threshold 5000
1006 "Maximum distance between `point' and cache position for cache use.
1007 Used for `antlr-slow-syntactic-context'.")
1010 ;;;;##########################################################################
1011 ;;;; The Code
1012 ;;;;##########################################################################
1016 ;;;===========================================================================
1017 ;;; Syntax functions -- Emacs vs XEmacs dependent, part 1
1018 ;;;===========================================================================
1020 ;; From help.el (XEmacs-21.1), without `copy-syntax-table'
1021 (defmacro antlr-with-syntax-table (syntab &rest body)
1022 "Evaluate BODY with the syntax table SYNTAB."
1023 `(let ((stab (syntax-table)))
1024 (unwind-protect
1025 (progn (set-syntax-table ,syntab) ,@body)
1026 (set-syntax-table stab))))
1027 (put 'antlr-with-syntax-table 'lisp-indent-function 1)
1028 (put 'antlr-with-syntax-table 'edebug-form-spec '(form body))
1030 (defunx antlr-default-directory ()
1031 :xemacs-and-try default-directory
1032 "Return `default-directory'."
1033 default-directory)
1035 ;; Check Emacs-21.1 simple.el, `shell-command'.
1036 (defunx antlr-read-shell-command (prompt &optional initial-input history)
1037 :xemacs-and-try read-shell-command
1038 "Read a string from the minibuffer, using `shell-command-history'."
1039 (read-from-minibuffer prompt initial-input nil nil
1040 (or history 'shell-command-history)))
1042 (defunx antlr-with-displaying-help-buffer (thunk &optional _name)
1043 :xemacs-and-try with-displaying-help-buffer
1044 "Make a help buffer and call `thunk' there."
1045 (with-output-to-temp-buffer "*Help*"
1046 (save-excursion (funcall thunk))))
1049 ;;;===========================================================================
1050 ;;; Context cache
1051 ;;;===========================================================================
1053 (defvar antlr-slow-context-cache nil "Internal.")
1055 ;;;(defvar antlr-statistics-full-neg 0)
1056 ;;;(defvar antlr-statistics-full-diff 0)
1057 ;;;(defvar antlr-statistics-full-other 0)
1058 ;;;(defvar antlr-statistics-cache 0)
1059 ;;;(defvar antlr-statistics-inval 0)
1061 (defunx antlr-invalidate-context-cache (&rest _dummies)
1062 ;; checkdoc-params: (dummies)
1063 "Invalidate context cache for syntactical context information."
1064 :XEMACS ; XEmacs bug workaround
1065 (with-current-buffer (get-buffer-create " ANTLR XEmacs bug workaround")
1066 (buffer-syntactic-context-depth)
1067 nil)
1068 :EMACS
1069 ;;; (incf antlr-statistics-inval)
1070 (setq antlr-slow-context-cache nil))
1072 (defunx antlr-syntactic-context ()
1073 "Return some syntactic context information.
1074 Return `string' if point is within a string, `block-comment' or
1075 `comment' is point is within a comment or the depth within all
1076 parenthesis-syntax delimiters at point otherwise.
1077 WARNING: this may alter `match-data'."
1078 :XEMACS
1079 (or (buffer-syntactic-context) (buffer-syntactic-context-depth))
1080 :EMACS
1081 (let ((orig (point)) diff state
1082 ;; Arg, Emacs's (buffer-modified-tick) changes with font-lock. Use
1083 ;; hack that `loudly' is bound during font-locking => cache use will
1084 ;; increase from 7% to 99.99% during font-locking.
1085 (tick (or (boundp antlr-slow-cache-enabling-symbol)
1086 (buffer-modified-tick))))
1087 (if (and (cdr antlr-slow-context-cache)
1088 (>= (setq diff (- orig (cadr antlr-slow-context-cache))) 0)
1089 (< diff antlr-slow-cache-diff-threshold)
1090 (eq (current-buffer) (caar antlr-slow-context-cache))
1091 (eq tick (cdar antlr-slow-context-cache)))
1092 ;; (setq antlr-statistics-cache (1+ antlr-statistics-cache) ...)
1093 (setq state (parse-partial-sexp (cadr antlr-slow-context-cache) orig
1094 nil nil
1095 (cddr antlr-slow-context-cache)))
1096 (if (>= orig antlr-slow-cache-diff-threshold)
1097 (beginning-of-defun)
1098 (goto-char (point-min)))
1099 ;;; (cond ((and diff (< diff 0)) (incf antlr-statistics-full-neg))
1100 ;;; ((and diff (>= diff 3000)) (incf antlr-statistics-full-diff))
1101 ;;; (t (incf antlr-statistics-full-other)))
1102 (setq state (parse-partial-sexp (point) orig)))
1103 (goto-char orig)
1104 (if antlr-slow-context-cache
1105 (setcdr antlr-slow-context-cache (cons orig state))
1106 (setq antlr-slow-context-cache
1107 (cons (cons (current-buffer) tick)
1108 (cons orig state))))
1109 (cond ((nth 3 state) 'string)
1110 ((nth 4 state) 'comment) ; block-comment? -- we don't care
1111 (t (car state)))))
1113 ;;; (incf (aref antlr-statistics 2))
1114 ;;; (unless (and (eq (current-buffer)
1115 ;;; (caar antlr-slow-context-cache))
1116 ;;; (eq (buffer-modified-tick)
1117 ;;; (cdar antlr-slow-context-cache)))
1118 ;;; (incf (aref antlr-statistics 1))
1119 ;;; (setq antlr-slow-context-cache nil))
1120 ;;; (let* ((orig (point))
1121 ;;; (base (cadr antlr-slow-context-cache))
1122 ;;; (curr (cddr antlr-slow-context-cache))
1123 ;;; (state (cond ((eq orig (car curr)) (cdr curr))
1124 ;;; ((eq orig (car base)) (cdr base))))
1125 ;;; diff diff2)
1126 ;;; (unless state
1127 ;;; (incf (aref antlr-statistics 3))
1128 ;;; (when curr
1129 ;;; (if (< (setq diff (abs (- orig (car curr))))
1130 ;;; (setq diff2 (abs (- orig (car base)))))
1131 ;;; (setq state curr)
1132 ;;; (setq state base
1133 ;;; diff diff2))
1134 ;;; (if (or (>= (1+ diff) (point)) (>= diff 3000))
1135 ;;; (setq state nil))) ; start from bod/bob
1136 ;;; (if state
1137 ;;; (setq state
1138 ;;; (parse-partial-sexp (car state) orig nil nil (cdr state)))
1139 ;;; (if (>= orig 3000) (beginning-of-defun) (goto-char (point-min)))
1140 ;;; (incf (aref antlr-statistics 4))
1141 ;;; (setq cw (list orig (point) base curr))
1142 ;;; (setq state (parse-partial-sexp (point) orig)))
1143 ;;; (goto-char orig)
1144 ;;; (if antlr-slow-context-cache
1145 ;;; (setcdr (cdr antlr-slow-context-cache) (cons orig state))
1146 ;;; (setq antlr-slow-context-cache
1147 ;;; (cons (cons (current-buffer) (buffer-modified-tick))
1148 ;;; (cons (cons orig state) (cons orig state))))))
1149 ;;; (cond ((nth 3 state) 'string)
1150 ;;; ((nth 4 state) 'comment) ; block-comment? -- we don't care
1151 ;;; (t (car state)))))
1153 ;;; (beginning-of-defun)
1154 ;;; (let ((state (parse-partial-sexp (point) orig)))
1155 ;;; (goto-char orig)
1156 ;;; (cond ((nth 3 state) 'string)
1157 ;;; ((nth 4 state) 'comment) ; block-comment? -- we don't care
1158 ;;; (t (car state))))))
1161 ;;;===========================================================================
1162 ;;; Miscellaneous functions
1163 ;;;===========================================================================
1165 (defun antlr-upcase-p (char)
1166 "Non-nil, if CHAR is an uppercase character (if CHAR was a char)."
1167 ;; in XEmacs, upcase only works for ASCII
1168 (or (and (<= ?A char) (<= char ?Z))
1169 (and (<= ?\300 char) (<= char ?\337)))) ; ?\327 is no letter
1171 (defun antlr-re-search-forward (regexp bound)
1172 "Search forward from point for regular expression REGEXP.
1173 Set point to the end of the occurrence found, and return point. Return
1174 nil if no occurrence was found. Do not search within comments, strings
1175 and actions/semantic predicates. BOUND bounds the search; it is a
1176 buffer position. See also the functions `match-beginning', `match-end'
1177 and `replace-match'."
1178 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1179 (let ((continue t))
1180 (while (and (re-search-forward regexp bound 'limit)
1181 (save-match-data
1182 (if (eq (antlr-syntactic-context) 0)
1183 (setq continue nil)
1184 t))))
1185 (if continue nil (point))))
1187 (defun antlr-search-forward (string)
1188 "Search forward from point for STRING.
1189 Set point to the end of the occurrence found, and return point. Return
1190 nil if no occurrence was found. Do not search within comments, strings
1191 and actions/semantic predicates."
1192 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1193 (let ((continue t))
1194 (while (and (search-forward string nil 'limit)
1195 (if (eq (antlr-syntactic-context) 0) (setq continue nil) t)))
1196 (if continue nil (point))))
1198 (defun antlr-search-backward (string)
1199 "Search backward from point for STRING.
1200 Set point to the beginning of the occurrence found, and return point.
1201 Return nil if no occurrence was found. Do not search within comments,
1202 strings and actions/semantic predicates."
1203 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1204 (let ((continue t))
1205 (while (and (search-backward string nil 'limit)
1206 (if (eq (antlr-syntactic-context) 0) (setq continue nil) t)))
1207 (if continue nil (point))))
1209 (defsubst antlr-skip-sexps (count)
1210 "Skip the next COUNT balanced expressions and the comments after it.
1211 Return position before the comments after the last expression."
1212 (goto-char (or (ignore-errors-x (scan-sexps (point) count)) (point-max)))
1213 (prog1 (point)
1214 (antlr-c-forward-sws)))
1217 ;;;===========================================================================
1218 ;;; font-lock
1219 ;;;===========================================================================
1221 (defun antlr-font-lock-keywords ()
1222 "Return font-lock keywords for current buffer.
1223 See `antlr-font-lock-additional-keywords', `antlr-language' and
1224 `antlr-font-lock-maximum-decoration'."
1225 (if (eq antlr-font-lock-maximum-decoration 'none)
1226 antlr-font-lock-additional-keywords
1227 (append antlr-font-lock-additional-keywords
1228 (eval (let ((major-mode antlr-language)) ; dynamic
1229 (font-lock-choose-keywords
1230 (cdr (assq antlr-language
1231 antlr-font-lock-keywords-alist))
1232 (if (eq antlr-font-lock-maximum-decoration 'inherit)
1233 font-lock-maximum-decoration
1234 antlr-font-lock-maximum-decoration)))))))
1237 ;;;===========================================================================
1238 ;;; imenu support
1239 ;;;===========================================================================
1241 (defun antlr-grammar-tokens ()
1242 "Return alist for tokens defined in current buffer."
1243 (save-excursion (antlr-imenu-create-index-function t)))
1245 (defun antlr-imenu-create-index-function (&optional tokenrefs-only)
1246 "Return imenu index-alist for ANTLR grammar files.
1247 IF TOKENREFS-ONLY is non-nil, just return alist with tokenref names."
1248 (let ((items nil)
1249 (classes nil)
1250 (continue t))
1251 ;; Using `imenu-progress-message' would require imenu for compilation, but
1252 ;; nobody is missing these messages. The generic imenu function searches
1253 ;; backward, which is slower and more likely not to work during editing.
1254 (antlr-with-syntax-table antlr-action-syntax-table
1255 (antlr-invalidate-context-cache)
1256 (goto-char (point-min))
1257 (antlr-skip-file-prelude t)
1258 (while continue
1259 (if (looking-at "{") (antlr-skip-sexps 1))
1260 (if (looking-at antlr-class-header-regexp)
1261 (or tokenrefs-only
1262 (push (cons (match-string 2)
1263 (if imenu-use-markers
1264 (copy-marker (match-beginning 2))
1265 (match-beginning 2)))
1266 classes))
1267 (if (looking-at "p\\(ublic\\|rotected\\|rivate\\)")
1268 (antlr-skip-sexps 1))
1269 (when (looking-at "\\sw+")
1270 (if tokenrefs-only
1271 (if (antlr-upcase-p (char-after (point)))
1272 (push (list (match-string 0)) items))
1273 (push (cons (match-string 0)
1274 (if imenu-use-markers
1275 (copy-marker (match-beginning 0))
1276 (match-beginning 0)))
1277 items))))
1278 (if (setq continue (antlr-search-forward ";"))
1279 (antlr-skip-exception-part t))))
1280 (if classes
1281 (cons (cons "Classes" (nreverse classes)) (nreverse items))
1282 (nreverse items))))
1285 ;;;===========================================================================
1286 ;;; Parse grammar files (internal functions)
1287 ;;;===========================================================================
1289 (defun antlr-skip-exception-part (skip-comment)
1290 "Skip exception part of current rule, i.e., everything after `;'.
1291 This also includes the options and tokens part of a grammar class
1292 header. If SKIP-COMMENT is non-nil, also skip the comment after that
1293 part."
1294 (let ((pos (point))
1295 (class nil))
1296 (antlr-c-forward-sws)
1297 (while (looking-at "options\\>\\|tokens\\>")
1298 (setq class t)
1299 (setq pos (antlr-skip-sexps 2)))
1300 (if class
1301 ;; Problem: an action only belongs to a class def, not a normal rule.
1302 ;; But checking the current rule type is too expensive => only expect
1303 ;; an action if we have found an option or tokens part.
1304 (if (looking-at "{") (setq pos (antlr-skip-sexps 1)))
1305 (while (looking-at "exception\\>")
1306 (setq pos (antlr-skip-sexps 1))
1307 (when (looking-at "\\[")
1308 (setq pos (antlr-skip-sexps 1)))
1309 (while (looking-at "catch\\>")
1310 (setq pos (antlr-skip-sexps 3)))))
1311 (or skip-comment (goto-char pos))))
1313 (defun antlr-skip-file-prelude (skip-comment)
1314 "Skip the file prelude: the header and file options.
1315 If SKIP-COMMENT is non-nil, also skip the comment after that part.
1316 Return the start position of the file prelude.
1318 Hack: if SKIP-COMMENT is `header-only' only skip header and return
1319 position before the comment after the header."
1320 (let* ((pos (point))
1321 (pos0 pos))
1322 (antlr-c-forward-sws)
1323 (if skip-comment (setq pos0 (point)))
1324 (while (looking-at "header\\>[ \t]*\\(\"\\)?")
1325 (setq pos (antlr-skip-sexps (if (match-beginning 1) 3 2))))
1326 (if (eq skip-comment 'header-only) ; a hack...
1328 (when (looking-at "options\\>")
1329 (setq pos (antlr-skip-sexps 2)))
1330 (or skip-comment (goto-char pos))
1331 pos0)))
1333 (defun antlr-next-rule (arg skip-comment)
1334 "Move forward to next end of rule. Do it ARG many times.
1335 A grammar class header and the file prelude are also considered as a
1336 rule. Negative argument ARG means move back to ARGth preceding end of
1337 rule. The behavior is not defined when ARG is zero. If SKIP-COMMENT
1338 is non-nil, move to beginning of the rule."
1339 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1340 ;; PRE: ARG<>0
1341 (let ((pos (point))
1342 (beg (point)))
1343 ;; first look whether point is in exception part
1344 (if (antlr-search-backward ";")
1345 (progn
1346 (setq beg (point))
1347 (forward-char)
1348 (antlr-skip-exception-part skip-comment))
1349 (antlr-skip-file-prelude skip-comment))
1350 (if (< arg 0)
1351 (unless (and (< (point) pos) (zerop (incf arg)))
1352 ;; if we have moved backward, we already moved one defun backward
1353 (goto-char beg) ; rewind (to ";" / point)
1354 (while (and arg (<= (incf arg) 0))
1355 (if (antlr-search-backward ";")
1356 (setq beg (point))
1357 (when (>= arg -1)
1358 ;; try file prelude:
1359 (setq pos (antlr-skip-file-prelude skip-comment))
1360 (if (zerop arg)
1361 (if (>= (point) beg)
1362 (goto-char (if (>= pos beg) (point-min) pos)))
1363 (goto-char (if (or (>= (point) beg) (= (point) pos))
1364 (point-min) pos))))
1365 (setq arg nil)))
1366 (when arg ; always found a ";"
1367 (forward-char)
1368 (antlr-skip-exception-part skip-comment)))
1369 (if (<= (point) pos) ; moved backward?
1370 (goto-char pos) ; rewind
1371 (decf arg)) ; already moved one defun forward
1372 (unless (zerop arg)
1373 (while (>= (decf arg) 0)
1374 (antlr-search-forward ";"))
1375 (antlr-skip-exception-part skip-comment)))))
1377 (defun antlr-outside-rule-p ()
1378 "Non-nil if point is outside a grammar rule.
1379 Move to the beginning of the current rule if point is inside a rule."
1380 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1381 (let ((pos (point)))
1382 (antlr-next-rule -1 nil)
1383 (let ((between (or (bobp) (< (point) pos))))
1384 (antlr-c-forward-sws)
1385 (and between (> (point) pos) (goto-char pos)))))
1388 ;;;===========================================================================
1389 ;;; Parse grammar files (commands)
1390 ;;;===========================================================================
1391 ;; No (interactive "_") in Emacs... use `zmacs-region-stays'.
1393 (defun antlr-inside-rule-p ()
1394 "Non-nil if point is inside a grammar rule.
1395 A grammar class header and the file prelude are also considered as a
1396 rule."
1397 (save-excursion
1398 (antlr-with-syntax-table antlr-action-syntax-table
1399 (not (antlr-outside-rule-p)))))
1401 (defunx antlr-end-of-rule (&optional arg)
1402 "Move forward to next end of rule. Do it ARG [default: 1] many times.
1403 A grammar class header and the file prelude are also considered as a
1404 rule. Negative argument ARG means move back to ARGth preceding end of
1405 rule. If ARG is zero, run `antlr-end-of-body'."
1406 (interactive "_p")
1407 (if (zerop arg)
1408 (antlr-end-of-body)
1409 (antlr-with-syntax-table antlr-action-syntax-table
1410 (antlr-next-rule arg nil))))
1412 (defunx antlr-beginning-of-rule (&optional arg)
1413 "Move backward to preceding beginning of rule. Do it ARG many times.
1414 A grammar class header and the file prelude are also considered as a
1415 rule. Negative argument ARG means move forward to ARGth next beginning
1416 of rule. If ARG is zero, run `antlr-beginning-of-body'."
1417 (interactive "_p")
1418 (if (zerop arg)
1419 (antlr-beginning-of-body)
1420 (antlr-with-syntax-table antlr-action-syntax-table
1421 (antlr-next-rule (- arg) t))))
1423 (defunx antlr-end-of-body (&optional msg)
1424 "Move to position after the `;' of the current rule.
1425 A grammar class header is also considered as a rule. With optional
1426 prefix arg MSG, move to `:'."
1427 (interactive "_")
1428 (antlr-with-syntax-table antlr-action-syntax-table
1429 (let ((orig (point)))
1430 (if (antlr-outside-rule-p)
1431 (error "Outside an ANTLR rule"))
1432 (let ((bor (point)))
1433 (when (< (antlr-skip-file-prelude t) (point))
1434 ;; Yes, we are in the file prelude
1435 (goto-char orig)
1436 (error (or msg "The file prelude is without `;'")))
1437 (antlr-search-forward ";")
1438 (when msg
1439 (when (< (point)
1440 (progn (goto-char bor)
1441 (or (antlr-search-forward ":") (point-max))))
1442 (goto-char orig)
1443 (error msg))
1444 (antlr-c-forward-sws))))))
1446 (defunx antlr-beginning-of-body ()
1447 "Move to the first element after the `:' of the current rule."
1448 (interactive "_")
1449 (antlr-end-of-body "Class headers and the file prelude are without `:'"))
1452 ;;;===========================================================================
1453 ;;; Literal normalization, Hide Actions
1454 ;;;===========================================================================
1456 (defun antlr-downcase-literals (&optional transform)
1457 "Convert all literals in buffer to lower case.
1458 If non-nil, TRANSFORM is used on literals instead of `downcase-region'."
1459 (interactive)
1460 (or transform (setq transform 'downcase-region))
1461 (let ((literals 0))
1462 (save-excursion
1463 (goto-char (point-min))
1464 (antlr-with-syntax-table antlr-action-syntax-table
1465 (antlr-invalidate-context-cache)
1466 (while (antlr-re-search-forward "\"\\(\\sw\\(\\sw\\|-\\)*\\)\"" nil)
1467 (funcall transform (match-beginning 0) (match-end 0))
1468 (incf literals))))
1469 (message "Transformed %d literals" literals)))
1471 (defun antlr-upcase-literals ()
1472 "Convert all literals in buffer to upper case."
1473 (interactive)
1474 (antlr-downcase-literals 'upcase-region))
1476 (defun antlr-hide-actions (arg &optional silent)
1477 "Hide or unhide all actions in buffer.
1478 Hide all actions including arguments in brackets if ARG is 1 or if
1479 called interactively without prefix argument. Hide all actions
1480 excluding arguments in brackets if ARG is 2 or higher. Unhide all
1481 actions if ARG is 0 or negative. See `antlr-action-visibility'.
1483 Display a message unless optional argument SILENT is non-nil."
1484 (interactive "p")
1485 (save-buffer-state-x
1486 (if (> arg 0)
1487 (let ((regexp (if (= arg 1) "[]}]" "}"))
1488 (diff (and antlr-action-visibility
1489 (+ (max antlr-action-visibility 0) 2))))
1490 (antlr-hide-actions 0 t)
1491 (save-excursion
1492 (goto-char (point-min))
1493 (antlr-with-syntax-table antlr-action-syntax-table
1494 (antlr-invalidate-context-cache)
1495 (while (antlr-re-search-forward regexp nil)
1496 (let ((beg (ignore-errors-x (scan-sexps (point) -1))))
1497 (when beg
1498 (if diff ; braces are visible
1499 (if (> (point) (+ beg diff))
1500 (add-text-properties (1+ beg) (1- (point))
1501 '(invisible t intangible t)))
1502 ;; if actions is on line(s) of its own, hide WS
1503 (and (looking-at "[ \t]*$")
1504 (save-excursion
1505 (goto-char beg)
1506 (skip-chars-backward " \t")
1507 (and (bolp) (setq beg (point))))
1508 (beginning-of-line 2)) ; beginning of next line
1509 (add-text-properties beg (point)
1510 '(invisible t intangible t))))))))
1511 (or silent
1512 (message "Hide all actions (%s arguments)...done"
1513 (if (= arg 1) "including" "excluding"))))
1514 (remove-text-properties (point-min) (point-max)
1515 '(invisible nil intangible nil))
1516 (or silent
1517 (message "Unhide all actions (including arguments)...done")))))
1520 ;;;===========================================================================
1521 ;;; Insert option: command
1522 ;;;===========================================================================
1524 (defun antlr-insert-option (level option &optional location)
1525 "Insert file/grammar/rule/subrule option near point.
1526 LEVEL determines option kind to insert: 1=file, 2=grammar, 3=rule,
1527 4=subrule. OPTION is a string with the name of the option to insert.
1528 LOCATION can be specified for not calling `antlr-option-kind' twice.
1530 Inserting an option with this command works as follows:
1532 1. When called interactively, LEVEL is determined by the prefix
1533 argument or automatically deduced without prefix argument.
1534 2. Signal an error if no option of that level could be inserted, e.g.,
1535 if the buffer is read-only, the option area is outside the visible
1536 part of the buffer or a subrule/rule option should be inserted with
1537 point outside a subrule/rule.
1538 3. When called interactively, OPTION is read from the minibuffer with
1539 completion over the known options of the given LEVEL.
1540 4. Ask user for confirmation if the given OPTION does not seem to be a
1541 valid option to insert into the current file.
1542 5. Find a correct position to insert the option.
1543 6. Depending on the option, insert it the following way (inserting an
1544 option also means inserting the option section if necessary):
1545 - Insert the option and let user insert the value at point.
1546 - Read a value (with completion) from the minibuffer, using a
1547 previous value as initial contents, and insert option with value.
1548 7. Final action depending on the option. For example, set the language
1549 according to a newly inserted language option.
1551 The name of all options with a specification for their values are stored
1552 in `antlr-options-alists'. The used specification also depends on the
1553 value of `antlr-tool-version', i.e., step 4 will warn you if you use an
1554 option that has been introduced in newer version of ANTLR, and step 5
1555 will offer completion using version-correct values.
1557 If the option already exists inside the visible part of the buffer, this
1558 command can be used to change the value of that option. Otherwise, find
1559 a correct position where the option can be inserted near point.
1561 The search for a correct position is as follows:
1563 * If search is within an area where options can be inserted, use the
1564 position of point. Inside the options section and if point is in
1565 the middle of a option definition, skip the rest of it.
1566 * If an options section already exists, insert the options at the end.
1567 If only the beginning of the area is visible, insert at the
1568 beginning.
1569 * Otherwise, find the position where an options section can be
1570 inserted and insert a new section before any comments. If the
1571 position before the comments is not visible, insert the new section
1572 after the comments.
1574 This function also inserts \"options {...}\" and the \":\" if necessary,
1575 see `antlr-options-auto-colon'. See also `antlr-options-assign-string'.
1577 This command might also set the mark like \\[set-mark-command] does, see
1578 `antlr-options-push-mark'."
1579 (interactive (antlr-insert-option-interactive current-prefix-arg))
1580 (barf-if-buffer-read-only)
1581 (or location (setq location (cdr (antlr-option-kind level))))
1582 (cond ((null level)
1583 (error "Cannot deduce what kind of option to insert"))
1584 ((atom location)
1585 (error "Cannot insert any %s options around here"
1586 (elt antlr-options-headings (1- level)))))
1587 (let ((area (car location))
1588 (place (cdr location)))
1589 (cond ((null place) ; invisible
1590 (error (if area
1591 "Invisible %s options, use %s to make them visible"
1592 "Invisible area for %s options, use %s to make it visible")
1593 (elt antlr-options-headings (1- level))
1594 (substitute-command-keys "\\[widen]")))
1595 ((null area) ; without option part
1596 (antlr-insert-option-do level option nil
1597 (null (cdr place))
1598 (car place)))
1599 ((save-excursion ; with option part, option visible
1600 (goto-char (max (point-min) (car area)))
1601 (re-search-forward (concat "\\(^\\|;\\)[ \t]*\\(\\<"
1602 (regexp-quote option)
1603 "\\>\\)[ \t\n]*\\(\\(=[ \t]?\\)[ \t]*\\(\\(\\sw\\|\\s_\\)+\\|\"\\([^\n\"\\]\\|[\\][^\n]\\)*\"\\)?\\)?")
1604 ;; 2=name, 3=4+5, 4="=", 5=value
1605 (min (point-max) (cdr area))
1607 (antlr-insert-option-do level option
1608 (cons (or (match-beginning 5)
1609 (match-beginning 3))
1610 (match-end 5))
1611 (and (null (cdr place)) area)
1612 (or (match-beginning 5)
1613 (match-end 4)
1614 (match-end 2))))
1615 (t ; with option part, option not yet
1616 (antlr-insert-option-do level option t
1617 (and (null (cdr place)) area)
1618 (car place))))))
1620 (defun antlr-insert-option-interactive (arg)
1621 "Interactive specification for `antlr-insert-option'.
1622 Return \(LEVEL OPTION LOCATION)."
1623 (barf-if-buffer-read-only)
1624 (if arg (setq arg (prefix-numeric-value arg)))
1625 (unless (memq arg '(nil 1 2 3 4))
1626 (error "Valid prefix args: no=auto, 1=file, 2=grammar, 3=rule, 4=subrule"))
1627 (let* ((kind (antlr-option-kind arg))
1628 (level (car kind)))
1629 (if (atom (cdr kind))
1630 (list level nil (cdr kind))
1631 (let* ((table (elt antlr-options-alists (1- level)))
1632 (completion-ignore-case t) ;dynamic
1633 (input (completing-read (format "Insert %s option: "
1634 (elt antlr-options-headings
1635 (1- level)))
1636 table)))
1637 (list level input (cdr kind))))))
1639 (defun antlr-options-menu-filter (level _menu-items)
1640 "Return items for options submenu of level LEVEL."
1641 ;; checkdoc-params: (menu-items)
1642 (let ((active (if buffer-read-only
1644 (consp (cdr-safe (cdr (antlr-option-kind level)))))))
1645 (mapcar (lambda (option)
1646 (vector option
1647 (list 'antlr-insert-option level option)
1648 :active active))
1649 (sort (mapcar 'car (elt antlr-options-alists (1- level)))
1650 'string-lessp))))
1653 ;;;===========================================================================
1654 ;;; Insert option: determine section-kind
1655 ;;;===========================================================================
1657 (defun antlr-option-kind (requested)
1658 "Return level and location for option to insert near point.
1659 Call function `antlr-option-level' with argument REQUESTED. If the
1660 result is nil, return \(REQUESTED . error). If the result has the
1661 non-nil value LEVEL, return \(LEVEL . LOCATION) where LOCATION looks
1662 like \(AREA . PLACE), see `antlr-option-location'."
1663 (save-excursion
1664 (save-restriction
1665 (let ((min0 (point-min)) ; before `widen'!
1666 (max0 (point-max))
1667 (orig (point))
1668 (level (antlr-option-level requested)) ; calls `widen'!
1669 pos)
1670 (cond ((null level)
1671 (setq level requested))
1672 ((eq level 1) ; file options
1673 (goto-char (point-min))
1674 (setq pos (antlr-skip-file-prelude 'header-only)))
1675 ((not (eq level 3)) ; grammar or subrule options
1676 (setq pos (point))
1677 (antlr-c-forward-sws))
1678 ((looking-at "^\\(private[ \t\n]\\|public[ \t\n]\\|protected[ \t\n]\\)?[ \t\n]*\\(\\(\\sw\\|\\s_\\)+\\)[ \t\n]*\\(!\\)?[ \t\n]*\\(\\[\\)?")
1679 ;; rule options, with complete rule header
1680 (goto-char (or (match-end 4) (match-end 3)))
1681 (setq pos (antlr-skip-sexps (if (match-end 5) 1 0)))
1682 (when (looking-at "returns[ \t\n]*\\[")
1683 (goto-char (1- (match-end 0)))
1684 (setq pos (antlr-skip-sexps 1)))))
1685 (cons level
1686 (cond ((null pos) 'error)
1687 ((looking-at "options[ \t\n]*{")
1688 (goto-char (match-end 0))
1689 (setq pos (ignore-errors-x (scan-lists (point) 1 1)))
1690 (antlr-option-location orig min0 max0
1691 (point)
1692 (if pos (1- pos) (point-max))
1695 (antlr-option-location orig min0 max0
1696 pos (point)
1697 nil))))))))
1699 (defun antlr-option-level (requested)
1700 "Return level for option to insert near point.
1701 Remove any restrictions from current buffer and return level for the
1702 option to insert near point, i.e., 1, 2, 3, 4, or nil if no such option
1703 can be inserted. If REQUESTED is non-nil, it is the only possible value
1704 to return except nil. If REQUESTED is nil, return level for the nearest
1705 option kind, i.e., the highest number possible.
1707 If the result is 2, point is at the beginning of the class after the
1708 class definition. If the result is 3 or 4, point is at the beginning of
1709 the rule/subrule after the init action. Otherwise, the point position
1710 is undefined."
1711 (widen)
1712 (if (eq requested 1)
1714 (antlr-with-syntax-table antlr-action-syntax-table
1715 (antlr-invalidate-context-cache)
1716 (let* ((orig (point))
1717 (outsidep (antlr-outside-rule-p))
1718 bor depth)
1719 (if (eq (char-after) ?\{) (antlr-skip-sexps 1))
1720 (setq bor (point)) ; beginning of rule (after init action)
1721 (cond ((eq requested 2) ; grammar options required?
1722 (let (boc) ; beginning of class
1723 (goto-char (point-min))
1724 (while (and (<= (point) bor)
1725 (antlr-re-search-forward antlr-class-header-regexp
1726 nil))
1727 (if (<= (match-beginning 0) bor)
1728 (setq boc (match-end 0))))
1729 (when boc
1730 (goto-char boc)
1731 2)))
1732 ((save-excursion ; in region of file options?
1733 (goto-char (point-min))
1734 (antlr-skip-file-prelude t) ; ws/comment after: OK
1735 (< orig (point)))
1736 (and (null requested) 1))
1737 (outsidep ; outside rule not OK
1738 nil)
1739 ((looking-at antlr-class-header-regexp) ; rule = class def?
1740 (goto-char (match-end 0))
1741 (and (null requested) 2))
1742 ((eq requested 3) ; rule options required?
1743 (goto-char bor)
1745 ((setq depth (antlr-syntactic-grammar-depth orig bor))
1746 (if (> depth 0) ; move out of actions
1747 (goto-char (scan-lists (point) -1 depth)))
1748 (set-syntax-table antlr-mode-syntax-table)
1749 (antlr-invalidate-context-cache)
1750 (if (eq (antlr-syntactic-context) 0) ; not in subrule?
1751 (unless (eq requested 4)
1752 (goto-char bor)
1754 (goto-char (1+ (scan-lists (point) -1 1)))
1755 4)))))))
1757 (defun antlr-option-location (orig min-vis max-vis min-area max-area withp)
1758 "Return location for the options area.
1759 ORIG is the original position of `point', MIN-VIS is `point-min' and
1760 MAX-VIS is `point-max'. If WITHP is non-nil, there exists an option
1761 specification and it starts after the brace at MIN-AREA and stops at
1762 MAX-AREA. If WITHP is nil, there is no area and the region where it
1763 could be inserted starts at MIN-AREA and stops at MAX-AREA.
1765 The result has the form (AREA . PLACE). AREA is (MIN-AREA . MAX-AREA)
1766 if WITHP is non-nil, and nil otherwise. PLACE is nil if the area is
1767 invisible, (ORIG) if ORIG is inside the area, (MIN-AREA . beginning) for
1768 a visible start position and (MAX-AREA . end) for a visible end position
1769 where the beginning is preferred if WITHP is nil and the end if WITHP is
1770 non-nil."
1771 (cons (and withp (cons min-area max-area))
1772 (cond ((and (<= min-area orig) (<= orig max-area)
1773 (save-excursion
1774 (goto-char orig)
1775 (not (memq (antlr-syntactic-context)
1776 '(comment block-comment)))))
1777 ;; point in options area and not in comment
1778 (list orig))
1779 ((and (null withp) (<= min-vis min-area) (<= min-area max-vis))
1780 ;; use start of options area (only if not `withp')
1781 (cons min-area 'beginning))
1782 ((and (<= min-vis max-area) (<= max-area max-vis))
1783 ;; use end of options area
1784 (cons max-area 'end))
1785 ((and withp (<= min-vis min-area) (<= min-area max-vis))
1786 ;; use start of options area (only if `withp')
1787 (cons min-area 'beginning)))))
1789 (defun antlr-syntactic-grammar-depth (pos beg)
1790 "Return syntactic context depth at POS.
1791 Move to POS and from there on to the beginning of the string or comment
1792 if POS is inside such a construct. Then, return the syntactic context
1793 depth at point if the point position is smaller than BEG.
1794 WARNING: this may alter `match-data'."
1795 (goto-char pos)
1796 (let ((context (or (antlr-syntactic-context) 0)))
1797 (while (and context (not (integerp context)))
1798 (cond ((eq context 'string)
1799 (setq context
1800 (and (search-backward "\"" nil t)
1801 (>= (point) beg)
1802 (or (antlr-syntactic-context) 0))))
1803 ((memq context '(comment block-comment))
1804 (setq context
1805 (and (re-search-backward "/[/*]" nil t)
1806 (>= (point) beg)
1807 (or (antlr-syntactic-context) 0))))))
1808 context))
1811 ;;;===========================================================================
1812 ;;; Insert options: do the insertion
1813 ;;;===========================================================================
1815 (defun antlr-insert-option-do (level option old area pos)
1816 "Insert option into buffer at position POS.
1817 Insert option of level LEVEL and name OPTION. If OLD is non-nil, an
1818 options area is already exists. If OLD looks like \(BEG . END), the
1819 option already exists. Then, BEG is the start position of the option
1820 value, the position of the `=' or nil, and END is the end position of
1821 the option value or nil.
1823 If the original point position was outside an options area, AREA is nil.
1824 Otherwise, and if an option specification already exists, AREA is a cons
1825 cell where the two values determine the area inside the braces."
1826 (let* ((spec (cdr (assoc option (elt antlr-options-alists (1- level)))))
1827 (value (antlr-option-spec level option (cdr spec) (consp old))))
1828 (if (fboundp (car spec)) (funcall (car spec) 'before-input option))
1829 ;; set mark (unless point was inside options area before)
1830 (if (cond (area (eq antlr-options-push-mark t))
1831 ((numberp antlr-options-push-mark)
1832 (> (count-lines (min (point) pos) (max (point) pos))
1833 antlr-options-push-mark))
1834 (antlr-options-push-mark))
1835 (push-mark))
1836 ;; read option value -----------------------------------------------------
1837 (goto-char pos)
1838 (if (null value)
1839 ;; no option specification found
1840 (if (y-or-n-p (format "Insert unknown %s option %s? "
1841 (elt antlr-options-headings (1- level))
1842 option))
1843 (message "Insert value for %s option %s"
1844 (elt antlr-options-headings (1- level))
1845 option)
1846 (error "Didn't insert unknown %s option %s"
1847 (elt antlr-options-headings (1- level))
1848 option))
1849 ;; option specification found
1850 (setq value (cdr value))
1851 (if (car value)
1852 (let ((initial (and (consp old) (cdr old)
1853 (buffer-substring (car old) (cdr old)))))
1854 (setq value (apply (car value)
1855 (and initial
1856 (if (eq (aref initial 0) ?\")
1857 (read initial)
1858 initial))
1859 (cdr value))))
1860 (message "%s" (or (cadr value) ""))
1861 (setq value nil)))
1862 ;; insert value ----------------------------------------------------------
1863 (if (consp old)
1864 (antlr-insert-option-existing old value)
1865 (if (consp area)
1866 ;; Move outside string/comment if point is inside option spec
1867 (antlr-syntactic-grammar-depth (point) (car area)))
1868 (antlr-insert-option-space area old)
1869 (or old (antlr-insert-option-area level))
1870 (insert option " = ;")
1871 (backward-char)
1872 (if value (insert value)))
1873 ;; final -----------------------------------------------------------------
1874 (if (fboundp (car spec)) (funcall (car spec) 'after-insertion option))))
1876 (defun antlr-option-spec (level option specs existsp)
1877 "Return version correct option value specification.
1878 Return specification for option OPTION of kind level LEVEL. SPECS
1879 should correspond to the VALUE-SPEC... in `antlr-option-alists'.
1880 EXISTSP determines whether the option already exists."
1881 (let (value)
1882 (while (and specs (>= antlr-tool-version (caar specs)))
1883 (setq value (pop specs)))
1884 (cond (value) ; found correct spec
1885 ((null specs) nil) ; didn't find any specs
1886 (existsp (car specs)) ; wrong version, but already present
1887 ((y-or-n-p (format "Insert v%s %s option %s in v%s? "
1888 (antlr-version-string (caar specs))
1889 (elt antlr-options-headings (1- level))
1890 option
1891 (antlr-version-string antlr-tool-version)))
1892 (car specs))
1894 (error "Didn't insert v%s %s option %s in v%s"
1895 (antlr-version-string (caar specs))
1896 (elt antlr-options-headings (1- level))
1897 option
1898 (antlr-version-string antlr-tool-version))))))
1900 (defun antlr-version-string (version)
1901 "Format the Antlr version number VERSION, see `antlr-tool-version'."
1902 (let ((version100 (/ version 100)))
1903 (format "%d.%d.%d"
1904 (/ version100 100) (mod version100 100) (mod version 100))))
1907 ;;;===========================================================================
1908 ;;; Insert options: the details (used by `antlr-insert-option-do')
1909 ;;;===========================================================================
1911 (defun antlr-insert-option-existing (old value)
1912 "Insert option value VALUE at point for existing option.
1913 For OLD, see `antlr-insert-option-do'."
1914 ;; no = => insert =
1915 (unless (car old) (insert antlr-options-assign-string))
1916 ;; with user input => insert if necessary
1917 (when value
1918 (if (cdr old) ; with value
1919 (if (string-equal value (buffer-substring (car old) (cdr old)))
1920 (goto-char (cdr old))
1921 (delete-region (car old) (cdr old))
1922 (insert value))
1923 (insert value)))
1924 (unless (looking-at "\\([^\n=;{}/'\"]\\|'\\([^\n'\\]\\|\\\\.\\)*'\\|\"\\([^\n\"\\]\\|\\\\.\\)*\"\\)*;")
1925 ;; stuff (no =, {, } or /) at point is not followed by ";"
1926 (insert ";")
1927 (backward-char)))
1929 (defun antlr-insert-option-space (area old)
1930 "Find appropriate place to insert option, insert newlines/spaces.
1931 For AREA and OLD, see `antlr-insert-option-do'."
1932 (let ((orig (point))
1933 (open t))
1934 (skip-chars-backward " \t")
1935 (unless (bolp)
1936 (let ((before (char-after (1- (point)))))
1937 (goto-char orig)
1938 (and old ; with existing options area
1939 (consp area) ; if point inside existing area
1940 (not (eq before ?\;)) ; if not at beginning of option
1941 ; => skip to end of option
1942 (if (and (search-forward ";" (cdr area) t)
1943 (let ((context (antlr-syntactic-context)))
1944 (or (null context) (numberp context))))
1945 (setq orig (point))
1946 (goto-char orig)))
1947 (skip-chars-forward " \t")
1949 (if (looking-at "$\\|//")
1950 ;; just comment after point => skip (+ lines w/ same col comment)
1951 (let ((same (if (> (match-end 0) (match-beginning 0))
1952 (current-column))))
1953 (beginning-of-line 2)
1954 (or (bolp) (insert "\n"))
1955 (when (and same (null area)) ; or (consp area)?
1956 (while (and (looking-at "[ \t]*\\(//\\)")
1957 (goto-char (match-beginning 1))
1958 (= (current-column) same))
1959 (beginning-of-line 2)
1960 (or (bolp) (insert "\n")))))
1961 (goto-char orig)
1962 (if (null old)
1963 (progn (insert "\n") (antlr-indent-line))
1964 (unless (eq (char-after (1- (point))) ?\ )
1965 (insert " "))
1966 (unless (eq (char-after (point)) ?\ )
1967 (insert " ")
1968 (backward-char))
1969 (setq open nil)))))
1970 (when open
1971 (beginning-of-line 1)
1972 (insert "\n")
1973 (backward-char)
1974 (antlr-indent-line))))
1976 (defun antlr-insert-option-area (level)
1977 "Insert new options area for options of level LEVEL.
1978 Used by `antlr-insert-option-do'."
1979 (insert "options {\n\n}")
1980 (when (and antlr-options-auto-colon
1981 (memq level '(3 4))
1982 (save-excursion
1983 (antlr-c-forward-sws)
1984 (if (eq (char-after (point)) ?\{) (antlr-skip-sexps 1))
1985 (not (eq (char-after (point)) ?\:))))
1986 (insert "\n:")
1987 (antlr-indent-line)
1988 (end-of-line 0))
1989 (backward-char 1)
1990 (antlr-indent-line)
1991 (beginning-of-line 0)
1992 (antlr-indent-line))
1995 ;;;===========================================================================
1996 ;;; Insert options: in `antlr-options-alists'
1997 ;;;===========================================================================
1999 (defun antlr-read-value (initial-contents prompt
2000 &optional as-string table table-x)
2001 "Read a string from the minibuffer, possibly with completion.
2002 If INITIAL-CONTENTS is non-nil, insert it in the minibuffer initially.
2003 PROMPT is a string to prompt with, normally it ends in a colon and a
2004 space. If AS-STRING is t or is a member \(comparison done with `eq') of
2005 `antlr-options-style', return printed representation of the user input,
2006 otherwise return the user input directly.
2008 If TABLE or TABLE-X is non-nil, read with completion. The completion
2009 table is the resulting alist of TABLE-X concatenated with TABLE where
2010 TABLE can also be a function evaluation to an alist.
2012 Used inside `antlr-options-alists'."
2013 (let* ((completion-ignore-case t) ; dynamic
2014 (table0 (and (or table table-x)
2015 (append table-x
2016 (if (functionp table) (funcall table) table))))
2017 (input (if table0
2018 (completing-read prompt table0 nil nil initial-contents)
2019 (read-from-minibuffer prompt initial-contents))))
2020 (if (and as-string
2021 (or (eq as-string t)
2022 (cdr (assq as-string antlr-options-style))))
2023 (format "%S" input)
2024 input)))
2026 (defun antlr-read-boolean (initial-contents prompt &optional table)
2027 "Read a boolean value from the minibuffer, with completion.
2028 If INITIAL-CONTENTS is non-nil, insert it in the minibuffer initially.
2029 PROMPT is a string to prompt with, normally it ends in a question mark
2030 and a space. \"(true or false) \" is appended if TABLE is nil.
2032 Read with completion over \"true\", \"false\" and the keys in TABLE, see
2033 also `antlr-read-value'.
2035 Used inside `antlr-options-alists'."
2036 (antlr-read-value initial-contents
2037 (if table prompt (concat prompt "(true or false) "))
2039 table '(("false") ("true"))))
2041 (defun antlr-language-option-extra (phase &rest _dummies)
2042 ;; checkdoc-params: (dummies)
2043 "Change language according to the new value of the \"language\" option.
2044 Call `antlr-mode' if the new language would be different from the value
2045 of `antlr-language', keeping the value of variable `font-lock-mode'.
2047 Called in PHASE `after-insertion', see `antlr-options-alists'."
2048 (when (eq phase 'after-insertion)
2049 (let ((new-language (antlr-language-option t)))
2050 (or (null new-language)
2051 (eq new-language antlr-language)
2052 (let ((font-lock (and (boundp 'font-lock-mode) font-lock-mode)))
2053 (if font-lock (font-lock-mode 0))
2054 (antlr-mode)
2055 (and font-lock (null font-lock-mode) (font-lock-mode 1)))))))
2057 (defun antlr-c++-mode-extra (phase option &rest _dummies)
2058 ;; checkdoc-params: (option dummies)
2059 "Warn if C++ option is used with the wrong language.
2060 Ask user \(\"y or n\"), if a C++ only option is going to be inserted but
2061 `antlr-language' has not the value `c++-mode'.
2063 Called in PHASE `before-input', see `antlr-options-alists'."
2064 (and (eq phase 'before-input)
2065 (not (eq antlr-language 'c++-mode))
2066 (not (y-or-n-p (format "Insert C++ %s option? " option)))
2067 (error "Didn't insert C++ %s option with language %s"
2068 option (cadr (assq antlr-language antlr-language-alist)))))
2071 ;;;===========================================================================
2072 ;;; Compute dependencies
2073 ;;;===========================================================================
2075 (defun antlr-file-dependencies ()
2076 "Return dependencies for grammar in current buffer.
2077 The result looks like \(FILE \(CLASSES . SUPERS) VOCABS . LANGUAGE)
2078 where CLASSES = ((CLASS . CLASS-EVOCAB) ...),
2079 SUPERS = ((SUPER . USE-EVOCAB-P) ...), and
2080 VOCABS = ((EVOCAB ...) . (IVOCAB ...))
2082 FILE is the current buffer's file-name without directory part and
2083 LANGUAGE is the value of `antlr-language' in the current buffer. Each
2084 EVOCAB is an export vocabulary and each IVOCAB is an import vocabulary.
2086 Each CLASS is a grammar class with its export vocabulary CLASS-EVOCAB.
2087 Each SUPER is a super-grammar class where USE-EVOCAB-P indicates whether
2088 its export vocabulary is used as an import vocabulary."
2089 (unless buffer-file-name
2090 (error "Grammar buffer does not visit a file"))
2091 (let (classes export-vocabs import-vocabs superclasses default-vocab)
2092 (antlr-with-syntax-table antlr-action-syntax-table
2093 (goto-char (point-min))
2094 (while (antlr-re-search-forward antlr-class-header-regexp nil)
2095 ;; parse class definition --------------------------------------------
2096 (let* ((class (match-string 2))
2097 (sclass (match-string 4))
2098 ;; export vocab defaults to class name (first grammar in file)
2099 ;; or to the export vocab of the first grammar in file:
2100 (evocab (or default-vocab class))
2101 (ivocab nil))
2102 (goto-char (match-end 0))
2103 (antlr-c-forward-sws)
2104 (while (looking-at "options\\>\\|\\(tokens\\)\\>")
2105 (if (match-beginning 1)
2106 (antlr-skip-sexps 2)
2107 (goto-char (match-end 0))
2108 (antlr-c-forward-sws)
2109 ;; parse grammar option sections -------------------------------
2110 (when (eq (char-after (point)) ?\{)
2111 (let* ((beg (1+ (point)))
2112 (end (1- (antlr-skip-sexps 1)))
2113 (cont (point)))
2114 (goto-char beg)
2115 (if (re-search-forward "\\<exportVocab[ \t]*=[ \t]*\\([A-Za-z\300-\326\330-\337]\\sw*\\)" end t)
2116 (setq evocab (match-string 1)))
2117 (goto-char beg)
2118 (if (re-search-forward "\\<importVocab[ \t]*=[ \t]*\\([A-Za-z\300-\326\330-\337]\\sw*\\)" end t)
2119 (setq ivocab (match-string 1)))
2120 (goto-char cont)))))
2121 (unless (member sclass '("Parser" "Lexer" "TreeParser"))
2122 (let ((super (assoc sclass superclasses)))
2123 (if super
2124 (or ivocab (setcdr super t))
2125 (push (cons sclass (null ivocab)) superclasses))))
2126 ;; remember class with export vocabulary:
2127 (push (cons class evocab) classes)
2128 ;; default export vocab is export vocab of first grammar in file:
2129 (or default-vocab (setq default-vocab evocab))
2130 (or (member evocab export-vocabs) (push evocab export-vocabs))
2131 (or (null ivocab)
2132 (member ivocab import-vocabs) (push ivocab import-vocabs)))))
2133 (if classes
2134 (list* (file-name-nondirectory buffer-file-name)
2135 (cons (nreverse classes) (nreverse superclasses))
2136 (cons (nreverse export-vocabs) (nreverse import-vocabs))
2137 antlr-language))))
2139 (defun antlr-directory-dependencies (dirname)
2140 "Return dependencies for all grammar files in directory DIRNAME.
2141 The result looks like \((CLASS-SPEC ...) . \(FILE-DEP ...))
2142 where CLASS-SPEC = (CLASS (FILE . EVOCAB) ...).
2144 FILE-DEP are the dependencies for each grammar file in DIRNAME, see
2145 `antlr-file-dependencies'. For each grammar class CLASS, FILE is a
2146 grammar file in which CLASS is defined and EVOCAB is the name of the
2147 export vocabulary specified in that file."
2148 (let ((grammar (directory-files dirname t "\\.g\\'")))
2149 (when grammar
2150 (let ((antlr-imenu-name nil) ; dynamic-let: no imenu
2151 (expanded-regexp
2152 (concat (format (regexp-quote
2153 (cadr antlr-special-file-formats))
2154 ".+")
2155 "\\'"))
2156 classes dependencies)
2157 (with-temp-buffer
2158 (dolist (file grammar)
2159 (when (and (file-regular-p file)
2160 (null (string-match expanded-regexp file)))
2161 (insert-file-contents file t nil nil t)
2162 (normal-mode t) ; necessary for major-mode, syntax
2163 ; table and `antlr-language'
2164 (when (derived-mode-p 'antlr-mode)
2165 (let* ((file-deps (antlr-file-dependencies))
2166 (file (car file-deps)))
2167 (when file-deps
2168 (dolist (class-def (caadr file-deps))
2169 (let ((file-evocab (cons file (cdr class-def)))
2170 (class-spec (assoc (car class-def) classes)))
2171 (if class-spec
2172 (nconc (cdr class-spec) (list file-evocab))
2173 (push (list (car class-def) file-evocab)
2174 classes))))
2175 (push file-deps dependencies)))))))
2176 (cons (nreverse classes) (nreverse dependencies))))))
2179 ;;;===========================================================================
2180 ;;; Compilation: run ANTLR tool
2181 ;;;===========================================================================
2183 (defun antlr-superclasses-glibs (supers classes)
2184 "Compute the grammar lib option for the super grammars SUPERS.
2185 Look in CLASSES for the right grammar lib files for SUPERS. SUPERS is
2186 part SUPER in the result of `antlr-file-dependencies'. CLASSES is the
2187 part \(CLASS-SPEC ...) in the result of `antlr-directory-dependencies'.
2189 The result looks like \(OPTION WITH-UNKNOWN GLIB ...). OPTION is the
2190 complete \"-glib\" option. WITH-UNKNOWN is t if there is none or more
2191 than one grammar file for at least one super grammar.
2193 Each GLIB looks like \(GRAMMAR-FILE . EVOCAB). GRAMMAR-FILE is a file
2194 in which a super-grammar is defined. EVOCAB is the value of the export
2195 vocabulary of the super-grammar or nil if it is not needed."
2196 ;; If the superclass is defined in the same file, that file will be included
2197 ;; with -glib again. This will lead to a redefinition. But defining a
2198 ;; analyzer of the same class twice in a file will lead to an error anyway...
2199 (let (glibs unknown)
2200 (while supers
2201 (let* ((super (pop supers))
2202 (sup-files (cdr (assoc (car super) classes)))
2203 (file (and sup-files (null (cdr sup-files)) (car sup-files))))
2204 (or file (setq unknown t)) ; not exactly one file
2205 (push (cons (or (car file)
2206 (format (car antlr-unknown-file-formats)
2207 (car super)))
2208 (and (cdr super)
2209 (or (cdr file)
2210 (format (cadr antlr-unknown-file-formats)
2211 (car super)))))
2212 glibs)))
2213 (cons (if glibs (concat " -glib " (mapconcat 'car glibs ";")) "")
2214 (cons unknown glibs))))
2216 (defun antlr-run-tool (command file &optional saved)
2217 "Run Antlr took COMMAND on grammar FILE.
2218 When called interactively, COMMAND is read from the minibuffer and
2219 defaults to `antlr-tool-command' with a computed \"-glib\" option if
2220 necessary.
2222 Save all buffers first unless optional value SAVED is non-nil. When
2223 called interactively, the buffers are always saved, see also variable
2224 `antlr-ask-about-save'."
2225 (interactive (antlr-run-tool-interactive))
2226 (or saved (save-some-buffers (not antlr-ask-about-save)))
2227 (let ((default-directory (file-name-directory file)))
2228 (compilation-start (concat command " " (file-name-nondirectory file))
2229 nil (lambda (_mode-name) "*Antlr-Run*"))))
2231 (defun antlr-run-tool-interactive ()
2232 ;; code in `interactive' is not compiled
2233 "Interactive specification for `antlr-run-tool'.
2234 Use prefix argument ARG to return \(COMMAND FILE SAVED)."
2235 (let* ((supers (cdadr (save-excursion
2236 (save-restriction
2237 (widen)
2238 (antlr-file-dependencies)))))
2239 (glibs ""))
2240 (when supers
2241 (save-some-buffers (not antlr-ask-about-save) nil)
2242 (setq glibs (car (antlr-superclasses-glibs
2243 supers
2244 (car (antlr-directory-dependencies
2245 (antlr-default-directory)))))))
2246 (list (antlr-read-shell-command "Run Antlr on current file with: "
2247 (concat antlr-tool-command glibs " "))
2248 buffer-file-name
2249 supers)))
2252 ;;;===========================================================================
2253 ;;; Makefile creation
2254 ;;;===========================================================================
2256 (defun antlr-makefile-insert-variable (number pre post)
2257 "Insert Makefile variable numbered NUMBER according to specification.
2258 Also insert strings PRE and POST before and after the variable."
2259 (let ((spec (cadr antlr-makefile-specification)))
2260 (when spec
2261 (insert pre
2262 (if number (format (cadr spec) number) (car spec))
2263 post))))
2265 (defun antlr-insert-makefile-rules (&optional in-makefile)
2266 "Insert Makefile rules in the current buffer at point.
2267 IN-MAKEFILE is non-nil, if the current buffer is the Makefile. See
2268 command `antlr-show-makefile-rules' for detail."
2269 (let* ((dirname (antlr-default-directory))
2270 (deps0 (antlr-directory-dependencies dirname))
2271 (classes (car deps0)) ; CLASS -> (FILE . EVOCAB) ...
2272 (deps (cdr deps0)) ; FILE -> (c . s) (ev . iv) . LANGUAGE
2273 (with-error nil)
2274 (gen-sep (or (caddr (cadr antlr-makefile-specification)) " "))
2275 (n (and (cdr deps) (cadr antlr-makefile-specification) 0)))
2276 (or in-makefile (set-buffer standard-output))
2277 (dolist (dep deps)
2278 (let ((supers (cdadr dep))
2279 (lang (cdr (assoc (cdddr dep) antlr-file-formats-alist))))
2280 (if n (incf n))
2281 (antlr-makefile-insert-variable n "" " =")
2282 (if supers
2283 (insert " "
2284 (format (cadr antlr-special-file-formats)
2285 (file-name-sans-extension (car dep)))))
2286 (dolist (class-def (caadr dep))
2287 (let ((sep gen-sep))
2288 (dolist (class-file (cadr lang))
2289 (insert sep (format class-file (car class-def)))
2290 (setq sep " "))))
2291 (dolist (evocab (caaddr dep))
2292 (let ((sep gen-sep))
2293 (dolist (vocab-file (cons (car antlr-special-file-formats)
2294 (car lang)))
2295 (insert sep (format vocab-file evocab))
2296 (setq sep " "))))
2297 (antlr-makefile-insert-variable n "\n$(" ")")
2298 (insert ": " (car dep))
2299 (dolist (ivocab (cdaddr dep))
2300 (insert " " (format (car antlr-special-file-formats) ivocab)))
2301 (let ((glibs (antlr-superclasses-glibs supers classes)))
2302 (if (cadr glibs) (setq with-error t))
2303 (dolist (super (cddr glibs))
2304 (insert " " (car super))
2305 (if (cdr super)
2306 (insert " " (format (car antlr-special-file-formats)
2307 (cdr super)))))
2308 (insert "\n\t"
2309 (caddr antlr-makefile-specification)
2310 (car glibs)
2311 " $<\n"
2312 (car antlr-makefile-specification)))))
2313 (if n
2314 (let ((i 0))
2315 (antlr-makefile-insert-variable nil "" " =")
2316 (while (<= (incf i) n)
2317 (antlr-makefile-insert-variable i " $(" ")"))
2318 (insert "\n" (car antlr-makefile-specification))))
2319 (if (string-equal (car antlr-makefile-specification) "\n")
2320 (backward-delete-char 1))
2321 (when with-error
2322 (goto-char (point-min))
2323 (insert antlr-help-unknown-file-text))
2324 (unless in-makefile
2325 (copy-region-as-kill (point-min) (point-max))
2326 (goto-char (point-min))
2327 (insert (format antlr-help-rules-intro dirname)))))
2329 ;;;###autoload
2330 (defun antlr-show-makefile-rules ()
2331 "Show Makefile rules for all grammar files in the current directory.
2332 If the `major-mode' of the current buffer has the value `makefile-mode',
2333 the rules are directory inserted at point. Otherwise, a *Help* buffer
2334 is shown with the rules which are also put into the `kill-ring' for
2335 \\[yank].
2337 This command considers import/export vocabularies and grammar
2338 inheritance and provides a value for the \"-glib\" option if necessary.
2339 Customize variable `antlr-makefile-specification' for the appearance of
2340 the rules.
2342 If the file for a super-grammar cannot be determined, special file names
2343 are used according to variable `antlr-unknown-file-formats' and a
2344 commentary with value `antlr-help-unknown-file-text' is added. The
2345 *Help* buffer always starts with the text in `antlr-help-rules-intro'."
2346 (interactive)
2347 (if (null (derived-mode-p 'makefile-mode))
2348 (antlr-with-displaying-help-buffer 'antlr-insert-makefile-rules)
2349 (push-mark)
2350 (antlr-insert-makefile-rules t)))
2353 ;;;===========================================================================
2354 ;;; Indentation
2355 ;;;===========================================================================
2357 (defun antlr-indent-line ()
2358 "Indent the current line as ANTLR grammar code.
2359 The indentation of grammar lines are calculated by `c-basic-offset',
2360 multiplied by:
2361 - the level of the paren/brace/bracket depth,
2362 - plus 0/2/1, depending on the position inside the rule: header, body,
2363 exception part,
2364 - minus 1 if `antlr-indent-item-regexp' matches the beginning of the
2365 line starting from the first non-whitespace.
2367 Lines inside block comments are indented by `c-indent-line' according to
2368 `antlr-indent-comment'.
2370 Lines in actions except top-level actions in a header part or an option
2371 area are indented by `c-indent-line'.
2373 Lines in header actions are indented at column 0 if `antlr-language'
2374 equals to a key in `antlr-indent-at-bol-alist' and the line starting at
2375 the first non-whitespace is matched by the corresponding value.
2377 For the initialization of `c-basic-offset', see `antlr-indent-style' and,
2378 to a lesser extent, `antlr-tab-offset-alist'."
2379 (save-restriction
2380 (let ((orig (point))
2381 (min0 (point-min))
2382 bol boi indent syntax cc-syntax)
2383 (widen)
2384 (beginning-of-line)
2385 (setq bol (point))
2386 (if (< bol min0)
2387 (error "Beginning of current line not visible"))
2388 (skip-chars-forward " \t")
2389 (setq boi (point))
2390 ;; check syntax at beginning of indentation ----------------------------
2391 (antlr-with-syntax-table antlr-action-syntax-table
2392 (antlr-invalidate-context-cache)
2393 (setq syntax (antlr-syntactic-context))
2394 (cond ((symbolp syntax)
2395 (setq indent nil)) ; block-comments, strings, (comments)
2396 ((progn
2397 (antlr-next-rule -1 t)
2398 (if (antlr-search-forward ":") (< boi (1- (point))) t))
2399 (setq indent 0)) ; in rule header
2400 ((if (antlr-search-forward ";") (< boi (point)) t)
2401 (setq indent 2)) ; in rule body
2403 (forward-char)
2404 (antlr-skip-exception-part nil)
2405 (setq indent (if (> (point) boi) 1 0))))) ; in exception part?
2406 ;; check whether to use indentation engine of cc-mode ------------------
2407 (antlr-invalidate-context-cache)
2408 (goto-char boi)
2409 (when (and indent (> syntax 0))
2410 (cond ((> syntax 1) ; block in action => use cc-mode
2411 (setq indent nil))
2412 ((and (= indent 0)
2413 (assq antlr-language antlr-indent-at-bol-alist)
2414 (looking-at (cdr (assq antlr-language
2415 antlr-indent-at-bol-alist))))
2416 (setq syntax 'bol))
2417 ((setq cc-syntax (c-guess-basic-syntax))
2418 (let ((cc cc-syntax) symbol)
2419 (while (setq symbol (pop cc))
2420 (when (cdr symbol)
2421 (or (memq (car symbol)
2422 antlr-disabling-cc-syntactic-symbols)
2423 (setq indent nil))
2424 (setq cc nil)))))))
2425 ;;; ((= indent 1) ; exception part => use cc-mode
2426 ;;; (setq indent nil))
2427 ;;; ((save-restriction ; not in option part => cc-mode
2428 ;;; (goto-char (scan-lists (point) -1 1))
2429 ;;; (skip-chars-backward " \t\n")
2430 ;;; (narrow-to-region (point-min) (point))
2431 ;;; (not (re-search-backward "\\<options\\'" nil t)))
2432 ;;; (setq indent nil)))))
2433 ;; compute the corresponding indentation and indent --------------------
2434 (if (null indent)
2435 ;; Use the indentation engine of cc-mode
2436 (progn
2437 (goto-char orig)
2438 (if (or (numberp syntax)
2439 (if (eq syntax 'string) nil (eq antlr-indent-comment t)))
2440 (c-indent-line cc-syntax)))
2441 ;; do it ourselves
2442 (goto-char boi)
2443 (unless (symbolp syntax) ; direct indentation
2444 ;;(antlr-invalidate-context-cache)
2445 (incf indent (antlr-syntactic-context))
2446 (and (> indent 0) (looking-at antlr-indent-item-regexp) (decf indent))
2447 (setq indent (* indent c-basic-offset)))
2448 ;; the usual major-mode indent stuff ---------------------------------
2449 (setq orig (- (point-max) orig))
2450 (unless (= (current-column) indent)
2451 (delete-region bol boi)
2452 (beginning-of-line)
2453 (indent-to indent))
2454 ;; If initial point was within line's indentation,
2455 ;; position after the indentation. Else stay at same point in text.
2456 (if (> (- (point-max) orig) (point))
2457 (goto-char (- (point-max) orig)))))))
2459 (defun antlr-indent-command (&optional arg)
2460 "Indent the current line or insert tabs/spaces.
2461 With optional prefix argument ARG or if the previous command was this
2462 command, insert ARG tabs or spaces according to `indent-tabs-mode'.
2463 Otherwise, indent the current line with `antlr-indent-line'."
2464 (interactive "*P")
2465 (if (or arg (eq last-command 'antlr-indent-command))
2466 (insert-tab arg)
2467 (let ((antlr-indent-comment (and antlr-indent-comment t))) ; dynamic
2468 (antlr-indent-line))))
2470 (defun antlr-electric-character (&optional arg)
2471 "Insert the character you type and indent the current line.
2472 Insert the character like `self-insert-command' and indent the current
2473 line as `antlr-indent-command' does. Do not indent the line if
2475 * this command is called with a prefix argument ARG,
2476 * there are characters except whitespaces between point and the
2477 beginning of the line, or
2478 * point is not inside a normal grammar code, { and } are also OK in
2479 actions.
2481 This command is useful for a character which has some special meaning in
2482 ANTLR's syntax and influences the auto indentation, see
2483 `antlr-indent-item-regexp'."
2484 (interactive "*P")
2485 (if (or arg
2486 (save-excursion (skip-chars-backward " \t") (not (bolp)))
2487 (antlr-with-syntax-table antlr-action-syntax-table
2488 (antlr-invalidate-context-cache)
2489 (let ((context (antlr-syntactic-context)))
2490 (not (and (numberp context)
2491 (or (zerop context)
2492 (memq last-command-event '(?\{ ?\}))))))))
2493 (self-insert-command (prefix-numeric-value arg))
2494 (self-insert-command (prefix-numeric-value arg))
2495 (antlr-indent-line)))
2498 ;;;===========================================================================
2499 ;;; Mode entry
2500 ;;;===========================================================================
2502 (defun antlr-c-init-language-vars ()
2503 "Like `c-init-language-vars-for' when using cc-mode before v5.29."
2504 (let ((settings ; (cdr '(setq...)) will be optimized
2505 (if (eq antlr-language 'c++-mode)
2506 (cdr '(setq ;' from `c++-mode' v5.20, v5.28
2507 c-keywords (c-identifier-re c-C++-keywords)
2508 c-conditional-key c-C++-conditional-key
2509 c-comment-start-regexp c-C++-comment-start-regexp
2510 c-class-key c-C++-class-key
2511 c-extra-toplevel-key c-C++-extra-toplevel-key
2512 c-access-key c-C++-access-key
2513 c-recognize-knr-p nil
2514 c-bitfield-key c-C-bitfield-key ; v5.28
2516 (cdr '(setq ; from `java-mode' v5.20, v5.28
2517 c-keywords (c-identifier-re c-Java-keywords)
2518 c-conditional-key c-Java-conditional-key
2519 c-comment-start-regexp c-Java-comment-start-regexp
2520 c-class-key c-Java-class-key
2521 c-method-key nil
2522 c-baseclass-key nil
2523 c-recognize-knr-p nil
2524 c-access-key c-Java-access-key ; v5.20
2525 c-inexpr-class-key c-Java-inexpr-class-key ; v5.28
2526 )))))
2527 (while settings
2528 (when (boundp (car settings))
2529 (ignore-errors
2530 (set (car settings) (eval (cadr settings)))))
2531 (setq settings (cddr settings)))))
2533 (defun antlr-language-option (search)
2534 "Find language in `antlr-language-alist' for language option.
2535 If SEARCH is non-nil, find element for language option. Otherwise, find
2536 the default language."
2537 (let ((value
2538 (and search
2539 (save-excursion
2540 (goto-char (point-min))
2541 (re-search-forward (cdr antlr-language-limit-n-regexp)
2542 (+ (point)
2543 (car antlr-language-limit-n-regexp))
2545 (match-string 1)))
2546 (seq antlr-language-alist)
2548 ;; Like (find VALUE antlr-language-alist :key 'cddr :test 'member)
2549 (while seq
2550 (setq r (pop seq))
2551 (if (member value (cddr r))
2552 (setq seq nil) ; stop
2553 (setq r nil))) ; no result yet
2554 (car r)))
2556 ;;;###autoload
2557 (define-derived-mode antlr-mode prog-mode
2558 ;; FIXME: Since it uses cc-mode, it bumps into c-update-modeline's
2559 ;; limitation to mode-name being a string.
2560 ;; '("Antlr." (:eval (cadr (assq antlr-language antlr-language-alist))))
2561 "Antlr"
2562 "Major mode for editing ANTLR grammar files."
2563 :abbrev-table antlr-mode-abbrev-table
2564 (c-initialize-cc-mode) ; cc-mode is required
2565 (unless (fboundp 'c-forward-sws) ; see above
2566 (fset 'antlr-c-forward-sws 'c-forward-syntactic-ws))
2567 ;; ANTLR specific ----------------------------------------------------------
2568 (unless antlr-language
2569 (set (make-local-variable 'antlr-language)
2570 (or (antlr-language-option t) (antlr-language-option nil))))
2571 (if (stringp (cadr (assq antlr-language antlr-language-alist)))
2572 (setq mode-name
2573 (concat "Antlr."
2574 (cadr (assq antlr-language antlr-language-alist)))))
2575 ;; indentation, for the C engine -------------------------------------------
2576 (setq c-buffer-is-cc-mode antlr-language)
2577 (cond ((fboundp 'c-init-language-vars-for) ; cc-mode 5.30.5+
2578 (c-init-language-vars-for antlr-language))
2579 ((fboundp 'c-init-c-language-vars) ; cc-mode 5.30 to 5.30.4
2580 (c-init-c-language-vars) ; not perfect, but OK
2581 (setq c-recognize-knr-p nil))
2582 ((fboundp 'c-init-language-vars) ; cc-mode 5.29
2583 (let ((init-fn 'c-init-language-vars))
2584 (funcall init-fn))) ; is a function in v5.29
2585 (t ; cc-mode upto 5.28
2586 (antlr-c-init-language-vars))) ; do it myself
2587 (c-basic-common-init antlr-language (or antlr-indent-style "gnu"))
2588 (set (make-local-variable 'outline-regexp) "[^#\n\^M]")
2589 (set (make-local-variable 'outline-level) 'c-outline-level) ;TODO: define own
2590 (set (make-local-variable 'indent-line-function) 'antlr-indent-line)
2591 (set (make-local-variable 'indent-region-function) nil) ; too lazy
2592 (setq comment-start "// "
2593 comment-end ""
2594 comment-start-skip "/\\*+ *\\|// *")
2595 ;; various -----------------------------------------------------------------
2596 (set (make-local-variable 'font-lock-defaults) antlr-font-lock-defaults)
2597 (easy-menu-add antlr-mode-menu)
2598 (set (make-local-variable 'imenu-create-index-function)
2599 'antlr-imenu-create-index-function)
2600 (set (make-local-variable 'imenu-generic-expression) t) ; fool stupid test
2601 (and antlr-imenu-name ; there should be a global variable...
2602 (fboundp 'imenu-add-to-menubar)
2603 (imenu-add-to-menubar
2604 (if (stringp antlr-imenu-name) antlr-imenu-name "Index")))
2605 (antlr-set-tabs))
2607 ;; A smarter version of `group-buffers-menu-by-mode-then-alphabetically' (in
2608 ;; XEmacs) could use the following property. The header of the submenu would
2609 ;; be "Antlr" instead of "Antlr.C++" or (not and!) "Antlr.Java".
2610 (put 'antlr-mode 'mode-name "Antlr")
2612 ;;;###autoload
2613 (defun antlr-set-tabs ()
2614 "Use ANTLR's convention for TABs according to `antlr-tab-offset-alist'.
2615 Used in `antlr-mode'. Also a useful function in `java-mode-hook'."
2616 (if buffer-file-name
2617 (let ((alist antlr-tab-offset-alist) elem)
2618 (while alist
2619 (setq elem (pop alist))
2620 (and (or (null (car elem)) (eq (car elem) major-mode))
2621 (or (null (cadr elem))
2622 (string-match (cadr elem) buffer-file-name))
2623 (setq tab-width (caddr elem)
2624 indent-tabs-mode (cadddr elem)
2625 alist nil))))))
2627 (provide 'antlr-mode)
2629 ;;; Local IspellPersDict: .ispell_antlr
2631 ;;; antlr-mode.el ends here