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