1 ;;; cc-defs.el --- compile time definitions for CC Mode
3 ;; Copyright (C) 1985, 1987, 1992-2016 Free Software Foundation, Inc.
5 ;; Authors: 2003- Alan Mackenzie
6 ;; 1998- Martin Stjernholm
7 ;; 1992-1999 Barry A. Warsaw
10 ;; 1985 Richard M. Stallman
11 ;; Maintainer: bug-cc-mode@gnu.org
12 ;; Created: 22-Apr-1997 (split from cc-mode.el)
13 ;; Keywords: c languages
16 ;; This file is part of GNU Emacs.
18 ;; GNU Emacs is free software: you can redistribute it and/or modify
19 ;; it under the terms of the GNU General Public License as published by
20 ;; the Free Software Foundation, either version 3 of the License, or
21 ;; (at your option) any later version.
23 ;; GNU Emacs is distributed in the hope that it will be useful,
24 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
25 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 ;; GNU General Public License for more details.
28 ;; You should have received a copy of the GNU General Public License
29 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
33 ;; This file contains macros, defsubsts, and various other things that
34 ;; must be loaded early both during compilation and at runtime.
40 (if (and (boundp 'byte-compile-dest-file)
41 (stringp byte-compile-dest-file))
42 (cons (file-name-directory byte-compile-dest-file) load-path)
44 (load "cc-bytecomp" nil t)))
47 (defvar c--mapcan-status
48 (cond ((and (fboundp 'mapcan)
49 (subrp (symbol-function 'mapcan)))
52 ((locate-file "cl-lib.elc" load-path)
59 (cc-external-require (if (eq c--mapcan-status 'cl-mapcan) 'cl-lib 'cl))
60 ; was (cc-external-require 'cl). ACM 2005/11/29.
61 ; Changed from (eval-when-compile (require 'cl)) back to
62 ; cc-external-require, 2015-08-12.
63 (cc-external-require 'regexp-opt)
65 ;; Silence the compiler.
66 (cc-bytecomp-defvar c-enable-xemacs-performance-kludge-p) ; In cc-vars.el
67 (cc-bytecomp-defun region-active-p) ; XEmacs
68 (cc-bytecomp-defvar mark-active) ; Emacs
69 (cc-bytecomp-defvar deactivate-mark) ; Emacs
70 (cc-bytecomp-defvar inhibit-point-motion-hooks) ; Emacs
71 (cc-bytecomp-defvar parse-sexp-lookup-properties) ; Emacs
72 (cc-bytecomp-defvar text-property-default-nonsticky) ; Emacs 21
73 (cc-bytecomp-defun string-to-syntax) ; Emacs 21
76 ;; cc-fix.el contains compatibility macros that should be used if
78 (cc-conditional-require
79 'cc-fix (or (/= (regexp-opt-depth "\\(\\(\\)\\)") 2)
81 ;; XEmacs 21.4 doesn't have `delete-dups'.
82 (not (fboundp 'delete-dups))))
84 (cc-conditional-require-after-load
90 (let (font-lock-keywords)
91 (font-lock-compile-keywords '("\\<\\>"))
92 font-lock-keywords))))
95 ;;; Variables also used at compile time.
97 (defconst c-version "5.33"
98 "CC Mode version number.")
100 (defconst c-version-sym (intern c-version))
101 ;; A little more compact and faster in comparisons.
103 (defvar c-buffer-is-cc-mode nil
104 "Non-nil for all buffers with a major mode derived from CC Mode.
105 Otherwise, this variable is nil. I.e. this variable is non-nil for
106 `c-mode', `c++-mode', `objc-mode', `java-mode', `idl-mode',
107 `pike-mode', `awk-mode', and any other non-CC Mode mode that calls
108 `c-initialize-cc-mode'. The value is the mode symbol itself
109 \(i.e. `c-mode' etc) of the original CC Mode mode, or just t if it's
111 (make-variable-buffer-local 'c-buffer-is-cc-mode)
113 ;; Have to make `c-buffer-is-cc-mode' permanently local so that it
114 ;; survives the initialization of the derived mode.
115 (put 'c-buffer-is-cc-mode 'permanent-local t)
118 ;; The following is used below during compilation.
120 (defvar c-inside-eval-when-compile nil)
122 (defmacro cc-eval-when-compile (&rest body)
123 "Like `progn', but evaluates the body at compile time.
124 The result of the body appears to the compiler as a quoted constant.
126 This variant works around bugs in `eval-when-compile' in various
127 \(X)Emacs versions. See cc-defs.el for details."
129 (if c-inside-eval-when-compile
130 ;; XEmacs 21.4.6 has a bug in `eval-when-compile' in that it
131 ;; evaluates its body at macro expansion time if it's nested
132 ;; inside another `eval-when-compile'. So we use a dynamically
133 ;; bound variable to avoid nesting them.
137 ;; In all (X)Emacsen so far, `eval-when-compile' byte compiles
138 ;; its contents before evaluating it. That can cause forms to
139 ;; be compiled in situations they aren't intended to be
142 ;; Example: It's not possible to defsubst a primitive, e.g. the
143 ;; following will produce an error (in any emacs flavor), since
144 ;; `nthcdr' is a primitive function that's handled specially by
145 ;; the byte compiler and thus can't be redefined:
147 ;; (defsubst nthcdr (val) val)
149 ;; `defsubst', like `defmacro', needs to be evaluated at
150 ;; compile time, so this will produce an error during byte
153 ;; CC Mode occasionally needs to do things like this for
154 ;; cross-emacs compatibility. It therefore uses the following
155 ;; to conditionally do a `defsubst':
157 ;; (eval-when-compile
158 ;; (if (not (fboundp 'foo))
159 ;; (defsubst foo ...)))
161 ;; But `eval-when-compile' byte compiles its contents and
162 ;; _then_ evaluates it (in all current emacs versions, up to
163 ;; and including Emacs 20.6 and XEmacs 21.1 as of this
164 ;; writing). So this will still produce an error, since the
165 ;; byte compiler will get to the defsubst anyway. That's
166 ;; arguably a bug because the point with `eval-when-compile' is
167 ;; that it should evaluate rather than compile its contents.
169 ;; We get around it by expanding the body to a quoted
170 ;; constant that we eval. That otoh introduce a problem in
171 ;; that a returned lambda expression doesn't get byte
172 ;; compiled (even if `function' is used).
173 (eval '(let ((c-inside-eval-when-compile t)) ,@body)))))
175 (put 'cc-eval-when-compile 'lisp-indent-hook 0))
179 (defmacro c--mapcan (fun liszt)
180 ;; CC Mode equivalent of `mapcan' which bridges the difference
181 ;; between the host [X]Emacsen."
182 ;; The motivation for this macro is to avoid the irritating message
183 ;; "function `mapcan' from cl package called at runtime" produced by Emacs.
185 ((eq c--mapcan-status 'mapcan)
186 `(mapcan ,fun ,liszt))
187 ((eq c--mapcan-status 'cl-mapcan)
188 `(cl-mapcan ,fun ,liszt))
190 ;; Emacs <= 24.2. It would be nice to be able to distinguish between
191 ;; compile-time and run-time use here.
192 `(apply 'nconc (mapcar ,fun ,liszt)))))
194 (defmacro c--set-difference (liszt1 liszt2 &rest other-args)
195 ;; Macro to smooth out the renaming of `set-difference' in Emacs 24.3.
196 (if (eq c--mapcan-status 'cl-mapcan)
197 `(cl-set-difference ,liszt1 ,liszt2 ,@other-args)
198 `(set-difference ,liszt1 ,liszt2 ,@other-args)))
200 (defmacro c--intersection (liszt1 liszt2 &rest other-args)
201 ;; Macro to smooth out the renaming of `intersection' in Emacs 24.3.
202 (if (eq c--mapcan-status 'cl-mapcan)
203 `(cl-intersection ,liszt1 ,liszt2 ,@other-args)
204 `(intersection ,liszt1 ,liszt2 ,@other-args)))
207 (defmacro c--macroexpand-all (form &optional environment)
208 ;; Macro to smooth out the renaming of `cl-macroexpand-all' in Emacs 24.3.
209 (if (fboundp 'macroexpand-all)
210 `(macroexpand-all ,form ,environment)
211 `(cl-macroexpand-all ,form ,environment)))
213 (defmacro c--delete-duplicates (cl-seq &rest cl-keys)
214 ;; Macro to smooth out the renaming of `delete-duplicates' in Emacs 24.3.
215 (if (eq c--mapcan-status 'cl-mapcan)
216 `(cl-delete-duplicates ,cl-seq ,@cl-keys)
217 `(delete-duplicates ,cl-seq ,@cl-keys))))
219 (defmacro c-point (position &optional point)
220 "Return the value of certain commonly referenced POSITIONs relative to POINT.
221 The current point is used if POINT isn't specified. POSITION can be
222 one of the following symbols:
224 `bol' -- beginning of line
226 `bod' -- beginning of defun
227 `eod' -- end of defun
228 `boi' -- beginning of indentation
229 `ionl' -- indentation of next line
230 `iopl' -- indentation of previous line
231 `bonl' -- beginning of next line
232 `eonl' -- end of next line
233 `bopl' -- beginning of previous line
234 `eopl' -- end of previous line
235 `bosws' -- beginning of syntactic whitespace
236 `eosws' -- end of syntactic whitespace
238 If the referenced position doesn't exist, the closest accessible point
239 to it is returned. This function does not modify the point or the mark."
241 (if (eq (car-safe position) 'quote)
242 (let ((position (eval position)))
246 (if (and (cc-bytecomp-fboundp 'line-beginning-position) (not point))
247 `(line-beginning-position)
249 ,@(if point `((goto-char ,point)))
254 (if (and (cc-bytecomp-fboundp 'line-end-position) (not point))
257 ,@(if point `((goto-char ,point)))
263 ,@(if point `((goto-char ,point)))
264 (back-to-indentation)
269 ,@(if point `((goto-char ,point)))
270 (c-beginning-of-defun-1)
275 ,@(if point `((goto-char ,point)))
280 (if (and (cc-bytecomp-fboundp 'line-beginning-position) (not point))
281 `(line-beginning-position 0)
283 ,@(if point `((goto-char ,point)))
288 (if (and (cc-bytecomp-fboundp 'line-beginning-position) (not point))
289 `(line-beginning-position 2)
291 ,@(if point `((goto-char ,point)))
296 (if (and (cc-bytecomp-fboundp 'line-end-position) (not point))
297 `(line-end-position 0)
299 ,@(if point `((goto-char ,point)))
301 (or (bobp) (backward-char))
305 (if (and (cc-bytecomp-fboundp 'line-end-position) (not point))
306 `(line-end-position 2)
308 ,@(if point `((goto-char ,point)))
315 ,@(if point `((goto-char ,point)))
317 (back-to-indentation)
322 ,@(if point `((goto-char ,point)))
324 (back-to-indentation)
327 ((eq position 'bosws)
329 ,@(if point `((goto-char ,point)))
330 (c-backward-syntactic-ws)
333 ((eq position 'eosws)
335 ,@(if point `((goto-char ,point)))
336 (c-forward-syntactic-ws)
339 (t (error "Unknown buffer position requested: %s" position))))
341 ;; The bulk of this should perhaps be in a function to avoid large
342 ;; expansions, but this case is not used anywhere in CC Mode (and
343 ;; probably not anywhere else either) so we only have it to be on
345 (message "Warning: c-point long expansion")
347 ,@(if point `((goto-char ,point)))
348 (let ((position ,position))
350 ((eq position 'bol) (beginning-of-line))
351 ((eq position 'eol) (end-of-line))
352 ((eq position 'boi) (back-to-indentation))
353 ((eq position 'bod) (c-beginning-of-defun-1))
354 ((eq position 'eod) (c-end-of-defun-1))
355 ((eq position 'bopl) (forward-line -1))
356 ((eq position 'bonl) (forward-line 1))
357 ((eq position 'eopl) (progn
359 (or (bobp) (backward-char))))
360 ((eq position 'eonl) (progn
363 ((eq position 'iopl) (progn
365 (back-to-indentation)))
366 ((eq position 'ionl) (progn
368 (back-to-indentation)))
369 ((eq position 'bosws) (c-backward-syntactic-ws))
370 ((eq position 'eosws) (c-forward-syntactic-ws))
371 (t (error "Unknown buffer position requested: %s" position))))
375 ;; Constant to decide at compilation time whether to use category
376 ;; properties. Currently (2010-03) they're available only on GNU Emacs.
377 (defconst c-use-category
379 (let ((parse-sexp-lookup-properties t)
380 (lookup-syntax-properties t))
381 (set-syntax-table (make-syntax-table))
383 (put-text-property (point-min) (1+ (point-min))
384 'category 'c-<-as-paren-syntax)
385 (put-text-property (+ 3 (point-min)) (+ 4 (point-min))
386 'category 'c->-as-paren-syntax)
387 (goto-char (point-min))
389 (= (point) (+ 4 (point-min)))))))
391 (defvar c-use-extents)
393 (defmacro c-next-single-property-change (position prop &optional object limit)
394 ;; See the doc string for either of the defuns expanded to.
395 (if (and c-use-extents
396 (fboundp 'next-single-char-property-change))
397 ;; XEmacs >= 2005-01-25
398 `(next-single-char-property-change ,position ,prop ,object ,limit)
399 ;; Emacs and earlier XEmacs
400 `(next-single-property-change ,position ,prop ,object ,limit)))
402 (defmacro c-region-is-active-p ()
403 ;; Return t when the region is active. The determination of region
404 ;; activeness is different in both Emacs and XEmacs.
405 (if (cc-bytecomp-fboundp 'region-active-p)
411 (defmacro c-set-region-active (activate)
412 ;; Activate the region if ACTIVE is non-nil, deactivate it
413 ;; otherwise. Covers the differences between Emacs and XEmacs.
414 (if (fboundp 'zmacs-activate-region)
417 (zmacs-activate-region)
418 (zmacs-deactivate-region))
420 `(setq mark-active ,activate)))
422 (defmacro c-delete-and-extract-region (start end)
423 "Delete the text between START and END and return it."
424 (if (cc-bytecomp-fboundp 'delete-and-extract-region)
425 ;; Emacs 21.1 and later
426 `(delete-and-extract-region ,start ,end)
427 ;; XEmacs and Emacs 20.x
429 (buffer-substring ,start ,end)
430 (delete-region ,start ,end))))
432 (defmacro c-safe (&rest body)
433 ;; safely execute BODY, return nil if an error occurred
437 (put 'c-safe 'lisp-indent-function 0)
439 (defmacro c-int-to-char (integer)
440 ;; In Emacs, a character is an integer. In XEmacs, a character is a
441 ;; type distinct from an integer. Sometimes we need to convert integers to
442 ;; characters. `c-int-to-char' makes this conversion, if necessary.
443 (if (fboundp 'int-to-char)
444 `(int-to-char ,integer)
447 (defmacro c-last-command-char ()
448 ;; The last character just typed. Note that `last-command-event' exists in
449 ;; both Emacs and XEmacs, but with confusingly different meanings.
450 (if (featurep 'xemacs)
452 'last-command-event))
454 (defmacro c-sentence-end ()
455 ;; Get the regular expression `sentence-end'.
456 (if (cc-bytecomp-fboundp 'sentence-end)
459 ;; Emacs <22 + XEmacs
462 (defmacro c-default-value-sentence-end ()
463 ;; Get the default value of the variable sentence end.
464 (if (cc-bytecomp-fboundp 'sentence-end)
466 `(let (sentence-end) (sentence-end))
467 ;; Emacs <22 + XEmacs
468 `(default-value 'sentence-end)))
470 ;; The following is essentially `save-buffer-state' from lazy-lock.el.
471 ;; It ought to be a standard macro.
472 (defmacro c-save-buffer-state (varlist &rest body)
473 "Bind variables according to VARLIST (in `let*' style) and eval BODY,
474 then restore the buffer state under the assumption that no significant
475 modification has been made in BODY. A change is considered
476 significant if it affects the buffer text in any way that isn't
477 completely restored again. Changes in text properties like `face' or
478 `syntax-table' are considered insignificant. This macro allows text
479 properties to be changed, even in a read-only buffer.
481 This macro should be placed around all calculations which set
482 \"insignificant\" text properties in a buffer, even when the buffer is
483 known to be writable. That way, these text properties remain set
484 even if the user undoes the command which set them.
486 This macro should ALWAYS be placed around \"temporary\" internal buffer
487 changes \(like adding a newline to calculate a text-property then
488 deleting it again), so that the user never sees them on his
489 `buffer-undo-list'. See also `c-tentative-buffer-changes'.
491 However, any user-visible changes to the buffer \(like auto-newlines)
492 must not be within a `c-save-buffer-state', since the user then
493 wouldn't be able to undo them.
495 The return value is the value of the last form in BODY."
496 (declare (debug t) (indent 1))
497 (if (fboundp 'with-silent-modifications)
498 `(with-silent-modifications (let* ,varlist ,@body))
499 `(let* ((modified (buffer-modified-p)) (buffer-undo-list t)
500 (inhibit-read-only t) (inhibit-point-motion-hooks t)
501 before-change-functions after-change-functions
503 buffer-file-name buffer-file-truename ; Prevent primitives checking
504 ; for file modification
510 (set-buffer-modified-p nil))))))
512 (defmacro c-tentative-buffer-changes (&rest body)
513 "Eval BODY and optionally restore the buffer contents to the state it
514 was in before BODY. Any changes are kept if the last form in BODY
515 returns non-nil. Otherwise it's undone using the undo facility, and
516 various other buffer state that might be affected by the changes is
517 restored. That includes the current buffer, point, mark, mark
518 activation \(similar to `save-excursion'), and the modified state.
519 The state is also restored if BODY exits nonlocally.
521 If BODY makes a change that unconditionally is undone then wrap this
522 macro inside `c-save-buffer-state'. That way the change can be done
523 even when the buffer is read-only, and without interference from
524 various buffer change hooks."
525 `(let (-tnt-chng-keep
528 ;; Insert an undo boundary for use with `undo-more'. We
529 ;; don't use `undo-boundary' since it doesn't insert one
531 (setq buffer-undo-list (cons nil buffer-undo-list)
532 -tnt-chng-state (c-tnt-chng-record-state)
533 -tnt-chng-keep (progn ,@body))
534 (c-tnt-chng-cleanup -tnt-chng-keep -tnt-chng-state))))
535 (put 'c-tentative-buffer-changes 'lisp-indent-function 0)
537 (defun c-tnt-chng-record-state ()
538 ;; Used internally in `c-tentative-buffer-changes'.
539 (vector buffer-undo-list ; 0
541 ;; No need to use markers for the point and mark; if the
542 ;; undo got out of synch we're hosed anyway.
545 (c-region-is-active-p) ; 4
546 (buffer-modified-p))) ; 5
548 (defun c-tnt-chng-cleanup (keep saved-state)
549 ;; Used internally in `c-tentative-buffer-changes'.
551 (let ((saved-undo-list (elt saved-state 0)))
552 (if (eq buffer-undo-list saved-undo-list)
553 ;; No change was done after all.
554 (setq buffer-undo-list (cdr saved-undo-list))
557 ;; Find and remove the undo boundary.
558 (let ((p buffer-undo-list))
559 (while (not (eq (cdr p) saved-undo-list))
561 (setcdr p (cdr saved-undo-list)))
563 ;; `primitive-undo' will remove the boundary.
564 (setq saved-undo-list (cdr saved-undo-list))
565 (let ((undo-in-progress t))
566 (while (not (eq (setq buffer-undo-list
567 (primitive-undo 1 buffer-undo-list))
570 (when (buffer-live-p (elt saved-state 1))
571 (set-buffer (elt saved-state 1))
572 (goto-char (elt saved-state 2))
573 (set-mark (elt saved-state 3))
574 (c-set-region-active (elt saved-state 4))
575 (and (not (elt saved-state 5))
577 (set-buffer-modified-p nil)))))))
579 (defmacro c-forward-syntactic-ws (&optional limit)
580 "Forward skip over syntactic whitespace.
581 Syntactic whitespace is defined as whitespace characters, comments,
582 and preprocessor directives. However if point starts inside a comment
583 or preprocessor directive, the content of it is not treated as
586 LIMIT sets an upper limit of the forward movement, if specified. If
587 LIMIT or the end of the buffer is reached inside a comment or
588 preprocessor directive, the point will be left there.
590 Note that this function might do hidden buffer changes. See the
591 comment at the start of cc-engine.el for more info."
594 (narrow-to-region (point-min) (or ,limit (point-max)))
598 (defmacro c-backward-syntactic-ws (&optional limit)
599 "Backward skip over syntactic whitespace.
600 Syntactic whitespace is defined as whitespace characters, comments,
601 and preprocessor directives. However if point starts inside a comment
602 or preprocessor directive, the content of it is not treated as
605 LIMIT sets a lower limit of the backward movement, if specified. If
606 LIMIT is reached inside a line comment or preprocessor directive then
607 the point is moved into it past the whitespace at the end.
609 Note that this function might do hidden buffer changes. See the
610 comment at the start of cc-engine.el for more info."
613 (narrow-to-region (or ,limit (point-min)) (point-max))
617 (defmacro c-forward-sexp (&optional count)
618 "Move forward across COUNT balanced expressions.
619 A negative COUNT means move backward. Signal an error if the move
620 fails for any reason.
622 This is like `forward-sexp' except that it isn't interactive and does
623 not do any user friendly adjustments of the point and that it isn't
624 susceptible to user configurations such as disabling of signals in
626 (or count (setq count 1))
627 `(goto-char (scan-sexps (point) ,count)))
629 (defmacro c-backward-sexp (&optional count)
630 "See `c-forward-sexp' and reverse directions."
631 (or count (setq count 1))
632 `(c-forward-sexp ,(if (numberp count) (- count) `(- ,count))))
634 (defmacro c-safe-scan-lists (from count depth &optional limit)
635 "Like `scan-lists' but returns nil instead of signaling errors
636 for unbalanced parens.
638 A limit for the search may be given. FROM is assumed to be on the
640 (let ((res (if (featurep 'xemacs)
641 `(scan-lists ,from ,count ,depth nil t)
642 `(c-safe (scan-lists ,from ,count ,depth)))))
647 `(narrow-to-region ,limit (point-max))
648 `(narrow-to-region (point-min) ,limit))
650 (narrow-to-region ,limit (point-max))
651 (narrow-to-region (point-min) ,limit)))
656 ;; Wrappers for common scan-lists cases, mainly because it's almost
657 ;; impossible to get a feel for how that function works.
659 (defmacro c-go-list-forward ()
660 "Move backward across one balanced group of parentheses.
662 Return POINT when we succeed, NIL when we fail. In the latter case, leave
664 `(c-safe (let ((endpos (scan-lists (point) 1 0)))
668 (defmacro c-go-list-backward ()
669 "Move backward across one balanced group of parentheses.
671 Return POINT when we succeed, NIL when we fail. In the latter case, leave
673 `(c-safe (let ((endpos (scan-lists (point) -1 0)))
677 (defmacro c-up-list-forward (&optional pos limit)
678 "Return the first position after the list sexp containing POS,
679 or nil if no such position exists. The point is used if POS is left out.
681 A limit for the search may be given. The start position is assumed to
683 `(c-safe-scan-lists ,(or pos `(point)) 1 1 ,limit))
685 (defmacro c-up-list-backward (&optional pos limit)
686 "Return the position of the start of the list sexp containing POS,
687 or nil if no such position exists. The point is used if POS is left out.
689 A limit for the search may be given. The start position is assumed to
691 `(c-safe-scan-lists ,(or pos `(point)) -1 1 ,limit))
693 (defmacro c-down-list-forward (&optional pos limit)
694 "Return the first position inside the first list sexp after POS,
695 or nil if no such position exists. The point is used if POS is left out.
697 A limit for the search may be given. The start position is assumed to
699 `(c-safe-scan-lists ,(or pos `(point)) 1 -1 ,limit))
701 (defmacro c-down-list-backward (&optional pos limit)
702 "Return the last position inside the last list sexp before POS,
703 or nil if no such position exists. The point is used if POS is left out.
705 A limit for the search may be given. The start position is assumed to
707 `(c-safe-scan-lists ,(or pos `(point)) -1 -1 ,limit))
709 (defmacro c-go-up-list-forward (&optional pos limit)
710 "Move the point to the first position after the list sexp containing POS,
711 or containing the point if POS is left out. Return t if such a
712 position exists, otherwise nil is returned and the point isn't moved.
714 A limit for the search may be given. The start position is assumed to
716 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) 1 1)) t)))
719 (narrow-to-region (point-min) ,limit)
723 (defmacro c-go-up-list-backward (&optional pos limit)
724 "Move the point to the position of the start of the list sexp containing POS,
725 or containing the point if POS is left out. Return t if such a
726 position exists, otherwise nil is returned and the point isn't moved.
728 A limit for the search may be given. The start position is assumed to
730 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) -1 1)) t)))
733 (narrow-to-region ,limit (point-max))
737 (defmacro c-go-down-list-forward (&optional pos limit)
738 "Move the point to the first position inside the first list sexp after POS,
739 or before the point if POS is left out. Return t if such a position
740 exists, otherwise nil is returned and the point isn't moved.
742 A limit for the search may be given. The start position is assumed to
744 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) 1 -1)) t)))
747 (narrow-to-region (point-min) ,limit)
751 (defmacro c-go-down-list-backward (&optional pos limit)
752 "Move the point to the last position inside the last list sexp before POS,
753 or before the point if POS is left out. Return t if such a position
754 exists, otherwise nil is returned and the point isn't moved.
756 A limit for the search may be given. The start position is assumed to
758 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) -1 -1)) t)))
761 (narrow-to-region ,limit (point-max))
766 (defmacro c-beginning-of-defun-1 ()
767 ;; Wrapper around beginning-of-defun.
769 ;; NOTE: This function should contain the only explicit use of
770 ;; beginning-of-defun in CC Mode. Eventually something better than
771 ;; b-o-d will be available and this should be the only place the
772 ;; code needs to change. Everything else should use
773 ;; (c-beginning-of-defun-1)
775 ;; This is really a bit too large to be a macro but that isn't a
776 ;; problem as long as it only is used in one place in
780 (if (and ,(fboundp 'buffer-syntactic-context-depth)
781 c-enable-xemacs-performance-kludge-p)
782 ,(when (fboundp 'buffer-syntactic-context-depth)
783 ;; XEmacs only. This can improve the performance of
784 ;; c-parse-state to between 3 and 60 times faster when
785 ;; braces are hung. It can also degrade performance by
786 ;; about as much when braces are not hung.
787 '(let (beginning-of-defun-function end-of-defun-function
792 (setq pos (c-safe-scan-lists
793 (point) -1 (buffer-syntactic-context-depth))))
795 ((bobp) (setq pos (point-min)))
797 (let ((distance (skip-chars-backward "^{")))
798 ;; unbalanced parenthesis, while invalid C code,
799 ;; shouldn't cause an infloop! See unbal.c
800 (when (zerop distance)
803 (setq pos (point)))))
805 ((not (eq (char-after pos) ?{))
810 ;; Emacs, which doesn't have buffer-syntactic-context-depth
811 (let (beginning-of-defun-function end-of-defun-function)
812 (beginning-of-defun)))
813 ;; if defun-prompt-regexp is non-nil, b-o-d won't leave us at the
815 (and defun-prompt-regexp
816 (looking-at defun-prompt-regexp)
817 (goto-char (match-end 0)))))
820 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
821 ;; V i r t u a l S e m i c o l o n s
823 ;; In most CC Mode languages, statements are terminated explicitly by
824 ;; semicolons or closing braces. In some of the CC modes (currently AWK Mode
825 ;; and certain user-specified #define macros in C, C++, etc. (November 2008)),
826 ;; statements are (or can be) terminated by EOLs. Such a statement is said to
827 ;; be terminated by a "virtual semicolon" (VS). A statement terminated by an
828 ;; actual semicolon or brace is never considered to have a VS.
830 ;; The indentation engine (or whatever) tests for a VS at a specific position
831 ;; by invoking the macro `c-at-vsemi-p', which in its turn calls the mode
832 ;; specific function (if any) which is the value of the language variable
833 ;; `c-at-vsemi-p-fn'. This function should only use "low-level" features of
834 ;; CC Mode, i.e. features which won't trigger infinite recursion. ;-) The
835 ;; actual details of what constitutes a VS in a language are thus encapsulated
836 ;; in code specific to that language (e.g. cc-awk.el). `c-at-vsemi-p' returns
837 ;; non-nil if point (or the optional parameter POS) is at a VS, nil otherwise.
839 ;; The language specific function might well do extensive analysis of the
840 ;; source text, and may use a caching scheme to speed up repeated calls.
842 ;; The "virtual semicolon" lies just after the last non-ws token on the line.
843 ;; Like POINT, it is considered to lie between two characters. For example,
844 ;; at the place shown in the following AWK source line:
846 ;; kbyte = 1024 # 1000 if you're not picky
851 ;; In addition to `c-at-vsemi-p-fn', a mode may need to supply a function for
852 ;; `c-vsemi-status-unknown-p-fn'. The macro `c-vsemi-status-unknown-p' is a
853 ;; rather recondite kludge. It exists because the function
854 ;; `c-beginning-of-statement-1' sometimes tests for VSs as an optimization,
855 ;; but `c-at-vsemi-p' might well need to call `c-beginning-of-statement-1' in
856 ;; its calculations, thus potentially leading to infinite recursion.
858 ;; The macro `c-vsemi-status-unknown-p' resolves this problem; it may return
859 ;; non-nil at any time; returning nil is a guarantee that an immediate
860 ;; invocation of `c-at-vsemi-p' at point will NOT call
861 ;; `c-beginning-of-statement-1'. `c-vsemi-status-unknown-p' may not itself
862 ;; call `c-beginning-of-statement-1'.
864 ;; The macro `c-vsemi-status-unknown-p' will typically check the caching
865 ;; scheme used by the `c-at-vsemi-p-fn', hence the name - the status is
866 ;; "unknown" if there is no cache entry current for the line.
867 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
869 (defmacro c-at-vsemi-p (&optional pos)
870 ;; Is there a virtual semicolon (not a real one or a }) at POS (defaults to
871 ;; point)? Always returns nil for languages which don't have Virtual
873 ;; This macro might do hidden buffer changes.
875 (funcall c-at-vsemi-p-fn ,@(if pos `(,pos)))))
877 (defmacro c-vsemi-status-unknown-p ()
878 ;; Return NIL only if it can be guaranteed that an immediate
879 ;; (c-at-vsemi-p) will NOT call c-beginning-of-statement-1. Otherwise,
880 ;; return non-nil. (See comments above). The function invoked by this
881 ;; macro MUST NOT UNDER ANY CIRCUMSTANCES itself call
882 ;; c-beginning-of-statement-1.
883 ;; Languages which don't have EOL terminated statements always return NIL
884 ;; (they _know_ there's no vsemi ;-).
885 `(if c-vsemi-status-unknown-p-fn (funcall c-vsemi-status-unknown-p-fn)))
888 (defmacro c-benign-error (format &rest args)
889 ;; Formats an error message for the echo area and dings, i.e. like
890 ;; `error' but doesn't abort.
892 (message ,format ,@args)
895 (defmacro c-with-syntax-table (table &rest code)
896 ;; Temporarily switches to the specified syntax table in a failsafe
897 ;; way to execute code.
898 ;; Maintainers' note: If TABLE is `c++-template-syntax-table', DON'T call
899 ;; any forms inside this that call `c-parse-state'. !!!!
900 `(let ((c-with-syntax-table-orig-table (syntax-table)))
903 (set-syntax-table ,table)
905 (set-syntax-table c-with-syntax-table-orig-table))))
906 (put 'c-with-syntax-table 'lisp-indent-function 1)
908 (defmacro c-skip-ws-forward (&optional limit)
909 "Skip over any whitespace following point.
910 This function skips over horizontal and vertical whitespace and line
913 `(let ((limit (or ,limit (point-max))))
915 ;; skip-syntax-* doesn't count \n as whitespace..
916 (skip-chars-forward " \t\n\r\f\v" limit)
917 (when (and (eq (char-after) ?\\)
921 (progn (backward-char) nil))))))
923 (skip-chars-forward " \t\n\r\f\v")
924 (when (eq (char-after) ?\\)
927 (progn (backward-char) nil)))))))
929 (defmacro c-skip-ws-backward (&optional limit)
930 "Skip over any whitespace preceding point.
931 This function skips over horizontal and vertical whitespace and line
934 `(let ((limit (or ,limit (point-min))))
936 ;; skip-syntax-* doesn't count \n as whitespace..
937 (skip-chars-backward " \t\n\r\f\v" limit)
939 (eq (char-before) ?\\)
943 (skip-chars-backward " \t\n\r\f\v")
945 (eq (char-before) ?\\)))
949 (defvar c-langs-are-parametric nil))
951 (defmacro c-major-mode-is (mode)
952 "Return non-nil if the current CC Mode major mode is MODE.
953 MODE is either a mode symbol or a list of mode symbols."
955 (if c-langs-are-parametric
956 ;; Inside a `c-lang-defconst'.
957 `(c-lang-major-mode-is ,mode)
959 (if (eq (car-safe mode) 'quote)
960 (let ((mode (eval mode)))
962 `(memq c-buffer-is-cc-mode ',mode)
963 `(eq c-buffer-is-cc-mode ',mode)))
967 (memq c-buffer-is-cc-mode mode)
968 (eq c-buffer-is-cc-mode mode))))))
971 ;; Macros/functions to handle so-called "char properties", which are
972 ;; properties set on a single character and that never spread to any
976 ;; Constant used at compile time to decide whether or not to use
977 ;; XEmacs extents. Check all the extent functions we'll use since
978 ;; some packages might add compatibility aliases for some of them in
980 (defconst c-use-extents (and (cc-bytecomp-fboundp 'extent-at)
981 (cc-bytecomp-fboundp 'set-extent-property)
982 (cc-bytecomp-fboundp 'set-extent-properties)
983 (cc-bytecomp-fboundp 'make-extent)
984 (cc-bytecomp-fboundp 'extent-property)
985 (cc-bytecomp-fboundp 'delete-extent)
986 (cc-bytecomp-fboundp 'map-extents))))
988 (defconst c-<-as-paren-syntax '(4 . ?>))
989 (put 'c-<-as-paren-syntax 'syntax-table c-<-as-paren-syntax)
991 (defconst c->-as-paren-syntax '(5 . ?<))
992 (put 'c->-as-paren-syntax 'syntax-table c->-as-paren-syntax)
994 ;; `c-put-char-property' is complex enough in XEmacs and Emacs < 21 to
995 ;; make it a function.
996 (defalias 'c-put-char-property-fun
997 (cc-eval-when-compile
1001 (lambda (pos property value)
1002 (let ((ext (extent-at pos nil property)))
1004 (set-extent-property ext property value)
1005 (set-extent-properties (make-extent pos (1+ pos))
1011 ((not (cc-bytecomp-boundp 'text-property-default-nonsticky))
1012 ;; In Emacs < 21 we have to mess with the `rear-nonsticky' property.
1014 (lambda (pos property value)
1015 (put-text-property pos (1+ pos) property value)
1016 (let ((prop (get-text-property pos 'rear-nonsticky)))
1017 (or (memq property prop)
1018 (put-text-property pos (1+ pos)
1020 (cons property prop)))))))
1021 ;; This won't be used for anything.
1023 (cc-bytecomp-defun c-put-char-property-fun) ; Make it known below.
1025 (defmacro c-put-char-property (pos property value)
1026 ;; Put the given property with the given value on the character at
1027 ;; POS and make it front and rear nonsticky, or start and end open
1028 ;; in XEmacs vocabulary. If the character already has the given
1029 ;; property then the value is replaced, and the behavior is
1030 ;; undefined if that property has been put by some other function.
1031 ;; PROPERTY is assumed to be constant.
1033 ;; If there's a `text-property-default-nonsticky' variable (Emacs
1034 ;; 21) then it's assumed that the property is present on it.
1036 ;; This macro does a hidden buffer change.
1037 (setq property (eval property))
1038 (if (or c-use-extents
1039 (not (cc-bytecomp-boundp 'text-property-default-nonsticky)))
1040 ;; XEmacs and Emacs < 21.
1041 `(c-put-char-property-fun ,pos ',property ,value)
1042 ;; In Emacs 21 we got the `rear-nonsticky' property covered
1043 ;; by `text-property-default-nonsticky'.
1044 `(let ((-pos- ,pos))
1045 (put-text-property -pos- (1+ -pos-) ',property ,value))))
1047 (defmacro c-get-char-property (pos property)
1048 ;; Get the value of the given property on the character at POS if
1049 ;; it's been put there by `c-put-char-property'. PROPERTY is
1050 ;; assumed to be constant.
1051 (setq property (eval property))
1054 `(let ((ext (extent-at ,pos nil ',property)))
1055 (if ext (extent-property ext ',property)))
1057 `(get-text-property ,pos ',property)))
1059 ;; `c-clear-char-property' is complex enough in Emacs < 21 to make it
1060 ;; a function, since we have to mess with the `rear-nonsticky' property.
1061 (defalias 'c-clear-char-property-fun
1062 (cc-eval-when-compile
1063 (unless (or c-use-extents
1064 (cc-bytecomp-boundp 'text-property-default-nonsticky))
1066 (lambda (pos property)
1067 (when (get-text-property pos property)
1068 (remove-text-properties pos (1+ pos) (list property nil))
1069 (put-text-property pos (1+ pos)
1071 (delq property (get-text-property
1072 pos 'rear-nonsticky)))))))))
1073 (cc-bytecomp-defun c-clear-char-property-fun) ; Make it known below.
1075 (defmacro c-clear-char-property (pos property)
1076 ;; Remove the given property on the character at POS if it's been put
1077 ;; there by `c-put-char-property'. PROPERTY is assumed to be
1080 ;; This macro does a hidden buffer change.
1081 (setq property (eval property))
1082 (cond (c-use-extents
1084 `(let ((ext (extent-at ,pos nil ',property)))
1085 (if ext (delete-extent ext))))
1086 ((cc-bytecomp-boundp 'text-property-default-nonsticky)
1087 ;; In Emacs 21 we got the `rear-nonsticky' property covered
1088 ;; by `text-property-default-nonsticky'.
1090 (remove-text-properties pos (1+ pos)
1094 `(c-clear-char-property-fun ,pos ',property))))
1096 (defmacro c-clear-char-properties (from to property)
1097 ;; Remove all the occurrences of the given property in the given
1098 ;; region that has been put with `c-put-char-property'. PROPERTY is
1099 ;; assumed to be constant.
1101 ;; Note that this function does not clean up the property from the
1102 ;; lists of the `rear-nonsticky' properties in the region, if such
1103 ;; are used. Thus it should not be used for common properties like
1106 ;; This macro does hidden buffer changes.
1107 (setq property (eval property))
1110 `(map-extents (lambda (ext ignored)
1111 (delete-extent ext))
1112 nil ,from ,to nil nil ',property)
1114 `(remove-text-properties ,from ,to '(,property nil))))
1116 (defmacro c-search-forward-char-property (property value &optional limit)
1117 "Search forward for a text-property PROPERTY having value VALUE.
1118 LIMIT bounds the search. The comparison is done with `equal'.
1120 Leave point just after the character, and set the match data on
1121 this character, and return point. If VALUE isn't found, Return
1122 nil; point is then left undefined."
1123 `(let ((place (point)))
1126 (< place ,(or limit '(point-max)))
1127 (not (equal (c-get-char-property place ,property) ,value)))
1128 (setq place (c-next-single-property-change
1129 place ,property nil ,(or limit '(point-max)))))
1130 (when (< place ,(or limit '(point-max)))
1132 (search-forward-regexp ".") ; to set the match-data.
1135 (defmacro c-search-backward-char-property (property value &optional limit)
1136 "Search backward for a text-property PROPERTY having value VALUE.
1137 LIMIT bounds the search. The comparison is done with `equal'.
1139 Leave point just before the character, set the match data on this
1140 character, and return point. If VALUE isn't found, Return nil;
1141 point is then left undefined."
1142 `(let ((place (point)))
1145 (> place ,(or limit '(point-min)))
1146 (not (equal (c-get-char-property (1- place) ,property) ,value)))
1147 (setq place (,(if (and c-use-extents
1148 (fboundp 'previous-single-char-property-change))
1149 ;; XEmacs > 2005-01-25.
1150 'previous-single-char-property-change
1151 ;; Emacs and earlier XEmacs.
1152 'previous-single-property-change)
1153 place ,property nil ,(or limit '(point-min)))))
1154 (when (> place ,(or limit '(point-min)))
1156 (search-backward-regexp ".") ; to set the match-data.
1159 (defun c-clear-char-property-with-value-function (from to property value)
1160 "Remove all text-properties PROPERTY from the region (FROM, TO)
1161 which have the value VALUE, as tested by `equal'. These
1162 properties are assumed to be over individual characters, having
1163 been put there by c-put-char-property. POINT remains unchanged."
1164 (let ((place from) end-place)
1165 (while ; loop round occurrences of (PROPERTY VALUE)
1167 (while ; loop round changes in PROPERTY till we find VALUE
1170 (not (equal (get-text-property place property) value)))
1171 (setq place (c-next-single-property-change place property nil to)))
1173 (setq end-place (c-next-single-property-change place property nil to))
1174 (remove-text-properties place end-place (cons property nil))
1175 ;; Do we have to do anything with stickiness here?
1176 (setq place end-place))))
1178 (defmacro c-clear-char-property-with-value (from to property value)
1179 "Remove all text-properties PROPERTY from the region [FROM, TO)
1180 which have the value VALUE, as tested by `equal'. These
1181 properties are assumed to be over individual characters, having
1182 been put there by c-put-char-property. POINT remains unchanged."
1185 `(let ((-property- ,property))
1186 (map-extents (lambda (ext val)
1187 (if (equal (extent-property ext -property-) val)
1188 (delete-extent ext)))
1189 nil ,from ,to ,value nil -property-))
1191 `(c-clear-char-property-with-value-function ,from ,to ,property ,value)))
1193 ;; Macros to put overlays (Emacs) or extents (XEmacs) on buffer text.
1194 ;; For our purposes, these are characterized by being possible to
1195 ;; remove again without affecting the other text properties in the
1196 ;; buffer that got overridden when they were put.
1198 (defmacro c-put-overlay (from to property value)
1199 ;; Put an overlay/extent covering the given range in the current
1200 ;; buffer. It's currently undefined whether it's front/end sticky
1201 ;; or not. The overlay/extent object is returned.
1202 (if (cc-bytecomp-fboundp 'make-overlay)
1204 `(let ((ol (make-overlay ,from ,to)))
1205 (overlay-put ol ,property ,value)
1208 `(let ((ext (make-extent ,from ,to)))
1209 (set-extent-property ext ,property ,value)
1212 (defmacro c-delete-overlay (overlay)
1213 ;; Deletes an overlay/extent object previously retrieved using
1215 (if (cc-bytecomp-fboundp 'make-overlay)
1217 `(delete-overlay ,overlay)
1219 `(delete-extent ,overlay)))
1222 ;; Make edebug understand the macros.
1223 ;(eval-after-load "edebug" ; 2006-07-09: def-edebug-spec is now in subr.el.
1225 (def-edebug-spec cc-eval-when-compile (&rest def-form))
1226 (def-edebug-spec c-point t)
1227 (def-edebug-spec c-set-region-active t)
1228 (def-edebug-spec c-safe t)
1229 (def-edebug-spec c-save-buffer-state let*)
1230 (def-edebug-spec c-tentative-buffer-changes t)
1231 (def-edebug-spec c-forward-syntactic-ws t)
1232 (def-edebug-spec c-backward-syntactic-ws t)
1233 (def-edebug-spec c-forward-sexp t)
1234 (def-edebug-spec c-backward-sexp t)
1235 (def-edebug-spec c-up-list-forward t)
1236 (def-edebug-spec c-up-list-backward t)
1237 (def-edebug-spec c-down-list-forward t)
1238 (def-edebug-spec c-down-list-backward t)
1239 (def-edebug-spec c-add-syntax t)
1240 (def-edebug-spec c-add-class-syntax t)
1241 (def-edebug-spec c-benign-error t)
1242 (def-edebug-spec c-with-syntax-table t)
1243 (def-edebug-spec c-skip-ws-forward t)
1244 (def-edebug-spec c-skip-ws-backward t)
1245 (def-edebug-spec c-major-mode-is t)
1246 (def-edebug-spec c-put-char-property t)
1247 (def-edebug-spec c-get-char-property t)
1248 (def-edebug-spec c-clear-char-property t)
1249 (def-edebug-spec c-clear-char-properties t)
1250 (def-edebug-spec c-put-overlay t)
1251 (def-edebug-spec c-delete-overlay t) ;))
1256 ;; Note: All these after the macros, to be on safe side in avoiding
1257 ;; bugs where macros are defined too late. These bugs often only show
1258 ;; when the files are compiled in a certain order within the same
1261 (defsubst c-end-of-defun-1 ()
1262 ;; Replacement for end-of-defun that use c-beginning-of-defun-1.
1263 (let ((start (point)))
1264 ;; Skip forward into the next defun block. Don't bother to avoid
1265 ;; comments, literals etc, since beginning-of-defun doesn't do that
1267 (skip-chars-forward "^}")
1268 (c-beginning-of-defun-1)
1269 (if (eq (char-after) ?{)
1271 (if (< (point) start)
1272 (goto-char (point-max)))))
1274 (defmacro c-mark-<-as-paren (pos)
1275 ;; Mark the "<" character at POS as a template opener using the
1276 ;; `syntax-table' property either directly (XEmacs) or via a `category'
1277 ;; property (GNU Emacs).
1279 ;; This function does a hidden buffer change. Note that we use
1280 ;; indirection through the `category' text property. This allows us to
1281 ;; toggle the property in all template brackets simultaneously and
1282 ;; cheaply. We use this, for instance, in `c-parse-state'.
1284 `(c-put-char-property ,pos 'category 'c-<-as-paren-syntax)
1285 `(c-put-char-property ,pos 'syntax-table c-<-as-paren-syntax)))
1288 (defmacro c-mark->-as-paren (pos)
1289 ;; Mark the ">" character at POS as an sexp list closer using the
1290 ;; `syntax-table' property either directly (XEmacs) or via a `category'
1291 ;; property (GNU Emacs).
1293 ;; This function does a hidden buffer change. Note that we use
1294 ;; indirection through the `category' text property. This allows us to
1295 ;; toggle the property in all template brackets simultaneously and
1296 ;; cheaply. We use this, for instance, in `c-parse-state'.
1298 `(c-put-char-property ,pos 'category 'c->-as-paren-syntax)
1299 `(c-put-char-property ,pos 'syntax-table c->-as-paren-syntax)))
1301 (defmacro c-unmark-<->-as-paren (pos)
1302 ;; Unmark the "<" or "<" character at POS as an sexp list opener using the
1303 ;; `syntax-table' property either directly or indirectly through a
1304 ;; `category' text property.
1306 ;; This function does a hidden buffer change. Note that we try to use
1307 ;; indirection through the `category' text property. This allows us to
1308 ;; toggle the property in all template brackets simultaneously and
1309 ;; cheaply. We use this, for instance, in `c-parse-state'.
1310 `(c-clear-char-property ,pos ,(if c-use-category ''category ''syntax-table)))
1312 (defsubst c-suppress-<->-as-parens ()
1313 ;; Suppress the syntactic effect of all marked < and > as parens. Note
1314 ;; that this effect is NOT buffer local. You should probably not use
1315 ;; this directly, but only through the macro
1316 ;; `c-with-<->-as-parens-suppressed'
1317 (put 'c-<-as-paren-syntax 'syntax-table nil)
1318 (put 'c->-as-paren-syntax 'syntax-table nil))
1320 (defsubst c-restore-<->-as-parens ()
1321 ;; Restore the syntactic effect of all marked <s and >s as parens. This
1322 ;; has no effect on unmarked <s and >s
1323 (put 'c-<-as-paren-syntax 'syntax-table c-<-as-paren-syntax)
1324 (put 'c->-as-paren-syntax 'syntax-table c->-as-paren-syntax))
1326 (defmacro c-with-<->-as-parens-suppressed (&rest forms)
1327 ;; Like progn, except that the paren property is suppressed on all
1328 ;; template brackets whilst they are running. This macro does a hidden
1332 (c-suppress-<->-as-parens)
1334 (c-restore-<->-as-parens)))
1338 (defconst c-cpp-delimiter '(14)) ; generic comment syntax
1339 ;; This is the value of the `category' text property placed on every #
1340 ;; which introduces a CPP construct and every EOL (or EOB, or character
1341 ;; preceding //, etc.) which terminates it. We can instantly "comment
1342 ;; out" all CPP constructs by giving `c-cpp-delimiter' a syntax-table
1343 ;; property '(14) (generic comment delimiter).
1344 (defmacro c-set-cpp-delimiters (beg end)
1345 ;; This macro does a hidden buffer change.
1347 (c-put-char-property ,beg 'category 'c-cpp-delimiter)
1348 (if (< ,end (point-max))
1349 (c-put-char-property ,end 'category 'c-cpp-delimiter))))
1350 (defmacro c-clear-cpp-delimiters (beg end)
1351 ;; This macro does a hidden buffer change.
1353 (c-clear-char-property ,beg 'category)
1354 (if (< ,end (point-max))
1355 (c-clear-char-property ,end 'category))))
1357 (defsubst c-comment-out-cpps ()
1358 ;; Render all preprocessor constructs syntactically commented out.
1359 (put 'c-cpp-delimiter 'syntax-table c-cpp-delimiter))
1360 (defsubst c-uncomment-out-cpps ()
1361 ;; Restore the syntactic visibility of preprocessor constructs.
1362 (put 'c-cpp-delimiter 'syntax-table nil))
1364 (defmacro c-with-cpps-commented-out (&rest forms)
1365 ;; Execute FORMS... whilst the syntactic effect of all characters in
1366 ;; all CPP regions is suppressed. In particular, this is to suppress
1367 ;; the syntactic significance of parens/braces/brackets to functions
1368 ;; such as `scan-lists' and `parse-partial-sexp'.
1370 (c-save-buffer-state ()
1371 (c-comment-out-cpps)
1373 (c-save-buffer-state ()
1374 (c-uncomment-out-cpps))))
1376 (defmacro c-with-all-but-one-cpps-commented-out (beg end &rest forms)
1377 ;; Execute FORMS... whilst the syntactic effect of all characters in
1378 ;; every CPP region APART FROM THE ONE BETWEEN BEG and END is
1381 (c-save-buffer-state ()
1384 (c-clear-cpp-delimiters ,beg ,end))
1385 ,`(c-with-cpps-commented-out ,@forms))
1386 (c-save-buffer-state ()
1389 (c-set-cpp-delimiters ,beg ,end)))))
1391 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1392 ;; The following macros are to be used only in `c-parse-state' and its
1393 ;; subroutines. Their main purpose is to simplify the handling of C++/Java
1394 ;; template delimiters and CPP macros. In GNU Emacs, this is done slickly by
1395 ;; the judicious use of 'category properties. These don't exist in XEmacs.
1397 ;; Note: in the following macros, there is no special handling for parentheses
1398 ;; inside CPP constructs. That is because CPPs are always syntactically
1399 ;; balanced, thanks to `c-neutralize-CPP-line' in cc-mode.el.
1400 (defmacro c-sc-scan-lists-no-category+1+1 (from)
1401 ;; Do a (scan-lists FROM 1 1). Any finishing position which either (i) is
1402 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1403 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1404 `(let ((here (point))
1405 (pos (scan-lists ,from 1 1)))
1406 (while (eq (char-before pos) ?>)
1407 (setq pos (scan-lists pos 1 1)))
1410 (defmacro c-sc-scan-lists-no-category+1-1 (from)
1411 ;; Do a (scan-lists FROM 1 -1). Any finishing position which either (i) is
1412 ;; determined by an angle bracket; or (ii) is inside a macro whose start
1413 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1414 `(let ((here (point))
1415 (pos (scan-lists ,from 1 -1)))
1416 (while (eq (char-before pos) ?<)
1417 (setq pos (scan-lists pos 1 1))
1418 (setq pos (scan-lists pos 1 -1)))
1421 (defmacro c-sc-scan-lists-no-category-1+1 (from)
1422 ;; Do a (scan-lists FROM -1 1). Any finishing position which either (i) is
1423 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1424 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1425 `(let ((here (point))
1426 (pos (scan-lists ,from -1 1)))
1427 (while (eq (char-after pos) ?<)
1428 (setq pos (scan-lists pos -1 1)))
1431 (defmacro c-sc-scan-lists-no-category-1-1 (from)
1432 ;; Do a (scan-lists FROM -1 -1). Any finishing position which either (i) is
1433 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1434 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1435 `(let ((here (point))
1436 (pos (scan-lists ,from -1 -1)))
1437 (while (eq (char-after pos) ?>)
1438 (setq pos (scan-lists pos -1 1))
1439 (setq pos (scan-lists pos -1 -1)))
1442 (defmacro c-sc-scan-lists (from count depth)
1444 `(scan-lists ,from ,count ,depth)
1446 ((and (eq count 1) (eq depth 1))
1447 `(c-sc-scan-lists-no-category+1+1 ,from))
1448 ((and (eq count 1) (eq depth -1))
1449 `(c-sc-scan-lists-no-category+1-1 ,from))
1450 ((and (eq count -1) (eq depth 1))
1451 `(c-sc-scan-lists-no-category-1+1 ,from))
1452 ((and (eq count -1) (eq depth -1))
1453 `(c-sc-scan-lists-no-category-1-1 ,from))
1454 (t (error "Invalid parameter(s) to c-sc-scan-lists")))))
1457 (defun c-sc-parse-partial-sexp-no-category (from to targetdepth stopbefore
1459 ;; Do a parse-partial-sexp using the supplied arguments, disregarding
1460 ;; template/generic delimiters < > and disregarding macros other than the
1461 ;; one at POINT-MACRO-START.
1463 ;; NOTE that STOPBEFORE must be nil. TARGETDEPTH should be one less than
1464 ;; the depth in OLDSTATE. This function is thus a SPECIAL PURPOSE variation
1465 ;; on parse-partial-sexp, designed for calling from
1466 ;; `c-remove-stale-state-cache'.
1468 ;; Any finishing position which is determined by an angle bracket delimiter
1469 ;; doesn't count as a finishing position.
1471 ;; Note there is no special handling of CPP constructs here, since these are
1472 ;; always syntactically balanced (thanks to `c-neutralize-CPP-line').
1474 (parse-partial-sexp from to targetdepth stopbefore oldstate)))
1477 ;; We must have hit targetdepth.
1478 (or (eq (char-before) ?<)
1479 (eq (char-before) ?>)))
1481 (if (memq (char-before) '(?> ?\) ?\} ?\]))
1485 (parse-partial-sexp (point) to targetdepth stopbefore oldstate)))
1488 (defmacro c-sc-parse-partial-sexp (from to &optional targetdepth stopbefore
1491 `(parse-partial-sexp ,from ,to ,targetdepth ,stopbefore ,oldstate)
1492 `(c-sc-parse-partial-sexp-no-category ,from ,to ,targetdepth ,stopbefore
1496 (defvar c-emacs-features)
1498 (defmacro c-looking-at-non-alphnumspace ()
1499 "Are we looking at a character which isn't alphanumeric or space?"
1500 (if (memq 'gen-comment-delim c-emacs-features)
1502 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\|\\s!\\)")
1504 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\)"
1505 (let ((prop (c-get-char-property (point) 'syntax-table)))
1506 (eq prop '(14))))))) ; '(14) is generic comment delimiter.
1509 (defsubst c-intersect-lists (list alist)
1510 ;; return the element of ALIST that matches the first element found
1511 ;; in LIST. Uses assq.
1514 (not (setq match (assq (car list) alist))))
1515 (setq list (cdr list)))
1518 (defsubst c-lookup-lists (list alist1 alist2)
1519 ;; first, find the first entry from LIST that is present in ALIST1,
1520 ;; then find the entry in ALIST2 for that entry.
1521 (assq (car (c-intersect-lists list alist1)) alist2))
1523 (defsubst c-langelem-sym (langelem)
1524 "Return the syntactic symbol in LANGELEM.
1526 LANGELEM is either a cons cell on the \"old\" form given as the first
1527 argument to lineup functions or a syntactic element on the \"new\"
1528 form as used in `c-syntactic-element'."
1531 (defsubst c-langelem-pos (langelem)
1532 "Return the anchor position in LANGELEM, or nil if there is none.
1534 LANGELEM is either a cons cell on the \"old\" form given as the first
1535 argument to lineup functions or a syntactic element on the \"new\"
1536 form as used in `c-syntactic-element'."
1537 (if (consp (cdr langelem))
1538 (car-safe (cdr langelem))
1541 (defun c-langelem-col (langelem &optional preserve-point)
1542 "Return the column of the anchor position in LANGELEM.
1543 Also move the point to that position unless PRESERVE-POINT is non-nil.
1545 LANGELEM is either a cons cell on the \"old\" form given as the first
1546 argument to lineup functions or a syntactic element on the \"new\"
1547 form as used in `c-syntactic-element'."
1548 (let ((pos (c-langelem-pos langelem))
1553 (prog1 (current-column)
1558 (defsubst c-langelem-2nd-pos (langelem)
1559 "Return the secondary position in LANGELEM, or nil if there is none.
1561 LANGELEM is typically a syntactic element on the \"new\" form as used
1562 in `c-syntactic-element'. It may also be a cons cell as passed in the
1563 first argument to lineup functions, but then the returned value always
1565 (car-safe (cdr-safe (cdr-safe langelem))))
1567 (defsubst c-keep-region-active ()
1568 ;; Do whatever is necessary to keep the region active in XEmacs.
1569 ;; This is not needed for Emacs.
1570 (and (boundp 'zmacs-region-stays)
1571 (setq zmacs-region-stays t)))
1573 (put 'c-mode 'c-mode-prefix "c-")
1574 (put 'c++-mode 'c-mode-prefix "c++-")
1575 (put 'objc-mode 'c-mode-prefix "objc-")
1576 (put 'java-mode 'c-mode-prefix "java-")
1577 (put 'idl-mode 'c-mode-prefix "idl-")
1578 (put 'pike-mode 'c-mode-prefix "pike-")
1579 (put 'awk-mode 'c-mode-prefix "awk-")
1581 (defsubst c-mode-symbol (suffix)
1582 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1583 the corresponding symbol."
1584 (or c-buffer-is-cc-mode
1585 (error "Not inside a CC Mode based mode"))
1586 (let ((mode-prefix (get c-buffer-is-cc-mode 'c-mode-prefix)))
1588 (error "%S has no mode prefix known to `c-mode-symbol'"
1589 c-buffer-is-cc-mode))
1590 (intern (concat mode-prefix suffix))))
1592 (defsubst c-mode-var (suffix)
1593 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1594 the value of the variable with that name."
1595 (symbol-value (c-mode-symbol suffix)))
1597 (defsubst c-got-face-at (pos faces)
1598 "Return non-nil if position POS in the current buffer has any of the
1599 faces in the list FACES."
1600 (let ((pos-faces (get-text-property pos 'face)))
1601 (if (consp pos-faces)
1603 (while (and pos-faces
1604 (not (memq (car pos-faces) faces)))
1605 (setq pos-faces (cdr pos-faces)))
1607 (memq pos-faces faces))))
1609 (defsubst c-face-name-p (facename)
1610 ;; Return t if FACENAME is the name of a face. This method is
1611 ;; necessary since facep in XEmacs only returns t for the actual
1612 ;; face objects (while it's only their names that are used just
1613 ;; about anywhere else) without providing a predicate that tests
1615 (memq facename (face-list)))
1617 (defun c-concat-separated (list separator)
1618 "Like `concat' on LIST, but separate each element with SEPARATOR.
1619 Notably, null elements in LIST are ignored."
1620 (mapconcat 'identity (delete nil (append list nil)) separator))
1622 (defun c-make-keywords-re (adorn list &optional mode)
1623 "Make a regexp that matches all the strings the list.
1624 Duplicates and nil elements in the list are removed. The
1625 resulting regexp may contain zero or more submatch expressions.
1627 If ADORN is t there will be at least one submatch and the first
1628 surrounds the matched alternative, and the regexp will also not match
1629 a prefix of any identifier. Adorned regexps cannot be appended. The
1630 language variable `c-nonsymbol-key' is used to make the adornment.
1632 A value `appendable' for ADORN is like above, but all alternatives in
1633 the list that end with a word constituent char will have \\> appended
1634 instead, so that the regexp remains appendable. Note that this
1635 variant doesn't always guarantee that an identifier prefix isn't
1636 matched since the symbol constituent `_' is normally considered a
1637 nonword token by \\>.
1639 The optional MODE specifies the language to get `c-nonsymbol-key' from
1640 when it's needed. The default is the current language taken from
1641 `c-buffer-is-cc-mode'."
1643 (setq list (delete nil (delete-dups list)))
1647 (if (eq adorn 'appendable)
1648 ;; This is kludgy but it works: Search for a string that
1649 ;; doesn't occur in any word in LIST. Append it to all
1650 ;; the alternatives where we want to add \>. Run through
1651 ;; `regexp-opt' and then replace it with \>.
1652 (let ((unique "") pos)
1654 (setq unique (concat unique "@")
1657 (if (string-match unique (car pos))
1658 (progn (setq found t)
1661 (setq pos (cdr pos)))
1665 (if (string-match "\\w\\'" (car pos))
1666 (setcar pos (concat (car pos) unique)))
1667 (setq pos (cdr pos)))
1668 (setq re (regexp-opt list))
1670 (while (string-match unique re pos)
1671 (setq pos (+ (match-beginning 0) 2)
1672 re (replace-match "\\>" t t re))))
1674 (setq re (regexp-opt list)))
1676 ;; Emacs 20 and XEmacs (all versions so far) has a buggy
1677 ;; regexp-opt that doesn't always cope with strings containing
1678 ;; newlines. This kludge doesn't handle shy parens correctly
1679 ;; so we can't advice regexp-opt directly with it.
1682 (and (string-match "\n" (car list)) ; To speed it up a little.
1683 (not (string-match (concat "\\`\\(" re "\\)\\'")
1685 (setq fail-list (cons (car list) fail-list)))
1686 (setq list (cdr list)))
1691 (if (eq adorn 'appendable)
1693 (if (string-match "\\w\\'" str)
1694 (concat (regexp-quote str)
1696 (regexp-quote str)))
1700 (> (length a) (length b))))
1703 ;; Add our own grouping parenthesis around re instead of
1704 ;; passing adorn to `regexp-opt', since in XEmacs it makes the
1705 ;; top level grouping "shy".
1706 (cond ((eq adorn 'appendable)
1707 (concat "\\(" re "\\)"))
1709 (concat "\\(" re "\\)"
1711 (c-get-lang-constant 'c-nonsymbol-key nil mode)
1716 ;; Produce a regexp that matches nothing.
1721 (put 'c-make-keywords-re 'lisp-indent-function 1)
1723 (defun c-make-bare-char-alt (chars &optional inverted)
1724 "Make a character alternative string from the list of characters CHARS.
1725 The returned string is of the type that can be used with
1726 `skip-chars-forward' and `skip-chars-backward'. If INVERTED is
1727 non-nil, a caret is prepended to invert the set."
1728 ;; This function ought to be in the elisp core somewhere.
1729 (let ((str (if inverted "^" "")) char char2)
1730 (setq chars (sort (append chars nil) `<))
1732 (setq char (pop chars))
1733 (if (memq char '(?\\ ?^ ?-))
1734 ;; Quoting necessary (this method only works in the skip
1736 (setq str (format "%s\\%c" str char))
1737 (setq str (format "%s%c" str char)))
1740 (while (and chars (>= (1+ char2) (car chars)))
1741 (setq char2 (pop chars)))
1742 (unless (= char char2)
1743 (if (< (1+ char) char2)
1744 (setq str (format "%s-%c" str char2))
1745 (push char2 chars))))
1748 ;; Leftovers from (X)Emacs 19 compatibility.
1749 (defalias 'c-regexp-opt 'regexp-opt)
1750 (defalias 'c-regexp-opt-depth 'regexp-opt-depth)
1753 ;; Figure out what features this Emacs has
1755 (cc-bytecomp-defvar open-paren-in-column-0-is-defun-start)
1757 (defvar lookup-syntax-properties) ;XEmacs.
1759 (defconst c-emacs-features
1762 (if (boundp 'infodock-version)
1763 ;; I've no idea what this actually is, but it's legacy. /mast
1764 (setq list (cons 'infodock list)))
1766 ;; XEmacs uses 8-bit modify-syntax-entry flags.
1767 ;; Emacs uses a 1-bit flag. We will have to set up our
1768 ;; syntax tables differently to handle this.
1769 (let ((table (copy-syntax-table))
1771 (modify-syntax-entry ?a ". 12345678" table)
1775 (setq entry (aref table ?a))
1776 ;; In Emacs, table entries are cons cells
1777 (if (consp entry) (setq entry (car entry))))
1779 ((fboundp 'get-char-table)
1780 (setq entry (get-char-table ?a table)))
1782 (t (error "CC Mode is incompatible with this version of Emacs")))
1783 (setq list (cons (if (= (logand (lsh entry -16) 255) 255)
1788 ;; Check whether beginning/end-of-defun call
1789 ;; beginning/end-of-defun-function nicely, passing through the
1790 ;; argument and respecting the return code.
1792 (bod-param 'foo) (eod-param 'foo)
1793 (beginning-of-defun-function
1794 (lambda (&optional arg)
1795 (or (eq bod-param 'foo) (setq bod-param 'bar))
1796 (and (eq bod-param 'foo)
1797 (setq bod-param arg)
1799 (end-of-defun-function
1800 (lambda (&optional arg)
1801 (and (eq eod-param 'foo)
1802 (setq eod-param arg)
1804 (if (save-excursion (and (beginning-of-defun 3) (eq bod-param 3)
1805 (not (beginning-of-defun))
1806 (end-of-defun 3) (eq eod-param 3)
1807 (not (end-of-defun))))
1808 (setq list (cons 'argumentative-bod-function list))))
1810 ;; Record whether the `category' text property works.
1811 (if c-use-category (setq list (cons 'category-properties list)))
1813 (let ((buf (generate-new-buffer " test"))
1814 parse-sexp-lookup-properties
1815 parse-sexp-ignore-comments
1816 lookup-syntax-properties) ; XEmacs
1817 (with-current-buffer buf
1818 (set-syntax-table (make-syntax-table))
1820 ;; For some reason we have to set some of these after the
1821 ;; buffer has been made current. (Specifically,
1822 ;; `parse-sexp-ignore-comments' in Emacs 21.)
1823 (setq parse-sexp-lookup-properties t
1824 parse-sexp-ignore-comments t
1825 lookup-syntax-properties t)
1827 ;; Find out if the `syntax-table' text property works.
1828 (modify-syntax-entry ?< ".")
1829 (modify-syntax-entry ?> ".")
1831 (c-mark-<-as-paren (point-min))
1832 (c-mark->-as-paren (+ 3 (point-min)))
1833 (goto-char (point-min))
1835 (if (= (point) (+ 4 (point-min)))
1836 (setq list (cons 'syntax-properties list))
1838 "CC Mode is incompatible with this version of Emacs - "
1839 "support for the `syntax-table' text property "
1842 ;; Find out if "\\s!" (generic comment delimiters) work.
1844 (modify-syntax-entry ?x "!")
1845 (if (string-match "\\s!" "x")
1846 (setq list (cons 'gen-comment-delim list))))
1848 ;; Find out if "\\s|" (generic string delimiters) work.
1850 (modify-syntax-entry ?x "|")
1851 (if (string-match "\\s|" "x")
1852 (setq list (cons 'gen-string-delim list))))
1854 ;; See if POSIX char classes work.
1855 (when (and (string-match "[[:alpha:]]" "a")
1856 ;; All versions of Emacs 21 so far haven't fixed
1857 ;; char classes in `skip-chars-forward' and
1858 ;; `skip-chars-backward'.
1860 (delete-region (point-min) (point-max))
1862 (skip-chars-backward "[:alnum:]")
1864 (= (skip-chars-forward "[:alpha:]") 3))
1865 (setq list (cons 'posix-char-classes list)))
1867 ;; See if `open-paren-in-column-0-is-defun-start' exists and
1868 ;; isn't buggy (Emacs >= 21.4).
1869 (when (boundp 'open-paren-in-column-0-is-defun-start)
1870 (let ((open-paren-in-column-0-is-defun-start nil)
1871 (parse-sexp-ignore-comments t))
1872 (delete-region (point-min) (point-max))
1873 (set-syntax-table (make-syntax-table))
1874 (modify-syntax-entry ?\' "\"")
1876 ;; XEmacs. Afaik this is currently an Emacs-only
1877 ;; feature, but it's good to be prepared.
1879 (modify-syntax-entry ?/ ". 1456")
1880 (modify-syntax-entry ?* ". 23"))
1883 (modify-syntax-entry ?/ ". 124b")
1884 (modify-syntax-entry ?* ". 23")))
1885 (modify-syntax-entry ?\n "> b")
1886 (insert "/* '\n () */")
1889 (setq list (cons 'col-0-paren list)))))
1891 (set-buffer-modified-p nil))
1894 ;; See if `parse-partial-sexp' returns the eighth element.
1895 (if (c-safe (>= (length (save-excursion
1896 (parse-partial-sexp (point) (point))))
1898 (setq list (cons 'pps-extended-state list))
1900 "CC Mode is incompatible with this version of Emacs - "
1901 "`parse-partial-sexp' has to return at least 10 elements.")))
1903 ;;(message "c-emacs-features: %S" list)
1905 "A list of certain features in the (X)Emacs you are using.
1906 There are many flavors of Emacs out there, each with different
1907 features supporting those needed by CC Mode. The following values
1910 `8-bit' 8 bit syntax entry flags (XEmacs style).
1911 `1-bit' 1 bit syntax entry flags (Emacs style).
1912 `argumentative-bod-function' beginning-of-defun and end-of-defun pass
1913 ARG through to beginning/end-of-defun-function.
1914 `syntax-properties' It works to override the syntax for specific characters
1915 in the buffer with the `syntax-table' property. It's
1916 always set - CC Mode no longer works in emacsen without
1918 `category-properties' Syntax routines can add a level of indirection to text
1919 properties using the `category' property.
1920 `gen-comment-delim' Generic comment delimiters work
1921 (i.e. the syntax class `!').
1922 `gen-string-delim' Generic string delimiters work
1923 (i.e. the syntax class `|').
1924 `pps-extended-state' `parse-partial-sexp' returns a list with at least 10
1925 elements, i.e. it contains the position of the start of
1926 the last comment or string. It's always set - CC Mode
1927 no longer works in emacsen without this feature.
1928 `posix-char-classes' The regexp engine understands POSIX character classes.
1929 `col-0-paren' It's possible to turn off the ad-hoc rule that a paren
1930 in column zero is the start of a defun.
1931 `infodock' This is Infodock (based on XEmacs).
1933 `8-bit' and `1-bit' are mutually exclusive.")
1936 ;;; Some helper constants.
1938 ;; If the regexp engine supports POSIX char classes then we can use
1939 ;; them to handle extended charsets correctly.
1940 (if (memq 'posix-char-classes c-emacs-features)
1942 (defconst c-alpha "[:alpha:]")
1943 (defconst c-alnum "[:alnum:]")
1944 (defconst c-digit "[:digit:]")
1945 (defconst c-upper "[:upper:]")
1946 (defconst c-lower "[:lower:]"))
1947 (defconst c-alpha "a-zA-Z")
1948 (defconst c-alnum "a-zA-Z0-9")
1949 (defconst c-digit "0-9")
1950 (defconst c-upper "A-Z")
1951 (defconst c-lower "a-z"))
1954 ;;; System for handling language dependent constants.
1956 ;; This is used to set various language dependent data in a flexible
1957 ;; way: Language constants can be built from the values of other
1958 ;; language constants, also those for other languages. They can also
1959 ;; process the values of other language constants uniformly across all
1960 ;; the languages. E.g. one language constant can list all the type
1961 ;; keywords in each language, and another can build a regexp for each
1962 ;; language from those lists without code duplication.
1964 ;; Language constants are defined with `c-lang-defconst', and their
1965 ;; value forms (referred to as source definitions) are evaluated only
1966 ;; on demand when requested for a particular language with
1967 ;; `c-lang-const'. It's therefore possible to refer to the values of
1968 ;; constants defined later in the file, or in another file, just as
1969 ;; long as all the relevant `c-lang-defconst' have been loaded when
1970 ;; `c-lang-const' is actually evaluated from somewhere else.
1972 ;; `c-lang-const' forms are also evaluated at compile time and
1973 ;; replaced with the values they produce. Thus there's no overhead
1974 ;; for this system when compiled code is used - only the values
1975 ;; actually used in the code are present, and the file(s) containing
1976 ;; the `c-lang-defconst' forms don't need to be loaded at all then.
1977 ;; There are however safeguards to make sure that they can be loaded
1978 ;; to get the source definitions for the values if there's a mismatch
1979 ;; in compiled versions, or if `c-lang-const' is used uncompiled.
1981 ;; Note that the source definitions in a `c-lang-defconst' form are
1982 ;; compiled into the .elc file where it stands; there's no need to
1983 ;; load the source file to get it.
1985 ;; See cc-langs.el for more details about how this system is deployed
1986 ;; in CC Mode, and how the associated language variable system
1987 ;; (`c-lang-defvar') works. That file also contains a lot of
1990 (defun c-add-language (mode base-mode)
1991 "Declare a new language in the language dependent variable system.
1992 This is intended to be used by modes that inherit CC Mode to add new
1993 languages. It should be used at the top level before any calls to
1994 `c-lang-defconst'. MODE is the mode name symbol for the new language,
1995 and BASE-MODE is the mode name symbol for the language in CC Mode that
1996 is to be the template for the new mode.
1998 The exact effect of BASE-MODE is to make all language constants that
1999 haven't got a setting in the new language fall back to their values in
2000 BASE-MODE. It does not have any effect outside the language constant
2002 (unless (string-match "\\`\\(.*-\\)mode\\'" (symbol-name mode))
2003 (error "The mode name symbol `%s' must end with \"-mode\"" mode))
2004 (put mode 'c-mode-prefix (match-string 1 (symbol-name mode)))
2005 (unless (get base-mode 'c-mode-prefix)
2006 (error "Unknown base mode `%s'" base-mode))
2007 (put mode 'c-fallback-mode base-mode))
2009 (defvar c-lang-constants (make-vector 151 0))
2010 ;; Obarray used as a cache to keep track of the language constants.
2011 ;; The constants stored are those defined by `c-lang-defconst' and the values
2012 ;; computed by `c-lang-const'. It's mostly used at compile time but it's not
2013 ;; stored in compiled files.
2015 ;; The obarray contains all the language constants as symbols. The
2016 ;; value cells hold the evaluated values as alists where each car is
2017 ;; the mode name symbol and the corresponding cdr is the evaluated
2018 ;; value in that mode. The property lists hold the source definitions
2019 ;; and other miscellaneous data. The obarray might also contain
2020 ;; various other symbols, but those don't have any variable bindings.
2022 (defvar c-lang-const-expansion nil)
2024 ;; Ugly hack to pull in the definition of `cc-bytecomp-compiling-or-loading'
2025 ;; from cc-bytecomp to make it available at loadtime. This is the same
2026 ;; mechanism used in cc-mode.el for `c-populate-syntax-table'.
2027 (defalias 'cc-bytecomp-compiling-or-loading
2028 (cc-eval-when-compile
2029 (let ((f (symbol-function 'cc-bytecomp-compiling-or-loading)))
2030 (if (byte-code-function-p f) f (byte-compile f)))))
2032 (defsubst c-get-current-file ()
2033 ;; Return the base name of the current file.
2034 (let* ((c-or-l (cc-bytecomp-compiling-or-loading))
2037 ((eq c-or-l 'loading) load-file-name)
2038 ((eq c-or-l 'compiling) byte-compile-dest-file)
2039 ((null c-or-l) (buffer-file-name)))))
2041 (file-name-sans-extension
2042 (file-name-nondirectory file)))))
2044 (defmacro c-lang-defconst-eval-immediately (form)
2045 "Can be used inside a VAL in `c-lang-defconst' to evaluate FORM
2046 immediately, i.e. at the same time as the `c-lang-defconst' form
2047 itself is evaluated."
2048 ;; Evaluate at macro expansion time, i.e. in the
2049 ;; `c--macroexpand-all' inside `c-lang-defconst'.
2052 (defmacro c-lang-defconst (name &rest args)
2053 "Set the language specific values of the language constant NAME.
2054 The second argument can optionally be a docstring. The rest of the
2055 arguments are one or more repetitions of LANG VAL where LANG specifies
2056 the language(s) that VAL applies to. LANG is the name of the
2057 language, i.e. the mode name without the \"-mode\" suffix, or a list
2058 of such language names, or t for all languages. VAL is a form to
2059 evaluate to get the value.
2061 If LANG isn't t or one of the core languages in CC Mode, it must
2062 have been declared with `c-add-language'.
2064 Neither NAME, LANG nor VAL are evaluated directly - they should not be
2065 quoted. `c-lang-defconst-eval-immediately' can however be used inside
2066 VAL to evaluate parts of it directly.
2068 When VAL is evaluated for some language, that language is temporarily
2069 made current so that `c-lang-const' without an explicit language can
2070 be used inside VAL to refer to the value of a language constant in the
2071 same language. That is particularly useful if LANG is t.
2073 VAL is not evaluated right away but rather when the value is requested
2074 with `c-lang-const'. Thus it's possible to use `c-lang-const' inside
2075 VAL to refer to language constants that haven't been defined yet.
2076 However, if the definition of a language constant is in another file
2077 then that file must be loaded \(at compile time) before it's safe to
2078 reference the constant.
2080 The assignments in ARGS are processed in sequence like `setq', so
2081 \(c-lang-const NAME) may be used inside a VAL to refer to the last
2082 assigned value to this language constant, or a value that it has
2083 gotten in another earlier loaded file.
2085 To work well with repeated loads and interactive reevaluation, only
2086 one `c-lang-defconst' for each NAME is permitted per file. If there
2087 already is one it will be completely replaced; the value in the
2088 earlier definition will not affect `c-lang-const' on the same
2089 constant. A file is identified by its base name."
2091 (let* ((sym (intern (symbol-name name) c-lang-constants))
2092 ;; Make `c-lang-const' expand to a straightforward call to
2093 ;; `c-get-lang-constant' in `c--macroexpand-all' below.
2095 ;; (The default behavior, i.e. to expand to a call inside
2096 ;; `eval-when-compile' should be equivalent, since that macro
2097 ;; should only expand to its content if it's used inside a
2098 ;; form that's already evaluated at compile time. It's
2099 ;; however necessary to use our cover macro
2100 ;; `cc-eval-when-compile' due to bugs in `eval-when-compile',
2101 ;; and it expands to a bulkier form that in this case only is
2102 ;; unnecessary garbage that we don't want to store in the
2103 ;; language constant source definitions.)
2104 (c-lang-const-expansion 'call)
2105 (c-langs-are-parametric t)
2107 (or (c-get-current-file)
2108 (error "`c-lang-defconst' can only be used in a file"))))
2113 (error "Not a symbol: %S" name))
2115 (when (stringp (car-safe args))
2116 ;; The docstring is hardly used anywhere since there's no normal
2117 ;; symbol to attach it to. It's primarily for getting the right
2118 ;; format in the source.
2119 (put sym 'variable-documentation (car args))
2120 (setq args (cdr args)))
2123 (error "No assignments in `c-lang-defconst' for %S" name))
2125 ;; Rework ARGS to an association list to make it easier to handle.
2126 ;; It's reversed at the same time to make it easier to implement
2127 ;; the demand-driven (i.e. reversed) evaluation in `c-lang-const'.
2129 (let ((assigned-mode
2130 (cond ((eq (car args) t) t)
2131 ((symbolp (car args))
2132 (list (intern (concat (symbol-name (car args))
2135 (mapcar (lambda (lang)
2137 (error "Not a list of symbols: %S"
2139 (intern (concat (symbol-name lang)
2142 (t (error "Not a symbol or a list of symbols: %S"
2147 (error "No value for %S" (car args)))
2148 (setq args (cdr args)
2151 ;; Emacs has a weird bug where it seems to fail to read
2152 ;; backquote lists from byte compiled files correctly (,@
2153 ;; forms, to be specific), so make sure the bindings in the
2154 ;; expansion below don't contain any backquote stuff.
2155 ;; (XEmacs handles it correctly and doesn't need this for that
2156 ;; reason, but we also use this expansion handle
2157 ;; `c-lang-defconst-eval-immediately' and to register
2158 ;; dependencies on the `c-lang-const's in VAL.)
2159 (setq val (c--macroexpand-all val))
2161 (setq bindings `(cons (cons ',assigned-mode (lambda () ,val)) ,bindings)
2164 ;; Compile in the other files that have provided source
2165 ;; definitions for this symbol, to make sure the order in the
2166 ;; `source' property is correct even when files are loaded out of
2168 (setq pre-files (mapcar 'car (get sym 'source)))
2169 (if (memq file pre-files)
2170 ;; This can happen when the source file (e.g. cc-langs.el) is first
2171 ;; loaded as source, setting a 'source property entry, and then itself
2173 (setq pre-files (cdr (memq file pre-files))))
2174 ;; Reverse to get the right load order.
2175 (setq pre-files (nreverse pre-files))
2178 (c-define-lang-constant ',name ,bindings
2179 ,@(and pre-files `(',pre-files))))))
2181 (put 'c-lang-defconst 'lisp-indent-function 1)
2182 ;(eval-after-load "edebug" ; 2006-07-09: def-edebug-spec is now in subr.el.
2184 (def-edebug-spec c-lang-defconst
2185 (&define name [&optional stringp] [&rest sexp def-form]))
2187 (defun c-define-lang-constant (name bindings &optional pre-files)
2188 ;; Used by `c-lang-defconst'.
2190 (let* ((sym (intern (symbol-name name) c-lang-constants))
2191 (source (get sym 'source))
2193 (or (c-get-current-file)
2194 (error "`c-lang-defconst' must be used in a file"))))
2195 (elem (assq file source)))
2197 ;;(when (cdr-safe elem)
2198 ;; (message "Language constant %s redefined in %S" name file))
2200 ;; Note that the order in the source alist is relevant. Like how
2201 ;; `c-lang-defconst' reverses the bindings, this reverses the
2202 ;; order between files so that the last to evaluate comes first.
2205 (unless (assq (car pre-files) source)
2206 (setq source (cons (list (car pre-files)) source)))
2207 (setq pre-files (cdr pre-files)))
2208 (put sym 'source (cons (setq elem (list file)) source)))
2210 (setcdr elem bindings)
2212 ;; Bind the symbol as a variable, or clear any earlier evaluated
2216 ;; Clear the evaluated values that depend on this source.
2217 (let ((agenda (get sym 'dependents))
2218 (visited (make-vector 101 0))
2221 (setq sym (car agenda)
2222 agenda (cdr agenda))
2223 (intern (symbol-name sym) visited)
2225 (setq ptr (get sym 'dependents))
2229 (unless (intern-soft (symbol-name sym) visited)
2230 (setq agenda (cons sym agenda))))))
2234 (defmacro c-lang-const (name &optional lang)
2235 "Get the mode specific value of the language constant NAME in language LANG.
2236 LANG is the name of the language, i.e. the mode name without the
2237 \"-mode\" suffix. If used inside `c-lang-defconst' or
2238 `c-lang-defvar', LANG may be left out to refer to the current
2239 language. NAME and LANG are not evaluated so they should not be
2243 (error "Not a symbol: %S" name))
2245 (error "Not a symbol: %S" lang))
2247 (let ((sym (intern (symbol-name name) c-lang-constants))
2248 (mode (when lang (intern (concat (symbol-name lang) "-mode")))))
2250 (or (get mode 'c-mode-prefix) (null mode)
2251 (error "Unknown language %S: no `c-mode-prefix' property"
2254 (if (eq c-lang-const-expansion 'immediate)
2255 ;; No need to find out the source file(s) when we evaluate
2256 ;; immediately since all the info is already there in the
2257 ;; `source' property.
2258 `',(c-get-lang-constant name nil mode)
2261 (let ((file (c-get-current-file)))
2262 (if file (setq file (intern file)))
2263 ;; Get the source file(s) that must be loaded to get the value
2264 ;; of the constant. If the symbol isn't defined yet we assume
2265 ;; that its definition will come later in this file, and thus
2266 ;; are no file dependencies needed.
2268 ;; Reverse to get the right load order.
2269 (c--mapcan (lambda (elem)
2270 (if (eq file (car elem))
2271 nil ; Exclude our own file.
2273 (get sym 'source)))))
2275 ;; Make some effort to do a compact call to
2276 ;; `c-get-lang-constant' since it will be compiled in.
2277 (args (and mode `(',mode))))
2279 (if (or source-files args)
2280 (push (and source-files `',source-files) args))
2282 (if (or (eq c-lang-const-expansion 'call)
2283 (and (not c-lang-const-expansion)
2285 (not (cc-bytecomp-is-compiling)))
2286 ;; Either a straight call is requested in the context, or
2287 ;; we're in an "uncontrolled" context and got no language,
2288 ;; or we're not being byte compiled so the compile time
2289 ;; stuff below is unnecessary.
2290 `(c-get-lang-constant ',name ,@args)
2292 ;; Being compiled. If the loading and compiling version is
2293 ;; the same we use a value that is evaluated at compile time,
2294 ;; otherwise it's evaluated at runtime.
2295 `(if (eq c-version-sym ',c-version-sym)
2296 (cc-eval-when-compile
2297 (c-get-lang-constant ',name ,@args))
2298 (c-get-lang-constant ',name ,@args)))))))
2300 (defvar c-lang-constants-under-evaluation nil
2301 "Alist of constants in the process of being evaluated.
2302 The `cdr' of each entry indicates how far we've looked in the list
2303 of definitions, so that the def for var FOO in c-mode can be defined in
2304 terms of the def for that same var FOO (which will then rely on the
2305 fallback definition for all modes, to break the cycle).")
2307 (defconst c-lang--novalue "novalue")
2309 (defun c-get-lang-constant (name &optional source-files mode)
2310 ;; Used by `c-lang-const'.
2313 (setq mode c-buffer-is-cc-mode)
2314 (error "No current language"))
2316 (let* ((sym (intern (symbol-name name) c-lang-constants))
2317 (source (get sym 'source))
2319 (eval-in-sym (and c-lang-constants-under-evaluation
2320 (caar c-lang-constants-under-evaluation))))
2322 ;; Record the dependencies between this symbol and the one we're
2323 ;; being evaluated in.
2325 (or (memq eval-in-sym (get sym 'dependents))
2326 (put sym 'dependents (cons eval-in-sym (get sym 'dependents)))))
2328 ;; Make sure the source files have entries on the `source'
2329 ;; property so that loading will take place when necessary.
2331 (unless (assq (car source-files) source)
2333 (setq source (cons (list (car source-files)) source)))
2334 ;; Might pull in more definitions which affect the value. The
2335 ;; clearing of dependent values etc is done when the
2336 ;; definition is encountered during the load; this is just to
2337 ;; jump past the check for a cached value below.
2339 (setq source-files (cdr source-files)))
2341 (if (and (boundp sym)
2342 (setq elem (assq mode (symbol-value sym))))
2345 ;; Check if an evaluation of this symbol is already underway.
2346 ;; In that case we just continue with the "assignment" before
2347 ;; the one currently being evaluated, thereby creating the
2348 ;; illusion if a `setq'-like sequence of assignments.
2349 (let* ((c-buffer-is-cc-mode mode)
2351 (or (assq sym c-lang-constants-under-evaluation)
2352 (cons sym (vector source nil))))
2353 ;; Append `c-lang-constants-under-evaluation' even if an
2354 ;; earlier entry is found. It's only necessary to get
2355 ;; the recording of dependencies above correct.
2356 (c-lang-constants-under-evaluation
2357 (cons source-pos c-lang-constants-under-evaluation))
2358 (fallback (get mode 'c-fallback-mode))
2360 ;; Make sure the recursion limits aren't very low
2361 ;; since the `c-lang-const' dependencies can go deep.
2362 (max-specpdl-size (max max-specpdl-size 3000))
2363 (max-lisp-eval-depth (max max-lisp-eval-depth 1000)))
2366 (let ((backup-source-pos (copy-sequence (cdr source-pos))))
2368 ;; First try the original mode but don't accept an
2369 ;; entry matching all languages since the fallback
2370 ;; mode might have an explicit entry before that.
2371 (eq (setq value (c-find-assignment-for-mode
2372 (cdr source-pos) mode nil name))
2374 ;; Try again with the fallback mode from the
2375 ;; original position. Note that
2376 ;; `c-buffer-is-cc-mode' still is the real mode if
2377 ;; language parameterization takes place.
2378 (eq (setq value (c-find-assignment-for-mode
2379 (setcdr source-pos backup-source-pos)
2382 ;; A simple lookup with no fallback mode.
2383 (eq (setq value (c-find-assignment-for-mode
2384 (cdr source-pos) mode t name))
2387 "`%s' got no (prior) value in %S (might be a cyclic reference)"
2391 (setq value (funcall value))
2393 ;; Print a message to aid in locating the error. We don't
2394 ;; print the error itself since that will be done later by
2395 ;; some caller higher up.
2396 (message "Eval error in the `c-lang-defconst' for `%S' in %s:"
2399 (signal (car err) (cdr err))))
2401 (set sym (cons (cons mode value) (symbol-value sym)))
2404 (defun c-find-assignment-for-mode (source-pos mode match-any-lang _name)
2405 ;; Find the first assignment entry that applies to MODE at or after
2406 ;; SOURCE-POS. If MATCH-ANY-LANG is non-nil, entries with t as
2407 ;; the language list are considered to match, otherwise they don't.
2408 ;; On return SOURCE-POS is updated to point to the next assignment
2409 ;; after the returned one. If no assignment is found,
2410 ;; `c-lang--novalue' is returned as a magic value.
2412 ;; SOURCE-POS is a vector that points out a specific assignment in
2413 ;; the double alist that's used in the `source' property. The first
2414 ;; element is the position in the top alist which is indexed with
2415 ;; the source files, and the second element is the position in the
2416 ;; nested bindings alist.
2418 ;; NAME is only used for error messages.
2421 (let ((file-entry (elt source-pos 0))
2422 (assignment-entry (elt source-pos 1))
2425 (while (if assignment-entry
2427 ;; Handled the last assignment from one file, begin on the
2428 ;; next. Due to the check in `c-lang-defconst', we know
2429 ;; there's at least one.
2432 (unless (aset source-pos 1
2433 (setq assignment-entry (cdar file-entry)))
2434 ;; The file containing the source definitions has not
2436 (let ((file (symbol-name (caar file-entry)))
2437 (c-lang-constants-under-evaluation nil))
2438 ;;(message (concat "Loading %s to get the source "
2439 ;; "value for language constant %s")
2443 (unless (setq assignment-entry (cdar file-entry))
2444 ;; The load didn't fill in the source for the
2445 ;; constant as expected. The situation is
2446 ;; probably that a derived mode was written for
2447 ;; and compiled with another version of CC Mode,
2448 ;; and the requested constant isn't in the
2449 ;; currently loaded one. Put in a dummy
2450 ;; assignment that matches no language.
2451 (setcdr (car file-entry)
2452 (setq assignment-entry (list (list nil))))))
2454 (aset source-pos 0 (setq file-entry (cdr file-entry)))
2457 (setq assignment (car assignment-entry))
2459 (setq assignment-entry (cdr assignment-entry)))
2461 (when (if (listp (car assignment))
2462 (memq mode (car assignment))
2464 (throw 'found (cdr assignment))))
2468 (defun c-lang-major-mode-is (mode)
2469 ;; `c-major-mode-is' expands to a call to this function inside
2470 ;; `c-lang-defconst'. Here we also match the mode(s) against any
2471 ;; fallback modes for the one in `c-buffer-is-cc-mode', so that
2472 ;; e.g. (c-major-mode-is 'c++-mode) is true in a derived language
2473 ;; that has c++-mode as base mode.
2474 (unless (listp mode)
2475 (setq mode (list mode)))
2476 (let (match (buf-mode c-buffer-is-cc-mode))
2477 (while (if (memq buf-mode mode)
2481 (setq buf-mode (get buf-mode 'c-fallback-mode))))
2485 (cc-provide 'cc-defs)
2488 ;; indent-tabs-mode: t
2491 ;;; cc-defs.el ends here