]> code.delx.au - gnu-emacs/blob - lisp/progmodes/cc-defs.el
f458904c87af68a115b3934ee74ccbeae6f463f1
[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. It is assumed that no
1404 ;; buffer changes will happen in FORMS, and no hidden buffer changes which could
1405 ;; affect the parsing will be made by FORMS.
1406 `(let ((c-state-cache (copy-tree c-state-cache))
1407 (c-state-cache-good-pos c-state-cache-good-pos)
1408 ;(c-state-nonlit-pos-cache (copy-tree c-state-nonlit-pos-cache))
1409 ;(c-state-nonlit-pos-cache-limit c-state-nonlit-pos-cache-limit)
1410 ;(c-state-semi-nonlit-pos-cache (copy-tree c-state-semi-nonlit-pos-cache))
1411 ;(c-state-semi-nonlit-pos-cache-limit c-state-semi-nonlit-pos-cache)
1412 (c-state-brace-pair-desert (copy-tree c-state-brace-pair-desert))
1413 (c-state-point-min c-state-point-min)
1414 (c-state-point-min-lit-type c-state-point-min-lit-type)
1415 (c-state-point-min-lit-start c-state-point-min-lit-start)
1416 (c-state-min-scan-pos c-state-min-scan-pos)
1417 (c-state-old-cpp-beg c-state-old-cpp-beg)
1418 (c-state-old-cpp-end c-state-old-cpp-end))
1419 ,@forms))
1420
1421 \f
1422 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1423 ;; The following macros are to be used only in `c-parse-state' and its
1424 ;; subroutines. Their main purpose is to simplify the handling of C++/Java
1425 ;; template delimiters and CPP macros. In GNU Emacs, this is done slickly by
1426 ;; the judicious use of 'category properties. These don't exist in XEmacs.
1427 ;;
1428 ;; Note: in the following macros, there is no special handling for parentheses
1429 ;; inside CPP constructs. That is because CPPs are always syntactically
1430 ;; balanced, thanks to `c-neutralize-CPP-line' in cc-mode.el.
1431 (defmacro c-sc-scan-lists-no-category+1+1 (from)
1432 ;; Do a (scan-lists FROM 1 1). Any finishing position which either (i) is
1433 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1434 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1435 `(let ((here (point))
1436 (pos (scan-lists ,from 1 1)))
1437 (while (eq (char-before pos) ?>)
1438 (setq pos (scan-lists pos 1 1)))
1439 pos))
1440
1441 (defmacro c-sc-scan-lists-no-category+1-1 (from)
1442 ;; Do a (scan-lists FROM 1 -1). Any finishing position which either (i) is
1443 ;; determined by an angle bracket; or (ii) is inside a macro whose start
1444 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1445 `(let ((here (point))
1446 (pos (scan-lists ,from 1 -1)))
1447 (while (eq (char-before pos) ?<)
1448 (setq pos (scan-lists pos 1 1))
1449 (setq pos (scan-lists pos 1 -1)))
1450 pos))
1451
1452 (defmacro c-sc-scan-lists-no-category-1+1 (from)
1453 ;; Do a (scan-lists FROM -1 1). Any finishing position which either (i) is
1454 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1455 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1456 `(let ((here (point))
1457 (pos (scan-lists ,from -1 1)))
1458 (while (eq (char-after pos) ?<)
1459 (setq pos (scan-lists pos -1 1)))
1460 pos))
1461
1462 (defmacro c-sc-scan-lists-no-category-1-1 (from)
1463 ;; Do a (scan-lists FROM -1 -1). Any finishing position which either (i) is
1464 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1465 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1466 `(let ((here (point))
1467 (pos (scan-lists ,from -1 -1)))
1468 (while (eq (char-after pos) ?>)
1469 (setq pos (scan-lists pos -1 1))
1470 (setq pos (scan-lists pos -1 -1)))
1471 pos))
1472
1473 (defmacro c-sc-scan-lists (from count depth)
1474 (if c-use-category
1475 `(scan-lists ,from ,count ,depth)
1476 (cond
1477 ((and (eq count 1) (eq depth 1))
1478 `(c-sc-scan-lists-no-category+1+1 ,from))
1479 ((and (eq count 1) (eq depth -1))
1480 `(c-sc-scan-lists-no-category+1-1 ,from))
1481 ((and (eq count -1) (eq depth 1))
1482 `(c-sc-scan-lists-no-category-1+1 ,from))
1483 ((and (eq count -1) (eq depth -1))
1484 `(c-sc-scan-lists-no-category-1-1 ,from))
1485 (t (error "Invalid parameter(s) to c-sc-scan-lists")))))
1486
1487
1488 (defun c-sc-parse-partial-sexp-no-category (from to targetdepth stopbefore
1489 oldstate)
1490 ;; Do a parse-partial-sexp using the supplied arguments, disregarding
1491 ;; template/generic delimiters < > and disregarding macros other than the
1492 ;; one at POINT-MACRO-START.
1493 ;;
1494 ;; NOTE that STOPBEFORE must be nil. TARGETDEPTH should be one less than
1495 ;; the depth in OLDSTATE. This function is thus a SPECIAL PURPOSE variation
1496 ;; on parse-partial-sexp, designed for calling from
1497 ;; `c-remove-stale-state-cache'.
1498 ;;
1499 ;; Any finishing position which is determined by an angle bracket delimiter
1500 ;; doesn't count as a finishing position.
1501 ;;
1502 ;; Note there is no special handling of CPP constructs here, since these are
1503 ;; always syntactically balanced (thanks to `c-neutralize-CPP-line').
1504 (let ((state
1505 (parse-partial-sexp from to targetdepth stopbefore oldstate)))
1506 (while
1507 (and (< (point) to)
1508 ;; We must have hit targetdepth.
1509 (or (eq (char-before) ?<)
1510 (eq (char-before) ?>)))
1511 (setcar state
1512 (if (memq (char-before) '(?> ?\) ?\} ?\]))
1513 (1+ (car state))
1514 (1- (car state))))
1515 (setq state
1516 (parse-partial-sexp (point) to targetdepth stopbefore oldstate)))
1517 state))
1518
1519 (defmacro c-sc-parse-partial-sexp (from to &optional targetdepth stopbefore
1520 oldstate)
1521 (if c-use-category
1522 `(parse-partial-sexp ,from ,to ,targetdepth ,stopbefore ,oldstate)
1523 `(c-sc-parse-partial-sexp-no-category ,from ,to ,targetdepth ,stopbefore
1524 ,oldstate)))
1525
1526 \f
1527 (defvar c-emacs-features)
1528
1529 (defmacro c-looking-at-non-alphnumspace ()
1530 "Are we looking at a character which isn't alphanumeric or space?"
1531 (if (memq 'gen-comment-delim c-emacs-features)
1532 `(looking-at
1533 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\|\\s!\\)")
1534 `(or (looking-at
1535 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\)"
1536 (let ((prop (c-get-char-property (point) 'syntax-table)))
1537 (eq prop '(14))))))) ; '(14) is generic comment delimiter.
1538
1539 \f
1540 (defsubst c-intersect-lists (list alist)
1541 ;; return the element of ALIST that matches the first element found
1542 ;; in LIST. Uses assq.
1543 (let (match)
1544 (while (and list
1545 (not (setq match (assq (car list) alist))))
1546 (setq list (cdr list)))
1547 match))
1548
1549 (defsubst c-lookup-lists (list alist1 alist2)
1550 ;; first, find the first entry from LIST that is present in ALIST1,
1551 ;; then find the entry in ALIST2 for that entry.
1552 (assq (car (c-intersect-lists list alist1)) alist2))
1553
1554 (defsubst c-langelem-sym (langelem)
1555 "Return the syntactic symbol in LANGELEM.
1556
1557 LANGELEM is either a cons cell on the \"old\" form given as the first
1558 argument to lineup functions or a syntactic element on the \"new\"
1559 form as used in `c-syntactic-element'."
1560 (car langelem))
1561
1562 (defsubst c-langelem-pos (langelem)
1563 "Return the anchor position in LANGELEM, or nil if there is none.
1564
1565 LANGELEM is either a cons cell on the \"old\" form given as the first
1566 argument to lineup functions or a syntactic element on the \"new\"
1567 form as used in `c-syntactic-element'."
1568 (if (consp (cdr langelem))
1569 (car-safe (cdr langelem))
1570 (cdr langelem)))
1571
1572 (defun c-langelem-col (langelem &optional preserve-point)
1573 "Return the column of the anchor position in LANGELEM.
1574 Also move the point to that position unless PRESERVE-POINT is non-nil.
1575
1576 LANGELEM is either a cons cell on the \"old\" form given as the first
1577 argument to lineup functions or a syntactic element on the \"new\"
1578 form as used in `c-syntactic-element'."
1579 (let ((pos (c-langelem-pos langelem))
1580 (here (point)))
1581 (if pos
1582 (progn
1583 (goto-char pos)
1584 (prog1 (current-column)
1585 (if preserve-point
1586 (goto-char here))))
1587 0)))
1588
1589 (defsubst c-langelem-2nd-pos (langelem)
1590 "Return the secondary position in LANGELEM, or nil if there is none.
1591
1592 LANGELEM is typically a syntactic element on the \"new\" form as used
1593 in `c-syntactic-element'. It may also be a cons cell as passed in the
1594 first argument to lineup functions, but then the returned value always
1595 will be nil."
1596 (car-safe (cdr-safe (cdr-safe langelem))))
1597
1598 (defsubst c-keep-region-active ()
1599 ;; Do whatever is necessary to keep the region active in XEmacs.
1600 ;; This is not needed for Emacs.
1601 (and (boundp 'zmacs-region-stays)
1602 (setq zmacs-region-stays t)))
1603
1604 (put 'c-mode 'c-mode-prefix "c-")
1605 (put 'c++-mode 'c-mode-prefix "c++-")
1606 (put 'objc-mode 'c-mode-prefix "objc-")
1607 (put 'java-mode 'c-mode-prefix "java-")
1608 (put 'idl-mode 'c-mode-prefix "idl-")
1609 (put 'pike-mode 'c-mode-prefix "pike-")
1610 (put 'awk-mode 'c-mode-prefix "awk-")
1611
1612 (defsubst c-mode-symbol (suffix)
1613 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1614 the corresponding symbol."
1615 (or c-buffer-is-cc-mode
1616 (error "Not inside a CC Mode based mode"))
1617 (let ((mode-prefix (get c-buffer-is-cc-mode 'c-mode-prefix)))
1618 (or mode-prefix
1619 (error "%S has no mode prefix known to `c-mode-symbol'"
1620 c-buffer-is-cc-mode))
1621 (intern (concat mode-prefix suffix))))
1622
1623 (defsubst c-mode-var (suffix)
1624 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1625 the value of the variable with that name."
1626 (symbol-value (c-mode-symbol suffix)))
1627
1628 (defsubst c-got-face-at (pos faces)
1629 "Return non-nil if position POS in the current buffer has any of the
1630 faces in the list FACES."
1631 (let ((pos-faces (get-text-property pos 'face)))
1632 (if (consp pos-faces)
1633 (progn
1634 (while (and pos-faces
1635 (not (memq (car pos-faces) faces)))
1636 (setq pos-faces (cdr pos-faces)))
1637 pos-faces)
1638 (memq pos-faces faces))))
1639
1640 (defsubst c-face-name-p (facename)
1641 ;; Return t if FACENAME is the name of a face. This method is
1642 ;; necessary since facep in XEmacs only returns t for the actual
1643 ;; face objects (while it's only their names that are used just
1644 ;; about anywhere else) without providing a predicate that tests
1645 ;; face names.
1646 (memq facename (face-list)))
1647
1648 (defun c-concat-separated (list separator)
1649 "Like `concat' on LIST, but separate each element with SEPARATOR.
1650 Notably, null elements in LIST are ignored."
1651 (mapconcat 'identity (delete nil (append list nil)) separator))
1652
1653 (defun c-make-keywords-re (adorn list &optional mode)
1654 "Make a regexp that matches all the strings the list.
1655 Duplicates and nil elements in the list are removed. The
1656 resulting regexp may contain zero or more submatch expressions.
1657
1658 If ADORN is t there will be at least one submatch and the first
1659 surrounds the matched alternative, and the regexp will also not match
1660 a prefix of any identifier. Adorned regexps cannot be appended. The
1661 language variable `c-nonsymbol-key' is used to make the adornment.
1662
1663 A value `appendable' for ADORN is like above, but all alternatives in
1664 the list that end with a word constituent char will have \\> appended
1665 instead, so that the regexp remains appendable. Note that this
1666 variant doesn't always guarantee that an identifier prefix isn't
1667 matched since the symbol constituent `_' is normally considered a
1668 nonword token by \\>.
1669
1670 The optional MODE specifies the language to get `c-nonsymbol-key' from
1671 when it's needed. The default is the current language taken from
1672 `c-buffer-is-cc-mode'."
1673
1674 (setq list (delete nil (delete-dups list)))
1675 (if list
1676 (let (re)
1677
1678 (if (eq adorn 'appendable)
1679 ;; This is kludgy but it works: Search for a string that
1680 ;; doesn't occur in any word in LIST. Append it to all
1681 ;; the alternatives where we want to add \>. Run through
1682 ;; `regexp-opt' and then replace it with \>.
1683 (let ((unique "") pos)
1684 (while (let (found)
1685 (setq unique (concat unique "@")
1686 pos list)
1687 (while (and pos
1688 (if (string-match unique (car pos))
1689 (progn (setq found t)
1690 nil)
1691 t))
1692 (setq pos (cdr pos)))
1693 found))
1694 (setq pos list)
1695 (while pos
1696 (if (string-match "\\w\\'" (car pos))
1697 (setcar pos (concat (car pos) unique)))
1698 (setq pos (cdr pos)))
1699 (setq re (regexp-opt list))
1700 (setq pos 0)
1701 (while (string-match unique re pos)
1702 (setq pos (+ (match-beginning 0) 2)
1703 re (replace-match "\\>" t t re))))
1704
1705 (setq re (regexp-opt list)))
1706
1707 ;; Emacs 20 and XEmacs (all versions so far) has a buggy
1708 ;; regexp-opt that doesn't always cope with strings containing
1709 ;; newlines. This kludge doesn't handle shy parens correctly
1710 ;; so we can't advice regexp-opt directly with it.
1711 (let (fail-list)
1712 (while list
1713 (and (string-match "\n" (car list)) ; To speed it up a little.
1714 (not (string-match (concat "\\`\\(" re "\\)\\'")
1715 (car list)))
1716 (setq fail-list (cons (car list) fail-list)))
1717 (setq list (cdr list)))
1718 (when fail-list
1719 (setq re (concat re
1720 "\\|"
1721 (mapconcat
1722 (if (eq adorn 'appendable)
1723 (lambda (str)
1724 (if (string-match "\\w\\'" str)
1725 (concat (regexp-quote str)
1726 "\\>")
1727 (regexp-quote str)))
1728 'regexp-quote)
1729 (sort fail-list
1730 (lambda (a b)
1731 (> (length a) (length b))))
1732 "\\|")))))
1733
1734 ;; Add our own grouping parenthesis around re instead of
1735 ;; passing adorn to `regexp-opt', since in XEmacs it makes the
1736 ;; top level grouping "shy".
1737 (cond ((eq adorn 'appendable)
1738 (concat "\\(" re "\\)"))
1739 (adorn
1740 (concat "\\(" re "\\)"
1741 "\\("
1742 (c-get-lang-constant 'c-nonsymbol-key nil mode)
1743 "\\|$\\)"))
1744 (t
1745 re)))
1746
1747 ;; Produce a regexp that matches nothing.
1748 (if adorn
1749 "\\(\\<\\>\\)"
1750 "\\<\\>")))
1751
1752 (put 'c-make-keywords-re 'lisp-indent-function 1)
1753
1754 (defun c-make-bare-char-alt (chars &optional inverted)
1755 "Make a character alternative string from the list of characters CHARS.
1756 The returned string is of the type that can be used with
1757 `skip-chars-forward' and `skip-chars-backward'. If INVERTED is
1758 non-nil, a caret is prepended to invert the set."
1759 ;; This function ought to be in the elisp core somewhere.
1760 (let ((str (if inverted "^" "")) char char2)
1761 (setq chars (sort (append chars nil) `<))
1762 (while chars
1763 (setq char (pop chars))
1764 (if (memq char '(?\\ ?^ ?-))
1765 ;; Quoting necessary (this method only works in the skip
1766 ;; functions).
1767 (setq str (format "%s\\%c" str char))
1768 (setq str (format "%s%c" str char)))
1769 ;; Check for range.
1770 (setq char2 char)
1771 (while (and chars (>= (1+ char2) (car chars)))
1772 (setq char2 (pop chars)))
1773 (unless (= char char2)
1774 (if (< (1+ char) char2)
1775 (setq str (format "%s-%c" str char2))
1776 (push char2 chars))))
1777 str))
1778
1779 ;; Leftovers from (X)Emacs 19 compatibility.
1780 (defalias 'c-regexp-opt 'regexp-opt)
1781 (defalias 'c-regexp-opt-depth 'regexp-opt-depth)
1782
1783 \f
1784 ;; Figure out what features this Emacs has
1785
1786 (cc-bytecomp-defvar open-paren-in-column-0-is-defun-start)
1787
1788 (defvar lookup-syntax-properties) ;XEmacs.
1789
1790 (defconst c-emacs-features
1791 (let (list)
1792
1793 (if (boundp 'infodock-version)
1794 ;; I've no idea what this actually is, but it's legacy. /mast
1795 (setq list (cons 'infodock list)))
1796
1797 ;; XEmacs uses 8-bit modify-syntax-entry flags.
1798 ;; Emacs uses a 1-bit flag. We will have to set up our
1799 ;; syntax tables differently to handle this.
1800 (let ((table (copy-syntax-table))
1801 entry)
1802 (modify-syntax-entry ?a ". 12345678" table)
1803 (cond
1804 ;; Emacs
1805 ((arrayp table)
1806 (setq entry (aref table ?a))
1807 ;; In Emacs, table entries are cons cells
1808 (if (consp entry) (setq entry (car entry))))
1809 ;; XEmacs
1810 ((fboundp 'get-char-table)
1811 (setq entry (get-char-table ?a table)))
1812 ;; incompatible
1813 (t (error "CC Mode is incompatible with this version of Emacs")))
1814 (setq list (cons (if (= (logand (lsh entry -16) 255) 255)
1815 '8-bit
1816 '1-bit)
1817 list)))
1818
1819 ;; Check whether beginning/end-of-defun call
1820 ;; beginning/end-of-defun-function nicely, passing through the
1821 ;; argument and respecting the return code.
1822 (let* (mark-ring
1823 (bod-param 'foo) (eod-param 'foo)
1824 (beginning-of-defun-function
1825 (lambda (&optional arg)
1826 (or (eq bod-param 'foo) (setq bod-param 'bar))
1827 (and (eq bod-param 'foo)
1828 (setq bod-param arg)
1829 (eq arg 3))))
1830 (end-of-defun-function
1831 (lambda (&optional arg)
1832 (and (eq eod-param 'foo)
1833 (setq eod-param arg)
1834 (eq arg 3)))))
1835 (if (save-excursion (and (beginning-of-defun 3) (eq bod-param 3)
1836 (not (beginning-of-defun))
1837 (end-of-defun 3) (eq eod-param 3)
1838 (not (end-of-defun))))
1839 (setq list (cons 'argumentative-bod-function list))))
1840
1841 ;; Record whether the `category' text property works.
1842 (if c-use-category (setq list (cons 'category-properties list)))
1843
1844 (let ((buf (generate-new-buffer " test"))
1845 parse-sexp-lookup-properties
1846 parse-sexp-ignore-comments
1847 lookup-syntax-properties) ; XEmacs
1848 (with-current-buffer buf
1849 (set-syntax-table (make-syntax-table))
1850
1851 ;; For some reason we have to set some of these after the
1852 ;; buffer has been made current. (Specifically,
1853 ;; `parse-sexp-ignore-comments' in Emacs 21.)
1854 (setq parse-sexp-lookup-properties t
1855 parse-sexp-ignore-comments t
1856 lookup-syntax-properties t)
1857
1858 ;; Find out if the `syntax-table' text property works.
1859 (modify-syntax-entry ?< ".")
1860 (modify-syntax-entry ?> ".")
1861 (insert "<()>")
1862 (c-mark-<-as-paren (point-min))
1863 (c-mark->-as-paren (+ 3 (point-min)))
1864 (goto-char (point-min))
1865 (c-forward-sexp)
1866 (if (= (point) (+ 4 (point-min)))
1867 (setq list (cons 'syntax-properties list))
1868 (error (concat
1869 "CC Mode is incompatible with this version of Emacs - "
1870 "support for the `syntax-table' text property "
1871 "is required.")))
1872
1873 ;; Find out if "\\s!" (generic comment delimiters) work.
1874 (c-safe
1875 (modify-syntax-entry ?x "!")
1876 (if (string-match "\\s!" "x")
1877 (setq list (cons 'gen-comment-delim list))))
1878
1879 ;; Find out if "\\s|" (generic string delimiters) work.
1880 (c-safe
1881 (modify-syntax-entry ?x "|")
1882 (if (string-match "\\s|" "x")
1883 (setq list (cons 'gen-string-delim list))))
1884
1885 ;; See if POSIX char classes work.
1886 (when (and (string-match "[[:alpha:]]" "a")
1887 ;; All versions of Emacs 21 so far haven't fixed
1888 ;; char classes in `skip-chars-forward' and
1889 ;; `skip-chars-backward'.
1890 (progn
1891 (delete-region (point-min) (point-max))
1892 (insert "foo123")
1893 (skip-chars-backward "[:alnum:]")
1894 (bobp))
1895 (= (skip-chars-forward "[:alpha:]") 3))
1896 (setq list (cons 'posix-char-classes list)))
1897
1898 ;; See if `open-paren-in-column-0-is-defun-start' exists and
1899 ;; isn't buggy (Emacs >= 21.4).
1900 (when (boundp 'open-paren-in-column-0-is-defun-start)
1901 (let ((open-paren-in-column-0-is-defun-start nil)
1902 (parse-sexp-ignore-comments t))
1903 (delete-region (point-min) (point-max))
1904 (set-syntax-table (make-syntax-table))
1905 (modify-syntax-entry ?\' "\"")
1906 (cond
1907 ;; XEmacs. Afaik this is currently an Emacs-only
1908 ;; feature, but it's good to be prepared.
1909 ((memq '8-bit list)
1910 (modify-syntax-entry ?/ ". 1456")
1911 (modify-syntax-entry ?* ". 23"))
1912 ;; Emacs
1913 ((memq '1-bit list)
1914 (modify-syntax-entry ?/ ". 124b")
1915 (modify-syntax-entry ?* ". 23")))
1916 (modify-syntax-entry ?\n "> b")
1917 (insert "/* '\n () */")
1918 (backward-sexp)
1919 (if (bobp)
1920 (setq list (cons 'col-0-paren list)))))
1921
1922 (set-buffer-modified-p nil))
1923 (kill-buffer buf))
1924
1925 ;; See if `parse-partial-sexp' returns the eighth element.
1926 (if (c-safe (>= (length (save-excursion
1927 (parse-partial-sexp (point) (point))))
1928 10))
1929 (setq list (cons 'pps-extended-state list))
1930 (error (concat
1931 "CC Mode is incompatible with this version of Emacs - "
1932 "`parse-partial-sexp' has to return at least 10 elements.")))
1933
1934 ;;(message "c-emacs-features: %S" list)
1935 list)
1936 "A list of certain features in the (X)Emacs you are using.
1937 There are many flavors of Emacs out there, each with different
1938 features supporting those needed by CC Mode. The following values
1939 might be present:
1940
1941 `8-bit' 8 bit syntax entry flags (XEmacs style).
1942 `1-bit' 1 bit syntax entry flags (Emacs style).
1943 `argumentative-bod-function' beginning-of-defun and end-of-defun pass
1944 ARG through to beginning/end-of-defun-function.
1945 `syntax-properties' It works to override the syntax for specific characters
1946 in the buffer with the `syntax-table' property. It's
1947 always set - CC Mode no longer works in emacsen without
1948 this feature.
1949 `category-properties' Syntax routines can add a level of indirection to text
1950 properties using the `category' property.
1951 `gen-comment-delim' Generic comment delimiters work
1952 (i.e. the syntax class `!').
1953 `gen-string-delim' Generic string delimiters work
1954 (i.e. the syntax class `|').
1955 `pps-extended-state' `parse-partial-sexp' returns a list with at least 10
1956 elements, i.e. it contains the position of the start of
1957 the last comment or string. It's always set - CC Mode
1958 no longer works in emacsen without this feature.
1959 `posix-char-classes' The regexp engine understands POSIX character classes.
1960 `col-0-paren' It's possible to turn off the ad-hoc rule that a paren
1961 in column zero is the start of a defun.
1962 `infodock' This is Infodock (based on XEmacs).
1963
1964 `8-bit' and `1-bit' are mutually exclusive.")
1965
1966 \f
1967 ;;; Some helper constants.
1968
1969 ;; If the regexp engine supports POSIX char classes then we can use
1970 ;; them to handle extended charsets correctly.
1971 (if (memq 'posix-char-classes c-emacs-features)
1972 (progn
1973 (defconst c-alpha "[:alpha:]")
1974 (defconst c-alnum "[:alnum:]")
1975 (defconst c-digit "[:digit:]")
1976 (defconst c-upper "[:upper:]")
1977 (defconst c-lower "[:lower:]"))
1978 (defconst c-alpha "a-zA-Z")
1979 (defconst c-alnum "a-zA-Z0-9")
1980 (defconst c-digit "0-9")
1981 (defconst c-upper "A-Z")
1982 (defconst c-lower "a-z"))
1983
1984 \f
1985 ;;; System for handling language dependent constants.
1986
1987 ;; This is used to set various language dependent data in a flexible
1988 ;; way: Language constants can be built from the values of other
1989 ;; language constants, also those for other languages. They can also
1990 ;; process the values of other language constants uniformly across all
1991 ;; the languages. E.g. one language constant can list all the type
1992 ;; keywords in each language, and another can build a regexp for each
1993 ;; language from those lists without code duplication.
1994 ;;
1995 ;; Language constants are defined with `c-lang-defconst', and their
1996 ;; value forms (referred to as source definitions) are evaluated only
1997 ;; on demand when requested for a particular language with
1998 ;; `c-lang-const'. It's therefore possible to refer to the values of
1999 ;; constants defined later in the file, or in another file, just as
2000 ;; long as all the relevant `c-lang-defconst' have been loaded when
2001 ;; `c-lang-const' is actually evaluated from somewhere else.
2002 ;;
2003 ;; `c-lang-const' forms are also evaluated at compile time and
2004 ;; replaced with the values they produce. Thus there's no overhead
2005 ;; for this system when compiled code is used - only the values
2006 ;; actually used in the code are present, and the file(s) containing
2007 ;; the `c-lang-defconst' forms don't need to be loaded at all then.
2008 ;; There are however safeguards to make sure that they can be loaded
2009 ;; to get the source definitions for the values if there's a mismatch
2010 ;; in compiled versions, or if `c-lang-const' is used uncompiled.
2011 ;;
2012 ;; Note that the source definitions in a `c-lang-defconst' form are
2013 ;; compiled into the .elc file where it stands; there's no need to
2014 ;; load the source file to get it.
2015 ;;
2016 ;; See cc-langs.el for more details about how this system is deployed
2017 ;; in CC Mode, and how the associated language variable system
2018 ;; (`c-lang-defvar') works. That file also contains a lot of
2019 ;; examples.
2020
2021 (defun c-add-language (mode base-mode)
2022 "Declare a new language in the language dependent variable system.
2023 This is intended to be used by modes that inherit CC Mode to add new
2024 languages. It should be used at the top level before any calls to
2025 `c-lang-defconst'. MODE is the mode name symbol for the new language,
2026 and BASE-MODE is the mode name symbol for the language in CC Mode that
2027 is to be the template for the new mode.
2028
2029 The exact effect of BASE-MODE is to make all language constants that
2030 haven't got a setting in the new language fall back to their values in
2031 BASE-MODE. It does not have any effect outside the language constant
2032 system."
2033 (unless (string-match "\\`\\(.*-\\)mode\\'" (symbol-name mode))
2034 (error "The mode name symbol `%s' must end with \"-mode\"" mode))
2035 (put mode 'c-mode-prefix (match-string 1 (symbol-name mode)))
2036 (unless (get base-mode 'c-mode-prefix)
2037 (error "Unknown base mode `%s'" base-mode))
2038 (put mode 'c-fallback-mode base-mode))
2039
2040 (defvar c-lang-constants (make-vector 151 0))
2041 ;; Obarray used as a cache to keep track of the language constants.
2042 ;; The constants stored are those defined by `c-lang-defconst' and the values
2043 ;; computed by `c-lang-const'. It's mostly used at compile time but it's not
2044 ;; stored in compiled files.
2045
2046 ;; The obarray contains all the language constants as symbols. The
2047 ;; value cells hold the evaluated values as alists where each car is
2048 ;; the mode name symbol and the corresponding cdr is the evaluated
2049 ;; value in that mode. The property lists hold the source definitions
2050 ;; and other miscellaneous data. The obarray might also contain
2051 ;; various other symbols, but those don't have any variable bindings.
2052
2053 (defvar c-lang-const-expansion nil)
2054
2055 ;; Ugly hack to pull in the definition of `cc-bytecomp-compiling-or-loading'
2056 ;; from cc-bytecomp to make it available at loadtime. This is the same
2057 ;; mechanism used in cc-mode.el for `c-populate-syntax-table'.
2058 (defalias 'cc-bytecomp-compiling-or-loading
2059 (cc-eval-when-compile
2060 (let ((f (symbol-function 'cc-bytecomp-compiling-or-loading)))
2061 (if (byte-code-function-p f) f (byte-compile f)))))
2062
2063 (defsubst c-get-current-file ()
2064 ;; Return the base name of the current file.
2065 (let* ((c-or-l (cc-bytecomp-compiling-or-loading))
2066 (file
2067 (cond
2068 ((eq c-or-l 'loading) load-file-name)
2069 ((eq c-or-l 'compiling) byte-compile-dest-file)
2070 ((null c-or-l) (buffer-file-name)))))
2071 (and file
2072 (file-name-sans-extension
2073 (file-name-nondirectory file)))))
2074
2075 (defmacro c-lang-defconst-eval-immediately (form)
2076 "Can be used inside a VAL in `c-lang-defconst' to evaluate FORM
2077 immediately, i.e. at the same time as the `c-lang-defconst' form
2078 itself is evaluated."
2079 ;; Evaluate at macro expansion time, i.e. in the
2080 ;; `c--macroexpand-all' inside `c-lang-defconst'.
2081 (eval form))
2082
2083 (defmacro c-lang-defconst (name &rest args)
2084 "Set the language specific values of the language constant NAME.
2085 The second argument can optionally be a docstring. The rest of the
2086 arguments are one or more repetitions of LANG VAL where LANG specifies
2087 the language(s) that VAL applies to. LANG is the name of the
2088 language, i.e. the mode name without the \"-mode\" suffix, or a list
2089 of such language names, or t for all languages. VAL is a form to
2090 evaluate to get the value.
2091
2092 If LANG isn't t or one of the core languages in CC Mode, it must
2093 have been declared with `c-add-language'.
2094
2095 Neither NAME, LANG nor VAL are evaluated directly - they should not be
2096 quoted. `c-lang-defconst-eval-immediately' can however be used inside
2097 VAL to evaluate parts of it directly.
2098
2099 When VAL is evaluated for some language, that language is temporarily
2100 made current so that `c-lang-const' without an explicit language can
2101 be used inside VAL to refer to the value of a language constant in the
2102 same language. That is particularly useful if LANG is t.
2103
2104 VAL is not evaluated right away but rather when the value is requested
2105 with `c-lang-const'. Thus it's possible to use `c-lang-const' inside
2106 VAL to refer to language constants that haven't been defined yet.
2107 However, if the definition of a language constant is in another file
2108 then that file must be loaded \(at compile time) before it's safe to
2109 reference the constant.
2110
2111 The assignments in ARGS are processed in sequence like `setq', so
2112 \(c-lang-const NAME) may be used inside a VAL to refer to the last
2113 assigned value to this language constant, or a value that it has
2114 gotten in another earlier loaded file.
2115
2116 To work well with repeated loads and interactive reevaluation, only
2117 one `c-lang-defconst' for each NAME is permitted per file. If there
2118 already is one it will be completely replaced; the value in the
2119 earlier definition will not affect `c-lang-const' on the same
2120 constant. A file is identified by its base name."
2121
2122 (let* ((sym (intern (symbol-name name) c-lang-constants))
2123 ;; Make `c-lang-const' expand to a straightforward call to
2124 ;; `c-get-lang-constant' in `c--macroexpand-all' below.
2125 ;;
2126 ;; (The default behavior, i.e. to expand to a call inside
2127 ;; `eval-when-compile' should be equivalent, since that macro
2128 ;; should only expand to its content if it's used inside a
2129 ;; form that's already evaluated at compile time. It's
2130 ;; however necessary to use our cover macro
2131 ;; `cc-eval-when-compile' due to bugs in `eval-when-compile',
2132 ;; and it expands to a bulkier form that in this case only is
2133 ;; unnecessary garbage that we don't want to store in the
2134 ;; language constant source definitions.)
2135 (c-lang-const-expansion 'call)
2136 (c-langs-are-parametric t)
2137 (file (intern
2138 (or (c-get-current-file)
2139 (error "`c-lang-defconst' can only be used in a file"))))
2140 bindings
2141 pre-files)
2142
2143 (or (symbolp name)
2144 (error "Not a symbol: %S" name))
2145
2146 (when (stringp (car-safe args))
2147 ;; The docstring is hardly used anywhere since there's no normal
2148 ;; symbol to attach it to. It's primarily for getting the right
2149 ;; format in the source.
2150 (put sym 'variable-documentation (car args))
2151 (setq args (cdr args)))
2152
2153 (or args
2154 (error "No assignments in `c-lang-defconst' for %S" name))
2155
2156 ;; Rework ARGS to an association list to make it easier to handle.
2157 ;; It's reversed at the same time to make it easier to implement
2158 ;; the demand-driven (i.e. reversed) evaluation in `c-lang-const'.
2159 (while args
2160 (let ((assigned-mode
2161 (cond ((eq (car args) t) t)
2162 ((symbolp (car args))
2163 (list (intern (concat (symbol-name (car args))
2164 "-mode"))))
2165 ((listp (car args))
2166 (mapcar (lambda (lang)
2167 (or (symbolp lang)
2168 (error "Not a list of symbols: %S"
2169 (car args)))
2170 (intern (concat (symbol-name lang)
2171 "-mode")))
2172 (car args)))
2173 (t (error "Not a symbol or a list of symbols: %S"
2174 (car args)))))
2175 val)
2176
2177 (or (cdr args)
2178 (error "No value for %S" (car args)))
2179 (setq args (cdr args)
2180 val (car args))
2181
2182 ;; Emacs has a weird bug where it seems to fail to read
2183 ;; backquote lists from byte compiled files correctly (,@
2184 ;; forms, to be specific), so make sure the bindings in the
2185 ;; expansion below don't contain any backquote stuff.
2186 ;; (XEmacs handles it correctly and doesn't need this for that
2187 ;; reason, but we also use this expansion handle
2188 ;; `c-lang-defconst-eval-immediately' and to register
2189 ;; dependencies on the `c-lang-const's in VAL.)
2190 (setq val (c--macroexpand-all val))
2191
2192 (setq bindings `(cons (cons ',assigned-mode (lambda () ,val)) ,bindings)
2193 args (cdr args))))
2194
2195 ;; Compile in the other files that have provided source
2196 ;; definitions for this symbol, to make sure the order in the
2197 ;; `source' property is correct even when files are loaded out of
2198 ;; order.
2199 (setq pre-files (mapcar 'car (get sym 'source)))
2200 (if (memq file pre-files)
2201 ;; This can happen when the source file (e.g. cc-langs.el) is first
2202 ;; loaded as source, setting a 'source property entry, and then itself
2203 ;; being compiled.
2204 (setq pre-files (cdr (memq file pre-files))))
2205 ;; Reverse to get the right load order.
2206 (setq pre-files (nreverse pre-files))
2207
2208 `(eval-and-compile
2209 (c-define-lang-constant ',name ,bindings
2210 ,@(and pre-files `(',pre-files))))))
2211
2212 (put 'c-lang-defconst 'lisp-indent-function 1)
2213 ;(eval-after-load "edebug" ; 2006-07-09: def-edebug-spec is now in subr.el.
2214 ; '
2215 (def-edebug-spec c-lang-defconst
2216 (&define name [&optional stringp] [&rest sexp def-form]))
2217
2218 (defun c-define-lang-constant (name bindings &optional pre-files)
2219 ;; Used by `c-lang-defconst'.
2220
2221 (let* ((sym (intern (symbol-name name) c-lang-constants))
2222 (source (get sym 'source))
2223 (file (intern
2224 (or (c-get-current-file)
2225 (error "`c-lang-defconst' must be used in a file"))))
2226 (elem (assq file source)))
2227
2228 ;;(when (cdr-safe elem)
2229 ;; (message "Language constant %s redefined in %S" name file))
2230
2231 ;; Note that the order in the source alist is relevant. Like how
2232 ;; `c-lang-defconst' reverses the bindings, this reverses the
2233 ;; order between files so that the last to evaluate comes first.
2234 (unless elem
2235 (while pre-files
2236 (unless (assq (car pre-files) source)
2237 (setq source (cons (list (car pre-files)) source)))
2238 (setq pre-files (cdr pre-files)))
2239 (put sym 'source (cons (setq elem (list file)) source)))
2240
2241 (setcdr elem bindings)
2242
2243 ;; Bind the symbol as a variable, or clear any earlier evaluated
2244 ;; value it has.
2245 (set sym nil)
2246
2247 ;; Clear the evaluated values that depend on this source.
2248 (let ((agenda (get sym 'dependents))
2249 (visited (make-vector 101 0))
2250 ptr)
2251 (while agenda
2252 (setq sym (car agenda)
2253 agenda (cdr agenda))
2254 (intern (symbol-name sym) visited)
2255 (set sym nil)
2256 (setq ptr (get sym 'dependents))
2257 (while ptr
2258 (setq sym (car ptr)
2259 ptr (cdr ptr))
2260 (unless (intern-soft (symbol-name sym) visited)
2261 (setq agenda (cons sym agenda))))))
2262
2263 name))
2264
2265 (defmacro c-lang-const (name &optional lang)
2266 "Get the mode specific value of the language constant NAME in language LANG.
2267 LANG is the name of the language, i.e. the mode name without the
2268 \"-mode\" suffix. If used inside `c-lang-defconst' or
2269 `c-lang-defvar', LANG may be left out to refer to the current
2270 language. NAME and LANG are not evaluated so they should not be
2271 quoted."
2272
2273 (or (symbolp name)
2274 (error "Not a symbol: %S" name))
2275 (or (symbolp lang)
2276 (error "Not a symbol: %S" lang))
2277
2278 (let ((sym (intern (symbol-name name) c-lang-constants))
2279 (mode (when lang (intern (concat (symbol-name lang) "-mode")))))
2280
2281 (or (get mode 'c-mode-prefix) (null mode)
2282 (error "Unknown language %S: no `c-mode-prefix' property"
2283 lang))
2284
2285 (if (eq c-lang-const-expansion 'immediate)
2286 ;; No need to find out the source file(s) when we evaluate
2287 ;; immediately since all the info is already there in the
2288 ;; `source' property.
2289 `',(c-get-lang-constant name nil mode)
2290
2291 (let ((source-files
2292 (let ((file (c-get-current-file)))
2293 (if file (setq file (intern file)))
2294 ;; Get the source file(s) that must be loaded to get the value
2295 ;; of the constant. If the symbol isn't defined yet we assume
2296 ;; that its definition will come later in this file, and thus
2297 ;; are no file dependencies needed.
2298 (nreverse
2299 ;; Reverse to get the right load order.
2300 (c--mapcan (lambda (elem)
2301 (if (eq file (car elem))
2302 nil ; Exclude our own file.
2303 (list (car elem))))
2304 (get sym 'source)))))
2305
2306 ;; Make some effort to do a compact call to
2307 ;; `c-get-lang-constant' since it will be compiled in.
2308 (args (and mode `(',mode))))
2309
2310 (if (or source-files args)
2311 (push (and source-files `',source-files) args))
2312
2313 (if (or (eq c-lang-const-expansion 'call)
2314 (and (not c-lang-const-expansion)
2315 (not mode))
2316 (not (cc-bytecomp-is-compiling)))
2317 ;; Either a straight call is requested in the context, or
2318 ;; we're in an "uncontrolled" context and got no language,
2319 ;; or we're not being byte compiled so the compile time
2320 ;; stuff below is unnecessary.
2321 `(c-get-lang-constant ',name ,@args)
2322
2323 ;; Being compiled. If the loading and compiling version is
2324 ;; the same we use a value that is evaluated at compile time,
2325 ;; otherwise it's evaluated at runtime.
2326 `(if (eq c-version-sym ',c-version-sym)
2327 (cc-eval-when-compile
2328 (c-get-lang-constant ',name ,@args))
2329 (c-get-lang-constant ',name ,@args)))))))
2330
2331 (defvar c-lang-constants-under-evaluation nil
2332 "Alist of constants in the process of being evaluated.
2333 The `cdr' of each entry indicates how far we've looked in the list
2334 of definitions, so that the def for var FOO in c-mode can be defined in
2335 terms of the def for that same var FOO (which will then rely on the
2336 fallback definition for all modes, to break the cycle).")
2337
2338 (defconst c-lang--novalue "novalue")
2339
2340 (defun c-get-lang-constant (name &optional source-files mode)
2341 ;; Used by `c-lang-const'.
2342
2343 (or mode
2344 (setq mode c-buffer-is-cc-mode)
2345 (error "No current language"))
2346
2347 (let* ((sym (intern (symbol-name name) c-lang-constants))
2348 (source (get sym 'source))
2349 elem
2350 (eval-in-sym (and c-lang-constants-under-evaluation
2351 (caar c-lang-constants-under-evaluation))))
2352
2353 ;; Record the dependencies between this symbol and the one we're
2354 ;; being evaluated in.
2355 (when eval-in-sym
2356 (or (memq eval-in-sym (get sym 'dependents))
2357 (put sym 'dependents (cons eval-in-sym (get sym 'dependents)))))
2358
2359 ;; Make sure the source files have entries on the `source'
2360 ;; property so that loading will take place when necessary.
2361 (while source-files
2362 (unless (assq (car source-files) source)
2363 (put sym 'source
2364 (setq source (cons (list (car source-files)) source)))
2365 ;; Might pull in more definitions which affect the value. The
2366 ;; clearing of dependent values etc is done when the
2367 ;; definition is encountered during the load; this is just to
2368 ;; jump past the check for a cached value below.
2369 (set sym nil))
2370 (setq source-files (cdr source-files)))
2371
2372 (if (and (boundp sym)
2373 (setq elem (assq mode (symbol-value sym))))
2374 (cdr elem)
2375
2376 ;; Check if an evaluation of this symbol is already underway.
2377 ;; In that case we just continue with the "assignment" before
2378 ;; the one currently being evaluated, thereby creating the
2379 ;; illusion if a `setq'-like sequence of assignments.
2380 (let* ((c-buffer-is-cc-mode mode)
2381 (source-pos
2382 (or (assq sym c-lang-constants-under-evaluation)
2383 (cons sym (vector source nil))))
2384 ;; Append `c-lang-constants-under-evaluation' even if an
2385 ;; earlier entry is found. It's only necessary to get
2386 ;; the recording of dependencies above correct.
2387 (c-lang-constants-under-evaluation
2388 (cons source-pos c-lang-constants-under-evaluation))
2389 (fallback (get mode 'c-fallback-mode))
2390 value
2391 ;; Make sure the recursion limits aren't very low
2392 ;; since the `c-lang-const' dependencies can go deep.
2393 (max-specpdl-size (max max-specpdl-size 3000))
2394 (max-lisp-eval-depth (max max-lisp-eval-depth 1000)))
2395
2396 (if (if fallback
2397 (let ((backup-source-pos (copy-sequence (cdr source-pos))))
2398 (and
2399 ;; First try the original mode but don't accept an
2400 ;; entry matching all languages since the fallback
2401 ;; mode might have an explicit entry before that.
2402 (eq (setq value (c-find-assignment-for-mode
2403 (cdr source-pos) mode nil name))
2404 c-lang--novalue)
2405 ;; Try again with the fallback mode from the
2406 ;; original position. Note that
2407 ;; `c-buffer-is-cc-mode' still is the real mode if
2408 ;; language parameterization takes place.
2409 (eq (setq value (c-find-assignment-for-mode
2410 (setcdr source-pos backup-source-pos)
2411 fallback t name))
2412 c-lang--novalue)))
2413 ;; A simple lookup with no fallback mode.
2414 (eq (setq value (c-find-assignment-for-mode
2415 (cdr source-pos) mode t name))
2416 c-lang--novalue))
2417 (error
2418 "`%s' got no (prior) value in %S (might be a cyclic reference)"
2419 name mode))
2420
2421 (condition-case err
2422 (setq value (funcall value))
2423 (error
2424 ;; Print a message to aid in locating the error. We don't
2425 ;; print the error itself since that will be done later by
2426 ;; some caller higher up.
2427 (message "Eval error in the `c-lang-defconst' for `%S' in %s:"
2428 sym mode)
2429 (makunbound sym)
2430 (signal (car err) (cdr err))))
2431
2432 (set sym (cons (cons mode value) (symbol-value sym)))
2433 value))))
2434
2435 (defun c-find-assignment-for-mode (source-pos mode match-any-lang _name)
2436 ;; Find the first assignment entry that applies to MODE at or after
2437 ;; SOURCE-POS. If MATCH-ANY-LANG is non-nil, entries with t as
2438 ;; the language list are considered to match, otherwise they don't.
2439 ;; On return SOURCE-POS is updated to point to the next assignment
2440 ;; after the returned one. If no assignment is found,
2441 ;; `c-lang--novalue' is returned as a magic value.
2442 ;;
2443 ;; SOURCE-POS is a vector that points out a specific assignment in
2444 ;; the double alist that's used in the `source' property. The first
2445 ;; element is the position in the top alist which is indexed with
2446 ;; the source files, and the second element is the position in the
2447 ;; nested bindings alist.
2448 ;;
2449 ;; NAME is only used for error messages.
2450
2451 (catch 'found
2452 (let ((file-entry (elt source-pos 0))
2453 (assignment-entry (elt source-pos 1))
2454 assignment)
2455
2456 (while (if assignment-entry
2457 t
2458 ;; Handled the last assignment from one file, begin on the
2459 ;; next. Due to the check in `c-lang-defconst', we know
2460 ;; there's at least one.
2461 (when file-entry
2462
2463 (unless (aset source-pos 1
2464 (setq assignment-entry (cdar file-entry)))
2465 ;; The file containing the source definitions has not
2466 ;; been loaded.
2467 (let ((file (symbol-name (caar file-entry)))
2468 (c-lang-constants-under-evaluation nil))
2469 ;;(message (concat "Loading %s to get the source "
2470 ;; "value for language constant %s")
2471 ;; file name)
2472 (load file nil t))
2473
2474 (unless (setq assignment-entry (cdar file-entry))
2475 ;; The load didn't fill in the source for the
2476 ;; constant as expected. The situation is
2477 ;; probably that a derived mode was written for
2478 ;; and compiled with another version of CC Mode,
2479 ;; and the requested constant isn't in the
2480 ;; currently loaded one. Put in a dummy
2481 ;; assignment that matches no language.
2482 (setcdr (car file-entry)
2483 (setq assignment-entry (list (list nil))))))
2484
2485 (aset source-pos 0 (setq file-entry (cdr file-entry)))
2486 t))
2487
2488 (setq assignment (car assignment-entry))
2489 (aset source-pos 1
2490 (setq assignment-entry (cdr assignment-entry)))
2491
2492 (when (if (listp (car assignment))
2493 (memq mode (car assignment))
2494 match-any-lang)
2495 (throw 'found (cdr assignment))))
2496
2497 c-lang--novalue)))
2498
2499 (defun c-lang-major-mode-is (mode)
2500 ;; `c-major-mode-is' expands to a call to this function inside
2501 ;; `c-lang-defconst'. Here we also match the mode(s) against any
2502 ;; fallback modes for the one in `c-buffer-is-cc-mode', so that
2503 ;; e.g. (c-major-mode-is 'c++-mode) is true in a derived language
2504 ;; that has c++-mode as base mode.
2505 (unless (listp mode)
2506 (setq mode (list mode)))
2507 (let (match (buf-mode c-buffer-is-cc-mode))
2508 (while (if (memq buf-mode mode)
2509 (progn
2510 (setq match t)
2511 nil)
2512 (setq buf-mode (get buf-mode 'c-fallback-mode))))
2513 match))
2514
2515 \f
2516 (cc-provide 'cc-defs)
2517
2518 ;; Local Variables:
2519 ;; indent-tabs-mode: t
2520 ;; tab-width: 8
2521 ;; End:
2522 ;;; cc-defs.el ends here