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