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