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