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