Merge from mainline.
[bpt/emacs.git] / 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 (if (< ,end (point-max))
1221 (c-put-char-property ,end 'category 'c-cpp-delimiter))))
1222 (defmacro c-clear-cpp-delimiters (beg end)
1223 ;; This macro does a hidden buffer change.
1224 `(progn
1225 (c-clear-char-property ,beg 'category)
1226 (if (< ,end (point-max))
1227 (c-clear-char-property ,end 'category))))
1228
1229 (defsubst c-comment-out-cpps ()
1230 ;; Render all preprocessor constructs syntactically commented out.
1231 (put 'c-cpp-delimiter 'syntax-table c-cpp-delimiter))
1232 (defsubst c-uncomment-out-cpps ()
1233 ;; Restore the syntactic visibility of preprocessor constructs.
1234 (put 'c-cpp-delimiter 'syntax-table nil))
1235
1236 (defmacro c-with-cpps-commented-out (&rest forms)
1237 ;; Execute FORMS... whilst the syntactic effect of all characters in
1238 ;; all CPP regions is suppressed. In particular, this is to suppress
1239 ;; the syntactic significance of parens/braces/brackets to functions
1240 ;; such as `scan-lists' and `parse-partial-sexp'.
1241 `(unwind-protect
1242 (c-save-buffer-state ()
1243 (c-comment-out-cpps)
1244 ,@forms)
1245 (c-save-buffer-state ()
1246 (c-uncomment-out-cpps))))
1247
1248 (defmacro c-with-all-but-one-cpps-commented-out (beg end &rest forms)
1249 ;; Execute FORMS... whilst the syntactic effect of all characters in
1250 ;; every CPP region APART FROM THE ONE BETWEEN BEG and END is
1251 ;; suppressed.
1252 `(unwind-protect
1253 (c-save-buffer-state ()
1254 (c-clear-cpp-delimiters ,beg ,end)
1255 ,`(c-with-cpps-commented-out ,@forms))
1256 (c-save-buffer-state ()
1257 (c-set-cpp-delimiters ,beg ,end))))
1258 \f
1259 (defsubst c-intersect-lists (list alist)
1260 ;; return the element of ALIST that matches the first element found
1261 ;; in LIST. Uses assq.
1262 (let (match)
1263 (while (and list
1264 (not (setq match (assq (car list) alist))))
1265 (setq list (cdr list)))
1266 match))
1267
1268 (defsubst c-lookup-lists (list alist1 alist2)
1269 ;; first, find the first entry from LIST that is present in ALIST1,
1270 ;; then find the entry in ALIST2 for that entry.
1271 (assq (car (c-intersect-lists list alist1)) alist2))
1272
1273 (defsubst c-langelem-sym (langelem)
1274 "Return the syntactic symbol in LANGELEM.
1275
1276 LANGELEM is either a cons cell on the \"old\" form given as the first
1277 argument to lineup functions or a syntactic element on the \"new\"
1278 form as used in `c-syntactic-element'."
1279 (car langelem))
1280
1281 (defsubst c-langelem-pos (langelem)
1282 "Return the anchor position in LANGELEM, or nil if there is none.
1283
1284 LANGELEM is either a cons cell on the \"old\" form given as the first
1285 argument to lineup functions or a syntactic element on the \"new\"
1286 form as used in `c-syntactic-element'."
1287 (if (consp (cdr langelem))
1288 (car-safe (cdr langelem))
1289 (cdr langelem)))
1290
1291 (defun c-langelem-col (langelem &optional preserve-point)
1292 "Return the column of the anchor position in LANGELEM.
1293 Also move the point to that position unless PRESERVE-POINT is non-nil.
1294
1295 LANGELEM is either a cons cell on the \"old\" form given as the first
1296 argument to lineup functions or a syntactic element on the \"new\"
1297 form as used in `c-syntactic-element'."
1298 (let ((pos (c-langelem-pos langelem))
1299 (here (point)))
1300 (if pos
1301 (progn
1302 (goto-char pos)
1303 (prog1 (current-column)
1304 (if preserve-point
1305 (goto-char here))))
1306 0)))
1307
1308 (defsubst c-langelem-2nd-pos (langelem)
1309 "Return the secondary position in LANGELEM, or nil if there is none.
1310
1311 LANGELEM is typically a syntactic element on the \"new\" form as used
1312 in `c-syntactic-element'. It may also be a cons cell as passed in the
1313 first argument to lineup functions, but then the returned value always
1314 will be nil."
1315 (car-safe (cdr-safe (cdr-safe langelem))))
1316
1317 (defsubst c-keep-region-active ()
1318 ;; Do whatever is necessary to keep the region active in XEmacs.
1319 ;; This is not needed for Emacs.
1320 (and (boundp 'zmacs-region-stays)
1321 (setq zmacs-region-stays t)))
1322
1323 (put 'c-mode 'c-mode-prefix "c-")
1324 (put 'c++-mode 'c-mode-prefix "c++-")
1325 (put 'objc-mode 'c-mode-prefix "objc-")
1326 (put 'java-mode 'c-mode-prefix "java-")
1327 (put 'idl-mode 'c-mode-prefix "idl-")
1328 (put 'pike-mode 'c-mode-prefix "pike-")
1329 (put 'awk-mode 'c-mode-prefix "awk-")
1330
1331 (defsubst c-mode-symbol (suffix)
1332 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1333 the corresponding symbol."
1334 (or c-buffer-is-cc-mode
1335 (error "Not inside a CC Mode based mode"))
1336 (let ((mode-prefix (get c-buffer-is-cc-mode 'c-mode-prefix)))
1337 (or mode-prefix
1338 (error "%S has no mode prefix known to `c-mode-symbol'"
1339 c-buffer-is-cc-mode))
1340 (intern (concat mode-prefix suffix))))
1341
1342 (defsubst c-mode-var (suffix)
1343 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1344 the value of the variable with that name."
1345 (symbol-value (c-mode-symbol suffix)))
1346
1347 (defsubst c-got-face-at (pos faces)
1348 "Return non-nil if position POS in the current buffer has any of the
1349 faces in the list FACES."
1350 (let ((pos-faces (get-text-property pos 'face)))
1351 (if (consp pos-faces)
1352 (progn
1353 (while (and pos-faces
1354 (not (memq (car pos-faces) faces)))
1355 (setq pos-faces (cdr pos-faces)))
1356 pos-faces)
1357 (memq pos-faces faces))))
1358
1359 (defsubst c-face-name-p (facename)
1360 ;; Return t if FACENAME is the name of a face. This method is
1361 ;; necessary since facep in XEmacs only returns t for the actual
1362 ;; face objects (while it's only their names that are used just
1363 ;; about anywhere else) without providing a predicate that tests
1364 ;; face names.
1365 (memq facename (face-list)))
1366
1367 (defun c-concat-separated (list separator)
1368 "Like `concat' on LIST, but separate each element with SEPARATOR.
1369 Notably, null elements in LIST are ignored."
1370 (mapconcat 'identity (delete nil (append list nil)) separator))
1371
1372 (defun c-make-keywords-re (adorn list &optional mode)
1373 "Make a regexp that matches all the strings the list.
1374 Duplicates and nil elements in the list are removed. The resulting
1375 regexp may contain zero or more submatch expressions.
1376
1377 If ADORN is t there will be at least one submatch and the first
1378 surrounds the matched alternative, and the regexp will also not match
1379 a prefix of any identifier. Adorned regexps cannot be appended. The
1380 language variable `c-nonsymbol-key' is used to make the adornment.
1381
1382 A value 'appendable for ADORN is like above, but all alternatives in
1383 the list that end with a word constituent char will have \\> appended
1384 instead, so that the regexp remains appendable. Note that this
1385 variant doesn't always guarantee that an identifier prefix isn't
1386 matched since the symbol constituent '_' is normally considered a
1387 nonword token by \\>.
1388
1389 The optional MODE specifies the language to get `c-nonsymbol-key' from
1390 when it's needed. The default is the current language taken from
1391 `c-buffer-is-cc-mode'."
1392
1393 (let (unique)
1394 (dolist (elt list)
1395 (unless (member elt unique)
1396 (push elt unique)))
1397 (setq list (delete nil unique)))
1398 (if list
1399 (let (re)
1400
1401 (if (eq adorn 'appendable)
1402 ;; This is kludgy but it works: Search for a string that
1403 ;; doesn't occur in any word in LIST. Append it to all
1404 ;; the alternatives where we want to add \>. Run through
1405 ;; `regexp-opt' and then replace it with \>.
1406 (let ((unique "") pos)
1407 (while (let (found)
1408 (setq unique (concat unique "@")
1409 pos list)
1410 (while (and pos
1411 (if (string-match unique (car pos))
1412 (progn (setq found t)
1413 nil)
1414 t))
1415 (setq pos (cdr pos)))
1416 found))
1417 (setq pos list)
1418 (while pos
1419 (if (string-match "\\w\\'" (car pos))
1420 (setcar pos (concat (car pos) unique)))
1421 (setq pos (cdr pos)))
1422 (setq re (regexp-opt list))
1423 (setq pos 0)
1424 (while (string-match unique re pos)
1425 (setq pos (+ (match-beginning 0) 2)
1426 re (replace-match "\\>" t t re))))
1427
1428 (setq re (regexp-opt list)))
1429
1430 ;; Emacs 20 and XEmacs (all versions so far) has a buggy
1431 ;; regexp-opt that doesn't always cope with strings containing
1432 ;; newlines. This kludge doesn't handle shy parens correctly
1433 ;; so we can't advice regexp-opt directly with it.
1434 (let (fail-list)
1435 (while list
1436 (and (string-match "\n" (car list)) ; To speed it up a little.
1437 (not (string-match (concat "\\`\\(" re "\\)\\'")
1438 (car list)))
1439 (setq fail-list (cons (car list) fail-list)))
1440 (setq list (cdr list)))
1441 (when fail-list
1442 (setq re (concat re
1443 "\\|"
1444 (mapconcat
1445 (if (eq adorn 'appendable)
1446 (lambda (str)
1447 (if (string-match "\\w\\'" str)
1448 (concat (regexp-quote str)
1449 "\\>")
1450 (regexp-quote str)))
1451 'regexp-quote)
1452 (sort fail-list
1453 (lambda (a b)
1454 (> (length a) (length b))))
1455 "\\|")))))
1456
1457 ;; Add our own grouping parenthesis around re instead of
1458 ;; passing adorn to `regexp-opt', since in XEmacs it makes the
1459 ;; top level grouping "shy".
1460 (cond ((eq adorn 'appendable)
1461 (concat "\\(" re "\\)"))
1462 (adorn
1463 (concat "\\(" re "\\)"
1464 "\\("
1465 (c-get-lang-constant 'c-nonsymbol-key nil mode)
1466 "\\|$\\)"))
1467 (t
1468 re)))
1469
1470 ;; Produce a regexp that matches nothing.
1471 (if adorn
1472 "\\(\\<\\>\\)"
1473 "\\<\\>")))
1474
1475 (put 'c-make-keywords-re 'lisp-indent-function 1)
1476
1477 (defun c-make-bare-char-alt (chars &optional inverted)
1478 "Make a character alternative string from the list of characters CHARS.
1479 The returned string is of the type that can be used with
1480 `skip-chars-forward' and `skip-chars-backward'. If INVERTED is
1481 non-nil, a caret is prepended to invert the set."
1482 ;; This function ought to be in the elisp core somewhere.
1483 (let ((str (if inverted "^" "")) char char2)
1484 (setq chars (sort (append chars nil) `<))
1485 (while chars
1486 (setq char (pop chars))
1487 (if (memq char '(?\\ ?^ ?-))
1488 ;; Quoting necessary (this method only works in the skip
1489 ;; functions).
1490 (setq str (format "%s\\%c" str char))
1491 (setq str (format "%s%c" str char)))
1492 ;; Check for range.
1493 (setq char2 char)
1494 (while (and chars (>= (1+ char2) (car chars)))
1495 (setq char2 (pop chars)))
1496 (unless (= char char2)
1497 (if (< (1+ char) char2)
1498 (setq str (format "%s-%c" str char2))
1499 (push char2 chars))))
1500 str))
1501
1502 ;; Leftovers from (X)Emacs 19 compatibility.
1503 (defalias 'c-regexp-opt 'regexp-opt)
1504 (defalias 'c-regexp-opt-depth 'regexp-opt-depth)
1505
1506 \f
1507 ;; Figure out what features this Emacs has
1508
1509 (cc-bytecomp-defvar open-paren-in-column-0-is-defun-start)
1510
1511 (defconst c-emacs-features
1512 (let (list)
1513
1514 (if (boundp 'infodock-version)
1515 ;; I've no idea what this actually is, but it's legacy. /mast
1516 (setq list (cons 'infodock list)))
1517
1518 ;; XEmacs uses 8-bit modify-syntax-entry flags.
1519 ;; Emacs uses a 1-bit flag. We will have to set up our
1520 ;; syntax tables differently to handle this.
1521 (let ((table (copy-syntax-table))
1522 entry)
1523 (modify-syntax-entry ?a ". 12345678" table)
1524 (cond
1525 ;; Emacs
1526 ((arrayp table)
1527 (setq entry (aref table ?a))
1528 ;; In Emacs, table entries are cons cells
1529 (if (consp entry) (setq entry (car entry))))
1530 ;; XEmacs
1531 ((fboundp 'get-char-table)
1532 (setq entry (get-char-table ?a table)))
1533 ;; incompatible
1534 (t (error "CC Mode is incompatible with this version of Emacs")))
1535 (setq list (cons (if (= (logand (lsh entry -16) 255) 255)
1536 '8-bit
1537 '1-bit)
1538 list)))
1539
1540 ;; Check whether beginning/end-of-defun call
1541 ;; beginning/end-of-defun-function nicely, passing through the
1542 ;; argument and respecting the return code.
1543 (let* (mark-ring
1544 (bod-param 'foo) (eod-param 'foo)
1545 (beginning-of-defun-function
1546 (lambda (&optional arg)
1547 (or (eq bod-param 'foo) (setq bod-param 'bar))
1548 (and (eq bod-param 'foo)
1549 (setq bod-param arg)
1550 (eq arg 3))))
1551 (end-of-defun-function
1552 (lambda (&optional arg)
1553 (and (eq eod-param 'foo)
1554 (setq eod-param arg)
1555 (eq arg 3)))))
1556 (if (save-excursion (and (beginning-of-defun 3) (eq bod-param 3)
1557 (not (beginning-of-defun))
1558 (end-of-defun 3) (eq eod-param 3)
1559 (not (end-of-defun))))
1560 (setq list (cons 'argumentative-bod-function list))))
1561
1562 (let ((buf (generate-new-buffer " test"))
1563 parse-sexp-lookup-properties
1564 parse-sexp-ignore-comments
1565 lookup-syntax-properties)
1566 (with-current-buffer buf
1567 (set-syntax-table (make-syntax-table))
1568
1569 ;; For some reason we have to set some of these after the
1570 ;; buffer has been made current. (Specifically,
1571 ;; `parse-sexp-ignore-comments' in Emacs 21.)
1572 (setq parse-sexp-lookup-properties t
1573 parse-sexp-ignore-comments t
1574 lookup-syntax-properties t)
1575
1576 ;; Find out if the `syntax-table' text property works.
1577 (modify-syntax-entry ?< ".")
1578 (modify-syntax-entry ?> ".")
1579 (insert "<()>")
1580 (c-mark-<-as-paren (point-min))
1581 (c-mark->-as-paren (+ 3 (point-min)))
1582 (goto-char (point-min))
1583 (c-forward-sexp)
1584 (if (= (point) (+ 4 (point-min)))
1585 (setq list (cons 'syntax-properties list))
1586 (error (concat
1587 "CC Mode is incompatible with this version of Emacs - "
1588 "support for the `syntax-table' text property "
1589 "is required.")))
1590
1591 ;; Find out if generic comment delimiters work.
1592 (c-safe
1593 (modify-syntax-entry ?x "!")
1594 (if (string-match "\\s!" "x")
1595 (setq list (cons 'gen-comment-delim list))))
1596
1597 ;; Find out if generic string delimiters work.
1598 (c-safe
1599 (modify-syntax-entry ?x "|")
1600 (if (string-match "\\s|" "x")
1601 (setq list (cons 'gen-string-delim list))))
1602
1603 ;; See if POSIX char classes work.
1604 (when (and (string-match "[[:alpha:]]" "a")
1605 ;; All versions of Emacs 21 so far haven't fixed
1606 ;; char classes in `skip-chars-forward' and
1607 ;; `skip-chars-backward'.
1608 (progn
1609 (delete-region (point-min) (point-max))
1610 (insert "foo123")
1611 (skip-chars-backward "[:alnum:]")
1612 (bobp))
1613 (= (skip-chars-forward "[:alpha:]") 3))
1614 (setq list (cons 'posix-char-classes list)))
1615
1616 ;; See if `open-paren-in-column-0-is-defun-start' exists and
1617 ;; isn't buggy (Emacs >= 21.4).
1618 (when (boundp 'open-paren-in-column-0-is-defun-start)
1619 (let ((open-paren-in-column-0-is-defun-start nil)
1620 (parse-sexp-ignore-comments t))
1621 (delete-region (point-min) (point-max))
1622 (set-syntax-table (make-syntax-table))
1623 (modify-syntax-entry ?\' "\"")
1624 (cond
1625 ;; XEmacs. Afaik this is currently an Emacs-only
1626 ;; feature, but it's good to be prepared.
1627 ((memq '8-bit list)
1628 (modify-syntax-entry ?/ ". 1456")
1629 (modify-syntax-entry ?* ". 23"))
1630 ;; Emacs
1631 ((memq '1-bit list)
1632 (modify-syntax-entry ?/ ". 124b")
1633 (modify-syntax-entry ?* ". 23")))
1634 (modify-syntax-entry ?\n "> b")
1635 (insert "/* '\n () */")
1636 (backward-sexp)
1637 (if (bobp)
1638 (setq list (cons 'col-0-paren list)))))
1639
1640 (set-buffer-modified-p nil))
1641 (kill-buffer buf))
1642
1643 ;; See if `parse-partial-sexp' returns the eighth element.
1644 (if (c-safe (>= (length (save-excursion (parse-partial-sexp (point) (point))))
1645 10))
1646 (setq list (cons 'pps-extended-state list))
1647 (error (concat
1648 "CC Mode is incompatible with this version of Emacs - "
1649 "`parse-partial-sexp' has to return at least 10 elements.")))
1650
1651 ;;(message "c-emacs-features: %S" list)
1652 list)
1653 "A list of certain features in the (X)Emacs you are using.
1654 There are many flavors of Emacs out there, each with different
1655 features supporting those needed by CC Mode. The following values
1656 might be present:
1657
1658 '8-bit 8 bit syntax entry flags (XEmacs style).
1659 '1-bit 1 bit syntax entry flags (Emacs style).
1660 'argumentative-bod-function beginning-of-defun passes ARG through
1661 to a non-null beginning-of-defun-function. It is assumed
1662 the end-of-defun does the same thing.
1663 'syntax-properties It works to override the syntax for specific characters
1664 in the buffer with the 'syntax-table property. It's
1665 always set - CC Mode no longer works in emacsen without
1666 this feature.
1667 'gen-comment-delim Generic comment delimiters work
1668 (i.e. the syntax class `!').
1669 'gen-string-delim Generic string delimiters work
1670 (i.e. the syntax class `|').
1671 'pps-extended-state `parse-partial-sexp' returns a list with at least 10
1672 elements, i.e. it contains the position of the start of
1673 the last comment or string. It's always set - CC Mode
1674 no longer works in emacsen without this feature.
1675 'posix-char-classes The regexp engine understands POSIX character classes.
1676 'col-0-paren It's possible to turn off the ad-hoc rule that a paren
1677 in column zero is the start of a defun.
1678 'infodock This is Infodock (based on XEmacs).
1679
1680 '8-bit and '1-bit are mutually exclusive.")
1681
1682 \f
1683 ;;; Some helper constants.
1684
1685 ;; If the regexp engine supports POSIX char classes then we can use
1686 ;; them to handle extended charsets correctly.
1687 (if (memq 'posix-char-classes c-emacs-features)
1688 (progn
1689 (defconst c-alpha "[:alpha:]")
1690 (defconst c-alnum "[:alnum:]")
1691 (defconst c-digit "[:digit:]")
1692 (defconst c-upper "[:upper:]")
1693 (defconst c-lower "[:lower:]"))
1694 (defconst c-alpha "a-zA-Z")
1695 (defconst c-alnum "a-zA-Z0-9")
1696 (defconst c-digit "0-9")
1697 (defconst c-upper "A-Z")
1698 (defconst c-lower "a-z"))
1699
1700 \f
1701 ;;; System for handling language dependent constants.
1702
1703 ;; This is used to set various language dependent data in a flexible
1704 ;; way: Language constants can be built from the values of other
1705 ;; language constants, also those for other languages. They can also
1706 ;; process the values of other language constants uniformly across all
1707 ;; the languages. E.g. one language constant can list all the type
1708 ;; keywords in each language, and another can build a regexp for each
1709 ;; language from those lists without code duplication.
1710 ;;
1711 ;; Language constants are defined with `c-lang-defconst', and their
1712 ;; value forms (referred to as source definitions) are evaluated only
1713 ;; on demand when requested for a particular language with
1714 ;; `c-lang-const'. It's therefore possible to refer to the values of
1715 ;; constants defined later in the file, or in another file, just as
1716 ;; long as all the relevant `c-lang-defconst' have been loaded when
1717 ;; `c-lang-const' is actually evaluated from somewhere else.
1718 ;;
1719 ;; `c-lang-const' forms are also evaluated at compile time and
1720 ;; replaced with the values they produce. Thus there's no overhead
1721 ;; for this system when compiled code is used - only the values
1722 ;; actually used in the code are present, and the file(s) containing
1723 ;; the `c-lang-defconst' forms don't need to be loaded at all then.
1724 ;; There are however safeguards to make sure that they can be loaded
1725 ;; to get the source definitions for the values if there's a mismatch
1726 ;; in compiled versions, or if `c-lang-const' is used uncompiled.
1727 ;;
1728 ;; Note that the source definitions in a `c-lang-defconst' form are
1729 ;; compiled into the .elc file where it stands; there's no need to
1730 ;; load the source file to get it.
1731 ;;
1732 ;; See cc-langs.el for more details about how this system is deployed
1733 ;; in CC Mode, and how the associated language variable system
1734 ;; (`c-lang-defvar') works. That file also contains a lot of
1735 ;; examples.
1736
1737 (defun c-add-language (mode base-mode)
1738 "Declare a new language in the language dependent variable system.
1739 This is intended to be used by modes that inherit CC Mode to add new
1740 languages. It should be used at the top level before any calls to
1741 `c-lang-defconst'. MODE is the mode name symbol for the new language,
1742 and BASE-MODE is the mode name symbol for the language in CC Mode that
1743 is to be the template for the new mode.
1744
1745 The exact effect of BASE-MODE is to make all language constants that
1746 haven't got a setting in the new language fall back to their values in
1747 BASE-MODE. It does not have any effect outside the language constant
1748 system."
1749 (unless (string-match "\\`\\(.*-\\)mode\\'" (symbol-name mode))
1750 (error "The mode name symbol `%s' must end with \"-mode\"" mode))
1751 (put mode 'c-mode-prefix (match-string 1 (symbol-name mode)))
1752 (unless (get base-mode 'c-mode-prefix)
1753 (error "Unknown base mode `%s'" base-mode))
1754 (put mode 'c-fallback-mode base-mode))
1755
1756 (defvar c-lang-constants (make-vector 151 0))
1757 ;; This obarray is a cache to keep track of the language constants
1758 ;; defined by `c-lang-defconst' and the evaluated values returned by
1759 ;; `c-lang-const'. It's mostly used at compile time but it's not
1760 ;; stored in compiled files.
1761 ;;
1762 ;; The obarray contains all the language constants as symbols. The
1763 ;; value cells hold the evaluated values as alists where each car is
1764 ;; the mode name symbol and the corresponding cdr is the evaluated
1765 ;; value in that mode. The property lists hold the source definitions
1766 ;; and other miscellaneous data. The obarray might also contain
1767 ;; various other symbols, but those don't have any variable bindings.
1768
1769 (defvar c-lang-const-expansion nil)
1770
1771 (defsubst c-get-current-file ()
1772 ;; Return the base name of the current file.
1773 (let ((file (cond
1774 (load-in-progress
1775 ;; Being loaded.
1776 load-file-name)
1777 ((and (boundp 'byte-compile-dest-file)
1778 (stringp byte-compile-dest-file))
1779 ;; Being compiled.
1780 byte-compile-dest-file)
1781 (t
1782 ;; Being evaluated interactively.
1783 (buffer-file-name)))))
1784 (and file
1785 (file-name-sans-extension
1786 (file-name-nondirectory file)))))
1787
1788 (defmacro c-lang-defconst-eval-immediately (form)
1789 "Can be used inside a VAL in `c-lang-defconst' to evaluate FORM
1790 immediately, i.e. at the same time as the `c-lang-defconst' form
1791 itself is evaluated."
1792 ;; Evaluate at macro expansion time, i.e. in the
1793 ;; `cl-macroexpand-all' inside `c-lang-defconst'.
1794 (eval form))
1795
1796 ;; Only used at compile time - suppress "might not be defined at runtime".
1797 (declare-function cl-macroexpand-all "cl-extra" (form &optional env))
1798
1799 (defmacro c-lang-defconst (name &rest args)
1800 "Set the language specific values of the language constant NAME.
1801 The second argument can optionally be a docstring. The rest of the
1802 arguments are one or more repetitions of LANG VAL where LANG specifies
1803 the language(s) that VAL applies to. LANG is the name of the
1804 language, i.e. the mode name without the \"-mode\" suffix, or a list
1805 of such language names, or `t' for all languages. VAL is a form to
1806 evaluate to get the value.
1807
1808 If LANG isn't `t' or one of the core languages in CC Mode, it must
1809 have been declared with `c-add-language'.
1810
1811 Neither NAME, LANG nor VAL are evaluated directly - they should not be
1812 quoted. `c-lang-defconst-eval-immediately' can however be used inside
1813 VAL to evaluate parts of it directly.
1814
1815 When VAL is evaluated for some language, that language is temporarily
1816 made current so that `c-lang-const' without an explicit language can
1817 be used inside VAL to refer to the value of a language constant in the
1818 same language. That is particularly useful if LANG is `t'.
1819
1820 VAL is not evaluated right away but rather when the value is requested
1821 with `c-lang-const'. Thus it's possible to use `c-lang-const' inside
1822 VAL to refer to language constants that haven't been defined yet.
1823 However, if the definition of a language constant is in another file
1824 then that file must be loaded \(at compile time) before it's safe to
1825 reference the constant.
1826
1827 The assignments in ARGS are processed in sequence like `setq', so
1828 \(c-lang-const NAME) may be used inside a VAL to refer to the last
1829 assigned value to this language constant, or a value that it has
1830 gotten in another earlier loaded file.
1831
1832 To work well with repeated loads and interactive reevaluation, only
1833 one `c-lang-defconst' for each NAME is permitted per file. If there
1834 already is one it will be completely replaced; the value in the
1835 earlier definition will not affect `c-lang-const' on the same
1836 constant. A file is identified by its base name."
1837
1838 (let* ((sym (intern (symbol-name name) c-lang-constants))
1839 ;; Make `c-lang-const' expand to a straightforward call to
1840 ;; `c-get-lang-constant' in `cl-macroexpand-all' below.
1841 ;;
1842 ;; (The default behavior, i.e. to expand to a call inside
1843 ;; `eval-when-compile' should be equivalent, since that macro
1844 ;; should only expand to its content if it's used inside a
1845 ;; form that's already evaluated at compile time. It's
1846 ;; however necessary to use our cover macro
1847 ;; `cc-eval-when-compile' due to bugs in `eval-when-compile',
1848 ;; and it expands to a bulkier form that in this case only is
1849 ;; unnecessary garbage that we don't want to store in the
1850 ;; language constant source definitions.)
1851 (c-lang-const-expansion 'call)
1852 (c-langs-are-parametric t)
1853 bindings
1854 pre-files)
1855
1856 (or (symbolp name)
1857 (error "Not a symbol: %s" name))
1858
1859 (when (stringp (car-safe args))
1860 ;; The docstring is hardly used anywhere since there's no normal
1861 ;; symbol to attach it to. It's primarily for getting the right
1862 ;; format in the source.
1863 (put sym 'variable-documentation (car args))
1864 (setq args (cdr args)))
1865
1866 (or args
1867 (error "No assignments in `c-lang-defconst' for %s" name))
1868
1869 ;; Rework ARGS to an association list to make it easier to handle.
1870 ;; It's reversed at the same time to make it easier to implement
1871 ;; the demand-driven (i.e. reversed) evaluation in `c-lang-const'.
1872 (while args
1873 (let ((assigned-mode
1874 (cond ((eq (car args) t) t)
1875 ((symbolp (car args))
1876 (list (intern (concat (symbol-name (car args))
1877 "-mode"))))
1878 ((listp (car args))
1879 (mapcar (lambda (lang)
1880 (or (symbolp lang)
1881 (error "Not a list of symbols: %s"
1882 (car args)))
1883 (intern (concat (symbol-name lang)
1884 "-mode")))
1885 (car args)))
1886 (t (error "Not a symbol or a list of symbols: %s"
1887 (car args)))))
1888 val)
1889
1890 (or (cdr args)
1891 (error "No value for %s" (car args)))
1892 (setq args (cdr args)
1893 val (car args))
1894
1895 ;; Emacs has a weird bug where it seems to fail to read
1896 ;; backquote lists from byte compiled files correctly (,@
1897 ;; forms, to be specific), so make sure the bindings in the
1898 ;; expansion below don't contain any backquote stuff.
1899 ;; (XEmacs handles it correctly and doesn't need this for that
1900 ;; reason, but we also use this expansion handle
1901 ;; `c-lang-defconst-eval-immediately' and to register
1902 ;; dependencies on the `c-lang-const's in VAL.)
1903 (setq val (cl-macroexpand-all val))
1904
1905 (setq bindings (cons (cons assigned-mode val) bindings)
1906 args (cdr args))))
1907
1908 ;; Compile in the other files that have provided source
1909 ;; definitions for this symbol, to make sure the order in the
1910 ;; `source' property is correct even when files are loaded out of
1911 ;; order.
1912 (setq pre-files (nreverse
1913 ;; Reverse to get the right load order.
1914 (mapcar 'car (get sym 'source))))
1915
1916 `(eval-and-compile
1917 (c-define-lang-constant ',name ',bindings
1918 ,@(and pre-files `(',pre-files))))))
1919
1920 (put 'c-lang-defconst 'lisp-indent-function 1)
1921 ;(eval-after-load "edebug" ; 2006-07-09: def-edebug-spec is now in subr.el.
1922 ; '
1923 (def-edebug-spec c-lang-defconst
1924 (&define name [&optional stringp] [&rest sexp def-form]))
1925
1926 (defun c-define-lang-constant (name bindings &optional pre-files)
1927 ;; Used by `c-lang-defconst'.
1928
1929 (let* ((sym (intern (symbol-name name) c-lang-constants))
1930 (source (get sym 'source))
1931 (file (intern
1932 (or (c-get-current-file)
1933 (error "`c-lang-defconst' must be used in a file"))))
1934 (elem (assq file source)))
1935
1936 ;;(when (cdr-safe elem)
1937 ;; (message "Language constant %s redefined in %S" name file))
1938
1939 ;; Note that the order in the source alist is relevant. Like how
1940 ;; `c-lang-defconst' reverses the bindings, this reverses the
1941 ;; order between files so that the last to evaluate comes first.
1942 (unless elem
1943 (while pre-files
1944 (unless (assq (car pre-files) source)
1945 (setq source (cons (list (car pre-files)) source)))
1946 (setq pre-files (cdr pre-files)))
1947 (put sym 'source (cons (setq elem (list file)) source)))
1948
1949 (setcdr elem bindings)
1950
1951 ;; Bind the symbol as a variable, or clear any earlier evaluated
1952 ;; value it has.
1953 (set sym nil)
1954
1955 ;; Clear the evaluated values that depend on this source.
1956 (let ((agenda (get sym 'dependents))
1957 (visited (make-vector 101 0))
1958 ptr)
1959 (while agenda
1960 (setq sym (car agenda)
1961 agenda (cdr agenda))
1962 (intern (symbol-name sym) visited)
1963 (set sym nil)
1964 (setq ptr (get sym 'dependents))
1965 (while ptr
1966 (setq sym (car ptr)
1967 ptr (cdr ptr))
1968 (unless (intern-soft (symbol-name sym) visited)
1969 (setq agenda (cons sym agenda))))))
1970
1971 name))
1972
1973 (defmacro c-lang-const (name &optional lang)
1974 "Get the mode specific value of the language constant NAME in language LANG.
1975 LANG is the name of the language, i.e. the mode name without the
1976 \"-mode\" suffix. If used inside `c-lang-defconst' or
1977 `c-lang-defvar', LANG may be left out to refer to the current
1978 language. NAME and LANG are not evaluated so they should not be
1979 quoted."
1980
1981 (or (symbolp name)
1982 (error "Not a symbol: %s" name))
1983 (or (symbolp lang)
1984 (error "Not a symbol: %s" lang))
1985
1986 (let ((sym (intern (symbol-name name) c-lang-constants))
1987 mode source-files args)
1988
1989 (when lang
1990 (setq mode (intern (concat (symbol-name lang) "-mode")))
1991 (unless (get mode 'c-mode-prefix)
1992 (error
1993 "Unknown language %S since it got no `c-mode-prefix' property"
1994 (symbol-name lang))))
1995
1996 (if (eq c-lang-const-expansion 'immediate)
1997 ;; No need to find out the source file(s) when we evaluate
1998 ;; immediately since all the info is already there in the
1999 ;; `source' property.
2000 `',(c-get-lang-constant name nil mode)
2001
2002 (let ((file (c-get-current-file)))
2003 (if file (setq file (intern file)))
2004 ;; Get the source file(s) that must be loaded to get the value
2005 ;; of the constant. If the symbol isn't defined yet we assume
2006 ;; that its definition will come later in this file, and thus
2007 ;; are no file dependencies needed.
2008 (setq source-files (nreverse
2009 ;; Reverse to get the right load order.
2010 (apply 'nconc
2011 (mapcar (lambda (elem)
2012 (if (eq file (car elem))
2013 nil ; Exclude our own file.
2014 (list (car elem))))
2015 (get sym 'source))))))
2016
2017 ;; Make some effort to do a compact call to
2018 ;; `c-get-lang-constant' since it will be compiled in.
2019 (setq args (and mode `(',mode)))
2020 (if (or source-files args)
2021 (setq args (cons (and source-files `',source-files)
2022 args)))
2023
2024 (if (or (eq c-lang-const-expansion 'call)
2025 (and (not c-lang-const-expansion)
2026 (not mode))
2027 load-in-progress
2028 (not (boundp 'byte-compile-dest-file))
2029 (not (stringp byte-compile-dest-file)))
2030 ;; Either a straight call is requested in the context, or
2031 ;; we're in an "uncontrolled" context and got no language,
2032 ;; or we're not being byte compiled so the compile time
2033 ;; stuff below is unnecessary.
2034 `(c-get-lang-constant ',name ,@args)
2035
2036 ;; Being compiled. If the loading and compiling version is
2037 ;; the same we use a value that is evaluated at compile time,
2038 ;; otherwise it's evaluated at runtime.
2039 `(if (eq c-version-sym ',c-version-sym)
2040 (cc-eval-when-compile
2041 (c-get-lang-constant ',name ,@args))
2042 (c-get-lang-constant ',name ,@args))))))
2043
2044 (defvar c-lang-constants-under-evaluation nil)
2045
2046 (defun c-get-lang-constant (name &optional source-files mode)
2047 ;; Used by `c-lang-const'.
2048
2049 (or mode
2050 (setq mode c-buffer-is-cc-mode)
2051 (error "No current language"))
2052
2053 (let* ((sym (intern (symbol-name name) c-lang-constants))
2054 (source (get sym 'source))
2055 elem
2056 (eval-in-sym (and c-lang-constants-under-evaluation
2057 (caar c-lang-constants-under-evaluation))))
2058
2059 ;; Record the dependencies between this symbol and the one we're
2060 ;; being evaluated in.
2061 (when eval-in-sym
2062 (or (memq eval-in-sym (get sym 'dependents))
2063 (put sym 'dependents (cons eval-in-sym (get sym 'dependents)))))
2064
2065 ;; Make sure the source files have entries on the `source'
2066 ;; property so that loading will take place when necessary.
2067 (while source-files
2068 (unless (assq (car source-files) source)
2069 (put sym 'source
2070 (setq source (cons (list (car source-files)) source)))
2071 ;; Might pull in more definitions which affect the value. The
2072 ;; clearing of dependent values etc is done when the
2073 ;; definition is encountered during the load; this is just to
2074 ;; jump past the check for a cached value below.
2075 (set sym nil))
2076 (setq source-files (cdr source-files)))
2077
2078 (if (and (boundp sym)
2079 (setq elem (assq mode (symbol-value sym))))
2080 (cdr elem)
2081
2082 ;; Check if an evaluation of this symbol is already underway.
2083 ;; In that case we just continue with the "assignment" before
2084 ;; the one currently being evaluated, thereby creating the
2085 ;; illusion if a `setq'-like sequence of assignments.
2086 (let* ((c-buffer-is-cc-mode mode)
2087 (source-pos
2088 (or (assq sym c-lang-constants-under-evaluation)
2089 (cons sym (vector source nil))))
2090 ;; Append `c-lang-constants-under-evaluation' even if an
2091 ;; earlier entry is found. It's only necessary to get
2092 ;; the recording of dependencies above correct.
2093 (c-lang-constants-under-evaluation
2094 (cons source-pos c-lang-constants-under-evaluation))
2095 (fallback (get mode 'c-fallback-mode))
2096 value
2097 ;; Make sure the recursion limits aren't very low
2098 ;; since the `c-lang-const' dependencies can go deep.
2099 (max-specpdl-size (max max-specpdl-size 3000))
2100 (max-lisp-eval-depth (max max-lisp-eval-depth 1000)))
2101
2102 (if (if fallback
2103 (let ((backup-source-pos (copy-sequence (cdr source-pos))))
2104 (and
2105 ;; First try the original mode but don't accept an
2106 ;; entry matching all languages since the fallback
2107 ;; mode might have an explicit entry before that.
2108 (eq (setq value (c-find-assignment-for-mode
2109 (cdr source-pos) mode nil name))
2110 c-lang-constants)
2111 ;; Try again with the fallback mode from the
2112 ;; original position. Note that
2113 ;; `c-buffer-is-cc-mode' still is the real mode if
2114 ;; language parameterization takes place.
2115 (eq (setq value (c-find-assignment-for-mode
2116 (setcdr source-pos backup-source-pos)
2117 fallback t name))
2118 c-lang-constants)))
2119 ;; A simple lookup with no fallback mode.
2120 (eq (setq value (c-find-assignment-for-mode
2121 (cdr source-pos) mode t name))
2122 c-lang-constants))
2123 (error
2124 "`%s' got no (prior) value in %s (might be a cyclic reference)"
2125 name mode))
2126
2127 (condition-case err
2128 (setq value (eval value))
2129 (error
2130 ;; Print a message to aid in locating the error. We don't
2131 ;; print the error itself since that will be done later by
2132 ;; some caller higher up.
2133 (message "Eval error in the `c-lang-defconst' for `%s' in %s:"
2134 sym mode)
2135 (makunbound sym)
2136 (signal (car err) (cdr err))))
2137
2138 (set sym (cons (cons mode value) (symbol-value sym)))
2139 value))))
2140
2141 (defun c-find-assignment-for-mode (source-pos mode match-any-lang name)
2142 ;; Find the first assignment entry that applies to MODE at or after
2143 ;; SOURCE-POS. If MATCH-ANY-LANG is non-nil, entries with `t' as
2144 ;; the language list are considered to match, otherwise they don't.
2145 ;; On return SOURCE-POS is updated to point to the next assignment
2146 ;; after the returned one. If no assignment is found,
2147 ;; `c-lang-constants' is returned as a magic value.
2148 ;;
2149 ;; SOURCE-POS is a vector that points out a specific assignment in
2150 ;; the double alist that's used in the `source' property. The first
2151 ;; element is the position in the top alist which is indexed with
2152 ;; the source files, and the second element is the position in the
2153 ;; nested bindings alist.
2154 ;;
2155 ;; NAME is only used for error messages.
2156
2157 (catch 'found
2158 (let ((file-entry (elt source-pos 0))
2159 (assignment-entry (elt source-pos 1))
2160 assignment)
2161
2162 (while (if assignment-entry
2163 t
2164 ;; Handled the last assignment from one file, begin on the
2165 ;; next. Due to the check in `c-lang-defconst', we know
2166 ;; there's at least one.
2167 (when file-entry
2168
2169 (unless (aset source-pos 1
2170 (setq assignment-entry (cdar file-entry)))
2171 ;; The file containing the source definitions has not
2172 ;; been loaded.
2173 (let ((file (symbol-name (caar file-entry)))
2174 (c-lang-constants-under-evaluation nil))
2175 ;;(message (concat "Loading %s to get the source "
2176 ;; "value for language constant %s")
2177 ;; file name)
2178 (load file))
2179
2180 (unless (setq assignment-entry (cdar file-entry))
2181 ;; The load didn't fill in the source for the
2182 ;; constant as expected. The situation is
2183 ;; probably that a derived mode was written for
2184 ;; and compiled with another version of CC Mode,
2185 ;; and the requested constant isn't in the
2186 ;; currently loaded one. Put in a dummy
2187 ;; assignment that matches no language.
2188 (setcdr (car file-entry)
2189 (setq assignment-entry (list (list nil))))))
2190
2191 (aset source-pos 0 (setq file-entry (cdr file-entry)))
2192 t))
2193
2194 (setq assignment (car assignment-entry))
2195 (aset source-pos 1
2196 (setq assignment-entry (cdr assignment-entry)))
2197
2198 (when (if (listp (car assignment))
2199 (memq mode (car assignment))
2200 match-any-lang)
2201 (throw 'found (cdr assignment))))
2202
2203 c-lang-constants)))
2204
2205 (defun c-lang-major-mode-is (mode)
2206 ;; `c-major-mode-is' expands to a call to this function inside
2207 ;; `c-lang-defconst'. Here we also match the mode(s) against any
2208 ;; fallback modes for the one in `c-buffer-is-cc-mode', so that
2209 ;; e.g. (c-major-mode-is 'c++-mode) is true in a derived language
2210 ;; that has c++-mode as base mode.
2211 (unless (listp mode)
2212 (setq mode (list mode)))
2213 (let (match (buf-mode c-buffer-is-cc-mode))
2214 (while (if (memq buf-mode mode)
2215 (progn
2216 (setq match t)
2217 nil)
2218 (setq buf-mode (get buf-mode 'c-fallback-mode))))
2219 match))
2220
2221 \f
2222 (cc-provide 'cc-defs)
2223
2224 ;; arch-tag: 3bb2629d-dd84-4ff0-ad39-584be0fe3cda
2225 ;;; cc-defs.el ends here