]> code.delx.au - gnu-emacs/blob - lisp/progmodes/cc-defs.el
Finish fixing a cacheing bug in CC Mode (see 2016-03-09)
[gnu-emacs] / lisp / progmodes / cc-defs.el
1 ;;; cc-defs.el --- compile time definitions for CC Mode
2
3 ;; Copyright (C) 1985, 1987, 1992-2016 Free Software Foundation, Inc.
4
5 ;; Authors: 2003- Alan Mackenzie
6 ;; 1998- Martin Stjernholm
7 ;; 1992-1999 Barry A. Warsaw
8 ;; 1987 Dave Detlefs
9 ;; 1987 Stewart Clamen
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
14 ;; Package: cc-mode
15
16 ;; This file is part of GNU Emacs.
17
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.
22
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.
27
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/>.
30
31 ;;; Commentary:
32
33 ;; This file contains macros, defsubsts, and various other things that
34 ;; must be loaded early both during compilation and at runtime.
35
36 ;;; Code:
37
38 (eval-when-compile
39 (let ((load-path
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)
43 load-path)))
44 (load "cc-bytecomp" nil t)))
45
46 (eval-and-compile
47 (defvar c--mapcan-status
48 (cond ((and (fboundp 'mapcan)
49 (subrp (symbol-function 'mapcan)))
50 ;; XEmacs
51 'mapcan)
52 ((locate-file "cl-lib.elc" load-path)
53 ;; Emacs >= 24.3
54 'cl-mapcan)
55 (t
56 ;; Emacs <= 24.2
57 nil))))
58
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)
64
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
74
75 \f
76 ;; cc-fix.el contains compatibility macros that should be used if
77 ;; needed.
78 (cc-conditional-require
79 'cc-fix (or (/= (regexp-opt-depth "\\(\\(\\)\\)") 2)
80 (not (fboundp 'push))
81 ;; XEmacs 21.4 doesn't have `delete-dups'.
82 (not (fboundp 'delete-dups))))
83
84 (cc-conditional-require-after-load
85 'cc-fix "font-lock"
86 (and
87 (featurep 'xemacs)
88 (progn
89 (require 'font-lock)
90 (let (font-lock-keywords)
91 (font-lock-compile-keywords '("\\<\\>"))
92 font-lock-keywords))))
93
94 \f
95 ;;; Variables also used at compile time.
96
97 (defconst c-version "5.33"
98 "CC Mode version number.")
99
100 (defconst c-version-sym (intern c-version))
101 ;; A little more compact and faster in comparisons.
102
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
110 not known.")
111 (make-variable-buffer-local 'c-buffer-is-cc-mode)
112
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)
116
117 \f
118 ;; The following is used below during compilation.
119 (eval-and-compile
120 (defvar c-inside-eval-when-compile nil)
121
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.
125
126 This variant works around bugs in `eval-when-compile' in various
127 \(X)Emacs versions. See cc-defs.el for details."
128
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.
134 `(progn ,@body)
135
136 `(eval-when-compile
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
140 ;; compiled.
141 ;;
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:
146 ;;
147 ;; (defsubst nthcdr (val) val)
148 ;;
149 ;; `defsubst', like `defmacro', needs to be evaluated at
150 ;; compile time, so this will produce an error during byte
151 ;; compilation.
152 ;;
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':
156 ;;
157 ;; (eval-when-compile
158 ;; (if (not (fboundp 'foo))
159 ;; (defsubst foo ...)))
160 ;;
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.
168 ;;
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)))))
174
175 (put 'cc-eval-when-compile 'lisp-indent-hook 0))
176
177 \f
178 ;;; Macros.
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.
184 (cond
185 ((eq c--mapcan-status 'mapcan)
186 `(mapcan ,fun ,liszt))
187 ((eq c--mapcan-status 'cl-mapcan)
188 `(cl-mapcan ,fun ,liszt))
189 (t
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)))))
193
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)))
199
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)))
205
206 (eval-and-compile
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 (eq c--mapcan-status 'cl-mapcan)
210 `(macroexpand-all ,form ,environment)
211 `(cl-macroexpand-all ,form ,environment)))
212
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))))
218
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:
223
224 `bol' -- beginning of line
225 `eol' -- end 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
237
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."
240
241 (if (eq (car-safe position) 'quote)
242 (let ((position (eval position)))
243 (cond
244
245 ((eq position 'bol)
246 (if (and (cc-bytecomp-fboundp 'line-beginning-position) (not point))
247 `(line-beginning-position)
248 `(save-excursion
249 ,@(if point `((goto-char ,point)))
250 (beginning-of-line)
251 (point))))
252
253 ((eq position 'eol)
254 (if (and (cc-bytecomp-fboundp 'line-end-position) (not point))
255 `(line-end-position)
256 `(save-excursion
257 ,@(if point `((goto-char ,point)))
258 (end-of-line)
259 (point))))
260
261 ((eq position 'boi)
262 `(save-excursion
263 ,@(if point `((goto-char ,point)))
264 (back-to-indentation)
265 (point)))
266
267 ((eq position 'bod)
268 `(save-excursion
269 ,@(if point `((goto-char ,point)))
270 (c-beginning-of-defun-1)
271 (point)))
272
273 ((eq position 'eod)
274 `(save-excursion
275 ,@(if point `((goto-char ,point)))
276 (c-end-of-defun-1)
277 (point)))
278
279 ((eq position 'bopl)
280 (if (and (cc-bytecomp-fboundp 'line-beginning-position) (not point))
281 `(line-beginning-position 0)
282 `(save-excursion
283 ,@(if point `((goto-char ,point)))
284 (forward-line -1)
285 (point))))
286
287 ((eq position 'bonl)
288 (if (and (cc-bytecomp-fboundp 'line-beginning-position) (not point))
289 `(line-beginning-position 2)
290 `(save-excursion
291 ,@(if point `((goto-char ,point)))
292 (forward-line 1)
293 (point))))
294
295 ((eq position 'eopl)
296 (if (and (cc-bytecomp-fboundp 'line-end-position) (not point))
297 `(line-end-position 0)
298 `(save-excursion
299 ,@(if point `((goto-char ,point)))
300 (beginning-of-line)
301 (or (bobp) (backward-char))
302 (point))))
303
304 ((eq position 'eonl)
305 (if (and (cc-bytecomp-fboundp 'line-end-position) (not point))
306 `(line-end-position 2)
307 `(save-excursion
308 ,@(if point `((goto-char ,point)))
309 (forward-line 1)
310 (end-of-line)
311 (point))))
312
313 ((eq position 'iopl)
314 `(save-excursion
315 ,@(if point `((goto-char ,point)))
316 (forward-line -1)
317 (back-to-indentation)
318 (point)))
319
320 ((eq position 'ionl)
321 `(save-excursion
322 ,@(if point `((goto-char ,point)))
323 (forward-line 1)
324 (back-to-indentation)
325 (point)))
326
327 ((eq position 'bosws)
328 `(save-excursion
329 ,@(if point `((goto-char ,point)))
330 (c-backward-syntactic-ws)
331 (point)))
332
333 ((eq position 'eosws)
334 `(save-excursion
335 ,@(if point `((goto-char ,point)))
336 (c-forward-syntactic-ws)
337 (point)))
338
339 (t (error "Unknown buffer position requested: %s" position))))
340
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
344 ;; the safe side.
345 (message "Warning: c-point long expansion")
346 `(save-excursion
347 ,@(if point `((goto-char ,point)))
348 (let ((position ,position))
349 (cond
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
358 (beginning-of-line)
359 (or (bobp) (backward-char))))
360 ((eq position 'eonl) (progn
361 (forward-line 1)
362 (end-of-line)))
363 ((eq position 'iopl) (progn
364 (forward-line -1)
365 (back-to-indentation)))
366 ((eq position 'ionl) (progn
367 (forward-line 1)
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))))
372 (point))))
373
374 (eval-and-compile
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
378 (with-temp-buffer
379 (let ((parse-sexp-lookup-properties t)
380 (lookup-syntax-properties t))
381 (set-syntax-table (make-syntax-table))
382 (insert "<()>")
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))
388 (forward-sexp)
389 (= (point) (+ 4 (point-min)))))))
390
391 (defvar c-use-extents)
392
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)))
401
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)
406 ;; XEmacs.
407 '(region-active-p)
408 ;; Old Emacs.
409 'mark-active))
410
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)
415 ;; XEmacs.
416 `(if ,activate
417 (zmacs-activate-region)
418 (zmacs-deactivate-region))
419 ;; Emacs.
420 `(setq mark-active ,activate)))
421
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
428 `(prog1
429 (buffer-substring ,start ,end)
430 (delete-region ,start ,end))))
431
432 (defmacro c-safe (&rest body)
433 ;; safely execute BODY, return nil if an error occurred
434 `(condition-case nil
435 (progn ,@body)
436 (error nil)))
437 (put 'c-safe 'lisp-indent-function 0)
438
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)
445 integer))
446
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)
451 'last-command-char
452 'last-command-event))
453
454 (defmacro c-sentence-end ()
455 ;; Get the regular expression `sentence-end'.
456 (if (cc-bytecomp-fboundp 'sentence-end)
457 ;; Emacs 22:
458 `(sentence-end)
459 ;; Emacs <22 + XEmacs
460 `sentence-end))
461
462 (defmacro c-default-value-sentence-end ()
463 ;; Get the default value of the variable sentence end.
464 (if (cc-bytecomp-fboundp 'sentence-end)
465 ;; Emacs 22:
466 `(let (sentence-end) (sentence-end))
467 ;; Emacs <22 + XEmacs
468 `(default-value 'sentence-end)))
469
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.
480
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.
485
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'.
490
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.
494
495 The return value is the value of the last form in BODY."
496 `(let* ((modified (buffer-modified-p)) (buffer-undo-list t)
497 (inhibit-read-only t) (inhibit-point-motion-hooks t)
498 before-change-functions after-change-functions
499 deactivate-mark
500 buffer-file-name buffer-file-truename ; Prevent primitives checking
501 ; for file modification
502 ,@varlist)
503 (unwind-protect
504 (progn ,@body)
505 (and (not modified)
506 (buffer-modified-p)
507 (set-buffer-modified-p nil)))))
508 (put 'c-save-buffer-state 'lisp-indent-function 1)
509
510 (defmacro c-tentative-buffer-changes (&rest body)
511 "Eval BODY and optionally restore the buffer contents to the state it
512 was in before BODY. Any changes are kept if the last form in BODY
513 returns non-nil. Otherwise it's undone using the undo facility, and
514 various other buffer state that might be affected by the changes is
515 restored. That includes the current buffer, point, mark, mark
516 activation \(similar to `save-excursion'), and the modified state.
517 The state is also restored if BODY exits nonlocally.
518
519 If BODY makes a change that unconditionally is undone then wrap this
520 macro inside `c-save-buffer-state'. That way the change can be done
521 even when the buffer is read-only, and without interference from
522 various buffer change hooks."
523 `(let (-tnt-chng-keep
524 -tnt-chng-state)
525 (unwind-protect
526 ;; Insert an undo boundary for use with `undo-more'. We
527 ;; don't use `undo-boundary' since it doesn't insert one
528 ;; unconditionally.
529 (setq buffer-undo-list (cons nil buffer-undo-list)
530 -tnt-chng-state (c-tnt-chng-record-state)
531 -tnt-chng-keep (progn ,@body))
532 (c-tnt-chng-cleanup -tnt-chng-keep -tnt-chng-state))))
533 (put 'c-tentative-buffer-changes 'lisp-indent-function 0)
534
535 (defun c-tnt-chng-record-state ()
536 ;; Used internally in `c-tentative-buffer-changes'.
537 (vector buffer-undo-list ; 0
538 (current-buffer) ; 1
539 ;; No need to use markers for the point and mark; if the
540 ;; undo got out of synch we're hosed anyway.
541 (point) ; 2
542 (mark t) ; 3
543 (c-region-is-active-p) ; 4
544 (buffer-modified-p))) ; 5
545
546 (defun c-tnt-chng-cleanup (keep saved-state)
547 ;; Used internally in `c-tentative-buffer-changes'.
548
549 (let ((saved-undo-list (elt saved-state 0)))
550 (if (eq buffer-undo-list saved-undo-list)
551 ;; No change was done after all.
552 (setq buffer-undo-list (cdr saved-undo-list))
553
554 (if keep
555 ;; Find and remove the undo boundary.
556 (let ((p buffer-undo-list))
557 (while (not (eq (cdr p) saved-undo-list))
558 (setq p (cdr p)))
559 (setcdr p (cdr saved-undo-list)))
560
561 ;; `primitive-undo' will remove the boundary.
562 (setq saved-undo-list (cdr saved-undo-list))
563 (let ((undo-in-progress t))
564 (while (not (eq (setq buffer-undo-list
565 (primitive-undo 1 buffer-undo-list))
566 saved-undo-list))))
567
568 (when (buffer-live-p (elt saved-state 1))
569 (set-buffer (elt saved-state 1))
570 (goto-char (elt saved-state 2))
571 (set-mark (elt saved-state 3))
572 (c-set-region-active (elt saved-state 4))
573 (and (not (elt saved-state 5))
574 (buffer-modified-p)
575 (set-buffer-modified-p nil)))))))
576
577 (defmacro c-forward-syntactic-ws (&optional limit)
578 "Forward skip over syntactic whitespace.
579 Syntactic whitespace is defined as whitespace characters, comments,
580 and preprocessor directives. However if point starts inside a comment
581 or preprocessor directive, the content of it is not treated as
582 whitespace.
583
584 LIMIT sets an upper limit of the forward movement, if specified. If
585 LIMIT or the end of the buffer is reached inside a comment or
586 preprocessor directive, the point will be left there.
587
588 Note that this function might do hidden buffer changes. See the
589 comment at the start of cc-engine.el for more info."
590 (if limit
591 `(save-restriction
592 (narrow-to-region (point-min) (or ,limit (point-max)))
593 (c-forward-sws))
594 '(c-forward-sws)))
595
596 (defmacro c-backward-syntactic-ws (&optional limit)
597 "Backward skip over syntactic whitespace.
598 Syntactic whitespace is defined as whitespace characters, comments,
599 and preprocessor directives. However if point starts inside a comment
600 or preprocessor directive, the content of it is not treated as
601 whitespace.
602
603 LIMIT sets a lower limit of the backward movement, if specified. If
604 LIMIT is reached inside a line comment or preprocessor directive then
605 the point is moved into it past the whitespace at the end.
606
607 Note that this function might do hidden buffer changes. See the
608 comment at the start of cc-engine.el for more info."
609 (if limit
610 `(save-restriction
611 (narrow-to-region (or ,limit (point-min)) (point-max))
612 (c-backward-sws))
613 '(c-backward-sws)))
614
615 (defmacro c-forward-sexp (&optional count)
616 "Move forward across COUNT balanced expressions.
617 A negative COUNT means move backward. Signal an error if the move
618 fails for any reason.
619
620 This is like `forward-sexp' except that it isn't interactive and does
621 not do any user friendly adjustments of the point and that it isn't
622 susceptible to user configurations such as disabling of signals in
623 certain situations."
624 (or count (setq count 1))
625 `(goto-char (scan-sexps (point) ,count)))
626
627 (defmacro c-backward-sexp (&optional count)
628 "See `c-forward-sexp' and reverse directions."
629 (or count (setq count 1))
630 `(c-forward-sexp ,(if (numberp count) (- count) `(- ,count))))
631
632 (defmacro c-safe-scan-lists (from count depth &optional limit)
633 "Like `scan-lists' but returns nil instead of signaling errors
634 for unbalanced parens.
635
636 A limit for the search may be given. FROM is assumed to be on the
637 right side of it."
638 (let ((res (if (featurep 'xemacs)
639 `(scan-lists ,from ,count ,depth nil t)
640 `(c-safe (scan-lists ,from ,count ,depth)))))
641 (if limit
642 `(save-restriction
643 ,(if (numberp count)
644 (if (< count 0)
645 `(narrow-to-region ,limit (point-max))
646 `(narrow-to-region (point-min) ,limit))
647 `(if (< ,count 0)
648 (narrow-to-region ,limit (point-max))
649 (narrow-to-region (point-min) ,limit)))
650 ,res)
651 res)))
652
653 \f
654 ;; Wrappers for common scan-lists cases, mainly because it's almost
655 ;; impossible to get a feel for how that function works.
656
657 (defmacro c-go-list-forward (&optional pos limit)
658 "Move forward across one balanced group of parentheses starting at POS or
659 point. Return POINT when we succeed, NIL when we fail. In the latter case,
660 leave point unmoved.
661
662 A LIMIT for the search may be given. The start position is assumed to be
663 before it."
664 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) 1 0)) (point))))
665 (if limit
666 `(save-restriction
667 (if ,limit
668 (narrow-to-region (point-min) ,limit))
669 ,res)
670 res)))
671
672 (defmacro c-go-list-backward (&optional pos limit)
673 "Move backward across one balanced group of parentheses starting at POS or
674 point. Return POINT when we succeed, NIL when we fail. In the latter case,
675 leave point unmoved.
676
677 A LIMIT for the search may be given. The start position is assumed to be
678 after it."
679 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) -1 0)) (point))))
680 (if limit
681 `(save-restriction
682 (if ,limit
683 (narrow-to-region ,limit (point-max)))
684 ,res)
685 res)))
686
687 (defmacro c-up-list-forward (&optional pos limit)
688 "Return the first position after the list sexp containing POS,
689 or nil if no such position exists. The point is used if POS is left out.
690
691 A limit for the search may be given. The start position is assumed to
692 be before it."
693 `(c-safe-scan-lists ,(or pos `(point)) 1 1 ,limit))
694
695 (defmacro c-up-list-backward (&optional pos limit)
696 "Return the position of the start of the list sexp containing POS,
697 or nil if no such position exists. The point is used if POS is left out.
698
699 A limit for the search may be given. The start position is assumed to
700 be after it."
701 `(c-safe-scan-lists ,(or pos `(point)) -1 1 ,limit))
702
703 (defmacro c-down-list-forward (&optional pos limit)
704 "Return the first position inside the first list sexp after POS,
705 or nil if no such position exists. The point is used if POS is left out.
706
707 A limit for the search may be given. The start position is assumed to
708 be before it."
709 `(c-safe-scan-lists ,(or pos `(point)) 1 -1 ,limit))
710
711 (defmacro c-down-list-backward (&optional pos limit)
712 "Return the last position inside the last list sexp before POS,
713 or nil if no such position exists. The point is used if POS is left out.
714
715 A limit for the search may be given. The start position is assumed to
716 be after it."
717 `(c-safe-scan-lists ,(or pos `(point)) -1 -1 ,limit))
718
719 (defmacro c-go-up-list-forward (&optional pos limit)
720 "Move the point to the first position after the list sexp containing POS,
721 or containing the point if POS is left out. Return t if such a
722 position exists, otherwise nil is returned and the point isn't moved.
723
724 A limit for the search may be given. The start position is assumed to
725 be before it."
726 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) 1 1)) t)))
727 (if limit
728 `(save-restriction
729 (narrow-to-region (point-min) ,limit)
730 ,res)
731 res)))
732
733 (defmacro c-go-up-list-backward (&optional pos limit)
734 "Move the point to the position of the start of the list sexp containing POS,
735 or containing the point if POS is left out. Return t if such a
736 position exists, otherwise nil is returned and the point isn't moved.
737
738 A limit for the search may be given. The start position is assumed to
739 be after it."
740 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) -1 1)) t)))
741 (if limit
742 `(save-restriction
743 (narrow-to-region ,limit (point-max))
744 ,res)
745 res)))
746
747 (defmacro c-go-down-list-forward (&optional pos limit)
748 "Move the point to the first position inside the first list sexp after POS,
749 or before the point if POS is left out. Return t if such a position
750 exists, otherwise nil is returned and the point isn't moved.
751
752 A limit for the search may be given. The start position is assumed to
753 be before it."
754 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) 1 -1)) t)))
755 (if limit
756 `(save-restriction
757 (narrow-to-region (point-min) ,limit)
758 ,res)
759 res)))
760
761 (defmacro c-go-down-list-backward (&optional pos limit)
762 "Move the point to the last position inside the last list sexp before POS,
763 or before the point if POS is left out. Return t if such a position
764 exists, otherwise nil is returned and the point isn't moved.
765
766 A limit for the search may be given. The start position is assumed to
767 be after it."
768 (let ((res `(c-safe (goto-char (scan-lists ,(or pos `(point)) -1 -1)) t)))
769 (if limit
770 `(save-restriction
771 (narrow-to-region ,limit (point-max))
772 ,res)
773 res)))
774
775 \f
776 (defmacro c-beginning-of-defun-1 ()
777 ;; Wrapper around beginning-of-defun.
778 ;;
779 ;; NOTE: This function should contain the only explicit use of
780 ;; beginning-of-defun in CC Mode. Eventually something better than
781 ;; b-o-d will be available and this should be the only place the
782 ;; code needs to change. Everything else should use
783 ;; (c-beginning-of-defun-1)
784 ;;
785 ;; This is really a bit too large to be a macro but that isn't a
786 ;; problem as long as it only is used in one place in
787 ;; `c-parse-state'.
788
789 `(progn
790 (if (and ,(fboundp 'buffer-syntactic-context-depth)
791 c-enable-xemacs-performance-kludge-p)
792 ,(when (fboundp 'buffer-syntactic-context-depth)
793 ;; XEmacs only. This can improve the performance of
794 ;; c-parse-state to between 3 and 60 times faster when
795 ;; braces are hung. It can also degrade performance by
796 ;; about as much when braces are not hung.
797 '(let (beginning-of-defun-function end-of-defun-function
798 pos)
799 (while (not pos)
800 (save-restriction
801 (widen)
802 (setq pos (c-safe-scan-lists
803 (point) -1 (buffer-syntactic-context-depth))))
804 (cond
805 ((bobp) (setq pos (point-min)))
806 ((not pos)
807 (let ((distance (skip-chars-backward "^{")))
808 ;; unbalanced parenthesis, while invalid C code,
809 ;; shouldn't cause an infloop! See unbal.c
810 (when (zerop distance)
811 ;; Punt!
812 (beginning-of-defun)
813 (setq pos (point)))))
814 ((= pos 0))
815 ((not (eq (char-after pos) ?{))
816 (goto-char pos)
817 (setq pos nil))
818 ))
819 (goto-char pos)))
820 ;; Emacs, which doesn't have buffer-syntactic-context-depth
821 (let (beginning-of-defun-function end-of-defun-function)
822 (beginning-of-defun)))
823 ;; if defun-prompt-regexp is non-nil, b-o-d won't leave us at the
824 ;; open brace.
825 (and defun-prompt-regexp
826 (looking-at defun-prompt-regexp)
827 (goto-char (match-end 0)))))
828
829 \f
830 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
831 ;; V i r t u a l S e m i c o l o n s
832 ;;
833 ;; In most CC Mode languages, statements are terminated explicitly by
834 ;; semicolons or closing braces. In some of the CC modes (currently AWK Mode
835 ;; and certain user-specified #define macros in C, C++, etc. (November 2008)),
836 ;; statements are (or can be) terminated by EOLs. Such a statement is said to
837 ;; be terminated by a "virtual semicolon" (VS). A statement terminated by an
838 ;; actual semicolon or brace is never considered to have a VS.
839 ;;
840 ;; The indentation engine (or whatever) tests for a VS at a specific position
841 ;; by invoking the macro `c-at-vsemi-p', which in its turn calls the mode
842 ;; specific function (if any) which is the value of the language variable
843 ;; `c-at-vsemi-p-fn'. This function should only use "low-level" features of
844 ;; CC Mode, i.e. features which won't trigger infinite recursion. ;-) The
845 ;; actual details of what constitutes a VS in a language are thus encapsulated
846 ;; in code specific to that language (e.g. cc-awk.el). `c-at-vsemi-p' returns
847 ;; non-nil if point (or the optional parameter POS) is at a VS, nil otherwise.
848 ;;
849 ;; The language specific function might well do extensive analysis of the
850 ;; source text, and may use a caching scheme to speed up repeated calls.
851 ;;
852 ;; The "virtual semicolon" lies just after the last non-ws token on the line.
853 ;; Like POINT, it is considered to lie between two characters. For example,
854 ;; at the place shown in the following AWK source line:
855 ;;
856 ;; kbyte = 1024 # 1000 if you're not picky
857 ;; ^
858 ;; |
859 ;; Virtual Semicolon
860 ;;
861 ;; In addition to `c-at-vsemi-p-fn', a mode may need to supply a function for
862 ;; `c-vsemi-status-unknown-p-fn'. The macro `c-vsemi-status-unknown-p' is a
863 ;; rather recondite kludge. It exists because the function
864 ;; `c-beginning-of-statement-1' sometimes tests for VSs as an optimization,
865 ;; but `c-at-vsemi-p' might well need to call `c-beginning-of-statement-1' in
866 ;; its calculations, thus potentially leading to infinite recursion.
867 ;;
868 ;; The macro `c-vsemi-status-unknown-p' resolves this problem; it may return
869 ;; non-nil at any time; returning nil is a guarantee that an immediate
870 ;; invocation of `c-at-vsemi-p' at point will NOT call
871 ;; `c-beginning-of-statement-1'. `c-vsemi-status-unknown-p' may not itself
872 ;; call `c-beginning-of-statement-1'.
873 ;;
874 ;; The macro `c-vsemi-status-unknown-p' will typically check the caching
875 ;; scheme used by the `c-at-vsemi-p-fn', hence the name - the status is
876 ;; "unknown" if there is no cache entry current for the line.
877 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
878
879 (defmacro c-at-vsemi-p (&optional pos)
880 ;; Is there a virtual semicolon (not a real one or a }) at POS (defaults to
881 ;; point)? Always returns nil for languages which don't have Virtual
882 ;; semicolons.
883 ;; This macro might do hidden buffer changes.
884 `(if c-at-vsemi-p-fn
885 (funcall c-at-vsemi-p-fn ,@(if pos `(,pos)))))
886
887 (defmacro c-vsemi-status-unknown-p ()
888 ;; Return NIL only if it can be guaranteed that an immediate
889 ;; (c-at-vsemi-p) will NOT call c-beginning-of-statement-1. Otherwise,
890 ;; return non-nil. (See comments above). The function invoked by this
891 ;; macro MUST NOT UNDER ANY CIRCUMSTANCES itself call
892 ;; c-beginning-of-statement-1.
893 ;; Languages which don't have EOL terminated statements always return NIL
894 ;; (they _know_ there's no vsemi ;-).
895 `(if c-vsemi-status-unknown-p-fn (funcall c-vsemi-status-unknown-p-fn)))
896
897 \f
898 (defmacro c-benign-error (format &rest args)
899 ;; Formats an error message for the echo area and dings, i.e. like
900 ;; `error' but doesn't abort.
901 `(progn
902 (message ,format ,@args)
903 (ding)))
904
905 (defmacro c-with-syntax-table (table &rest code)
906 ;; Temporarily switches to the specified syntax table in a failsafe
907 ;; way to execute code.
908 ;; Maintainers' note: If TABLE is `c++-template-syntax-table', DON'T call
909 ;; any forms inside this that call `c-parse-state'. !!!!
910 `(let ((c-with-syntax-table-orig-table (syntax-table)))
911 (unwind-protect
912 (progn
913 (set-syntax-table ,table)
914 ,@code)
915 (set-syntax-table c-with-syntax-table-orig-table))))
916 (put 'c-with-syntax-table 'lisp-indent-function 1)
917
918 (defmacro c-skip-ws-forward (&optional limit)
919 "Skip over any whitespace following point.
920 This function skips over horizontal and vertical whitespace and line
921 continuations."
922 (if limit
923 `(let ((limit (or ,limit (point-max))))
924 (while (progn
925 ;; skip-syntax-* doesn't count \n as whitespace..
926 (skip-chars-forward " \t\n\r\f\v" limit)
927 (when (and (eq (char-after) ?\\)
928 (< (point) limit))
929 (forward-char)
930 (or (eolp)
931 (progn (backward-char) nil))))))
932 '(while (progn
933 (skip-chars-forward " \t\n\r\f\v")
934 (when (eq (char-after) ?\\)
935 (forward-char)
936 (or (eolp)
937 (progn (backward-char) nil)))))))
938
939 (defmacro c-skip-ws-backward (&optional limit)
940 "Skip over any whitespace preceding point.
941 This function skips over horizontal and vertical whitespace and line
942 continuations."
943 (if limit
944 `(let ((limit (or ,limit (point-min))))
945 (while (progn
946 ;; skip-syntax-* doesn't count \n as whitespace..
947 (skip-chars-backward " \t\n\r\f\v" limit)
948 (and (eolp)
949 (eq (char-before) ?\\)
950 (> (point) limit)))
951 (backward-char)))
952 '(while (progn
953 (skip-chars-backward " \t\n\r\f\v")
954 (and (eolp)
955 (eq (char-before) ?\\)))
956 (backward-char))))
957
958 (eval-and-compile
959 (defvar c-langs-are-parametric nil))
960
961 (defmacro c-major-mode-is (mode)
962 "Return non-nil if the current CC Mode major mode is MODE.
963 MODE is either a mode symbol or a list of mode symbols."
964
965 (if c-langs-are-parametric
966 ;; Inside a `c-lang-defconst'.
967 `(c-lang-major-mode-is ,mode)
968
969 (if (eq (car-safe mode) 'quote)
970 (let ((mode (eval mode)))
971 (if (listp mode)
972 `(memq c-buffer-is-cc-mode ',mode)
973 `(eq c-buffer-is-cc-mode ',mode)))
974
975 `(let ((mode ,mode))
976 (if (listp mode)
977 (memq c-buffer-is-cc-mode mode)
978 (eq c-buffer-is-cc-mode mode))))))
979
980 \f
981 ;; Macros/functions to handle so-called "char properties", which are
982 ;; properties set on a single character and that never spread to any
983 ;; other characters.
984
985 (eval-and-compile
986 ;; Constant used at compile time to decide whether or not to use
987 ;; XEmacs extents. Check all the extent functions we'll use since
988 ;; some packages might add compatibility aliases for some of them in
989 ;; Emacs.
990 (defconst c-use-extents (and (cc-bytecomp-fboundp 'extent-at)
991 (cc-bytecomp-fboundp 'set-extent-property)
992 (cc-bytecomp-fboundp 'set-extent-properties)
993 (cc-bytecomp-fboundp 'make-extent)
994 (cc-bytecomp-fboundp 'extent-property)
995 (cc-bytecomp-fboundp 'delete-extent)
996 (cc-bytecomp-fboundp 'map-extents))))
997
998 (defconst c-<-as-paren-syntax '(4 . ?>))
999 (put 'c-<-as-paren-syntax 'syntax-table c-<-as-paren-syntax)
1000
1001 (defconst c->-as-paren-syntax '(5 . ?<))
1002 (put 'c->-as-paren-syntax 'syntax-table c->-as-paren-syntax)
1003
1004 ;; `c-put-char-property' is complex enough in XEmacs and Emacs < 21 to
1005 ;; make it a function.
1006 (defalias 'c-put-char-property-fun
1007 (cc-eval-when-compile
1008 (cond (c-use-extents
1009 ;; XEmacs.
1010 (byte-compile
1011 (lambda (pos property value)
1012 (let ((ext (extent-at pos nil property)))
1013 (if ext
1014 (set-extent-property ext property value)
1015 (set-extent-properties (make-extent pos (1+ pos))
1016 (cons property
1017 (cons value
1018 '(start-open t
1019 end-open t)))))))))
1020
1021 ((not (cc-bytecomp-boundp 'text-property-default-nonsticky))
1022 ;; In Emacs < 21 we have to mess with the `rear-nonsticky' property.
1023 (byte-compile
1024 (lambda (pos property value)
1025 (put-text-property pos (1+ pos) property value)
1026 (let ((prop (get-text-property pos 'rear-nonsticky)))
1027 (or (memq property prop)
1028 (put-text-property pos (1+ pos)
1029 'rear-nonsticky
1030 (cons property prop)))))))
1031 ;; This won't be used for anything.
1032 (t 'ignore))))
1033 (cc-bytecomp-defun c-put-char-property-fun) ; Make it known below.
1034
1035 (defmacro c-put-char-property (pos property value)
1036 ;; Put the given property with the given value on the character at
1037 ;; POS and make it front and rear nonsticky, or start and end open
1038 ;; in XEmacs vocabulary. If the character already has the given
1039 ;; property then the value is replaced, and the behavior is
1040 ;; undefined if that property has been put by some other function.
1041 ;; PROPERTY is assumed to be constant.
1042 ;;
1043 ;; If there's a `text-property-default-nonsticky' variable (Emacs
1044 ;; 21) then it's assumed that the property is present on it.
1045 ;;
1046 ;; This macro does a hidden buffer change.
1047 (setq property (eval property))
1048 (if (or c-use-extents
1049 (not (cc-bytecomp-boundp 'text-property-default-nonsticky)))
1050 ;; XEmacs and Emacs < 21.
1051 `(c-put-char-property-fun ,pos ',property ,value)
1052 ;; In Emacs 21 we got the `rear-nonsticky' property covered
1053 ;; by `text-property-default-nonsticky'.
1054 `(let ((-pos- ,pos))
1055 (put-text-property -pos- (1+ -pos-) ',property ,value))))
1056
1057 (defmacro c-get-char-property (pos property)
1058 ;; Get the value of the given property on the character at POS if
1059 ;; it's been put there by `c-put-char-property'. PROPERTY is
1060 ;; assumed to be constant.
1061 (setq property (eval property))
1062 (if c-use-extents
1063 ;; XEmacs.
1064 `(let ((ext (extent-at ,pos nil ',property)))
1065 (if ext (extent-property ext ',property)))
1066 ;; Emacs.
1067 `(get-text-property ,pos ',property)))
1068
1069 ;; `c-clear-char-property' is complex enough in Emacs < 21 to make it
1070 ;; a function, since we have to mess with the `rear-nonsticky' property.
1071 (defalias 'c-clear-char-property-fun
1072 (cc-eval-when-compile
1073 (unless (or c-use-extents
1074 (cc-bytecomp-boundp 'text-property-default-nonsticky))
1075 (byte-compile
1076 (lambda (pos property)
1077 (when (get-text-property pos property)
1078 (remove-text-properties pos (1+ pos) (list property nil))
1079 (put-text-property pos (1+ pos)
1080 'rear-nonsticky
1081 (delq property (get-text-property
1082 pos 'rear-nonsticky)))))))))
1083 (cc-bytecomp-defun c-clear-char-property-fun) ; Make it known below.
1084
1085 (defmacro c-clear-char-property (pos property)
1086 ;; Remove the given property on the character at POS if it's been put
1087 ;; there by `c-put-char-property'. PROPERTY is assumed to be
1088 ;; constant.
1089 ;;
1090 ;; This macro does a hidden buffer change.
1091 (setq property (eval property))
1092 (cond (c-use-extents
1093 ;; XEmacs.
1094 `(let ((ext (extent-at ,pos nil ',property)))
1095 (if ext (delete-extent ext))))
1096 ((cc-bytecomp-boundp 'text-property-default-nonsticky)
1097 ;; In Emacs 21 we got the `rear-nonsticky' property covered
1098 ;; by `text-property-default-nonsticky'.
1099 `(let ((pos ,pos))
1100 (remove-text-properties pos (1+ pos)
1101 '(,property nil))))
1102 (t
1103 ;; Emacs < 21.
1104 `(c-clear-char-property-fun ,pos ',property))))
1105
1106 (defmacro c-clear-char-properties (from to property)
1107 ;; Remove all the occurrences of the given property in the given
1108 ;; region that has been put with `c-put-char-property'. PROPERTY is
1109 ;; assumed to be constant.
1110 ;;
1111 ;; Note that this function does not clean up the property from the
1112 ;; lists of the `rear-nonsticky' properties in the region, if such
1113 ;; are used. Thus it should not be used for common properties like
1114 ;; `syntax-table'.
1115 ;;
1116 ;; This macro does hidden buffer changes.
1117 (setq property (eval property))
1118 (if c-use-extents
1119 ;; XEmacs.
1120 `(map-extents (lambda (ext ignored)
1121 (delete-extent ext))
1122 nil ,from ,to nil nil ',property)
1123 ;; Emacs.
1124 `(remove-text-properties ,from ,to '(,property nil))))
1125
1126 (defmacro c-search-forward-char-property (property value &optional limit)
1127 "Search forward for a text-property PROPERTY having value VALUE.
1128 LIMIT bounds the search. The comparison is done with `equal'.
1129
1130 Leave point just after the character, and set the match data on
1131 this character, and return point. If VALUE isn't found, Return
1132 nil; point is then left undefined."
1133 `(let ((place (point)))
1134 (while
1135 (and
1136 (< place ,(or limit '(point-max)))
1137 (not (equal (c-get-char-property place ,property) ,value)))
1138 (setq place (c-next-single-property-change
1139 place ,property nil ,(or limit '(point-max)))))
1140 (when (< place ,(or limit '(point-max)))
1141 (goto-char place)
1142 (search-forward-regexp ".") ; to set the match-data.
1143 (point))))
1144
1145 (defmacro c-search-backward-char-property (property value &optional limit)
1146 "Search backward for a text-property PROPERTY having value VALUE.
1147 LIMIT bounds the search. The comparison is done with `equal'.
1148
1149 Leave point just before the character, set the match data on this
1150 character, and return point. If VALUE isn't found, Return nil;
1151 point is then left undefined."
1152 `(let ((place (point)))
1153 (while
1154 (and
1155 (> place ,(or limit '(point-min)))
1156 (not (equal (c-get-char-property (1- place) ,property) ,value)))
1157 (setq place (,(if (and c-use-extents
1158 (fboundp 'previous-single-char-property-change))
1159 ;; XEmacs > 2005-01-25.
1160 'previous-single-char-property-change
1161 ;; Emacs and earlier XEmacs.
1162 'previous-single-property-change)
1163 place ,property nil ,(or limit '(point-min)))))
1164 (when (> place ,(or limit '(point-min)))
1165 (goto-char place)
1166 (search-backward-regexp ".") ; to set the match-data.
1167 (point))))
1168
1169 (defun c-clear-char-property-with-value-function (from to property value)
1170 "Remove all text-properties PROPERTY from the region (FROM, TO)
1171 which have the value VALUE, as tested by `equal'. These
1172 properties are assumed to be over individual characters, having
1173 been put there by c-put-char-property. POINT remains unchanged."
1174 (let ((place from) end-place)
1175 (while ; loop round occurrences of (PROPERTY VALUE)
1176 (progn
1177 (while ; loop round changes in PROPERTY till we find VALUE
1178 (and
1179 (< place to)
1180 (not (equal (get-text-property place property) value)))
1181 (setq place (c-next-single-property-change place property nil to)))
1182 (< place to))
1183 (setq end-place (c-next-single-property-change place property nil to))
1184 (remove-text-properties place end-place (cons property nil))
1185 ;; Do we have to do anything with stickiness here?
1186 (setq place end-place))))
1187
1188 (defmacro c-clear-char-property-with-value (from to property value)
1189 "Remove all text-properties PROPERTY from the region [FROM, TO)
1190 which have the value VALUE, as tested by `equal'. These
1191 properties are assumed to be over individual characters, having
1192 been put there by c-put-char-property. POINT remains unchanged."
1193 (if c-use-extents
1194 ;; XEmacs
1195 `(let ((-property- ,property))
1196 (map-extents (lambda (ext val)
1197 (if (equal (extent-property ext -property-) val)
1198 (delete-extent ext)))
1199 nil ,from ,to ,value nil -property-))
1200 ;; GNU Emacs
1201 `(c-clear-char-property-with-value-function ,from ,to ,property ,value)))
1202 \f
1203 ;; Macros to put overlays (Emacs) or extents (XEmacs) on buffer text.
1204 ;; For our purposes, these are characterized by being possible to
1205 ;; remove again without affecting the other text properties in the
1206 ;; buffer that got overridden when they were put.
1207
1208 (defmacro c-put-overlay (from to property value)
1209 ;; Put an overlay/extent covering the given range in the current
1210 ;; buffer. It's currently undefined whether it's front/end sticky
1211 ;; or not. The overlay/extent object is returned.
1212 (if (cc-bytecomp-fboundp 'make-overlay)
1213 ;; Emacs.
1214 `(let ((ol (make-overlay ,from ,to)))
1215 (overlay-put ol ,property ,value)
1216 ol)
1217 ;; XEmacs.
1218 `(let ((ext (make-extent ,from ,to)))
1219 (set-extent-property ext ,property ,value)
1220 ext)))
1221
1222 (defmacro c-delete-overlay (overlay)
1223 ;; Deletes an overlay/extent object previously retrieved using
1224 ;; `c-put-overlay'.
1225 (if (cc-bytecomp-fboundp 'make-overlay)
1226 ;; Emacs.
1227 `(delete-overlay ,overlay)
1228 ;; XEmacs.
1229 `(delete-extent ,overlay)))
1230
1231 \f
1232 ;; Make edebug understand the macros.
1233 ;(eval-after-load "edebug" ; 2006-07-09: def-edebug-spec is now in subr.el.
1234 ; '(progn
1235 (def-edebug-spec cc-eval-when-compile (&rest def-form))
1236 (def-edebug-spec c-point t)
1237 (def-edebug-spec c-set-region-active t)
1238 (def-edebug-spec c-safe t)
1239 (def-edebug-spec c-save-buffer-state let*)
1240 (def-edebug-spec c-tentative-buffer-changes t)
1241 (def-edebug-spec c-forward-syntactic-ws t)
1242 (def-edebug-spec c-backward-syntactic-ws t)
1243 (def-edebug-spec c-forward-sexp t)
1244 (def-edebug-spec c-backward-sexp t)
1245 (def-edebug-spec c-up-list-forward t)
1246 (def-edebug-spec c-up-list-backward t)
1247 (def-edebug-spec c-down-list-forward t)
1248 (def-edebug-spec c-down-list-backward t)
1249 (def-edebug-spec c-add-syntax t)
1250 (def-edebug-spec c-add-class-syntax t)
1251 (def-edebug-spec c-benign-error t)
1252 (def-edebug-spec c-with-syntax-table t)
1253 (def-edebug-spec c-skip-ws-forward t)
1254 (def-edebug-spec c-skip-ws-backward t)
1255 (def-edebug-spec c-major-mode-is t)
1256 (def-edebug-spec c-put-char-property t)
1257 (def-edebug-spec c-get-char-property t)
1258 (def-edebug-spec c-clear-char-property t)
1259 (def-edebug-spec c-clear-char-properties t)
1260 (def-edebug-spec c-put-overlay t)
1261 (def-edebug-spec c-delete-overlay t)
1262 (def-edebug-spec c-self-bind-state-cache t);))
1263
1264 \f
1265 ;;; Functions.
1266
1267 ;; Note: All these after the macros, to be on safe side in avoiding
1268 ;; bugs where macros are defined too late. These bugs often only show
1269 ;; when the files are compiled in a certain order within the same
1270 ;; session.
1271
1272 (defsubst c-end-of-defun-1 ()
1273 ;; Replacement for end-of-defun that use c-beginning-of-defun-1.
1274 (let ((start (point)))
1275 ;; Skip forward into the next defun block. Don't bother to avoid
1276 ;; comments, literals etc, since beginning-of-defun doesn't do that
1277 ;; anyway.
1278 (skip-chars-forward "^}")
1279 (c-beginning-of-defun-1)
1280 (if (eq (char-after) ?{)
1281 (c-forward-sexp))
1282 (if (< (point) start)
1283 (goto-char (point-max)))))
1284
1285 (defmacro c-mark-<-as-paren (pos)
1286 ;; Mark the "<" character at POS as a template opener using the
1287 ;; `syntax-table' property either directly (XEmacs) or via a `category'
1288 ;; property (GNU Emacs).
1289 ;;
1290 ;; This function does a hidden buffer change. Note that we use
1291 ;; indirection through the `category' text property. This allows us to
1292 ;; toggle the property in all template brackets simultaneously and
1293 ;; cheaply. We use this, for instance, in `c-parse-state'.
1294 (if c-use-category
1295 `(c-put-char-property ,pos 'category 'c-<-as-paren-syntax)
1296 `(c-put-char-property ,pos 'syntax-table c-<-as-paren-syntax)))
1297
1298
1299 (defmacro c-mark->-as-paren (pos)
1300 ;; Mark the ">" character at POS as an sexp list closer using the
1301 ;; `syntax-table' property either directly (XEmacs) or via a `category'
1302 ;; property (GNU Emacs).
1303 ;;
1304 ;; This function does a hidden buffer change. Note that we use
1305 ;; indirection through the `category' text property. This allows us to
1306 ;; toggle the property in all template brackets simultaneously and
1307 ;; cheaply. We use this, for instance, in `c-parse-state'.
1308 (if c-use-category
1309 `(c-put-char-property ,pos 'category 'c->-as-paren-syntax)
1310 `(c-put-char-property ,pos 'syntax-table c->-as-paren-syntax)))
1311
1312 (defmacro c-unmark-<->-as-paren (pos)
1313 ;; Unmark the "<" or "<" character at POS as an sexp list opener using the
1314 ;; `syntax-table' property either directly or indirectly through a
1315 ;; `category' text property.
1316 ;;
1317 ;; This function does a hidden buffer change. Note that we try to use
1318 ;; indirection through the `category' text property. This allows us to
1319 ;; toggle the property in all template brackets simultaneously and
1320 ;; cheaply. We use this, for instance, in `c-parse-state'.
1321 `(c-clear-char-property ,pos ,(if c-use-category ''category ''syntax-table)))
1322
1323 (defsubst c-suppress-<->-as-parens ()
1324 ;; Suppress the syntactic effect of all marked < and > as parens. Note
1325 ;; that this effect is NOT buffer local. You should probably not use
1326 ;; this directly, but only through the macro
1327 ;; `c-with-<->-as-parens-suppressed'
1328 (put 'c-<-as-paren-syntax 'syntax-table nil)
1329 (put 'c->-as-paren-syntax 'syntax-table nil))
1330
1331 (defsubst c-restore-<->-as-parens ()
1332 ;; Restore the syntactic effect of all marked <s and >s as parens. This
1333 ;; has no effect on unmarked <s and >s
1334 (put 'c-<-as-paren-syntax 'syntax-table c-<-as-paren-syntax)
1335 (put 'c->-as-paren-syntax 'syntax-table c->-as-paren-syntax))
1336
1337 (defmacro c-with-<->-as-parens-suppressed (&rest forms)
1338 ;; Like progn, except that the paren property is suppressed on all
1339 ;; template brackets whilst they are running. This macro does a hidden
1340 ;; buffer change.
1341 `(unwind-protect
1342 (progn
1343 (c-suppress-<->-as-parens)
1344 ,@forms)
1345 (c-restore-<->-as-parens)))
1346
1347 ;;;;;;;;;;;;;;;
1348
1349 (defconst c-cpp-delimiter '(14)) ; generic comment syntax
1350 ;; This is the value of the `category' text property placed on every #
1351 ;; which introduces a CPP construct and every EOL (or EOB, or character
1352 ;; preceding //, etc.) which terminates it. We can instantly "comment
1353 ;; out" all CPP constructs by giving `c-cpp-delimiter' a syntax-table
1354 ;; property '(14) (generic comment delimiter).
1355 (defmacro c-set-cpp-delimiters (beg end)
1356 ;; This macro does a hidden buffer change.
1357 `(progn
1358 (c-put-char-property ,beg 'category 'c-cpp-delimiter)
1359 (if (< ,end (point-max))
1360 (c-put-char-property ,end 'category 'c-cpp-delimiter))))
1361 (defmacro c-clear-cpp-delimiters (beg end)
1362 ;; This macro does a hidden buffer change.
1363 `(progn
1364 (c-clear-char-property ,beg 'category)
1365 (if (< ,end (point-max))
1366 (c-clear-char-property ,end 'category))))
1367
1368 (defsubst c-comment-out-cpps ()
1369 ;; Render all preprocessor constructs syntactically commented out.
1370 (put 'c-cpp-delimiter 'syntax-table c-cpp-delimiter))
1371 (defsubst c-uncomment-out-cpps ()
1372 ;; Restore the syntactic visibility of preprocessor constructs.
1373 (put 'c-cpp-delimiter 'syntax-table nil))
1374
1375 (defmacro c-with-cpps-commented-out (&rest forms)
1376 ;; Execute FORMS... whilst the syntactic effect of all characters in
1377 ;; all CPP regions is suppressed. In particular, this is to suppress
1378 ;; the syntactic significance of parens/braces/brackets to functions
1379 ;; such as `scan-lists' and `parse-partial-sexp'.
1380 `(unwind-protect
1381 (c-save-buffer-state ()
1382 (c-comment-out-cpps)
1383 ,@forms)
1384 (c-save-buffer-state ()
1385 (c-uncomment-out-cpps))))
1386
1387 (defmacro c-with-all-but-one-cpps-commented-out (beg end &rest forms)
1388 ;; Execute FORMS... whilst the syntactic effect of all characters in
1389 ;; every CPP region APART FROM THE ONE BETWEEN BEG and END is
1390 ;; suppressed.
1391 `(unwind-protect
1392 (c-save-buffer-state ()
1393 (save-restriction
1394 (widen)
1395 (c-clear-cpp-delimiters ,beg ,end))
1396 ,`(c-with-cpps-commented-out ,@forms))
1397 (c-save-buffer-state ()
1398 (save-restriction
1399 (widen)
1400 (c-set-cpp-delimiters ,beg ,end)))))
1401
1402 (defmacro c-self-bind-state-cache (&rest forms)
1403 ;; Bind the state cache to itself and execute the FORMS. Return the result
1404 ;; of the last FORM executed. It is assumed that no buffer changes will
1405 ;; happen in FORMS, and no hidden buffer changes which could affect the
1406 ;; parsing will be made by FORMS.
1407 `(let* ((c-state-cache (copy-tree c-state-cache))
1408 (c-state-cache-good-pos c-state-cache-good-pos)
1409 ;(c-state-nonlit-pos-cache (copy-tree c-state-nonlit-pos-cache))
1410 ;(c-state-nonlit-pos-cache-limit c-state-nonlit-pos-cache-limit)
1411 ;(c-state-semi-nonlit-pos-cache (copy-tree c-state-semi-nonlit-pos-cache))
1412 ;(c-state-semi-nonlit-pos-cache-limit c-state-semi-nonlit-pos-cache)
1413 (c-state-brace-pair-desert (copy-tree c-state-brace-pair-desert))
1414 (c-state-point-min c-state-point-min)
1415 (c-state-point-min-lit-type c-state-point-min-lit-type)
1416 (c-state-point-min-lit-start c-state-point-min-lit-start)
1417 (c-state-min-scan-pos c-state-min-scan-pos)
1418 (c-state-old-cpp-beg-marker (if (markerp c-state-old-cpp-beg-marker)
1419 (copy-marker c-state-old-cpp-beg-marker)
1420 c-state-old-cpp-beg-marker))
1421 (c-state-old-cpp-beg (if (markerp c-state-old-cpp-beg)
1422 c-state-old-cpp-beg-marker
1423 c-state-old-cpp-beg))
1424 (c-state-old-cpp-end-marker (if (markerp c-state-old-cpp-end-marker)
1425 (copy-marker c-state-old-cpp-end-marker)
1426 c-state-old-cpp-end-marker))
1427 (c-state-old-cpp-end (if (markerp c-state-old-cpp-end)
1428 c-state-old-cpp-end-marker
1429 c-state-old-cpp-end))
1430 (c-parse-state-state c-parse-state-state))
1431 (prog1
1432 (progn ,@forms)
1433 (if (markerp c-state-old-cpp-beg-marker)
1434 (move-marker c-state-old-cpp-beg-marker nil))
1435 (if (markerp c-state-old-cpp-end-marker)
1436 (move-marker c-state-old-cpp-end-marker nil)))))
1437
1438 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1439 ;; The following macros are to be used only in `c-parse-state' and its
1440 ;; subroutines. Their main purpose is to simplify the handling of C++/Java
1441 ;; template delimiters and CPP macros. In GNU Emacs, this is done slickly by
1442 ;; the judicious use of 'category properties. These don't exist in XEmacs.
1443 ;;
1444 ;; Note: in the following macros, there is no special handling for parentheses
1445 ;; inside CPP constructs. That is because CPPs are always syntactically
1446 ;; balanced, thanks to `c-neutralize-CPP-line' in cc-mode.el.
1447 (defmacro c-sc-scan-lists-no-category+1+1 (from)
1448 ;; Do a (scan-lists FROM 1 1). Any finishing position which either (i) is
1449 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1450 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1451 `(let ((here (point))
1452 (pos (scan-lists ,from 1 1)))
1453 (while (eq (char-before pos) ?>)
1454 (setq pos (scan-lists pos 1 1)))
1455 pos))
1456
1457 (defmacro c-sc-scan-lists-no-category+1-1 (from)
1458 ;; Do a (scan-lists FROM 1 -1). Any finishing position which either (i) is
1459 ;; determined by an angle bracket; or (ii) is inside a macro whose start
1460 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1461 `(let ((here (point))
1462 (pos (scan-lists ,from 1 -1)))
1463 (while (eq (char-before pos) ?<)
1464 (setq pos (scan-lists pos 1 1))
1465 (setq pos (scan-lists pos 1 -1)))
1466 pos))
1467
1468 (defmacro c-sc-scan-lists-no-category-1+1 (from)
1469 ;; Do a (scan-lists FROM -1 1). Any finishing position which either (i) is
1470 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1471 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1472 `(let ((here (point))
1473 (pos (scan-lists ,from -1 1)))
1474 (while (eq (char-after pos) ?<)
1475 (setq pos (scan-lists pos -1 1)))
1476 pos))
1477
1478 (defmacro c-sc-scan-lists-no-category-1-1 (from)
1479 ;; Do a (scan-lists FROM -1 -1). Any finishing position which either (i) is
1480 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1481 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1482 `(let ((here (point))
1483 (pos (scan-lists ,from -1 -1)))
1484 (while (eq (char-after pos) ?>)
1485 (setq pos (scan-lists pos -1 1))
1486 (setq pos (scan-lists pos -1 -1)))
1487 pos))
1488
1489 (defmacro c-sc-scan-lists (from count depth)
1490 (if c-use-category
1491 `(scan-lists ,from ,count ,depth)
1492 (cond
1493 ((and (eq count 1) (eq depth 1))
1494 `(c-sc-scan-lists-no-category+1+1 ,from))
1495 ((and (eq count 1) (eq depth -1))
1496 `(c-sc-scan-lists-no-category+1-1 ,from))
1497 ((and (eq count -1) (eq depth 1))
1498 `(c-sc-scan-lists-no-category-1+1 ,from))
1499 ((and (eq count -1) (eq depth -1))
1500 `(c-sc-scan-lists-no-category-1-1 ,from))
1501 (t (error "Invalid parameter(s) to c-sc-scan-lists")))))
1502
1503
1504 (defun c-sc-parse-partial-sexp-no-category (from to targetdepth stopbefore
1505 oldstate)
1506 ;; Do a parse-partial-sexp using the supplied arguments, disregarding
1507 ;; template/generic delimiters < > and disregarding macros other than the
1508 ;; one at POINT-MACRO-START.
1509 ;;
1510 ;; NOTE that STOPBEFORE must be nil. TARGETDEPTH should be one less than
1511 ;; the depth in OLDSTATE. This function is thus a SPECIAL PURPOSE variation
1512 ;; on parse-partial-sexp, designed for calling from
1513 ;; `c-remove-stale-state-cache'.
1514 ;;
1515 ;; Any finishing position which is determined by an angle bracket delimiter
1516 ;; doesn't count as a finishing position.
1517 ;;
1518 ;; Note there is no special handling of CPP constructs here, since these are
1519 ;; always syntactically balanced (thanks to `c-neutralize-CPP-line').
1520 (let ((state
1521 (parse-partial-sexp from to targetdepth stopbefore oldstate)))
1522 (while
1523 (and (< (point) to)
1524 ;; We must have hit targetdepth.
1525 (or (eq (char-before) ?<)
1526 (eq (char-before) ?>)))
1527 (setcar state
1528 (if (memq (char-before) '(?> ?\) ?\} ?\]))
1529 (1+ (car state))
1530 (1- (car state))))
1531 (setq state
1532 (parse-partial-sexp (point) to targetdepth stopbefore oldstate)))
1533 state))
1534
1535 (defmacro c-sc-parse-partial-sexp (from to &optional targetdepth stopbefore
1536 oldstate)
1537 (if c-use-category
1538 `(parse-partial-sexp ,from ,to ,targetdepth ,stopbefore ,oldstate)
1539 `(c-sc-parse-partial-sexp-no-category ,from ,to ,targetdepth ,stopbefore
1540 ,oldstate)))
1541
1542 \f
1543 (defvar c-emacs-features)
1544
1545 (defmacro c-looking-at-non-alphnumspace ()
1546 "Are we looking at a character which isn't alphanumeric or space?"
1547 (if (memq 'gen-comment-delim c-emacs-features)
1548 `(looking-at
1549 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\|\\s!\\)")
1550 `(or (looking-at
1551 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\)"
1552 (let ((prop (c-get-char-property (point) 'syntax-table)))
1553 (eq prop '(14))))))) ; '(14) is generic comment delimiter.
1554
1555 \f
1556 (defsubst c-intersect-lists (list alist)
1557 ;; return the element of ALIST that matches the first element found
1558 ;; in LIST. Uses assq.
1559 (let (match)
1560 (while (and list
1561 (not (setq match (assq (car list) alist))))
1562 (setq list (cdr list)))
1563 match))
1564
1565 (defsubst c-lookup-lists (list alist1 alist2)
1566 ;; first, find the first entry from LIST that is present in ALIST1,
1567 ;; then find the entry in ALIST2 for that entry.
1568 (assq (car (c-intersect-lists list alist1)) alist2))
1569
1570 (defsubst c-langelem-sym (langelem)
1571 "Return the syntactic symbol in LANGELEM.
1572
1573 LANGELEM is either a cons cell on the \"old\" form given as the first
1574 argument to lineup functions or a syntactic element on the \"new\"
1575 form as used in `c-syntactic-element'."
1576 (car langelem))
1577
1578 (defsubst c-langelem-pos (langelem)
1579 "Return the anchor position in LANGELEM, or nil if there is none.
1580
1581 LANGELEM is either a cons cell on the \"old\" form given as the first
1582 argument to lineup functions or a syntactic element on the \"new\"
1583 form as used in `c-syntactic-element'."
1584 (if (consp (cdr langelem))
1585 (car-safe (cdr langelem))
1586 (cdr langelem)))
1587
1588 (defun c-langelem-col (langelem &optional preserve-point)
1589 "Return the column of the anchor position in LANGELEM.
1590 Also move the point to that position unless PRESERVE-POINT is non-nil.
1591
1592 LANGELEM is either a cons cell on the \"old\" form given as the first
1593 argument to lineup functions or a syntactic element on the \"new\"
1594 form as used in `c-syntactic-element'."
1595 (let ((pos (c-langelem-pos langelem))
1596 (here (point)))
1597 (if pos
1598 (progn
1599 (goto-char pos)
1600 (prog1 (current-column)
1601 (if preserve-point
1602 (goto-char here))))
1603 0)))
1604
1605 (defsubst c-langelem-2nd-pos (langelem)
1606 "Return the secondary position in LANGELEM, or nil if there is none.
1607
1608 LANGELEM is typically a syntactic element on the \"new\" form as used
1609 in `c-syntactic-element'. It may also be a cons cell as passed in the
1610 first argument to lineup functions, but then the returned value always
1611 will be nil."
1612 (car-safe (cdr-safe (cdr-safe langelem))))
1613
1614 (defsubst c-keep-region-active ()
1615 ;; Do whatever is necessary to keep the region active in XEmacs.
1616 ;; This is not needed for Emacs.
1617 (and (boundp 'zmacs-region-stays)
1618 (setq zmacs-region-stays t)))
1619
1620 (put 'c-mode 'c-mode-prefix "c-")
1621 (put 'c++-mode 'c-mode-prefix "c++-")
1622 (put 'objc-mode 'c-mode-prefix "objc-")
1623 (put 'java-mode 'c-mode-prefix "java-")
1624 (put 'idl-mode 'c-mode-prefix "idl-")
1625 (put 'pike-mode 'c-mode-prefix "pike-")
1626 (put 'awk-mode 'c-mode-prefix "awk-")
1627
1628 (defsubst c-mode-symbol (suffix)
1629 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1630 the corresponding symbol."
1631 (or c-buffer-is-cc-mode
1632 (error "Not inside a CC Mode based mode"))
1633 (let ((mode-prefix (get c-buffer-is-cc-mode 'c-mode-prefix)))
1634 (or mode-prefix
1635 (error "%S has no mode prefix known to `c-mode-symbol'"
1636 c-buffer-is-cc-mode))
1637 (intern (concat mode-prefix suffix))))
1638
1639 (defsubst c-mode-var (suffix)
1640 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1641 the value of the variable with that name."
1642 (symbol-value (c-mode-symbol suffix)))
1643
1644 (defsubst c-got-face-at (pos faces)
1645 "Return non-nil if position POS in the current buffer has any of the
1646 faces in the list FACES."
1647 (let ((pos-faces (get-text-property pos 'face)))
1648 (if (consp pos-faces)
1649 (progn
1650 (while (and pos-faces
1651 (not (memq (car pos-faces) faces)))
1652 (setq pos-faces (cdr pos-faces)))
1653 pos-faces)
1654 (memq pos-faces faces))))
1655
1656 (defsubst c-face-name-p (facename)
1657 ;; Return t if FACENAME is the name of a face. This method is
1658 ;; necessary since facep in XEmacs only returns t for the actual
1659 ;; face objects (while it's only their names that are used just
1660 ;; about anywhere else) without providing a predicate that tests
1661 ;; face names.
1662 (memq facename (face-list)))
1663
1664 (defun c-concat-separated (list separator)
1665 "Like `concat' on LIST, but separate each element with SEPARATOR.
1666 Notably, null elements in LIST are ignored."
1667 (mapconcat 'identity (delete nil (append list nil)) separator))
1668
1669 (defun c-make-keywords-re (adorn list &optional mode)
1670 "Make a regexp that matches all the strings the list.
1671 Duplicates and nil elements in the list are removed. The
1672 resulting regexp may contain zero or more submatch expressions.
1673
1674 If ADORN is t there will be at least one submatch and the first
1675 surrounds the matched alternative, and the regexp will also not match
1676 a prefix of any identifier. Adorned regexps cannot be appended. The
1677 language variable `c-nonsymbol-key' is used to make the adornment.
1678
1679 A value `appendable' for ADORN is like above, but all alternatives in
1680 the list that end with a word constituent char will have \\> appended
1681 instead, so that the regexp remains appendable. Note that this
1682 variant doesn't always guarantee that an identifier prefix isn't
1683 matched since the symbol constituent `_' is normally considered a
1684 nonword token by \\>.
1685
1686 The optional MODE specifies the language to get `c-nonsymbol-key' from
1687 when it's needed. The default is the current language taken from
1688 `c-buffer-is-cc-mode'."
1689
1690 (setq list (delete nil (delete-dups list)))
1691 (if list
1692 (let (re)
1693
1694 (if (eq adorn 'appendable)
1695 ;; This is kludgy but it works: Search for a string that
1696 ;; doesn't occur in any word in LIST. Append it to all
1697 ;; the alternatives where we want to add \>. Run through
1698 ;; `regexp-opt' and then replace it with \>.
1699 (let ((unique "") pos)
1700 (while (let (found)
1701 (setq unique (concat unique "@")
1702 pos list)
1703 (while (and pos
1704 (if (string-match unique (car pos))
1705 (progn (setq found t)
1706 nil)
1707 t))
1708 (setq pos (cdr pos)))
1709 found))
1710 (setq pos list)
1711 (while pos
1712 (if (string-match "\\w\\'" (car pos))
1713 (setcar pos (concat (car pos) unique)))
1714 (setq pos (cdr pos)))
1715 (setq re (regexp-opt list))
1716 (setq pos 0)
1717 (while (string-match unique re pos)
1718 (setq pos (+ (match-beginning 0) 2)
1719 re (replace-match "\\>" t t re))))
1720
1721 (setq re (regexp-opt list)))
1722
1723 ;; Emacs 20 and XEmacs (all versions so far) has a buggy
1724 ;; regexp-opt that doesn't always cope with strings containing
1725 ;; newlines. This kludge doesn't handle shy parens correctly
1726 ;; so we can't advice regexp-opt directly with it.
1727 (let (fail-list)
1728 (while list
1729 (and (string-match "\n" (car list)) ; To speed it up a little.
1730 (not (string-match (concat "\\`\\(" re "\\)\\'")
1731 (car list)))
1732 (setq fail-list (cons (car list) fail-list)))
1733 (setq list (cdr list)))
1734 (when fail-list
1735 (setq re (concat re
1736 "\\|"
1737 (mapconcat
1738 (if (eq adorn 'appendable)
1739 (lambda (str)
1740 (if (string-match "\\w\\'" str)
1741 (concat (regexp-quote str)
1742 "\\>")
1743 (regexp-quote str)))
1744 'regexp-quote)
1745 (sort fail-list
1746 (lambda (a b)
1747 (> (length a) (length b))))
1748 "\\|")))))
1749
1750 ;; Add our own grouping parenthesis around re instead of
1751 ;; passing adorn to `regexp-opt', since in XEmacs it makes the
1752 ;; top level grouping "shy".
1753 (cond ((eq adorn 'appendable)
1754 (concat "\\(" re "\\)"))
1755 (adorn
1756 (concat "\\(" re "\\)"
1757 "\\("
1758 (c-get-lang-constant 'c-nonsymbol-key nil mode)
1759 "\\|$\\)"))
1760 (t
1761 re)))
1762
1763 ;; Produce a regexp that matches nothing.
1764 (if adorn
1765 "\\(\\<\\>\\)"
1766 "\\<\\>")))
1767
1768 (put 'c-make-keywords-re 'lisp-indent-function 1)
1769
1770 (defun c-make-bare-char-alt (chars &optional inverted)
1771 "Make a character alternative string from the list of characters CHARS.
1772 The returned string is of the type that can be used with
1773 `skip-chars-forward' and `skip-chars-backward'. If INVERTED is
1774 non-nil, a caret is prepended to invert the set."
1775 ;; This function ought to be in the elisp core somewhere.
1776 (let ((str (if inverted "^" "")) char char2)
1777 (setq chars (sort (append chars nil) `<))
1778 (while chars
1779 (setq char (pop chars))
1780 (if (memq char '(?\\ ?^ ?-))
1781 ;; Quoting necessary (this method only works in the skip
1782 ;; functions).
1783 (setq str (format "%s\\%c" str char))
1784 (setq str (format "%s%c" str char)))
1785 ;; Check for range.
1786 (setq char2 char)
1787 (while (and chars (>= (1+ char2) (car chars)))
1788 (setq char2 (pop chars)))
1789 (unless (= char char2)
1790 (if (< (1+ char) char2)
1791 (setq str (format "%s-%c" str char2))
1792 (push char2 chars))))
1793 str))
1794
1795 ;; Leftovers from (X)Emacs 19 compatibility.
1796 (defalias 'c-regexp-opt 'regexp-opt)
1797 (defalias 'c-regexp-opt-depth 'regexp-opt-depth)
1798
1799 \f
1800 ;; Figure out what features this Emacs has
1801
1802 (cc-bytecomp-defvar open-paren-in-column-0-is-defun-start)
1803
1804 (defvar lookup-syntax-properties) ;XEmacs.
1805
1806 (defconst c-emacs-features
1807 (let (list)
1808
1809 (if (boundp 'infodock-version)
1810 ;; I've no idea what this actually is, but it's legacy. /mast
1811 (setq list (cons 'infodock list)))
1812
1813 ;; XEmacs uses 8-bit modify-syntax-entry flags.
1814 ;; Emacs uses a 1-bit flag. We will have to set up our
1815 ;; syntax tables differently to handle this.
1816 (let ((table (copy-syntax-table))
1817 entry)
1818 (modify-syntax-entry ?a ". 12345678" table)
1819 (cond
1820 ;; Emacs
1821 ((arrayp table)
1822 (setq entry (aref table ?a))
1823 ;; In Emacs, table entries are cons cells
1824 (if (consp entry) (setq entry (car entry))))
1825 ;; XEmacs
1826 ((fboundp 'get-char-table)
1827 (setq entry (get-char-table ?a table)))
1828 ;; incompatible
1829 (t (error "CC Mode is incompatible with this version of Emacs")))
1830 (setq list (cons (if (= (logand (lsh entry -16) 255) 255)
1831 '8-bit
1832 '1-bit)
1833 list)))
1834
1835 ;; Check whether beginning/end-of-defun call
1836 ;; beginning/end-of-defun-function nicely, passing through the
1837 ;; argument and respecting the return code.
1838 (let* (mark-ring
1839 (bod-param 'foo) (eod-param 'foo)
1840 (beginning-of-defun-function
1841 (lambda (&optional arg)
1842 (or (eq bod-param 'foo) (setq bod-param 'bar))
1843 (and (eq bod-param 'foo)
1844 (setq bod-param arg)
1845 (eq arg 3))))
1846 (end-of-defun-function
1847 (lambda (&optional arg)
1848 (and (eq eod-param 'foo)
1849 (setq eod-param arg)
1850 (eq arg 3)))))
1851 (if (save-excursion (and (beginning-of-defun 3) (eq bod-param 3)
1852 (not (beginning-of-defun))
1853 (end-of-defun 3) (eq eod-param 3)
1854 (not (end-of-defun))))
1855 (setq list (cons 'argumentative-bod-function list))))
1856
1857 ;; Record whether the `category' text property works.
1858 (if c-use-category (setq list (cons 'category-properties list)))
1859
1860 (let ((buf (generate-new-buffer " test"))
1861 parse-sexp-lookup-properties
1862 parse-sexp-ignore-comments
1863 lookup-syntax-properties) ; XEmacs
1864 (with-current-buffer buf
1865 (set-syntax-table (make-syntax-table))
1866
1867 ;; For some reason we have to set some of these after the
1868 ;; buffer has been made current. (Specifically,
1869 ;; `parse-sexp-ignore-comments' in Emacs 21.)
1870 (setq parse-sexp-lookup-properties t
1871 parse-sexp-ignore-comments t
1872 lookup-syntax-properties t)
1873
1874 ;; Find out if the `syntax-table' text property works.
1875 (modify-syntax-entry ?< ".")
1876 (modify-syntax-entry ?> ".")
1877 (insert "<()>")
1878 (c-mark-<-as-paren (point-min))
1879 (c-mark->-as-paren (+ 3 (point-min)))
1880 (goto-char (point-min))
1881 (c-forward-sexp)
1882 (if (= (point) (+ 4 (point-min)))
1883 (setq list (cons 'syntax-properties list))
1884 (error (concat
1885 "CC Mode is incompatible with this version of Emacs - "
1886 "support for the `syntax-table' text property "
1887 "is required.")))
1888
1889 ;; Find out if "\\s!" (generic comment delimiters) work.
1890 (c-safe
1891 (modify-syntax-entry ?x "!")
1892 (if (string-match "\\s!" "x")
1893 (setq list (cons 'gen-comment-delim list))))
1894
1895 ;; Find out if "\\s|" (generic string delimiters) work.
1896 (c-safe
1897 (modify-syntax-entry ?x "|")
1898 (if (string-match "\\s|" "x")
1899 (setq list (cons 'gen-string-delim list))))
1900
1901 ;; See if POSIX char classes work.
1902 (when (and (string-match "[[:alpha:]]" "a")
1903 ;; All versions of Emacs 21 so far haven't fixed
1904 ;; char classes in `skip-chars-forward' and
1905 ;; `skip-chars-backward'.
1906 (progn
1907 (delete-region (point-min) (point-max))
1908 (insert "foo123")
1909 (skip-chars-backward "[:alnum:]")
1910 (bobp))
1911 (= (skip-chars-forward "[:alpha:]") 3))
1912 (setq list (cons 'posix-char-classes list)))
1913
1914 ;; See if `open-paren-in-column-0-is-defun-start' exists and
1915 ;; isn't buggy (Emacs >= 21.4).
1916 (when (boundp 'open-paren-in-column-0-is-defun-start)
1917 (let ((open-paren-in-column-0-is-defun-start nil)
1918 (parse-sexp-ignore-comments t))
1919 (delete-region (point-min) (point-max))
1920 (set-syntax-table (make-syntax-table))
1921 (modify-syntax-entry ?\' "\"")
1922 (cond
1923 ;; XEmacs. Afaik this is currently an Emacs-only
1924 ;; feature, but it's good to be prepared.
1925 ((memq '8-bit list)
1926 (modify-syntax-entry ?/ ". 1456")
1927 (modify-syntax-entry ?* ". 23"))
1928 ;; Emacs
1929 ((memq '1-bit list)
1930 (modify-syntax-entry ?/ ". 124b")
1931 (modify-syntax-entry ?* ". 23")))
1932 (modify-syntax-entry ?\n "> b")
1933 (insert "/* '\n () */")
1934 (backward-sexp)
1935 (if (bobp)
1936 (setq list (cons 'col-0-paren list)))))
1937
1938 (set-buffer-modified-p nil))
1939 (kill-buffer buf))
1940
1941 ;; See if `parse-partial-sexp' returns the eighth element.
1942 (if (c-safe (>= (length (save-excursion
1943 (parse-partial-sexp (point) (point))))
1944 10))
1945 (setq list (cons 'pps-extended-state list))
1946 (error (concat
1947 "CC Mode is incompatible with this version of Emacs - "
1948 "`parse-partial-sexp' has to return at least 10 elements.")))
1949
1950 ;;(message "c-emacs-features: %S" list)
1951 list)
1952 "A list of certain features in the (X)Emacs you are using.
1953 There are many flavors of Emacs out there, each with different
1954 features supporting those needed by CC Mode. The following values
1955 might be present:
1956
1957 `8-bit' 8 bit syntax entry flags (XEmacs style).
1958 `1-bit' 1 bit syntax entry flags (Emacs style).
1959 `argumentative-bod-function' beginning-of-defun and end-of-defun pass
1960 ARG through to beginning/end-of-defun-function.
1961 `syntax-properties' It works to override the syntax for specific characters
1962 in the buffer with the `syntax-table' property. It's
1963 always set - CC Mode no longer works in emacsen without
1964 this feature.
1965 `category-properties' Syntax routines can add a level of indirection to text
1966 properties using the `category' property.
1967 `gen-comment-delim' Generic comment delimiters work
1968 (i.e. the syntax class `!').
1969 `gen-string-delim' Generic string delimiters work
1970 (i.e. the syntax class `|').
1971 `pps-extended-state' `parse-partial-sexp' returns a list with at least 10
1972 elements, i.e. it contains the position of the start of
1973 the last comment or string. It's always set - CC Mode
1974 no longer works in emacsen without this feature.
1975 `posix-char-classes' The regexp engine understands POSIX character classes.
1976 `col-0-paren' It's possible to turn off the ad-hoc rule that a paren
1977 in column zero is the start of a defun.
1978 `infodock' This is Infodock (based on XEmacs).
1979
1980 `8-bit' and `1-bit' are mutually exclusive.")
1981
1982 \f
1983 ;;; Some helper constants.
1984
1985 ;; If the regexp engine supports POSIX char classes then we can use
1986 ;; them to handle extended charsets correctly.
1987 (if (memq 'posix-char-classes c-emacs-features)
1988 (progn
1989 (defconst c-alpha "[:alpha:]")
1990 (defconst c-alnum "[:alnum:]")
1991 (defconst c-digit "[:digit:]")
1992 (defconst c-upper "[:upper:]")
1993 (defconst c-lower "[:lower:]"))
1994 (defconst c-alpha "a-zA-Z")
1995 (defconst c-alnum "a-zA-Z0-9")
1996 (defconst c-digit "0-9")
1997 (defconst c-upper "A-Z")
1998 (defconst c-lower "a-z"))
1999
2000 \f
2001 ;;; System for handling language dependent constants.
2002
2003 ;; This is used to set various language dependent data in a flexible
2004 ;; way: Language constants can be built from the values of other
2005 ;; language constants, also those for other languages. They can also
2006 ;; process the values of other language constants uniformly across all
2007 ;; the languages. E.g. one language constant can list all the type
2008 ;; keywords in each language, and another can build a regexp for each
2009 ;; language from those lists without code duplication.
2010 ;;
2011 ;; Language constants are defined with `c-lang-defconst', and their
2012 ;; value forms (referred to as source definitions) are evaluated only
2013 ;; on demand when requested for a particular language with
2014 ;; `c-lang-const'. It's therefore possible to refer to the values of
2015 ;; constants defined later in the file, or in another file, just as
2016 ;; long as all the relevant `c-lang-defconst' have been loaded when
2017 ;; `c-lang-const' is actually evaluated from somewhere else.
2018 ;;
2019 ;; `c-lang-const' forms are also evaluated at compile time and
2020 ;; replaced with the values they produce. Thus there's no overhead
2021 ;; for this system when compiled code is used - only the values
2022 ;; actually used in the code are present, and the file(s) containing
2023 ;; the `c-lang-defconst' forms don't need to be loaded at all then.
2024 ;; There are however safeguards to make sure that they can be loaded
2025 ;; to get the source definitions for the values if there's a mismatch
2026 ;; in compiled versions, or if `c-lang-const' is used uncompiled.
2027 ;;
2028 ;; Note that the source definitions in a `c-lang-defconst' form are
2029 ;; compiled into the .elc file where it stands; there's no need to
2030 ;; load the source file to get it.
2031 ;;
2032 ;; See cc-langs.el for more details about how this system is deployed
2033 ;; in CC Mode, and how the associated language variable system
2034 ;; (`c-lang-defvar') works. That file also contains a lot of
2035 ;; examples.
2036
2037 (defun c-add-language (mode base-mode)
2038 "Declare a new language in the language dependent variable system.
2039 This is intended to be used by modes that inherit CC Mode to add new
2040 languages. It should be used at the top level before any calls to
2041 `c-lang-defconst'. MODE is the mode name symbol for the new language,
2042 and BASE-MODE is the mode name symbol for the language in CC Mode that
2043 is to be the template for the new mode.
2044
2045 The exact effect of BASE-MODE is to make all language constants that
2046 haven't got a setting in the new language fall back to their values in
2047 BASE-MODE. It does not have any effect outside the language constant
2048 system."
2049 (unless (string-match "\\`\\(.*-\\)mode\\'" (symbol-name mode))
2050 (error "The mode name symbol `%s' must end with \"-mode\"" mode))
2051 (put mode 'c-mode-prefix (match-string 1 (symbol-name mode)))
2052 (unless (get base-mode 'c-mode-prefix)
2053 (error "Unknown base mode `%s'" base-mode))
2054 (put mode 'c-fallback-mode base-mode))
2055
2056 (defvar c-lang-constants (make-vector 151 0))
2057 ;; Obarray used as a cache to keep track of the language constants.
2058 ;; The constants stored are those defined by `c-lang-defconst' and the values
2059 ;; computed by `c-lang-const'. It's mostly used at compile time but it's not
2060 ;; stored in compiled files.
2061
2062 ;; The obarray contains all the language constants as symbols. The
2063 ;; value cells hold the evaluated values as alists where each car is
2064 ;; the mode name symbol and the corresponding cdr is the evaluated
2065 ;; value in that mode. The property lists hold the source definitions
2066 ;; and other miscellaneous data. The obarray might also contain
2067 ;; various other symbols, but those don't have any variable bindings.
2068
2069 (defvar c-lang-const-expansion nil)
2070
2071 ;; Ugly hack to pull in the definition of `cc-bytecomp-compiling-or-loading'
2072 ;; from cc-bytecomp to make it available at loadtime. This is the same
2073 ;; mechanism used in cc-mode.el for `c-populate-syntax-table'.
2074 (defalias 'cc-bytecomp-compiling-or-loading
2075 (cc-eval-when-compile
2076 (let ((f (symbol-function 'cc-bytecomp-compiling-or-loading)))
2077 (if (byte-code-function-p f) f (byte-compile f)))))
2078
2079 (defsubst c-get-current-file ()
2080 ;; Return the base name of the current file.
2081 (let* ((c-or-l (cc-bytecomp-compiling-or-loading))
2082 (file
2083 (cond
2084 ((eq c-or-l 'loading) load-file-name)
2085 ((eq c-or-l 'compiling) byte-compile-dest-file)
2086 ((null c-or-l) (buffer-file-name)))))
2087 (and file
2088 (file-name-sans-extension
2089 (file-name-nondirectory file)))))
2090
2091 (defmacro c-lang-defconst-eval-immediately (form)
2092 "Can be used inside a VAL in `c-lang-defconst' to evaluate FORM
2093 immediately, i.e. at the same time as the `c-lang-defconst' form
2094 itself is evaluated."
2095 ;; Evaluate at macro expansion time, i.e. in the
2096 ;; `c--macroexpand-all' inside `c-lang-defconst'.
2097 (eval form))
2098
2099 (defmacro c-lang-defconst (name &rest args)
2100 "Set the language specific values of the language constant NAME.
2101 The second argument can optionally be a docstring. The rest of the
2102 arguments are one or more repetitions of LANG VAL where LANG specifies
2103 the language(s) that VAL applies to. LANG is the name of the
2104 language, i.e. the mode name without the \"-mode\" suffix, or a list
2105 of such language names, or t for all languages. VAL is a form to
2106 evaluate to get the value.
2107
2108 If LANG isn't t or one of the core languages in CC Mode, it must
2109 have been declared with `c-add-language'.
2110
2111 Neither NAME, LANG nor VAL are evaluated directly - they should not be
2112 quoted. `c-lang-defconst-eval-immediately' can however be used inside
2113 VAL to evaluate parts of it directly.
2114
2115 When VAL is evaluated for some language, that language is temporarily
2116 made current so that `c-lang-const' without an explicit language can
2117 be used inside VAL to refer to the value of a language constant in the
2118 same language. That is particularly useful if LANG is t.
2119
2120 VAL is not evaluated right away but rather when the value is requested
2121 with `c-lang-const'. Thus it's possible to use `c-lang-const' inside
2122 VAL to refer to language constants that haven't been defined yet.
2123 However, if the definition of a language constant is in another file
2124 then that file must be loaded \(at compile time) before it's safe to
2125 reference the constant.
2126
2127 The assignments in ARGS are processed in sequence like `setq', so
2128 \(c-lang-const NAME) may be used inside a VAL to refer to the last
2129 assigned value to this language constant, or a value that it has
2130 gotten in another earlier loaded file.
2131
2132 To work well with repeated loads and interactive reevaluation, only
2133 one `c-lang-defconst' for each NAME is permitted per file. If there
2134 already is one it will be completely replaced; the value in the
2135 earlier definition will not affect `c-lang-const' on the same
2136 constant. A file is identified by its base name."
2137
2138 (let* ((sym (intern (symbol-name name) c-lang-constants))
2139 ;; Make `c-lang-const' expand to a straightforward call to
2140 ;; `c-get-lang-constant' in `c--macroexpand-all' below.
2141 ;;
2142 ;; (The default behavior, i.e. to expand to a call inside
2143 ;; `eval-when-compile' should be equivalent, since that macro
2144 ;; should only expand to its content if it's used inside a
2145 ;; form that's already evaluated at compile time. It's
2146 ;; however necessary to use our cover macro
2147 ;; `cc-eval-when-compile' due to bugs in `eval-when-compile',
2148 ;; and it expands to a bulkier form that in this case only is
2149 ;; unnecessary garbage that we don't want to store in the
2150 ;; language constant source definitions.)
2151 (c-lang-const-expansion 'call)
2152 (c-langs-are-parametric t)
2153 (file (intern
2154 (or (c-get-current-file)
2155 (error "`c-lang-defconst' can only be used in a file"))))
2156 bindings
2157 pre-files)
2158
2159 (or (symbolp name)
2160 (error "Not a symbol: %S" name))
2161
2162 (when (stringp (car-safe args))
2163 ;; The docstring is hardly used anywhere since there's no normal
2164 ;; symbol to attach it to. It's primarily for getting the right
2165 ;; format in the source.
2166 (put sym 'variable-documentation (car args))
2167 (setq args (cdr args)))
2168
2169 (or args
2170 (error "No assignments in `c-lang-defconst' for %S" name))
2171
2172 ;; Rework ARGS to an association list to make it easier to handle.
2173 ;; It's reversed at the same time to make it easier to implement
2174 ;; the demand-driven (i.e. reversed) evaluation in `c-lang-const'.
2175 (while args
2176 (let ((assigned-mode
2177 (cond ((eq (car args) t) t)
2178 ((symbolp (car args))
2179 (list (intern (concat (symbol-name (car args))
2180 "-mode"))))
2181 ((listp (car args))
2182 (mapcar (lambda (lang)
2183 (or (symbolp lang)
2184 (error "Not a list of symbols: %S"
2185 (car args)))
2186 (intern (concat (symbol-name lang)
2187 "-mode")))
2188 (car args)))
2189 (t (error "Not a symbol or a list of symbols: %S"
2190 (car args)))))
2191 val)
2192
2193 (or (cdr args)
2194 (error "No value for %S" (car args)))
2195 (setq args (cdr args)
2196 val (car args))
2197
2198 ;; Emacs has a weird bug where it seems to fail to read
2199 ;; backquote lists from byte compiled files correctly (,@
2200 ;; forms, to be specific), so make sure the bindings in the
2201 ;; expansion below don't contain any backquote stuff.
2202 ;; (XEmacs handles it correctly and doesn't need this for that
2203 ;; reason, but we also use this expansion handle
2204 ;; `c-lang-defconst-eval-immediately' and to register
2205 ;; dependencies on the `c-lang-const's in VAL.)
2206 (setq val (c--macroexpand-all val))
2207
2208 (setq bindings `(cons (cons ',assigned-mode (lambda () ,val)) ,bindings)
2209 args (cdr args))))
2210
2211 ;; Compile in the other files that have provided source
2212 ;; definitions for this symbol, to make sure the order in the
2213 ;; `source' property is correct even when files are loaded out of
2214 ;; order.
2215 (setq pre-files (mapcar 'car (get sym 'source)))
2216 (if (memq file pre-files)
2217 ;; This can happen when the source file (e.g. cc-langs.el) is first
2218 ;; loaded as source, setting a 'source property entry, and then itself
2219 ;; being compiled.
2220 (setq pre-files (cdr (memq file pre-files))))
2221 ;; Reverse to get the right load order.
2222 (setq pre-files (nreverse pre-files))
2223
2224 `(eval-and-compile
2225 (c-define-lang-constant ',name ,bindings
2226 ,@(and pre-files `(',pre-files))))))
2227
2228 (put 'c-lang-defconst 'lisp-indent-function 1)
2229 ;(eval-after-load "edebug" ; 2006-07-09: def-edebug-spec is now in subr.el.
2230 ; '
2231 (def-edebug-spec c-lang-defconst
2232 (&define name [&optional stringp] [&rest sexp def-form]))
2233
2234 (defun c-define-lang-constant (name bindings &optional pre-files)
2235 ;; Used by `c-lang-defconst'.
2236
2237 (let* ((sym (intern (symbol-name name) c-lang-constants))
2238 (source (get sym 'source))
2239 (file (intern
2240 (or (c-get-current-file)
2241 (error "`c-lang-defconst' must be used in a file"))))
2242 (elem (assq file source)))
2243
2244 ;;(when (cdr-safe elem)
2245 ;; (message "Language constant %s redefined in %S" name file))
2246
2247 ;; Note that the order in the source alist is relevant. Like how
2248 ;; `c-lang-defconst' reverses the bindings, this reverses the
2249 ;; order between files so that the last to evaluate comes first.
2250 (unless elem
2251 (while pre-files
2252 (unless (assq (car pre-files) source)
2253 (setq source (cons (list (car pre-files)) source)))
2254 (setq pre-files (cdr pre-files)))
2255 (put sym 'source (cons (setq elem (list file)) source)))
2256
2257 (setcdr elem bindings)
2258
2259 ;; Bind the symbol as a variable, or clear any earlier evaluated
2260 ;; value it has.
2261 (set sym nil)
2262
2263 ;; Clear the evaluated values that depend on this source.
2264 (let ((agenda (get sym 'dependents))
2265 (visited (make-vector 101 0))
2266 ptr)
2267 (while agenda
2268 (setq sym (car agenda)
2269 agenda (cdr agenda))
2270 (intern (symbol-name sym) visited)
2271 (set sym nil)
2272 (setq ptr (get sym 'dependents))
2273 (while ptr
2274 (setq sym (car ptr)
2275 ptr (cdr ptr))
2276 (unless (intern-soft (symbol-name sym) visited)
2277 (setq agenda (cons sym agenda))))))
2278
2279 name))
2280
2281 (defmacro c-lang-const (name &optional lang)
2282 "Get the mode specific value of the language constant NAME in language LANG.
2283 LANG is the name of the language, i.e. the mode name without the
2284 \"-mode\" suffix. If used inside `c-lang-defconst' or
2285 `c-lang-defvar', LANG may be left out to refer to the current
2286 language. NAME and LANG are not evaluated so they should not be
2287 quoted."
2288
2289 (or (symbolp name)
2290 (error "Not a symbol: %S" name))
2291 (or (symbolp lang)
2292 (error "Not a symbol: %S" lang))
2293
2294 (let ((sym (intern (symbol-name name) c-lang-constants))
2295 (mode (when lang (intern (concat (symbol-name lang) "-mode")))))
2296
2297 (or (get mode 'c-mode-prefix) (null mode)
2298 (error "Unknown language %S: no `c-mode-prefix' property"
2299 lang))
2300
2301 (if (eq c-lang-const-expansion 'immediate)
2302 ;; No need to find out the source file(s) when we evaluate
2303 ;; immediately since all the info is already there in the
2304 ;; `source' property.
2305 `',(c-get-lang-constant name nil mode)
2306
2307 (let ((source-files
2308 (let ((file (c-get-current-file)))
2309 (if file (setq file (intern file)))
2310 ;; Get the source file(s) that must be loaded to get the value
2311 ;; of the constant. If the symbol isn't defined yet we assume
2312 ;; that its definition will come later in this file, and thus
2313 ;; are no file dependencies needed.
2314 (nreverse
2315 ;; Reverse to get the right load order.
2316 (c--mapcan (lambda (elem)
2317 (if (eq file (car elem))
2318 nil ; Exclude our own file.
2319 (list (car elem))))
2320 (get sym 'source)))))
2321
2322 ;; Make some effort to do a compact call to
2323 ;; `c-get-lang-constant' since it will be compiled in.
2324 (args (and mode `(',mode))))
2325
2326 (if (or source-files args)
2327 (push (and source-files `',source-files) args))
2328
2329 (if (or (eq c-lang-const-expansion 'call)
2330 (and (not c-lang-const-expansion)
2331 (not mode))
2332 (not (cc-bytecomp-is-compiling)))
2333 ;; Either a straight call is requested in the context, or
2334 ;; we're in an "uncontrolled" context and got no language,
2335 ;; or we're not being byte compiled so the compile time
2336 ;; stuff below is unnecessary.
2337 `(c-get-lang-constant ',name ,@args)
2338
2339 ;; Being compiled. If the loading and compiling version is
2340 ;; the same we use a value that is evaluated at compile time,
2341 ;; otherwise it's evaluated at runtime.
2342 `(if (eq c-version-sym ',c-version-sym)
2343 (cc-eval-when-compile
2344 (c-get-lang-constant ',name ,@args))
2345 (c-get-lang-constant ',name ,@args)))))))
2346
2347 (defvar c-lang-constants-under-evaluation nil
2348 "Alist of constants in the process of being evaluated.
2349 The `cdr' of each entry indicates how far we've looked in the list
2350 of definitions, so that the def for var FOO in c-mode can be defined in
2351 terms of the def for that same var FOO (which will then rely on the
2352 fallback definition for all modes, to break the cycle).")
2353
2354 (defconst c-lang--novalue "novalue")
2355
2356 (defun c-get-lang-constant (name &optional source-files mode)
2357 ;; Used by `c-lang-const'.
2358
2359 (or mode
2360 (setq mode c-buffer-is-cc-mode)
2361 (error "No current language"))
2362
2363 (let* ((sym (intern (symbol-name name) c-lang-constants))
2364 (source (get sym 'source))
2365 elem
2366 (eval-in-sym (and c-lang-constants-under-evaluation
2367 (caar c-lang-constants-under-evaluation))))
2368
2369 ;; Record the dependencies between this symbol and the one we're
2370 ;; being evaluated in.
2371 (when eval-in-sym
2372 (or (memq eval-in-sym (get sym 'dependents))
2373 (put sym 'dependents (cons eval-in-sym (get sym 'dependents)))))
2374
2375 ;; Make sure the source files have entries on the `source'
2376 ;; property so that loading will take place when necessary.
2377 (while source-files
2378 (unless (assq (car source-files) source)
2379 (put sym 'source
2380 (setq source (cons (list (car source-files)) source)))
2381 ;; Might pull in more definitions which affect the value. The
2382 ;; clearing of dependent values etc is done when the
2383 ;; definition is encountered during the load; this is just to
2384 ;; jump past the check for a cached value below.
2385 (set sym nil))
2386 (setq source-files (cdr source-files)))
2387
2388 (if (and (boundp sym)
2389 (setq elem (assq mode (symbol-value sym))))
2390 (cdr elem)
2391
2392 ;; Check if an evaluation of this symbol is already underway.
2393 ;; In that case we just continue with the "assignment" before
2394 ;; the one currently being evaluated, thereby creating the
2395 ;; illusion if a `setq'-like sequence of assignments.
2396 (let* ((c-buffer-is-cc-mode mode)
2397 (source-pos
2398 (or (assq sym c-lang-constants-under-evaluation)
2399 (cons sym (vector source nil))))
2400 ;; Append `c-lang-constants-under-evaluation' even if an
2401 ;; earlier entry is found. It's only necessary to get
2402 ;; the recording of dependencies above correct.
2403 (c-lang-constants-under-evaluation
2404 (cons source-pos c-lang-constants-under-evaluation))
2405 (fallback (get mode 'c-fallback-mode))
2406 value
2407 ;; Make sure the recursion limits aren't very low
2408 ;; since the `c-lang-const' dependencies can go deep.
2409 (max-specpdl-size (max max-specpdl-size 3000))
2410 (max-lisp-eval-depth (max max-lisp-eval-depth 1000)))
2411
2412 (if (if fallback
2413 (let ((backup-source-pos (copy-sequence (cdr source-pos))))
2414 (and
2415 ;; First try the original mode but don't accept an
2416 ;; entry matching all languages since the fallback
2417 ;; mode might have an explicit entry before that.
2418 (eq (setq value (c-find-assignment-for-mode
2419 (cdr source-pos) mode nil name))
2420 c-lang--novalue)
2421 ;; Try again with the fallback mode from the
2422 ;; original position. Note that
2423 ;; `c-buffer-is-cc-mode' still is the real mode if
2424 ;; language parameterization takes place.
2425 (eq (setq value (c-find-assignment-for-mode
2426 (setcdr source-pos backup-source-pos)
2427 fallback t name))
2428 c-lang--novalue)))
2429 ;; A simple lookup with no fallback mode.
2430 (eq (setq value (c-find-assignment-for-mode
2431 (cdr source-pos) mode t name))
2432 c-lang--novalue))
2433 (error
2434 "`%s' got no (prior) value in %S (might be a cyclic reference)"
2435 name mode))
2436
2437 (condition-case err
2438 (setq value (funcall value))
2439 (error
2440 ;; Print a message to aid in locating the error. We don't
2441 ;; print the error itself since that will be done later by
2442 ;; some caller higher up.
2443 (message "Eval error in the `c-lang-defconst' for `%S' in %s:"
2444 sym mode)
2445 (makunbound sym)
2446 (signal (car err) (cdr err))))
2447
2448 (set sym (cons (cons mode value) (symbol-value sym)))
2449 value))))
2450
2451 (defun c-find-assignment-for-mode (source-pos mode match-any-lang _name)
2452 ;; Find the first assignment entry that applies to MODE at or after
2453 ;; SOURCE-POS. If MATCH-ANY-LANG is non-nil, entries with t as
2454 ;; the language list are considered to match, otherwise they don't.
2455 ;; On return SOURCE-POS is updated to point to the next assignment
2456 ;; after the returned one. If no assignment is found,
2457 ;; `c-lang--novalue' is returned as a magic value.
2458 ;;
2459 ;; SOURCE-POS is a vector that points out a specific assignment in
2460 ;; the double alist that's used in the `source' property. The first
2461 ;; element is the position in the top alist which is indexed with
2462 ;; the source files, and the second element is the position in the
2463 ;; nested bindings alist.
2464 ;;
2465 ;; NAME is only used for error messages.
2466
2467 (catch 'found
2468 (let ((file-entry (elt source-pos 0))
2469 (assignment-entry (elt source-pos 1))
2470 assignment)
2471
2472 (while (if assignment-entry
2473 t
2474 ;; Handled the last assignment from one file, begin on the
2475 ;; next. Due to the check in `c-lang-defconst', we know
2476 ;; there's at least one.
2477 (when file-entry
2478
2479 (unless (aset source-pos 1
2480 (setq assignment-entry (cdar file-entry)))
2481 ;; The file containing the source definitions has not
2482 ;; been loaded.
2483 (let ((file (symbol-name (caar file-entry)))
2484 (c-lang-constants-under-evaluation nil))
2485 ;;(message (concat "Loading %s to get the source "
2486 ;; "value for language constant %s")
2487 ;; file name)
2488 (load file nil t))
2489
2490 (unless (setq assignment-entry (cdar file-entry))
2491 ;; The load didn't fill in the source for the
2492 ;; constant as expected. The situation is
2493 ;; probably that a derived mode was written for
2494 ;; and compiled with another version of CC Mode,
2495 ;; and the requested constant isn't in the
2496 ;; currently loaded one. Put in a dummy
2497 ;; assignment that matches no language.
2498 (setcdr (car file-entry)
2499 (setq assignment-entry (list (list nil))))))
2500
2501 (aset source-pos 0 (setq file-entry (cdr file-entry)))
2502 t))
2503
2504 (setq assignment (car assignment-entry))
2505 (aset source-pos 1
2506 (setq assignment-entry (cdr assignment-entry)))
2507
2508 (when (if (listp (car assignment))
2509 (memq mode (car assignment))
2510 match-any-lang)
2511 (throw 'found (cdr assignment))))
2512
2513 c-lang--novalue)))
2514
2515 (defun c-lang-major-mode-is (mode)
2516 ;; `c-major-mode-is' expands to a call to this function inside
2517 ;; `c-lang-defconst'. Here we also match the mode(s) against any
2518 ;; fallback modes for the one in `c-buffer-is-cc-mode', so that
2519 ;; e.g. (c-major-mode-is 'c++-mode) is true in a derived language
2520 ;; that has c++-mode as base mode.
2521 (unless (listp mode)
2522 (setq mode (list mode)))
2523 (let (match (buf-mode c-buffer-is-cc-mode))
2524 (while (if (memq buf-mode mode)
2525 (progn
2526 (setq match t)
2527 nil)
2528 (setq buf-mode (get buf-mode 'c-fallback-mode))))
2529 match))
2530
2531 \f
2532 (cc-provide 'cc-defs)
2533
2534 ;; Local Variables:
2535 ;; indent-tabs-mode: t
2536 ;; tab-width: 8
2537 ;; End:
2538 ;;; cc-defs.el ends here