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