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