]> code.delx.au - gnu-emacs/blob - lisp/cedet/semantic/bovine/c.el
Update copyright notices for 2013.
[gnu-emacs] / lisp / cedet / semantic / bovine / c.el
1 ;;; semantic/bovine/c.el --- Semantic details for C
2
3 ;; Copyright (C) 1999-2013 Free Software Foundation, Inc.
4
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23 ;;
24 ;; Support for the C/C++ bovine parser for Semantic.
25 ;;
26 ;; @todo - can I support c++-font-lock-extra-types ?
27
28 (require 'semantic)
29 (require 'semantic/analyze)
30 (require 'semantic/bovine)
31 (require 'semantic/bovine/gcc)
32 (require 'semantic/idle)
33 (require 'semantic/lex-spp)
34 (require 'semantic/bovine/c-by)
35 (require 'semantic/db-find)
36 (require 'hideif)
37
38 (eval-when-compile
39 (require 'semantic/find))
40
41 (declare-function semantic-brute-find-tag-by-attribute "semantic/find")
42 (declare-function semanticdb-minor-mode-p "semantic/db-mode")
43 (declare-function semanticdb-needs-refresh-p "semantic/db")
44 (declare-function semanticdb-typecache-faux-namespace "semantic/db-typecache")
45 (declare-function c-forward-conditional "cc-cmds")
46 (declare-function ede-system-include-path "ede")
47
48 ;;; Compatibility
49 ;;
50 (eval-when-compile (require 'cc-mode))
51
52 (if (fboundp 'c-end-of-macro)
53 (eval-and-compile
54 (defalias 'semantic-c-end-of-macro 'c-end-of-macro))
55 ;; From cc-mode 5.30
56 (defun semantic-c-end-of-macro ()
57 "Go to the end of a preprocessor directive.
58 More accurately, move point to the end of the closest following line
59 that doesn't end with a line continuation backslash.
60
61 This function does not do any hidden buffer changes."
62 (while (progn
63 (end-of-line)
64 (when (and (eq (char-before) ?\\)
65 (not (eobp)))
66 (forward-char)
67 t))))
68 )
69
70 ;;; Code:
71 (define-child-mode c++-mode c-mode
72 "`c++-mode' uses the same parser as `c-mode'.")
73
74 \f
75 ;;; Include Paths
76 ;;
77 (defcustom-mode-local-semantic-dependency-system-include-path
78 c-mode semantic-c-dependency-system-include-path
79 '("/usr/include")
80 "The system include path used by the C language.")
81
82 (defcustom semantic-default-c-path nil
83 "Default set of include paths for C code.
84 Used by `semantic-dep' to define an include path.
85 NOTE: In process of obsoleting this."
86 :group 'c
87 :group 'semantic
88 :type '(repeat (string :tag "Path")))
89
90 (defvar-mode-local c-mode semantic-dependency-include-path
91 semantic-default-c-path
92 "System path to search for include files.")
93
94 ;;; Compile Options
95 ;;
96 ;; Compiler options need to show up after path setup, but before
97 ;; the preprocessor section.
98
99 (if (memq system-type '(gnu gnu/linux darwin cygwin))
100 (semantic-gcc-setup))
101
102 ;;; Pre-processor maps
103 ;;
104 ;;; Lexical analysis
105 (defvar semantic-lex-c-preprocessor-symbol-map-builtin
106 '( ("__THROW" . "")
107 ("__const" . "const")
108 ("__restrict" . "")
109 ("__attribute_pure__" . "")
110 ("__attribute_malloc__" . "")
111 ("__nonnull" . "")
112 ("__wur" . "")
113 ("__declspec" . ((spp-arg-list ("foo") 1 . 2)))
114 ("__attribute__" . ((spp-arg-list ("foo") 1 . 2)))
115 ("__asm" . ((spp-arg-list ("foo") 1 . 2)))
116 )
117 "List of symbols to include by default.")
118
119 (defvar semantic-c-in-reset-preprocessor-table nil
120 "Non-nil while resetting the preprocessor symbol map.
121 Used to prevent a reset while trying to parse files that are
122 part of the preprocessor map.")
123
124 (defvar semantic-lex-c-preprocessor-symbol-file)
125 (defvar semantic-lex-c-preprocessor-symbol-map)
126
127 (defun semantic-c-reset-preprocessor-symbol-map ()
128 "Reset the C preprocessor symbol map based on all input variables."
129 (when (and semantic-mode
130 (featurep 'semantic/bovine/c))
131 (remove-hook 'mode-local-init-hook 'semantic-c-reset-preprocessor-symbol-map)
132 ;; Initialize semantic-lex-spp-macro-symbol-obarray with symbols.
133 (setq-mode-local c-mode
134 semantic-lex-spp-macro-symbol-obarray
135 (semantic-lex-make-spp-table
136 (append semantic-lex-c-preprocessor-symbol-map-builtin
137 semantic-lex-c-preprocessor-symbol-map)))
138 (let ((filemap nil)
139 )
140 (when (and (not semantic-c-in-reset-preprocessor-table)
141 (featurep 'semantic/db-mode)
142 (semanticdb-minor-mode-p))
143 (let ( ;; Don't use external parsers. We need the internal one.
144 (semanticdb-out-of-buffer-create-table-fcn nil)
145 ;; Don't recurse while parsing these files the first time.
146 (semantic-c-in-reset-preprocessor-table t)
147 )
148 (dolist (sf semantic-lex-c-preprocessor-symbol-file)
149 ;; Global map entries
150 (let* ((table (semanticdb-file-table-object sf t)))
151 (when table
152 (when (semanticdb-needs-refresh-p table)
153 (condition-case nil
154 ;; Call with FORCE, as the file is very likely to
155 ;; not be in a buffer.
156 (semanticdb-refresh-table table t)
157 (error (message "Error updating tables for %S"
158 (object-name table)))))
159 (setq filemap (append filemap (oref table lexical-table)))
160 ;; Update symbol obarray
161 (setq-mode-local c-mode
162 semantic-lex-spp-macro-symbol-obarray
163 (semantic-lex-make-spp-table
164 (append semantic-lex-c-preprocessor-symbol-map-builtin
165 semantic-lex-c-preprocessor-symbol-map
166 filemap)))))))))))
167
168 ;; Make sure the preprocessor symbols are set up when mode-local kicks
169 ;; in.
170 (add-hook 'mode-local-init-hook 'semantic-c-reset-preprocessor-symbol-map)
171
172 (defcustom semantic-lex-c-preprocessor-symbol-map nil
173 "Table of C Preprocessor keywords used by the Semantic C lexer.
174 Each entry is a cons cell like this:
175 ( \"KEYWORD\" . \"REPLACEMENT\" )
176 Where KEYWORD is the macro that gets replaced in the lexical phase,
177 and REPLACEMENT is a string that is inserted in its place. Empty string
178 implies that the lexical analyzer will discard KEYWORD when it is encountered.
179
180 Alternately, it can be of the form:
181 ( \"KEYWORD\" ( LEXSYM1 \"str\" 1 1 ) ... ( LEXSYMN \"str\" 1 1 ) )
182 where LEXSYM is a symbol that would normally be produced by the
183 lexical analyzer, such as `symbol' or `string'. The string in the
184 second position is the text that makes up the replacement. This is
185 the way to have multiple lexical symbols in a replacement. Using the
186 first way to specify text like \"foo::bar\" would not work, because :
187 is a separate lexical symbol.
188
189 A quick way to see what you would need to insert is to place a
190 definition such as:
191
192 #define MYSYM foo::bar
193
194 into a C file, and do this:
195 \\[semantic-lex-spp-describe]
196
197 The output table will describe the symbols needed."
198 :group 'c
199 :type '(repeat (cons (string :tag "Keyword")
200 (sexp :tag "Replacement")))
201 :set (lambda (sym value)
202 (set-default sym value)
203 (condition-case nil
204 (semantic-c-reset-preprocessor-symbol-map)
205 (error nil))
206 )
207 )
208
209 (defcustom semantic-lex-c-preprocessor-symbol-file nil
210 "List of C/C++ files that contain preprocessor macros for the C lexer.
211 Each entry is a filename and each file is parsed, and those macros
212 are included in every C/C++ file parsed by semantic.
213 You can use this variable instead of `semantic-lex-c-preprocessor-symbol-map'
214 to store your global macros in a more natural way."
215 :group 'c
216 :type '(repeat (file :tag "File"))
217 :set (lambda (sym value)
218 (set-default sym value)
219 (condition-case nil
220 (semantic-c-reset-preprocessor-symbol-map)
221 (error nil))
222 )
223 )
224
225 (defcustom semantic-c-member-of-autocast 't
226 "Non-nil means classes with a '->' operator will cast to its return type.
227
228 For Examples:
229
230 class Foo {
231 Bar *operator->();
232 }
233
234 Foo foo;
235
236 if `semantic-c-member-of-autocast' is non-nil :
237 foo->[here completion will list method of Bar]
238
239 if `semantic-c-member-of-autocast' is nil :
240 foo->[here completion will list method of Foo]"
241 :group 'c
242 :type 'boolean)
243
244 (define-lex-spp-macro-declaration-analyzer semantic-lex-cpp-define
245 "A #define of a symbol with some value.
246 Record the symbol in the semantic preprocessor.
247 Return the defined symbol as a special spp lex token."
248 "^\\s-*#\\s-*define\\s-+\\(\\(\\sw\\|\\s_\\)+\\)" 1
249 (goto-char (match-end 0))
250 (skip-chars-forward " \t")
251 (if (eolp)
252 nil
253 (let* ((name (buffer-substring-no-properties
254 (match-beginning 1) (match-end 1)))
255 (beginning-of-define (match-end 1))
256 (with-args (save-excursion
257 (goto-char (match-end 0))
258 (looking-at "(")))
259 (semantic-lex-spp-replacements-enabled nil)
260 ;; Temporarily override the lexer to include
261 ;; special items needed inside a macro
262 (semantic-lex-analyzer #'semantic-cpp-lexer)
263 (raw-stream
264 (semantic-lex-spp-stream-for-macro (save-excursion
265 (semantic-c-end-of-macro)
266 ;; HACK - If there's a C comment after
267 ;; the macro, do not parse it.
268 (if (looking-back "/\\*.*" beginning-of-define)
269 (progn
270 (goto-char (match-beginning 0))
271 (1- (point)))
272 (point)))))
273 )
274
275 ;; Only do argument checking if the paren was immediately after
276 ;; the macro name.
277 (if with-args
278 (semantic-lex-spp-first-token-arg-list (car raw-stream)))
279
280 ;; Magical spp variable for end point.
281 (setq semantic-lex-end-point (point))
282
283 ;; Handled nested macro streams.
284 (semantic-lex-spp-merge-streams raw-stream)
285 )))
286
287 (define-lex-spp-macro-undeclaration-analyzer semantic-lex-cpp-undef
288 "A #undef of a symbol.
289 Remove the symbol from the semantic preprocessor.
290 Return the defined symbol as a special spp lex token."
291 "^\\s-*#\\s-*undef\\s-+\\(\\(\\sw\\|\\s_\\)+\\)" 1)
292
293 \f
294 ;;; Conditional Skipping
295 ;;
296 (defcustom semantic-c-obey-conditional-section-parsing-flag t
297 "*Non-nil means to interpret preprocessor #if sections.
298 This implies that some blocks of code will not be parsed based on the
299 values of the conditions in the #if blocks."
300 :group 'c
301 :type 'boolean)
302
303 (defun semantic-c-skip-conditional-section ()
304 "Skip one section of a conditional.
305 Moves forward to a matching #elif, #else, or #endif.
306 Moves completely over balanced #if blocks."
307 (require 'cc-cmds)
308 (let ((done nil))
309 ;; (if (looking-at "^\\s-*#if")
310 ;; (semantic-lex-spp-push-if (point))
311 (end-of-line)
312 (while (and semantic-c-obey-conditional-section-parsing-flag
313 (and (not done)
314 (re-search-forward
315 "^\\s-*#\\s-*\\(if\\(n?def\\)?\\|el\\(if\\|se\\)\\|endif\\)\\>"
316 nil t)))
317 (goto-char (match-beginning 0))
318 (cond
319 ((looking-at "^\\s-*#\\s-*if")
320 ;; We found a nested if. Skip it.
321 (if (fboundp 'c-scan-conditionals)
322 (goto-char (c-scan-conditionals 1))
323 ;; For older Emacsen, but this will set the mark.
324 (c-forward-conditional 1)))
325 ((looking-at "^\\s-*#\\s-*elif")
326 ;; We need to let the preprocessor analyze this one.
327 (beginning-of-line)
328 (setq done t)
329 )
330 ((looking-at "^\\s-*#\\s-*\\(endif\\|else\\)\\>")
331 ;; We are at the end. Pop our state.
332 ;; (semantic-lex-spp-pop-if)
333 ;; Note: We include ELSE and ENDIF the same. If skip some previous
334 ;; section, then we should do the else by default, making it much
335 ;; like the endif.
336 (end-of-line)
337 (forward-char 1)
338 (setq done t))
339 (t
340 ;; We found an elif. Stop here.
341 (setq done t))))))
342
343 ;;; HIDEIF USAGE:
344 ;; NOTE: All hideif using code was contributed by Brian Carlson as
345 ;; copies from hideif plus modifications and additions.
346 ;; Eric then converted things to use hideif functions directly,
347 ;; deleting most of that code, and added the advice.
348
349 ;;; SPP SYM EVAL
350 ;;
351 ;; Convert SPP symbols into values usable by hideif.
352 ;;
353 ;; @TODO - can these conversion fcns be a part of semantic-lex-spp.el?
354 ;; -- TRY semantic-lex-spp-one-token-to-txt
355 (defun semantic-c-convert-spp-value-to-hideif-value (symbol macrovalue)
356 "Convert an spp macro SYMBOL MACROVALUE, to something that hideif can use.
357 Take the first interesting thing and convert it."
358 ;; Just warn for complex macros.
359 (when (> (length macrovalue) 1)
360 (semantic-push-parser-warning
361 (format "Complex macro value (%s) may be improperly evaluated. "
362 symbol) 0 0))
363
364 (let* ((lextoken (car macrovalue))
365 (key (semantic-lex-token-class lextoken))
366 (value (semantic-lex-token-text lextoken)))
367 (cond
368 ((eq key 'number) (string-to-number value))
369 ((eq key 'symbol) (semantic-c-evaluate-symbol-for-hideif value))
370 ((eq key 'string)
371 (if (string-match "^[0-9]+L?$" value)
372 ;; If it matches a number expression, then
373 ;; convert to a number.
374 (string-to-number value)
375 value))
376 (t (semantic-push-parser-warning
377 (format "Unknown macro value. Token class = %s value = %s. " key value)
378 0 0)
379 nil)
380 )))
381
382 (defun semantic-c-evaluate-symbol-for-hideif (spp-symbol)
383 "Lookup the symbol SPP-SYMBOL (a string) to something hideif can use.
384 Pulls out the symbol list, and call `semantic-c-convert-spp-value-to-hideif-value'."
385 (interactive "sSymbol name: ")
386 (when (symbolp spp-symbol) (setq spp-symbol (symbol-name spp-symbol)))
387
388 (if (semantic-lex-spp-symbol-p spp-symbol )
389 ;; Convert the symbol into a stream of tokens from the macro which we
390 ;; can then interpret.
391 (let ((stream (semantic-lex-spp-symbol-stream spp-symbol)))
392 (cond
393 ;; Empty string means defined, so t.
394 ((null stream) t)
395 ;; A list means a parsed macro stream.
396 ((listp stream)
397 ;; Convert the macro to something we can return.
398 (semantic-c-convert-spp-value-to-hideif-value spp-symbol stream))
399
400 ;; Strings might need to be turned into numbers
401 ((stringp stream)
402 (if (string-match "^[0-9]+L?$" stream)
403 ;; If it matches a number expression, then convert to a
404 ;; number.
405 (string-to-number stream)
406 stream))
407
408 ;; Just return the stream. A user might have just stuck some
409 ;; value in it directly.
410 (t stream)
411 ))
412 ;; Else, store an error, return nil.
413 (progn
414 (semantic-push-parser-warning
415 (format "SPP Symbol %s not available" spp-symbol)
416 (point) (point))
417 nil)))
418
419 ;;; HIDEIF HACK support fcns
420 ;;
421 ;; These fcns can replace the impl of some hideif features.
422 ;;
423 ;; @TODO - Should hideif and semantic-c merge?
424 ;; I picture a grammar just for CPP that expands into
425 ;; a second token stream for the parser.
426 (defun semantic-c-hideif-lookup (var)
427 "Replacement for `hif-lookup'.
428 I think it just gets the value for some CPP variable VAR."
429 (let ((val (semantic-c-evaluate-symbol-for-hideif
430 (cond
431 ((stringp var) var)
432 ((symbolp var) (symbol-name var))
433 (t "Unable to determine var")))))
434 (if val
435 val
436 ;; Real hideif will return the right undefined symbol.
437 nil)))
438
439 (defun semantic-c-hideif-defined (var)
440 "Replacement for `hif-defined'.
441 I think it just returns t/nil dependent on if VAR has been defined."
442 (let ((var-symbol-name
443 (cond
444 ((symbolp var) (symbol-name var))
445 ((stringp var) var)
446 (t "Not A Symbol"))))
447 (if (not (semantic-lex-spp-symbol-p var-symbol-name))
448 (progn
449 (semantic-push-parser-warning
450 (format "Skip %s" (buffer-substring-no-properties
451 (point-at-bol) (point-at-eol)))
452 (point-at-bol) (point-at-eol))
453 nil)
454 t)))
455
456 ;;; HIDEIF ADVICE
457 ;;
458 ;; Advise hideif functions to use our lexical tables instead.
459 (defvar semantic-c-takeover-hideif nil
460 "Non-nil when Semantic is taking over hideif features.")
461
462 ;; (defadvice hif-defined (around semantic-c activate)
463 ;; "Is the variable defined?"
464 ;; (if semantic-c-takeover-hideif
465 ;; (setq ad-return-value
466 ;; (semantic-c-hideif-defined (ad-get-arg 0)))
467 ;; ad-do-it))
468
469 ;; (defadvice hif-lookup (around semantic-c activate)
470 ;; "Is the argument defined? Return true or false."
471 ;; (let ((ans nil))
472 ;; (when semantic-c-takeover-hideif
473 ;; (setq ans (semantic-c-hideif-lookup (ad-get-arg 0))))
474 ;; (if (null ans)
475 ;; ad-do-it
476 ;; (setq ad-return-value ans))))
477
478 ;;; #if macros
479 ;;
480 ;; Support #if macros by evaluating the values via use of hideif
481 ;; logic. See above for hacks to make this work.
482 (define-lex-regex-analyzer semantic-lex-c-if
483 "Code blocks wrapped up in #if, or #ifdef.
484 Uses known macro tables in SPP to determine what block to skip."
485 "^\\s-*#\\s-*\\(if\\|elif\\).*$"
486 (semantic-c-do-lex-if))
487
488 (defun semantic-c-do-lex-if ()
489 "Handle lexical CPP if statements.
490 Enables a takeover of some hideif functions, then uses hideif to
491 evaluate the #if expression and enables us to make decisions on which
492 code to parse."
493 ;; Enable our advice, and use hideif to parse.
494 (let* ((semantic-c-takeover-hideif t)
495 (hif-ifx-regexp (concat hif-cpp-prefix "\\(elif\\|if\\(n?def\\)?\\)[ \t]+"))
496 (parsedtokelist
497 (condition-case nil
498 ;; This is imperfect, so always assume on error.
499 (hif-canonicalize)
500 (error nil))))
501
502 (let ((eval-form (eval parsedtokelist)))
503 (if (or (not eval-form)
504 (and (numberp eval-form)
505 (equal eval-form 0)));; ifdefline resulted in false
506
507 ;; The if indicates to skip this preprocessor section
508 (let ((pt nil))
509 (semantic-push-parser-warning (format "Skip %s" (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
510 (point-at-bol) (point-at-eol))
511 (beginning-of-line)
512 (setq pt (point))
513 ;; This skips only a section of a conditional. Once that section
514 ;; is opened, encountering any new #else or related conditional
515 ;; should be skipped.
516 (semantic-c-skip-conditional-section)
517 (setq semantic-lex-end-point (point))
518
519 ;; @TODO -somewhere around here, we also need to skip
520 ;; other sections of the conditional.
521
522 nil)
523 ;; Else, don't ignore it, but do handle the internals.
524 (end-of-line)
525 (setq semantic-lex-end-point (point))
526 nil))))
527
528 (define-lex-regex-analyzer semantic-lex-c-ifdef
529 "Code blocks wrapped up in #ifdef.
530 Uses known macro tables in SPP to determine what block to skip."
531 "^\\s-*#\\s-*\\(ifndef\\|ifdef\\)\\s-+\\(\\(\\sw\\|\\s_\\)+\\)$"
532 (semantic-c-do-lex-ifdef))
533
534 (defun semantic-c-do-lex-ifdef ()
535 "Handle lexical CPP if statements."
536 (let* ((sym (buffer-substring-no-properties
537 (match-beginning 2) (match-end 2)))
538 (ift (buffer-substring-no-properties
539 (match-beginning 1) (match-end 1)))
540 (ifdef (string= ift "ifdef"))
541 (ifndef (string= ift "ifndef"))
542 )
543 (if (or (and ifdef (not (semantic-lex-spp-symbol-p sym)))
544 (and ifndef (semantic-lex-spp-symbol-p sym)))
545 ;; The if indicates to skip this preprocessor section.
546 (let ((pt nil))
547 ;; (message "%s %s yes" ift sym)
548 (beginning-of-line)
549 (setq pt (point))
550 ;; This skips only a section of a conditional. Once that section
551 ;; is opened, encountering any new #else or related conditional
552 ;; should be skipped.
553 (semantic-c-skip-conditional-section)
554 (setq semantic-lex-end-point (point))
555 (semantic-push-parser-warning (format "Skip #%s %s" ift sym)
556 pt (point))
557 ;; (semantic-lex-push-token
558 ;; (semantic-lex-token 'c-preprocessor-skip pt (point)))
559 nil)
560 ;; Else, don't ignore it, but do handle the internals.
561 ;;(message "%s %s no" ift sym)
562 (end-of-line)
563 (setq semantic-lex-end-point (point))
564 nil)))
565
566 (define-lex-regex-analyzer semantic-lex-c-macro-else
567 "Ignore an #else block.
568 We won't see the #else due to the macro skip section block
569 unless we are actively parsing an open #if statement. In that
570 case, we must skip it since it is the ELSE part."
571 "^\\s-*#\\s-*\\(else\\)"
572 (let ((pt (point)))
573 (semantic-c-skip-conditional-section)
574 (setq semantic-lex-end-point (point))
575 (semantic-push-parser-warning "Skip #else" pt (point))
576 ;; (semantic-lex-push-token
577 ;; (semantic-lex-token 'c-preprocessor-skip pt (point)))
578 nil))
579
580 (define-lex-regex-analyzer semantic-lex-c-macrobits
581 "Ignore various forms of #if/#else/#endif conditionals."
582 "^\\s-*#\\s-*\\(if\\(n?def\\)?\\|endif\\|elif\\|else\\)"
583 (semantic-c-end-of-macro)
584 (setq semantic-lex-end-point (point))
585 nil)
586
587 (define-lex-spp-include-analyzer semantic-lex-c-include-system
588 "Identify include strings, and return special tokens."
589 "^\\s-*#\\s-*include\\s-*<\\([^ \t\n>]+\\)>" 0
590 ;; Hit 1 is the name of the include.
591 (goto-char (match-end 0))
592 (setq semantic-lex-end-point (point))
593 (cons (buffer-substring-no-properties (match-beginning 1)
594 (match-end 1))
595 'system))
596
597 (define-lex-spp-include-analyzer semantic-lex-c-include
598 "Identify include strings, and return special tokens."
599 "^\\s-*#\\s-*include\\s-*\"\\([^ \t\n>]+\\)\"" 0
600 ;; Hit 1 is the name of the include.
601 (goto-char (match-end 0))
602 (setq semantic-lex-end-point (point))
603 (cons (buffer-substring-no-properties (match-beginning 1)
604 (match-end 1))
605 nil))
606
607
608 (define-lex-regex-analyzer semantic-lex-c-ignore-ending-backslash
609 "Skip backslash ending a line.
610 Go to the next line."
611 "\\\\\\s-*\n"
612 (setq semantic-lex-end-point (match-end 0)))
613
614 (define-lex-regex-analyzer semantic-lex-c-namespace-begin-macro
615 "Handle G++'s namespace macros which the pre-processor can't handle."
616 "\\(_GLIBCXX_BEGIN_NAMESPACE\\)(\\s-*\\(\\(?:\\w\\|\\s_\\)+\\)\\s-*)"
617 (let* ((nsend (match-end 1))
618 (sym-start (match-beginning 2))
619 (sym-end (match-end 2))
620 (ms (buffer-substring-no-properties sym-start sym-end)))
621 ;; Push the namespace keyword.
622 (semantic-lex-push-token
623 (semantic-lex-token 'NAMESPACE (match-beginning 0) nsend "namespace"))
624 ;; Push the name.
625 (semantic-lex-push-token
626 (semantic-lex-token 'symbol sym-start sym-end ms))
627 )
628 (goto-char (match-end 0))
629 (let ((start (point))
630 (end 0))
631 ;; If we can't find a matching end, then create the fake list.
632 (when (re-search-forward "_GLIBCXX_END_NAMESPACE" nil t)
633 (setq end (point))
634 (semantic-lex-push-token
635 (semantic-lex-token 'semantic-list start end
636 (list 'prefix-fake)))))
637 (setq semantic-lex-end-point (point)))
638
639 (defcustom semantic-lex-c-nested-namespace-ignore-second t
640 "Should _GLIBCXX_BEGIN_NESTED_NAMESPACE ignore the second namespace?
641 It is really there, but if a majority of uses is to squeeze out
642 the second namespace in use, then it should not be included.
643
644 If you are having problems with smart completion and STL templates,
645 it may be that this is set incorrectly. After changing the value
646 of this flag, you will need to delete any semanticdb cache files
647 that may have been incorrectly parsed."
648 :group 'semantic
649 :type 'boolean)
650
651 (define-lex-regex-analyzer semantic-lex-c-VC++-begin-std-namespace
652 "Handle VC++'s definition of the std namespace."
653 "\\(_STD_BEGIN\\)"
654 (semantic-lex-push-token
655 (semantic-lex-token 'NAMESPACE (match-beginning 0) (match-end 0) "namespace"))
656 (semantic-lex-push-token
657 (semantic-lex-token 'symbol (match-beginning 0) (match-end 0) "std"))
658 (goto-char (match-end 0))
659 (let ((start (point))
660 (end 0))
661 (when (re-search-forward "_STD_END" nil t)
662 (setq end (point))
663 (semantic-lex-push-token
664 (semantic-lex-token 'semantic-list start end
665 (list 'prefix-fake)))))
666 (setq semantic-lex-end-point (point)))
667
668 (define-lex-regex-analyzer semantic-lex-c-VC++-end-std-namespace
669 "Handle VC++'s definition of the std namespace."
670 "\\(_STD_END\\)"
671 (goto-char (match-end 0))
672 (setq semantic-lex-end-point (point)))
673
674 (define-lex-regex-analyzer semantic-lex-c-namespace-begin-nested-macro
675 "Handle G++'s namespace macros which the pre-processor can't handle."
676 "\\(_GLIBCXX_BEGIN_NESTED_NAMESPACE\\)(\\s-*\\(\\(?:\\w\\|\\s_\\)+\\)\\s-*,\\s-*\\(\\(?:\\w\\|\\s_\\)+\\)\\s-*)"
677 (goto-char (match-end 0))
678 (let* ((nsend (match-end 1))
679 (sym-start (match-beginning 2))
680 (sym-end (match-end 2))
681 (ms (buffer-substring-no-properties sym-start sym-end))
682 (sym2-start (match-beginning 3))
683 (sym2-end (match-end 3))
684 (ms2 (buffer-substring-no-properties sym2-start sym2-end)))
685 ;; Push the namespace keyword.
686 (semantic-lex-push-token
687 (semantic-lex-token 'NAMESPACE (match-beginning 0) nsend "namespace"))
688 ;; Push the name.
689 (semantic-lex-push-token
690 (semantic-lex-token 'symbol sym-start sym-end ms))
691
692 (goto-char (match-end 0))
693 (let ((start (point))
694 (end 0))
695 ;; If we can't find a matching end, then create the fake list.
696 (when (re-search-forward "_GLIBCXX_END_NESTED_NAMESPACE" nil t)
697 (setq end (point))
698 (if semantic-lex-c-nested-namespace-ignore-second
699 ;; The same as _GLIBCXX_BEGIN_NAMESPACE
700 (semantic-lex-push-token
701 (semantic-lex-token 'semantic-list start end
702 (list 'prefix-fake)))
703 ;; Do both the top and second level namespace
704 (semantic-lex-push-token
705 (semantic-lex-token 'semantic-list start end
706 ;; We'll depend on a quick hack
707 (list 'prefix-fake-plus
708 (semantic-lex-token 'NAMESPACE
709 sym-end sym2-start
710 "namespace")
711 (semantic-lex-token 'symbol
712 sym2-start sym2-end
713 ms2)
714 (semantic-lex-token 'semantic-list start end
715 (list 'prefix-fake)))
716 )))
717 )))
718 (setq semantic-lex-end-point (point)))
719
720 (define-lex-regex-analyzer semantic-lex-c-namespace-end-macro
721 "Handle G++'s namespace macros which the pre-processor can't handle."
722 "_GLIBCXX_END_\\(NESTED_\\)?NAMESPACE"
723 (goto-char (match-end 0))
724 (setq semantic-lex-end-point (point)))
725
726 (define-lex-regex-analyzer semantic-lex-c-string
727 "Detect and create a C string token."
728 "L?\\(\\s\"\\)"
729 ;; Zing to the end of this string.
730 (semantic-lex-push-token
731 (semantic-lex-token
732 'string (point)
733 (save-excursion
734 ;; Skip L prefix if present.
735 (goto-char (match-beginning 1))
736 (semantic-lex-unterminated-syntax-protection 'string
737 (forward-sexp 1)
738 (point))
739 ))))
740
741 (define-lex-regex-analyzer semantic-c-lex-ignore-newline
742 "Detect and ignore newline tokens.
743 Use this ONLY if newlines are not whitespace characters (such as when
744 they are comment end characters)."
745 ;; Just like semantic-lex-ignore-newline, but also ignores
746 ;; trailing \.
747 "\\s-*\\\\?\\s-*\\(\n\\|\\s>\\)"
748 (setq semantic-lex-end-point (match-end 0)))
749
750
751 (define-lex semantic-c-lexer
752 "Lexical Analyzer for C code.
753 Use semantic-cpp-lexer for parsing text inside a CPP macro."
754 ;; C preprocessor features
755 semantic-lex-cpp-define
756 semantic-lex-cpp-undef
757 semantic-lex-c-ifdef
758 semantic-lex-c-if
759 semantic-lex-c-macro-else
760 semantic-lex-c-macrobits
761 semantic-lex-c-include
762 semantic-lex-c-include-system
763 semantic-lex-c-ignore-ending-backslash
764 ;; Whitespace handling
765 semantic-lex-ignore-whitespace
766 semantic-c-lex-ignore-newline
767 ;; Non-preprocessor features
768 semantic-lex-number
769 ;; Must detect C strings before symbols because of possible L prefix!
770 semantic-lex-c-string
771 ;; Custom handlers for some macros come before the macro replacement analyzer.
772 semantic-lex-c-namespace-begin-macro
773 semantic-lex-c-namespace-begin-nested-macro
774 semantic-lex-c-namespace-end-macro
775 semantic-lex-c-VC++-begin-std-namespace
776 semantic-lex-c-VC++-end-std-namespace
777 ;; Handle macros, symbols, and keywords
778 semantic-lex-spp-replace-or-symbol-or-keyword
779 semantic-lex-charquote
780 semantic-lex-paren-or-list
781 semantic-lex-close-paren
782 semantic-lex-ignore-comments
783 semantic-lex-punctuation
784 semantic-lex-default-action)
785
786 (define-lex-simple-regex-analyzer semantic-lex-cpp-hashhash
787 "Match ## inside a CPP macro as special."
788 "##" 'spp-concat)
789
790 (define-lex semantic-cpp-lexer
791 "Lexical Analyzer for CPP macros in C code."
792 ;; CPP special
793 semantic-lex-cpp-hashhash
794 ;; C preprocessor features
795 semantic-lex-cpp-define
796 semantic-lex-cpp-undef
797 semantic-lex-c-if
798 semantic-lex-c-macro-else
799 semantic-lex-c-macrobits
800 semantic-lex-c-include
801 semantic-lex-c-include-system
802 semantic-lex-c-ignore-ending-backslash
803 ;; Whitespace handling
804 semantic-lex-ignore-whitespace
805 semantic-c-lex-ignore-newline
806 ;; Non-preprocessor features
807 semantic-lex-number
808 ;; Must detect C strings before symbols because of possible L prefix!
809 semantic-lex-c-string
810 ;; Parsing inside a macro means that we don't do macro replacement.
811 ;; semantic-lex-spp-replace-or-symbol-or-keyword
812 semantic-lex-symbol-or-keyword
813 semantic-lex-charquote
814 semantic-lex-paren-or-list
815 semantic-lex-close-paren
816 semantic-lex-ignore-comments
817 semantic-lex-punctuation
818 semantic-lex-default-action)
819
820 (define-mode-local-override semantic-parse-region c-mode
821 (start end &optional nonterminal depth returnonerror)
822 "Calls `semantic-parse-region-default', except in a macro expansion.
823 MACRO expansion mode is handled through the nature of Emacs's non-lexical
824 binding of variables.
825 START, END, NONTERMINAL, DEPTH, and RETURNONERRORS are the same
826 as for the parent."
827 (if (and (boundp 'lse) (or (/= start 1) (/= end (point-max))))
828 (let* ((last-lexical-token lse)
829 (llt-class (semantic-lex-token-class last-lexical-token))
830 (llt-fakebits (car (cdr last-lexical-token)))
831 (macroexpand (stringp (car (cdr last-lexical-token)))))
832 (if macroexpand
833 (progn
834 ;; It is a macro expansion. Do something special.
835 ;;(message "MOOSE %S %S, %S : %S" start end nonterminal lse)
836 (semantic-c-parse-lexical-token
837 lse nonterminal depth returnonerror)
838 )
839 ;; Not a macro expansion, but perhaps a funny semantic-list
840 ;; is at the start? Remove the depth if our semantic list is not
841 ;; made of list tokens.
842 (if (and depth (= depth 1)
843 (eq llt-class 'semantic-list)
844 (not (null llt-fakebits))
845 (consp llt-fakebits)
846 (symbolp (car llt-fakebits))
847 )
848 (progn
849 (setq depth 0)
850
851 ;; This is a copy of semantic-parse-region-default where we
852 ;; are doing something special with the lexing of the
853 ;; contents of the semantic-list token. Stuff not used by C
854 ;; removed.
855 (let ((tokstream
856 (if (and (consp llt-fakebits)
857 (eq (car llt-fakebits) 'prefix-fake-plus))
858 ;; If our semantic-list is special, then only stick in the
859 ;; fake tokens.
860 (cdr llt-fakebits)
861 ;; Lex up the region with a depth of 0
862 (semantic-lex start end 0))))
863
864 ;; Do the parse
865 (nreverse
866 (semantic-repeat-parse-whole-stream tokstream
867 nonterminal
868 returnonerror))
869
870 ))
871
872 ;; It was not a macro expansion, nor a special semantic-list.
873 ;; Do old thing.
874 (semantic-parse-region-default start end
875 nonterminal depth
876 returnonerror)
877 )))
878 ;; Do the parse
879 (semantic-parse-region-default start end nonterminal
880 depth returnonerror)
881 ))
882
883 (defvar semantic-c-parse-token-hack-depth 0
884 "Current depth of recursive calls to `semantic-c-parse-lexical-token'.")
885
886 (defun semantic-c-parse-lexical-token (lexicaltoken nonterminal depth
887 returnonerror)
888 "Do a region parse on the contents of LEXICALTOKEN.
889 Presumably, this token has a string in it from a macro.
890 The text of the token is inserted into a different buffer, and
891 parsed there.
892 Argument NONTERMINAL, DEPTH, and RETURNONERROR are passed into
893 the regular parser."
894 (let* ((semantic-c-parse-token-hack-depth (1+ semantic-c-parse-token-hack-depth))
895 (buf (get-buffer-create (format " *C parse hack %d*"
896 semantic-c-parse-token-hack-depth)))
897 (mode major-mode)
898 (spp-syms semantic-lex-spp-dynamic-macro-symbol-obarray)
899 (stream nil)
900 (start (semantic-lex-token-start lexicaltoken))
901 (end (semantic-lex-token-end lexicaltoken))
902 (symtext (semantic-lex-token-text lexicaltoken))
903 (macros (get-text-property 0 'macros symtext))
904 )
905 (if (> semantic-c-parse-token-hack-depth 5)
906 nil
907 (with-current-buffer buf
908 (erase-buffer)
909 (when (not (eq major-mode mode))
910 (save-match-data
911
912 ;; Protect against user hooks throwing errors.
913 (condition-case nil
914 (funcall mode)
915 (error
916 (if (y-or-n-p
917 (format "There was an error initializing %s in buffer \"%s\". Debug your hooks? "
918 mode (buffer-name)))
919 (semantic-c-debug-mode-init mode)
920 (message "Macro parsing state may be broken...")
921 (sit-for 1))))
922 ) ; save match data
923
924 ;; Hack in mode-local
925 (activate-mode-local-bindings)
926 ;; Setup C parser
927 (semantic-default-c-setup)
928 ;; CHEATER! The following 3 lines are from
929 ;; `semantic-new-buffer-fcn', but we don't want to turn
930 ;; on all the other annoying modes for this little task.
931 (setq semantic-new-buffer-fcn-was-run t)
932 (semantic-lex-init)
933 (semantic-clear-toplevel-cache)
934 (remove-hook 'semantic-lex-reset-functions
935 'semantic-lex-spp-reset-hook t)
936 )
937 ;; Get the macro symbol table right.
938 (setq semantic-lex-spp-dynamic-macro-symbol-obarray spp-syms)
939 ;; (message "%S" macros)
940 (dolist (sym macros)
941 (semantic-lex-spp-symbol-set (car sym) (cdr sym)))
942
943 (insert symtext)
944
945 (setq stream
946 (semantic-parse-region-default
947 (point-min) (point-max) nonterminal depth returnonerror))
948
949 ;; Clean up macro symbols
950 (dolist (sym macros)
951 (semantic-lex-spp-symbol-remove (car sym)))
952
953 ;; Convert the text of the stream.
954 (dolist (tag stream)
955 ;; Only do two levels here 'cause I'm lazy.
956 (semantic--tag-set-overlay tag (list start end))
957 (dolist (stag (semantic-tag-components-with-overlays tag))
958 (semantic--tag-set-overlay stag (list start end))
959 ))
960 ))
961 stream))
962
963 (defvar semantic-c-debug-mode-init-last-mode nil
964 "The most recent mode needing debugging.")
965
966 (defun semantic-c-debug-mode-init (mm)
967 "Debug mode init for major mode MM after we're done parsing now."
968 (interactive (list semantic-c-debug-mode-init-last-mode))
969 (if (called-interactively-p 'interactive)
970 ;; Do the debug.
971 (progn
972 (switch-to-buffer (get-buffer-create "*MODE HACK TEST*"))
973 (let ((debug-on-error t))
974 (funcall mm)))
975
976 ;; Notify about the debug
977 (setq semantic-c-debug-mode-init-last-mode mm)
978
979 (add-hook 'post-command-hook 'semantic-c-debug-mode-init-pch)))
980
981 (defun semantic-c-debug-mode-init-pch ()
982 "Notify user about needing to debug their major mode hooks."
983 (let ((mm semantic-c-debug-mode-init-last-mode))
984 (switch-to-buffer-other-window
985 (get-buffer-create "*MODE HACK TEST*"))
986 (erase-buffer)
987 (insert "A failure occurred while parsing your buffers.
988
989 The failure occurred while attempting to initialize " (symbol-name mm) " in a
990 buffer not associated with a file. To debug this problem, type
991
992 M-x semantic-c-debug-mode-init
993
994 now.
995 ")
996 (remove-hook 'post-command-hook 'semantic-c-debug-mode-init-pch)))
997
998 (defun semantic-expand-c-tag (tag)
999 "Expand TAG into a list of equivalent tags, or nil."
1000 (let ((return-list nil)
1001 )
1002 ;; Expand an EXTERN C first.
1003 (when (eq (semantic-tag-class tag) 'extern)
1004 (setq return-list (semantic-expand-c-extern-C tag))
1005 ;; The members will be expanded in the next iteration. The
1006 ;; 'extern' tag itself isn't needed anymore.
1007 (setq tag nil))
1008
1009 ;; Check if we have a complex type
1010 (when (or (semantic-tag-of-class-p tag 'function)
1011 (semantic-tag-of-class-p tag 'variable))
1012 (setq tag (semantic-expand-c-complex-type tag))
1013 ;; Extract new basetag
1014 (setq return-list (car tag))
1015 (setq tag (cdr tag)))
1016
1017 ;; Name of the tag is a list, so expand it. Tag lists occur
1018 ;; for variables like this: int var1, var2, var3;
1019 ;;
1020 ;; This will expand that to 3 tags that happen to share the
1021 ;; same overlay information.
1022 (if (consp (semantic-tag-name tag))
1023 (let ((rl (semantic-expand-c-tag-namelist tag)))
1024 (cond
1025 ;; If this returns nothing, then return nil overall
1026 ;; because that will restore the old TAG input.
1027 ((not rl) (setq return-list nil))
1028 ;; If we have a return, append it to the existing list
1029 ;; of returns.
1030 ((consp rl)
1031 (setq return-list (append rl return-list)))
1032 ))
1033 ;; If we didn't have a list, but the return-list is non-empty,
1034 ;; that means we still need to take our existing tag, and glom
1035 ;; it onto our extracted type.
1036 (if (and tag (consp return-list))
1037 (setq return-list (cons tag return-list)))
1038 )
1039
1040 ;; Default, don't change the tag means returning nil.
1041 return-list))
1042
1043 (defun semantic-expand-c-extern-C (tag)
1044 "Expand TAG containing an 'extern \"C\"' statement.
1045 This will return all members of TAG with 'extern \"C\"' added to
1046 the typemodifiers attribute."
1047 (when (eq (semantic-tag-class tag) 'extern)
1048 (let* ((mb (semantic-tag-get-attribute tag :members))
1049 (ret mb))
1050 (while mb
1051 (let ((mods (semantic-tag-get-attribute (car mb) :typemodifiers)))
1052 (setq mods (cons "extern" (cons "\"C\"" mods)))
1053 (semantic-tag-put-attribute (car mb) :typemodifiers mods))
1054 (setq mb (cdr mb)))
1055 (nreverse ret))))
1056
1057 (defun semantic-expand-c-complex-type (tag)
1058 "Check if TAG has a full :type with a name on its own.
1059 If so, extract it, and replace it with a reference to that type.
1060 Thus, 'struct A { int a; } B;' will create 2 toplevel tags, one
1061 is type A, and the other variable B where the :type of B is just
1062 a type tag A that is a prototype, and the actual struct info of A
1063 is its own toplevel tag. This function will return (cons A B)."
1064 (let* ((basetype (semantic-tag-type tag))
1065 (typeref nil)
1066 (ret nil)
1067 (tname (when (consp basetype)
1068 (semantic-tag-name basetype))))
1069 ;; Make tname be a string.
1070 (when (consp tname) (setq tname (car (car tname))))
1071 ;; Is the basetype a full type with a name of its own?
1072 (when (and basetype (semantic-tag-p basetype)
1073 (not (semantic-tag-prototype-p basetype))
1074 tname
1075 (not (string= tname "")))
1076 ;; a type tag referencing the type we are extracting.
1077 (setq typeref (semantic-tag-new-type
1078 (semantic-tag-name basetype)
1079 (semantic-tag-type basetype)
1080 nil nil
1081 :prototype t))
1082 ;; Convert original tag to only have a reference.
1083 (setq tag (semantic-tag-copy tag))
1084 (semantic-tag-put-attribute tag :type typeref)
1085 ;; Convert basetype to have the location information.
1086 (semantic--tag-copy-properties tag basetype)
1087 (semantic--tag-set-overlay basetype
1088 (semantic-tag-overlay tag))
1089 ;; Store the base tag as part of the return list.
1090 (setq ret (cons basetype ret)))
1091 (cons ret tag)))
1092
1093 (defun semantic-expand-c-tag-namelist (tag)
1094 "Expand TAG whose name is a list into a list of tags, or nil."
1095 (cond ((semantic-tag-of-class-p tag 'variable)
1096 ;; The name part comes back in the form of:
1097 ;; ( NAME NUMSTARS BITS ARRAY ASSIGN )
1098 (let ((vl nil)
1099 (basety (semantic-tag-type tag))
1100 (ty "")
1101 (mods (semantic-tag-get-attribute tag :typemodifiers))
1102 (suffix "")
1103 (lst (semantic-tag-name tag))
1104 (default nil)
1105 (cur nil))
1106 ;; Open up each name in the name list.
1107 (while lst
1108 (setq suffix "" ty "")
1109 (setq cur (car lst))
1110 (if (nth 2 cur)
1111 (setq suffix (concat ":" (nth 2 cur))))
1112 (if (= (length basety) 1)
1113 (setq ty (car basety))
1114 (setq ty basety))
1115 (setq default (nth 4 cur))
1116 (setq vl (cons
1117 (semantic-tag-new-variable
1118 (car cur) ;name
1119 ty ;type
1120 (if default
1121 (buffer-substring-no-properties
1122 (car default) (car (cdr default))))
1123 :constant-flag (semantic-tag-variable-constant-p tag)
1124 :suffix suffix
1125 :typemodifiers mods
1126 :dereference (length (nth 3 cur))
1127 :pointer (nth 1 cur)
1128 :reference (semantic-tag-get-attribute tag :reference)
1129 :documentation (semantic-tag-docstring tag) ;doc
1130 )
1131 vl))
1132 (semantic--tag-copy-properties tag (car vl))
1133 (semantic--tag-set-overlay (car vl)
1134 (semantic-tag-overlay tag))
1135 (setq lst (cdr lst)))
1136 ;; Return the list
1137 (nreverse vl)))
1138 ((semantic-tag-of-class-p tag 'type)
1139 ;; We may someday want to add an extra check for a type
1140 ;; of type "typedef".
1141 ;; Each elt of NAME is ( STARS NAME )
1142 (let ((vl nil)
1143 (names (semantic-tag-name tag))
1144 (super (semantic-tag-get-attribute tag :superclasses))
1145 (addlast nil))
1146
1147 (when (and (semantic-tag-of-type-p tag "typedef")
1148 (semantic-tag-of-class-p super 'type)
1149 (semantic-tag-type-members super))
1150 ;; This is a typedef of a real type. Extract
1151 ;; the super class, and stick it into the tags list.
1152 (setq addlast super)
1153
1154 ;; Clone super and remove the members IFF super has a name.
1155 ;; Note: anonymous struct/enums that are typedef'd shouldn't
1156 ;; exist in the top level type list, so they will appear only
1157 ;; in the :typedef slot of the typedef.
1158 (setq super (semantic-tag-clone super))
1159 (if (not (string= (semantic-tag-name super) ""))
1160 (semantic-tag-put-attribute super :members nil)
1161 (setq addlast nil))
1162
1163 ;; Add in props to the full superclass.
1164 (when addlast
1165 (semantic--tag-copy-properties tag addlast)
1166 (semantic--tag-set-overlay addlast (semantic-tag-overlay tag)))
1167 )
1168
1169 (while names
1170
1171 (setq vl (cons (semantic-tag-new-type
1172 (nth 1 (car names)) ; name
1173 "typedef"
1174 (semantic-tag-type-members tag)
1175 ;; parent is just the name of what
1176 ;; is passed down as a tag.
1177 (list
1178 (semantic-tag-name
1179 (semantic-tag-type-superclasses tag)))
1180 :pointer
1181 (let ((stars (car (car (car names)))))
1182 (if (= stars 0) nil stars))
1183 ;; This specifies what the typedef
1184 ;; is expanded out as. Just the
1185 ;; name shows up as a parent of this
1186 ;; typedef.
1187 :typedef super
1188 ;;(semantic-tag-type-superclasses tag)
1189 :documentation
1190 (semantic-tag-docstring tag))
1191 vl))
1192 (semantic--tag-copy-properties tag (car vl))
1193 (semantic--tag-set-overlay (car vl) (semantic-tag-overlay tag))
1194 (setq names (cdr names)))
1195
1196 ;; Add typedef superclass last.
1197 (when addlast (setq vl (cons addlast vl)))
1198
1199 vl))
1200 ((and (listp (car tag))
1201 (semantic-tag-of-class-p (car tag) 'variable))
1202 ;; Argument lists come in this way. Append all the expansions!
1203 (let ((vl nil))
1204 (while tag
1205 (setq vl (append (semantic-tag-components (car vl))
1206 vl)
1207 tag (cdr tag)))
1208 vl))
1209 (t nil)))
1210
1211 (defvar-mode-local c-mode semantic-tag-expand-function 'semantic-expand-c-tag
1212 "Function used to expand tags generated in the C bovine parser.")
1213
1214 (defvar semantic-c-classname nil
1215 "At parse time, assign a class or struct name text here.
1216 It is picked up by `semantic-c-reconstitute-token' to determine
1217 if something is a constructor. Value should be:
1218 (TYPENAME . TYPEOFTYPE)
1219 where typename is the name of the type, and typeoftype is \"class\"
1220 or \"struct\".")
1221
1222 (define-mode-local-override semantic-analyze-split-name c-mode (name)
1223 "Split up tag names on colon (:) boundaries."
1224 (let ((ans (split-string name ":")))
1225 (if (= (length ans) 1)
1226 name
1227 (delete "" ans))))
1228
1229 (defun semantic-c-reconstitute-token (tokenpart declmods typedecl)
1230 "Reconstitute a token TOKENPART with DECLMODS and TYPEDECL.
1231 This is so we don't have to match the same starting text several times.
1232 Optional argument STAR and REF indicate the number of * and & in the typedef."
1233 (when (and (listp typedecl)
1234 (= 1 (length typedecl))
1235 (stringp (car typedecl)))
1236 (setq typedecl (car typedecl)))
1237 (cond ((eq (nth 1 tokenpart) 'variable)
1238 (semantic-tag-new-variable
1239 (car tokenpart)
1240 (or typedecl "int") ;type
1241 nil ;default value (filled with expand)
1242 :constant-flag (if (member "const" declmods) t nil)
1243 :typemodifiers (delete "const" declmods)
1244 )
1245 )
1246 ((eq (nth 1 tokenpart) 'function)
1247 ;; We should look at part 4 (the arglist) here, and throw an
1248 ;; error of some sort if it contains parser errors so that we
1249 ;; don't parser function calls, but that is a little beyond what
1250 ;; is available for data here.
1251 (let* ((constructor
1252 (and (or (and semantic-c-classname
1253 (string= (car semantic-c-classname)
1254 (car tokenpart)))
1255 (and (stringp (car (nth 2 tokenpart)))
1256 (string= (car (nth 2 tokenpart)) (car tokenpart)))
1257 (nth 10 tokenpart) ; initializers
1258 )
1259 (not (car (nth 3 tokenpart)))))
1260 (fcnpointer (string-match "^\\*" (car tokenpart)))
1261 (fnname (if fcnpointer
1262 (substring (car tokenpart) 1)
1263 (car tokenpart)))
1264 (operator (if (string-match "[a-zA-Z]" fnname)
1265 nil
1266 t))
1267 )
1268 (if fcnpointer
1269 ;; Function pointers are really variables.
1270 (semantic-tag-new-variable
1271 fnname
1272 typedecl
1273 nil
1274 ;; It is a function pointer
1275 :functionpointer-flag t
1276 )
1277 ;; The function
1278 (semantic-tag-new-function
1279 fnname
1280 (or typedecl ;type
1281 (cond ((car (nth 3 tokenpart) )
1282 "void") ; Destructors have no return?
1283 (constructor
1284 ;; Constructors return an object.
1285 (semantic-tag-new-type
1286 ;; name
1287 (or (car semantic-c-classname)
1288 (let ((split (semantic-analyze-split-name-c-mode
1289 (car (nth 2 tokenpart)))))
1290 (if (stringp split) split
1291 (car (last split)))))
1292 ;; type
1293 (or (cdr semantic-c-classname)
1294 "class")
1295 ;; members
1296 nil
1297 ;; parents
1298 nil
1299 ))
1300 (t "int")))
1301 (nth 4 tokenpart) ;arglist
1302 :constant-flag (if (member "const" declmods) t nil)
1303 :typemodifiers (delete "const" declmods)
1304 :parent (car (nth 2 tokenpart))
1305 :destructor-flag (if (car (nth 3 tokenpart) ) t)
1306 :constructor-flag (if constructor t)
1307 :pointer (nth 7 tokenpart)
1308 :operator-flag operator
1309 ;; Even though it is "throw" in C++, we use
1310 ;; `throws' as a common name for things that toss
1311 ;; exceptions about.
1312 :throws (nth 5 tokenpart)
1313 ;; Reentrant is a C++ thingy. Add it here
1314 :reentrant-flag (if (member "reentrant" (nth 6 tokenpart)) t)
1315 ;; A function post-const is funky. Try stuff
1316 :methodconst-flag (if (member "const" (nth 6 tokenpart)) t)
1317 ;; prototypes are functions w/ no body
1318 :prototype-flag (if (nth 8 tokenpart) t)
1319 ;; Pure virtual
1320 :pure-virtual-flag (if (eq (nth 8 tokenpart) :pure-virtual-flag) t)
1321 ;; Template specifier.
1322 :template-specifier (nth 9 tokenpart)
1323 )))
1324 )
1325 ))
1326
1327 (defun semantic-c-reconstitute-template (tag specifier)
1328 "Reconstitute the token TAG with the template SPECIFIER."
1329 (semantic-tag-put-attribute tag :template (or specifier ""))
1330 tag)
1331
1332 \f
1333 ;;; Override methods & Variables
1334 ;;
1335 (define-mode-local-override semantic-format-tag-name
1336 c-mode (tag &optional parent color)
1337 "Convert TAG to a string that is the print name for TAG.
1338 Optional PARENT and COLOR are ignored."
1339 (let ((name (semantic-format-tag-name-default tag parent color))
1340 (fnptr (semantic-tag-get-attribute tag :functionpointer-flag))
1341 )
1342 (if (not fnptr)
1343 name
1344 (concat "(*" name ")"))
1345 ))
1346
1347 (define-mode-local-override semantic-format-tag-canonical-name
1348 c-mode (tag &optional parent color)
1349 "Create a canonical name for TAG.
1350 PARENT specifies a parent class.
1351 COLOR indicates that the text should be type colorized.
1352 Enhances the base class to search for the entire parent
1353 tree to make the name accurate."
1354 (semantic-format-tag-canonical-name-default tag parent color)
1355 )
1356
1357 (define-mode-local-override semantic-format-tag-type c-mode (tag color)
1358 "Convert the data type of TAG to a string usable in tag formatting.
1359 Adds pointer and reference symbols to the default.
1360 Argument COLOR adds color to the text."
1361 (let* ((type (semantic-tag-type tag))
1362 (defaulttype nil)
1363 (point (semantic-tag-get-attribute tag :pointer))
1364 (ref (semantic-tag-get-attribute tag :reference))
1365 )
1366 (if (semantic-tag-p type)
1367 (let ((typetype (semantic-tag-type type))
1368 (typename (semantic-tag-name type)))
1369 ;; Create the string that expresses the type
1370 (if (string= typetype "class")
1371 (setq defaulttype typename)
1372 (setq defaulttype (concat typetype " " typename))))
1373 (setq defaulttype (semantic-format-tag-type-default tag color)))
1374
1375 ;; Colorize
1376 (when color
1377 (setq defaulttype (semantic--format-colorize-text defaulttype 'type)))
1378
1379 ;; Add refs, ptrs, etc
1380 (if ref (setq ref "&"))
1381 (if point (setq point (make-string point ?*)) "")
1382 (when type
1383 (concat defaulttype ref point))
1384 ))
1385
1386 (define-mode-local-override semantic-find-tags-by-scope-protection
1387 c-mode (scopeprotection parent &optional table)
1388 "Override the usual search for protection.
1389 We can be more effective than the default by scanning through once,
1390 and collecting tags based on the labels we see along the way."
1391 (if (not table) (setq table (semantic-tag-type-members parent)))
1392 (if (null scopeprotection)
1393 table
1394 (let ((ans nil)
1395 (curprot 1)
1396 (targetprot (cond ((eq scopeprotection 'public)
1397 1)
1398 ((eq scopeprotection 'protected)
1399 2)
1400 (t 3)
1401 ))
1402 (alist '(("public" . 1)
1403 ("protected" . 2)
1404 ("private" . 3)))
1405 )
1406 (dolist (tag table)
1407 (cond
1408 ((semantic-tag-of-class-p tag 'label)
1409 (setq curprot (cdr (assoc (semantic-tag-name tag) alist)))
1410 )
1411 ((>= targetprot curprot)
1412 (setq ans (cons tag ans)))
1413 ))
1414 ans)))
1415
1416 (define-mode-local-override semantic-tag-protection
1417 c-mode (tag &optional parent)
1418 "Return the protection of TAG in PARENT.
1419 Override function for `semantic-tag-protection'."
1420 (let ((mods (semantic-tag-modifiers tag))
1421 (prot nil))
1422 ;; Check the modifiers for protection if we are not a child
1423 ;; of some class type.
1424 (when (or (not parent) (not (eq (semantic-tag-class parent) 'type)))
1425 (while (and (not prot) mods)
1426 (if (stringp (car mods))
1427 (let ((s (car mods)))
1428 ;; A few silly defaults to get things started.
1429 (cond ((or (string= s "extern")
1430 (string= s "export"))
1431 'public)
1432 ((string= s "static")
1433 'private))))
1434 (setq mods (cdr mods))))
1435 ;; If we have a typed parent, look for :public style labels.
1436 (when (and parent (eq (semantic-tag-class parent) 'type))
1437 (let ((pp (semantic-tag-type-members parent)))
1438 (while (and pp (not (semantic-equivalent-tag-p (car pp) tag)))
1439 (when (eq (semantic-tag-class (car pp)) 'label)
1440 (setq prot
1441 (cond ((string= (semantic-tag-name (car pp)) "public")
1442 'public)
1443 ((string= (semantic-tag-name (car pp)) "private")
1444 'private)
1445 ((string= (semantic-tag-name (car pp)) "protected")
1446 'protected)))
1447 )
1448 (setq pp (cdr pp)))))
1449 (when (and (not prot) (eq (semantic-tag-class parent) 'type))
1450 (setq prot
1451 (cond ((string= (semantic-tag-type parent) "class") 'private)
1452 ((string= (semantic-tag-type parent) "struct") 'public)
1453 (t 'unknown))))
1454 (or prot
1455 (if (and parent (semantic-tag-of-class-p parent 'type))
1456 'public
1457 nil))))
1458
1459 (define-mode-local-override semantic-find-tags-included c-mode
1460 (&optional table)
1461 "Find all tags in TABLE that are of the 'include class.
1462 TABLE is a tag table. See `semantic-something-to-tag-table'.
1463 For C++, we also have to search namespaces for include tags."
1464 (let ((tags (semantic-find-tags-by-class 'include table))
1465 (namespaces (semantic-find-tags-by-type "namespace" table)))
1466 (dolist (cur namespaces)
1467 (setq tags
1468 (append tags
1469 (semantic-find-tags-by-class
1470 'include
1471 (semantic-tag-get-attribute cur :members)))))
1472 tags))
1473
1474
1475 (define-mode-local-override semantic-tag-components c-mode (tag)
1476 "Return components for TAG."
1477 (if (and (eq (semantic-tag-class tag) 'type)
1478 (string= (semantic-tag-type tag) "typedef"))
1479 ;; A typedef can contain a parent who has positional children,
1480 ;; but that parent will not have a position. Do this funny hack
1481 ;; to make sure we can apply overlays properly.
1482 (let ((sc (semantic-tag-get-attribute tag :typedef)))
1483 (when (semantic-tag-p sc) (semantic-tag-components sc)))
1484 (semantic-tag-components-default tag)))
1485
1486 (defun semantic-c-tag-template (tag)
1487 "Return the template specification for TAG, or nil."
1488 (semantic-tag-get-attribute tag :template))
1489
1490 (defun semantic-c-tag-template-specifier (tag)
1491 "Return the template specifier specification for TAG, or nil."
1492 (semantic-tag-get-attribute tag :template-specifier))
1493
1494 (defun semantic-c-template-string-body (templatespec)
1495 "Convert TEMPLATESPEC into a string.
1496 This might be a string, or a list of tokens."
1497 (cond ((stringp templatespec)
1498 templatespec)
1499 ((semantic-tag-p templatespec)
1500 (semantic-format-tag-abbreviate templatespec))
1501 ((listp templatespec)
1502 (mapconcat 'semantic-format-tag-abbreviate templatespec ", "))))
1503
1504 (defun semantic-c-template-string (token &optional parent color)
1505 "Return a string representing the TEMPLATE attribute of TOKEN.
1506 This string is prefixed with a space, or is the empty string.
1507 Argument PARENT specifies a parent type.
1508 Argument COLOR specifies that the string should be colorized."
1509 (let ((t2 (semantic-c-tag-template-specifier token))
1510 (t1 (semantic-c-tag-template token))
1511 ;; @todo - Need to account for a parent that is a template
1512 (pt1 (if parent (semantic-c-tag-template parent)))
1513 (pt2 (if parent (semantic-c-tag-template-specifier parent)))
1514 )
1515 (cond (t2 ;; we have a template with specifier
1516 (concat " <"
1517 ;; Fill in the parts here
1518 (semantic-c-template-string-body t2)
1519 ">"))
1520 (t1 ;; we have a template without specifier
1521 " <>")
1522 (t
1523 ""))))
1524
1525 (define-mode-local-override semantic-format-tag-concise-prototype
1526 c-mode (token &optional parent color)
1527 "Return an abbreviated string describing TOKEN for C and C++.
1528 Optional PARENT and COLOR as specified with
1529 `semantic-format-tag-abbreviate-default'."
1530 ;; If we have special template things, append.
1531 (concat (semantic-format-tag-concise-prototype-default token parent color)
1532 (semantic-c-template-string token parent color)))
1533
1534 (define-mode-local-override semantic-format-tag-uml-prototype
1535 c-mode (token &optional parent color)
1536 "Return an UML string describing TOKEN for C and C++.
1537 Optional PARENT and COLOR as specified with
1538 `semantic-abbreviate-tag-default'."
1539 ;; If we have special template things, append.
1540 (concat (semantic-format-tag-uml-prototype-default token parent color)
1541 (semantic-c-template-string token parent color)))
1542
1543 (define-mode-local-override semantic-tag-abstract-p
1544 c-mode (tag &optional parent)
1545 "Return non-nil if TAG is considered abstract.
1546 PARENT is tag's parent.
1547 In C, a method is abstract if it is `virtual', which is already
1548 handled. A class is abstract iff its destructor is virtual."
1549 (cond
1550 ((eq (semantic-tag-class tag) 'type)
1551 (require 'semantic/find)
1552 (or (semantic-brute-find-tag-by-attribute :pure-virtual-flag
1553 (semantic-tag-components tag)
1554 )
1555 (let* ((ds (semantic-brute-find-tag-by-attribute
1556 :destructor-flag
1557 (semantic-tag-components tag)
1558 ))
1559 (cs (semantic-brute-find-tag-by-attribute
1560 :constructor-flag
1561 (semantic-tag-components tag)
1562 )))
1563 (and ds (member "virtual" (semantic-tag-modifiers (car ds)))
1564 cs (eq 'protected (semantic-tag-protection (car cs) tag))
1565 )
1566 )))
1567 ((eq (semantic-tag-class tag) 'function)
1568 (or (semantic-tag-get-attribute tag :pure-virtual-flag)
1569 (member "virtual" (semantic-tag-modifiers tag))))
1570 (t (semantic-tag-abstract-p-default tag parent))))
1571
1572 (defun semantic-c-dereference-typedef (type scope &optional type-declaration)
1573 "If TYPE is a typedef, get TYPE's type by name or tag, and return.
1574 SCOPE is not used, and TYPE-DECLARATION is used only if TYPE is not a typedef."
1575 (if (and (eq (semantic-tag-class type) 'type)
1576 (string= (semantic-tag-type type) "typedef"))
1577 (let ((dt (semantic-tag-get-attribute type :typedef)))
1578 (cond ((and (semantic-tag-p dt)
1579 (not (semantic-tag-prototype-p dt)))
1580 ;; In this case, DT was declared directly. We need
1581 ;; to clone DT and apply a filename to it.
1582 (let* ((fname (semantic-tag-file-name type))
1583 (def (semantic-tag-copy dt nil fname)))
1584 (list def def)))
1585 ((stringp dt) (list dt (semantic-tag dt 'type)))
1586 ((consp dt) (list (car dt) dt))))
1587
1588 (list type type-declaration)))
1589
1590 (defun semantic-c--instantiate-template (tag def-list spec-list)
1591 "Replace TAG name according to template specification.
1592 DEF-LIST is the template information.
1593 SPEC-LIST is the template specifier of the datatype instantiated."
1594 (when (and (car def-list) (car spec-list))
1595
1596 (when (and (string= (semantic-tag-type (car def-list)) "class")
1597 (string= (semantic-tag-name tag) (semantic-tag-name (car def-list))))
1598 (semantic-tag-set-name tag (semantic-tag-name (car spec-list))))
1599
1600 (semantic-c--instantiate-template tag (cdr def-list) (cdr spec-list))))
1601
1602 (defun semantic-c--template-name-1 (spec-list)
1603 "Return a string used to compute template class name.
1604 Based on SPEC-LIST, for ref<Foo,Bar> it will return 'Foo,Bar'."
1605 (when (car spec-list)
1606 (let* ((endpart (semantic-c--template-name-1 (cdr spec-list)))
1607 (separator (and endpart ",")))
1608 (concat (semantic-tag-name (car spec-list)) separator endpart))))
1609
1610 (defun semantic-c--template-name (type spec-list)
1611 "Return a template class name for TYPE based on SPEC-LIST.
1612 For a type `ref' with a template specifier of (Foo Bar) it will
1613 return 'ref<Foo,Bar>'."
1614 (concat (semantic-tag-name type)
1615 "<" (semantic-c--template-name-1 (cdr spec-list)) ">"))
1616
1617 (defun semantic-c-dereference-template (type scope &optional type-declaration)
1618 "Dereference any template specifiers in TYPE within SCOPE.
1619 If TYPE is a template, return a TYPE copy with the templates types
1620 instantiated as specified in TYPE-DECLARATION."
1621 (when (semantic-tag-p type-declaration)
1622 (let ((def-list (semantic-tag-get-attribute type :template))
1623 (spec-list (semantic-tag-get-attribute type-declaration :template-specifier)))
1624 (when (and def-list spec-list)
1625 (setq type (semantic-tag-deep-copy-one-tag
1626 type
1627 (lambda (tag)
1628 (when (semantic-tag-of-class-p tag 'type)
1629 (semantic-c--instantiate-template
1630 tag def-list spec-list))
1631 tag)
1632 ))
1633 (semantic-tag-set-name type (semantic-c--template-name type spec-list))
1634 (semantic-tag-put-attribute type :template nil)
1635 (semantic-tag-set-faux type))))
1636 (list type type-declaration))
1637
1638 ;;; Patch here by "Raf" for instantiating templates.
1639 (defun semantic-c-dereference-member-of (type scope &optional type-declaration)
1640 "Dereference through the `->' operator of TYPE.
1641 Uses the return type of the '->' operator if it is contained in TYPE.
1642 SCOPE is the current local scope to perform searches in.
1643 TYPE-DECLARATION is passed through."
1644 (if semantic-c-member-of-autocast
1645 (let ((operator (car (semantic-find-tags-by-name "->" (semantic-analyze-scoped-type-parts type)))))
1646 (if operator
1647 (list (semantic-tag-get-attribute operator :type) (semantic-tag-get-attribute operator :type))
1648 (list type type-declaration)))
1649 (list type type-declaration)))
1650
1651 ;; David Engster: The following three functions deal with namespace
1652 ;; aliases and types which are member of a namespace through a using
1653 ;; statement. For examples, see the file semantic/tests/testusing.cpp,
1654 ;; tests 5 and following.
1655
1656 (defun semantic-c-dereference-namespace (type scope &optional type-declaration)
1657 "Dereference namespace which might hold an 'alias' for TYPE.
1658 Such an alias can be created through 'using' statements in a
1659 namespace declaration. This function checks the namespaces in
1660 SCOPE for such statements."
1661 (let ((scopetypes (oref scope scopetypes))
1662 typename currentns tmp usingname result namespaces)
1663 (when (and (semantic-tag-p type-declaration)
1664 (or (null type) (semantic-tag-prototype-p type)))
1665 (setq typename (semantic-analyze-split-name (semantic-tag-name type-declaration)))
1666 ;; If we already have that TYPE in SCOPE, we do nothing
1667 (unless (semantic-deep-find-tags-by-name (or (car-safe typename) typename) scopetypes)
1668 (if (stringp typename)
1669 ;; The type isn't fully qualified, so we have to search in all namespaces in SCOPE.
1670 (setq namespaces (semantic-find-tags-by-type "namespace" scopetypes))
1671 ;; This is a fully qualified name, so we only have to search one namespace.
1672 (setq namespaces (semanticdb-typecache-find (car typename)))
1673 ;; Make sure it's really a namespace.
1674 (if (string= (semantic-tag-type namespaces) "namespace")
1675 (setq namespaces (list namespaces))
1676 (setq namespaces nil)))
1677 (setq result nil)
1678 ;; Iterate over all the namespaces we have to check.
1679 (while (and namespaces
1680 (null result))
1681 (setq currentns (car namespaces))
1682 ;; Check if this is namespace is an alias and dereference it if necessary.
1683 (setq result (semantic-c-dereference-namespace-alias type-declaration currentns))
1684 (unless result
1685 ;; Otherwise, check if we can reach the type through 'using' statements.
1686 (setq result
1687 (semantic-c-check-type-namespace-using type-declaration currentns)))
1688 (setq namespaces (cdr namespaces)))))
1689 (if result
1690 ;; we have found the original type
1691 (list result result)
1692 (list type type-declaration))))
1693
1694 (defun semantic-c-dereference-namespace-alias (type namespace)
1695 "Dereference TYPE in NAMESPACE, given that NAMESPACE is an alias.
1696 Checks if NAMESPACE is an alias and if so, returns a new type
1697 with a fully qualified name in the original namespace. Returns
1698 nil if NAMESPACE is not an alias."
1699 (when (eq (semantic-tag-get-attribute namespace :kind) 'alias)
1700 (let ((typename (semantic-analyze-split-name (semantic-tag-name type)))
1701 ns nstype originaltype newtype)
1702 ;; Make typename unqualified
1703 (if (listp typename)
1704 (setq typename (last typename))
1705 (setq typename (list typename)))
1706 (when
1707 (and
1708 ;; Get original namespace and make sure TYPE exists there.
1709 (setq ns (semantic-tag-name
1710 (car (semantic-tag-get-attribute namespace :members))))
1711 (setq nstype (semanticdb-typecache-find ns))
1712 (setq originaltype (semantic-find-tags-by-name
1713 (car typename)
1714 (semantic-tag-get-attribute nstype :members))))
1715 ;; Construct new type with name in original namespace.
1716 (setq ns (semantic-analyze-split-name ns))
1717 (setq newtype
1718 (semantic-tag-clone
1719 (car originaltype)
1720 (semantic-analyze-unsplit-name
1721 (if (listp ns)
1722 (append ns typename)
1723 (append (list ns) typename)))))))))
1724
1725 ;; This searches a type in a namespace, following through all using
1726 ;; statements.
1727 (defun semantic-c-check-type-namespace-using (type namespace)
1728 "Check if TYPE is accessible in NAMESPACE through a using statement.
1729 Returns the original type from the namespace where it is defined,
1730 or nil if it cannot be found."
1731 (let (usings result usingname usingtype unqualifiedname members shortname tmp)
1732 ;; Get all using statements from NAMESPACE.
1733 (when (and (setq usings (semantic-tag-get-attribute namespace :members))
1734 (setq usings (semantic-find-tags-by-class 'using usings)))
1735 ;; Get unqualified typename.
1736 (when (listp (setq unqualifiedname (semantic-analyze-split-name
1737 (semantic-tag-name type))))
1738 (setq unqualifiedname (car (last unqualifiedname))))
1739 ;; Iterate over all using statements in NAMESPACE.
1740 (while (and usings
1741 (null result))
1742 (setq usingname (semantic-analyze-split-name
1743 (semantic-tag-name (car usings)))
1744 usingtype (semantic-tag-type (semantic-tag-type (car usings))))
1745 (cond
1746 ((or (string= usingtype "namespace")
1747 (stringp usingname))
1748 ;; We are dealing with a 'using [namespace] NAMESPACE;'
1749 ;; Search for TYPE in that namespace
1750 (setq result
1751 (semanticdb-typecache-find usingname))
1752 (if (and result
1753 (setq members (semantic-tag-get-attribute result :members))
1754 (setq members (semantic-find-tags-by-name unqualifiedname members)))
1755 ;; TYPE is member of that namespace, so we are finished
1756 (setq result (car members))
1757 ;; otherwise recursively search in that namespace for an alias
1758 (setq result (semantic-c-check-type-namespace-using type result))
1759 (when result
1760 (setq result (semantic-tag-type result)))))
1761 ((and (string= usingtype "class")
1762 (listp usingname))
1763 ;; We are dealing with a 'using TYPE;'
1764 (when (string= unqualifiedname (car (last usingname)))
1765 ;; We have found the correct tag.
1766 (setq result (semantic-tag-type (car usings))))))
1767 (setq usings (cdr usings))))
1768 result))
1769
1770
1771 (define-mode-local-override semantic-analyze-dereference-metatype
1772 c-mode (type scope &optional type-declaration)
1773 "Dereference TYPE as described in `semantic-analyze-dereference-metatype'.
1774 Handle typedef, template instantiation, and '->' operator."
1775 (let* ((dereferencer-list '(semantic-c-dereference-typedef
1776 semantic-c-dereference-template
1777 semantic-c-dereference-member-of
1778 semantic-c-dereference-namespace))
1779 (dereferencer (pop dereferencer-list))
1780 (type-tuple)
1781 (original-type type))
1782 (while dereferencer
1783 (setq type-tuple (funcall dereferencer type scope type-declaration)
1784 type (car type-tuple)
1785 type-declaration (cadr type-tuple))
1786 (if (not (eq type original-type))
1787 ;; we found a new type so break the dereferencer loop now !
1788 ;; (we will be recalled with the new type expanded by
1789 ;; semantic-analyze-dereference-metatype-stack).
1790 (setq dereferencer nil)
1791 ;; no new type found try the next dereferencer :
1792 (setq dereferencer (pop dereferencer-list)))))
1793 (list type type-declaration))
1794
1795 (define-mode-local-override semantic-analyze-type-constants c-mode (type)
1796 "When TYPE is a tag for an enum, return its parts.
1797 These are constants which are of type TYPE."
1798 (if (and (eq (semantic-tag-class type) 'type)
1799 (string= (semantic-tag-type type) "enum"))
1800 (semantic-tag-type-members type)))
1801
1802 (define-mode-local-override semantic-analyze-unsplit-name c-mode (namelist)
1803 "Assemble the list of names NAMELIST into a namespace name."
1804 (mapconcat 'identity namelist "::"))
1805
1806 (define-mode-local-override semantic-ctxt-scoped-types c++-mode (&optional point)
1807 "Return a list of tags of CLASS type based on POINT.
1808 DO NOT return the list of tags encompassing point."
1809 (when point (goto-char (point)))
1810 (let ((tagsaroundpoint (semantic-find-tag-by-overlay))
1811 (tagreturn nil)
1812 (tmp nil))
1813 ;; In C++, we want to find all the namespaces declared
1814 ;; locally and add them to the list.
1815 (setq tmp (semantic-find-tags-by-class 'type (current-buffer)))
1816 (setq tmp (semantic-find-tags-by-type "namespace" tmp))
1817 (setq tmp (semantic-find-tags-by-name "unnamed" tmp))
1818 (setq tagreturn tmp)
1819 ;; We should also find all "using" type statements and
1820 ;; accept those entities in as well.
1821 (setq tmp (semanticdb-find-tags-by-class 'using))
1822 (let ((idx 0)
1823 (len (semanticdb-find-result-length tmp)))
1824 (while (< idx len)
1825 (setq tagreturn (cons (semantic-tag-type (car (semanticdb-find-result-nth tmp idx))) tagreturn))
1826 (setq idx (1+ idx)))
1827 )
1828 ;; Use the encompassed types around point to also look for using statements.
1829 ;;(setq tagreturn (cons "bread_name" tagreturn))
1830 (while (cdr tagsaroundpoint) ; don't search the last one
1831 (setq tmp (semantic-find-tags-by-class 'using (semantic-tag-components (car tagsaroundpoint))))
1832 (dolist (T tmp)
1833 (setq tagreturn (cons (semantic-tag-type T) tagreturn))
1834 )
1835 (setq tagsaroundpoint (cdr tagsaroundpoint))
1836 )
1837 ;; If in a function...
1838 (when (and (semantic-tag-of-class-p (car tagsaroundpoint) 'function)
1839 ;; ...search for using statements in the local scope...
1840 (setq tmp (semantic-find-tags-by-class
1841 'using
1842 (semantic-get-local-variables))))
1843 ;; ... and add them.
1844 (setq tagreturn
1845 (append tagreturn
1846 (mapcar 'semantic-tag-type tmp))))
1847 ;; Return the stuff
1848 tagreturn
1849 ))
1850
1851 (define-mode-local-override semantic-ctxt-imported-packages c++-mode (&optional point)
1852 "Return the list of using tag types in scope of POINT."
1853 (when point (goto-char (point)))
1854 (let ((tagsaroundpoint (semantic-find-tag-by-overlay))
1855 (namereturn nil)
1856 (tmp nil)
1857 )
1858 ;; Collect using statements from the top level.
1859 (setq tmp (semantic-find-tags-by-class 'using (current-buffer)))
1860 (dolist (T tmp) (setq namereturn (cons (semantic-tag-type T) namereturn)))
1861 ;; Move through the tags around point looking for more using statements
1862 (while (cdr tagsaroundpoint) ; don't search the last one
1863 (setq tmp (semantic-find-tags-by-class 'using (semantic-tag-components (car tagsaroundpoint))))
1864 (dolist (T tmp) (setq namereturn (cons (semantic-tag-type T) namereturn)))
1865 (setq tagsaroundpoint (cdr tagsaroundpoint))
1866 )
1867 namereturn))
1868
1869 (define-mode-local-override semanticdb-expand-nested-tag c++-mode (tag)
1870 "Expand TAG if it has a fully qualified name.
1871 For types with a :parent, create faux namespaces to put TAG into."
1872 (let ((p (semantic-tag-get-attribute tag :parent)))
1873 (if (and p (semantic-tag-of-class-p tag 'type))
1874 ;; Expand the tag
1875 (let ((s (semantic-analyze-split-name p))
1876 (newtag (semantic-tag-copy tag nil t)))
1877 ;; Erase the qualified name.
1878 (semantic-tag-put-attribute newtag :parent nil)
1879 ;; Fixup the namespace name
1880 (setq s (if (stringp s) (list s) (nreverse s)))
1881 ;; Loop over all the parents, creating the nested
1882 ;; namespace.
1883 (require 'semantic/db-typecache)
1884 (dolist (namespace s)
1885 (setq newtag (semanticdb-typecache-faux-namespace
1886 namespace (list newtag)))
1887 )
1888 ;; Return the last created namespace.
1889 newtag)
1890 ;; Else, return tag unmodified.
1891 tag)))
1892
1893 (define-mode-local-override semanticdb-find-table-for-include c-mode
1894 (includetag &optional table)
1895 "For a single INCLUDETAG found in TABLE, find a `semanticdb-table' object
1896 INCLUDETAG is a semantic TAG of class 'include.
1897 TABLE is a semanticdb table that identifies where INCLUDETAG came from.
1898 TABLE is optional if INCLUDETAG has an overlay of :filename attribute.
1899
1900 For C++, we also have to check if the include is inside a
1901 namespace, since this means all tags inside this include will
1902 have to be wrapped in that namespace."
1903 (let ((inctable (semanticdb-find-table-for-include-default includetag table))
1904 (inside-ns (semantic-tag-get-attribute includetag :inside-ns))
1905 tags newtags namespaces prefix parenttable newtable)
1906 (if (or (null inside-ns)
1907 (not inctable)
1908 (not (slot-boundp inctable 'tags)))
1909 inctable
1910 (when (and (eq inside-ns t)
1911 ;; Get the table which has this include.
1912 (setq parenttable
1913 (semanticdb-find-table-for-include-default
1914 (semantic-tag-new-include
1915 (semantic--tag-get-property includetag :filename) nil)))
1916 table)
1917 ;; Find the namespace where this include is located.
1918 (setq namespaces
1919 (semantic-find-tags-by-type "namespace" parenttable))
1920 (when (and namespaces
1921 (slot-boundp inctable 'tags))
1922 (dolist (cur namespaces)
1923 (when (semantic-find-tags-by-name
1924 (semantic-tag-name includetag)
1925 (semantic-tag-get-attribute cur :members))
1926 (setq inside-ns (semantic-tag-name cur))
1927 ;; Cache the namespace value.
1928 (semantic-tag-put-attribute includetag :inside-ns inside-ns)))))
1929 (unless (semantic-find-tags-by-name
1930 inside-ns
1931 (semantic-find-tags-by-type "namespace" inctable))
1932 (setq tags (oref inctable tags))
1933 ;; Wrap tags inside namespace tag
1934 (setq newtags
1935 (list (semantic-tag-new-type inside-ns "namespace" tags nil)))
1936 ;; Create new semantic-table for the wrapped tags, since we don't want
1937 ;; the namespace to actually be a part of the header file.
1938 (setq newtable (semanticdb-table "include with context"))
1939 (oset newtable tags newtags)
1940 (oset newtable parent-db (oref inctable parent-db))
1941 (oset newtable file (oref inctable file)))
1942 newtable)))
1943
1944
1945 (define-mode-local-override semantic-get-local-variables c++-mode ()
1946 "Do what `semantic-get-local-variables' does, plus add `this' if needed."
1947 (let* ((origvar (semantic-get-local-variables-default))
1948 (ct (semantic-current-tag))
1949 (p (semantic-tag-function-parent ct)))
1950 ;; If we have a function parent, then that implies we can
1951 (if (and p (semantic-tag-of-class-p ct 'function))
1952 ;; Append a new tag THIS into our space.
1953 (cons (semantic-tag-new-variable "this" p nil)
1954 origvar)
1955 ;; No parent, just return the usual
1956 origvar)
1957 ))
1958
1959 (define-mode-local-override semantic-idle-summary-current-symbol-info
1960 c-mode ()
1961 "Handle the SPP keywords, then use the default mechanism."
1962 (let* ((sym (car (semantic-ctxt-current-thing)))
1963 (spp-sym (semantic-lex-spp-symbol sym)))
1964 (if spp-sym
1965 (let* ((txt (concat "Macro: " sym))
1966 (sv (symbol-value spp-sym))
1967 (arg (semantic-lex-spp-macro-with-args sv))
1968 )
1969 (when arg
1970 (setq txt (concat txt (format "%S" arg)))
1971 (setq sv (cdr sv)))
1972
1973 ;; This is optional, and potentially fraught w/ errors.
1974 (condition-case nil
1975 (dolist (lt sv)
1976 (setq txt (concat txt " " (semantic-lex-token-text lt))))
1977 (error (setq txt (concat txt " #error in summary fcn"))))
1978
1979 txt)
1980 (semantic-idle-summary-current-symbol-info-default))))
1981
1982 (define-mode-local-override semantic--tag-similar-names-p c-mode (tag1 tag2 blankok)
1983 "Compare the names of TAG1 and TAG2.
1984 If BLANKOK is false, then the names must exactly match.
1985 If BLANKOK is true, then always return t, as for C, the names don't matter
1986 for arguments compared."
1987 (if blankok t (semantic--tag-similar-names-p-default tag1 tag2 nil)))
1988
1989 (define-mode-local-override semantic--tag-similar-types-p c-mode (tag1 tag2)
1990 "For c-mode, deal with TAG1 and TAG2 being used in different namespaces.
1991 In this case, one type will be shorter than the other. Instead
1992 of fully resolving all namespaces currently in scope for both
1993 types, we simply compare as many elements as the shorter type
1994 provides."
1995 ;; First, we see if the default method fails
1996 (if (semantic--tag-similar-types-p-default tag1 tag2)
1997 t
1998 (let* ((names
1999 (mapcar
2000 (lambda (tag)
2001 (let ((type (semantic-tag-type tag)))
2002 (unless (stringp type)
2003 (setq type (semantic-tag-name type)))
2004 (setq type (semantic-analyze-split-name type))
2005 (when (stringp type)
2006 (setq type (list type)))
2007 type))
2008 (list tag1 tag2)))
2009 (len1 (length (car names)))
2010 (len2 (length (cadr names))))
2011 (cond
2012 ((<= len1 len2)
2013 (equal (nthcdr len1 (cadr names)) (car names)))
2014 ((< len2 len1)
2015 (equal (nthcdr len2 (car names)) (cadr names)))))))
2016
2017
2018 (define-mode-local-override semantic--tag-attribute-similar-p c-mode
2019 (attr value1 value2 ignorable-attributes)
2020 "For c-mode, allow function :arguments to ignore the :name attributes."
2021 (cond ((eq attr :arguments)
2022 (semantic--tag-attribute-similar-p-default attr value1 value2
2023 (cons :name ignorable-attributes)))
2024 (t
2025 (semantic--tag-attribute-similar-p-default attr value1 value2
2026 ignorable-attributes))))
2027
2028 (defvar-mode-local c-mode semantic-orphaned-member-metaparent-type "struct"
2029 "When lost members are found in the class hierarchy generator, use a struct.")
2030
2031 (defvar-mode-local c-mode semantic-symbol->name-assoc-list
2032 '((type . "Types")
2033 (variable . "Variables")
2034 (function . "Functions")
2035 (include . "Includes")
2036 )
2037 "List of tag classes, and strings to describe them.")
2038
2039 (defvar-mode-local c-mode semantic-symbol->name-assoc-list-for-type-parts
2040 '((type . "Types")
2041 (variable . "Attributes")
2042 (function . "Methods")
2043 (label . "Labels")
2044 )
2045 "List of tag classes in a datatype decl, and strings to describe them.")
2046
2047 (defvar-mode-local c-mode imenu-create-index-function 'semantic-create-imenu-index
2048 "Imenu index function for C.")
2049
2050 (defvar-mode-local c-mode semantic-type-relation-separator-character
2051 '("." "->" "::")
2052 "Separator characters between something of a given type, and a field.")
2053
2054 (defvar-mode-local c-mode semantic-command-separation-character ";"
2055 "Command separation character for C.")
2056
2057 (defvar-mode-local c-mode senator-step-at-tag-classes '(function variable)
2058 "Tag classes where senator will stop at the end.")
2059
2060 (defvar-mode-local c-mode semantic-tag-similar-ignorable-attributes
2061 '(:prototype-flag :parent :typemodifiers)
2062 "Tag attributes to ignore during similarity tests.
2063 :parent is here because some tags might specify a parent, while others are
2064 actually in their parent which is not accessible.")
2065
2066 ;;;###autoload
2067 (defun semantic-default-c-setup ()
2068 "Set up a buffer for semantic parsing of the C language."
2069 (semantic-c-by--install-parser)
2070 (setq semantic-lex-syntax-modifications '((?> ".")
2071 (?< ".")
2072 )
2073 )
2074
2075 (setq semantic-lex-analyzer #'semantic-c-lexer)
2076 (add-hook 'semantic-lex-reset-functions 'semantic-lex-spp-reset-hook nil t)
2077 (when (eq major-mode 'c++-mode)
2078 (add-to-list 'semantic-lex-c-preprocessor-symbol-map '("__cplusplus" . "")))
2079 )
2080
2081 ;;;###autoload
2082 (defun semantic-c-add-preprocessor-symbol (sym replacement)
2083 "Add a preprocessor symbol SYM with a REPLACEMENT value."
2084 (interactive "sSymbol: \nsReplacement: ")
2085 (let ((SA (assoc sym semantic-lex-c-preprocessor-symbol-map)))
2086 (if SA
2087 ;; Replace if there is one.
2088 (setcdr SA replacement)
2089 ;; Otherwise, append
2090 (setq semantic-lex-c-preprocessor-symbol-map
2091 (cons (cons sym replacement)
2092 semantic-lex-c-preprocessor-symbol-map))))
2093
2094 (semantic-c-reset-preprocessor-symbol-map)
2095 )
2096
2097 ;;; SETUP QUERY
2098 ;;
2099 (defun semantic-c-describe-environment ()
2100 "Describe the Semantic features of the current C environment."
2101 (interactive)
2102 (if (not (member 'c-mode (mode-local-equivalent-mode-p major-mode)))
2103 (error "Not useful to query C mode in %s mode" major-mode))
2104 (let ((gcc (when (boundp 'semantic-gcc-setup-data)
2105 semantic-gcc-setup-data))
2106 )
2107 (semantic-fetch-tags)
2108
2109 (with-output-to-temp-buffer "*Semantic C Environment*"
2110 (when gcc
2111 (princ "Calculated GCC Parameters:")
2112 (dolist (P gcc)
2113 (princ "\n ")
2114 (princ (car P))
2115 (princ " = ")
2116 (princ (cdr P))
2117 )
2118 )
2119
2120 (princ "\n\nInclude Path Summary:\n")
2121 (when (and (boundp 'ede-object) ede-object)
2122 (princ "\n This file's project include is handled by:\n")
2123 (let ((objs (if (listp ede-object)
2124 ede-object
2125 (list ede-object))))
2126 (dolist (O objs)
2127 (princ " EDE : ")
2128 (princ (object-print O))
2129 (let ((ipath (ede-system-include-path O)))
2130 (if (not ipath)
2131 (princ "\n with NO specified system include path.\n")
2132 (princ "\n with the system path:\n")
2133 (dolist (dir ipath)
2134 (princ " ")
2135 (princ dir)
2136 (princ "\n"))))))
2137 )
2138
2139 (when semantic-dependency-include-path
2140 (princ "\n This file's generic include path is:\n")
2141 (dolist (dir semantic-dependency-include-path)
2142 (princ " ")
2143 (princ dir)
2144 (princ "\n")))
2145
2146 (when semantic-dependency-system-include-path
2147 (princ "\n This file's system include path is:\n")
2148 (dolist (dir semantic-dependency-system-include-path)
2149 (princ " ")
2150 (princ dir)
2151 (princ "\n")))
2152
2153 (princ "\n\nMacro Summary:\n")
2154 (when semantic-lex-c-preprocessor-symbol-file
2155 (princ "\n Your CPP table is primed from these files:\n")
2156 (dolist (file semantic-lex-c-preprocessor-symbol-file)
2157 (princ " ")
2158 (princ file)
2159 (princ "\n")
2160 (princ " in table: ")
2161 (princ (object-print (semanticdb-file-table-object file)))
2162 (princ "\n")
2163 ))
2164
2165 (when semantic-lex-c-preprocessor-symbol-map-builtin
2166 (princ "\n Built-in symbol map:\n")
2167 (dolist (S semantic-lex-c-preprocessor-symbol-map-builtin)
2168 (princ " ")
2169 (princ (car S))
2170 (princ " = ")
2171 (princ (cdr S))
2172 (princ "\n")
2173 ))
2174
2175 (when semantic-lex-c-preprocessor-symbol-map
2176 (princ "\n User symbol map:\n")
2177 (dolist (S semantic-lex-c-preprocessor-symbol-map)
2178 (princ " ")
2179 (princ (car S))
2180 (princ " = ")
2181 (princ (cdr S))
2182 (princ "\n")
2183 ))
2184
2185 (when (and (boundp 'ede-object)
2186 ede-object
2187 (arrayp semantic-lex-spp-project-macro-symbol-obarray))
2188 (princ "\n Project symbol map:\n")
2189 (when (and (boundp 'ede-object) ede-object)
2190 (princ " Your project symbol map is derived from the EDE object:\n ")
2191 (princ (object-print ede-object)))
2192 (princ "\n\n")
2193 (let ((macros nil))
2194 (mapatoms
2195 #'(lambda (symbol)
2196 (setq macros (cons symbol macros)))
2197 semantic-lex-spp-project-macro-symbol-obarray)
2198 (dolist (S macros)
2199 (princ " ")
2200 (princ (symbol-name S))
2201 (princ " = ")
2202 (princ (symbol-value S))
2203 (princ "\n")
2204 )))
2205
2206 (princ "\n\n Use: M-x semantic-lex-spp-describe RET\n")
2207 (princ "\n to see the complete macro table.\n")
2208
2209 )))
2210
2211 (provide 'semantic/bovine/c)
2212
2213 (semantic-c-reset-preprocessor-symbol-map)
2214
2215 ;; Local variables:
2216 ;; generated-autoload-file: "../loaddefs.el"
2217 ;; generated-autoload-load-name: "semantic/bovine/c"
2218 ;; End:
2219
2220 ;;; semantic/bovine/c.el ends here