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