Update copyright year to 2015
[emacs.git] / lisp / cedet / semantic / bovine / c.el
blobaa93e246cc83bbe02fd56b4897d0d356e63eeb45
1 ;;; semantic/bovine/c.el --- Semantic details for C
3 ;; Copyright (C) 1999-2015 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 (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 (condition-case err
505 (eval parsedtokelist)
506 (error
507 (semantic-push-parser-warning
508 (format "Hideif forms produced an error. Assuming false.\n%S" err)
509 (point) (1+ (point)))
510 nil))))
511 (if (or (not eval-form)
512 (and (numberp eval-form)
513 (equal eval-form 0)));; ifdef line resulted in false
515 ;; The if indicates to skip this preprocessor section
516 (let ((pt nil))
517 (semantic-push-parser-warning (format "Skip %s" (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
518 (point-at-bol) (point-at-eol))
519 (beginning-of-line)
520 (setq pt (point))
521 ;; This skips only a section of a conditional. Once that section
522 ;; is opened, encountering any new #else or related conditional
523 ;; should be skipped.
524 (semantic-c-skip-conditional-section)
525 (setq semantic-lex-end-point (point))
527 ;; @TODO -somewhere around here, we also need to skip
528 ;; other sections of the conditional.
530 nil)
531 ;; Else, don't ignore it, but do handle the internals.
532 (end-of-line)
533 (setq semantic-lex-end-point (point))
534 nil))))
536 (define-lex-regex-analyzer semantic-lex-c-ifdef
537 "Code blocks wrapped up in #ifdef.
538 Uses known macro tables in SPP to determine what block to skip."
539 "^\\s-*#\\s-*\\(ifndef\\|ifdef\\)\\s-+\\(\\(\\sw\\|\\s_\\)+\\)\\([ \t\C-m].*\\)?$"
540 (semantic-c-do-lex-ifdef))
542 (defun semantic-c-do-lex-ifdef ()
543 "Handle lexical CPP if statements."
544 (let* ((sym (buffer-substring-no-properties
545 (match-beginning 2) (match-end 2)))
546 (ift (buffer-substring-no-properties
547 (match-beginning 1) (match-end 1)))
548 (ifdef (string= ift "ifdef"))
549 (ifndef (string= ift "ifndef"))
551 (if (or (and ifdef (not (semantic-lex-spp-symbol-p sym)))
552 (and ifndef (semantic-lex-spp-symbol-p sym)))
553 ;; The if indicates to skip this preprocessor section.
554 (let ((pt nil))
555 ;; (message "%s %s yes" ift sym)
556 (beginning-of-line)
557 (setq pt (point))
558 ;; This skips only a section of a conditional. Once that section
559 ;; is opened, encountering any new #else or related conditional
560 ;; should be skipped.
561 (semantic-c-skip-conditional-section)
562 (setq semantic-lex-end-point (point))
563 (semantic-push-parser-warning (format "Skip #%s %s" ift sym)
564 pt (point))
565 ;; (semantic-lex-push-token
566 ;; (semantic-lex-token 'c-preprocessor-skip pt (point)))
567 nil)
568 ;; Else, don't ignore it, but do handle the internals.
569 ;;(message "%s %s no" ift sym)
570 (end-of-line)
571 (setq semantic-lex-end-point (point))
572 nil)))
574 (define-lex-regex-analyzer semantic-lex-c-macro-else
575 "Ignore an #else block.
576 We won't see the #else due to the macro skip section block
577 unless we are actively parsing an open #if statement. In that
578 case, we must skip it since it is the ELSE part."
579 "^\\s-*#\\s-*\\(else\\)"
580 (let ((pt (point)))
581 (semantic-c-skip-conditional-section)
582 (setq semantic-lex-end-point (point))
583 (semantic-push-parser-warning "Skip #else" pt (point))
584 ;; (semantic-lex-push-token
585 ;; (semantic-lex-token 'c-preprocessor-skip pt (point)))
586 nil))
588 (define-lex-regex-analyzer semantic-lex-c-macrobits
589 "Ignore various forms of #if/#else/#endif conditionals."
590 "^\\s-*#\\s-*\\(if\\(n?def\\)?\\|endif\\|elif\\|else\\)"
591 (semantic-c-end-of-macro)
592 (setq semantic-lex-end-point (point))
593 nil)
595 (define-lex-spp-include-analyzer semantic-lex-c-include-system
596 "Identify include strings, and return special tokens."
597 "^\\s-*#\\s-*include\\s-*<\\([^ \t\n>]+\\)>" 0
598 ;; Hit 1 is the name of the include.
599 (goto-char (match-end 0))
600 (setq semantic-lex-end-point (point))
601 (cons (buffer-substring-no-properties (match-beginning 1)
602 (match-end 1))
603 'system))
605 (define-lex-spp-include-analyzer semantic-lex-c-include
606 "Identify include strings, and return special tokens."
607 "^\\s-*#\\s-*include\\s-*\"\\([^ \t\n>]+\\)\"" 0
608 ;; Hit 1 is the name of the include.
609 (goto-char (match-end 0))
610 (setq semantic-lex-end-point (point))
611 (cons (buffer-substring-no-properties (match-beginning 1)
612 (match-end 1))
613 nil))
616 (define-lex-regex-analyzer semantic-lex-c-ignore-ending-backslash
617 "Skip backslash ending a line.
618 Go to the next line."
619 "\\\\\\s-*\n"
620 (setq semantic-lex-end-point (match-end 0)))
622 (define-lex-regex-analyzer semantic-lex-c-namespace-begin-macro
623 "Handle G++'s namespace macros which the pre-processor can't handle."
624 "\\(_GLIBCXX_BEGIN_NAMESPACE\\)(\\s-*\\(\\(?:\\w\\|\\s_\\)+\\)\\s-*)"
625 (let* ((nsend (match-end 1))
626 (sym-start (match-beginning 2))
627 (sym-end (match-end 2))
628 (ms (buffer-substring-no-properties sym-start sym-end)))
629 ;; Push the namespace keyword.
630 (semantic-lex-push-token
631 (semantic-lex-token 'NAMESPACE (match-beginning 0) nsend "namespace"))
632 ;; Push the name.
633 (semantic-lex-push-token
634 (semantic-lex-token 'symbol sym-start sym-end ms))
636 (goto-char (match-end 0))
637 (let ((start (point))
638 (end 0))
639 ;; If we can't find a matching end, then create the fake list.
640 (when (re-search-forward "_GLIBCXX_END_NAMESPACE" nil t)
641 (setq end (point))
642 (semantic-lex-push-token
643 (semantic-lex-token 'semantic-list start end
644 (list 'prefix-fake)))))
645 (setq semantic-lex-end-point (point)))
647 (defcustom semantic-lex-c-nested-namespace-ignore-second t
648 "Should _GLIBCXX_BEGIN_NESTED_NAMESPACE ignore the second namespace?
649 It is really there, but if a majority of uses is to squeeze out
650 the second namespace in use, then it should not be included.
652 If you are having problems with smart completion and STL templates,
653 it may be that this is set incorrectly. After changing the value
654 of this flag, you will need to delete any semanticdb cache files
655 that may have been incorrectly parsed."
656 :group 'semantic
657 :type 'boolean)
659 (define-lex-regex-analyzer semantic-lex-c-VC++-begin-std-namespace
660 "Handle VC++'s definition of the std namespace."
661 "\\(_STD_BEGIN\\)"
662 (semantic-lex-push-token
663 (semantic-lex-token 'NAMESPACE (match-beginning 0) (match-end 0) "namespace"))
664 (semantic-lex-push-token
665 (semantic-lex-token 'symbol (match-beginning 0) (match-end 0) "std"))
666 (goto-char (match-end 0))
667 (let ((start (point))
668 (end 0))
669 (when (re-search-forward "_STD_END" nil t)
670 (setq end (point))
671 (semantic-lex-push-token
672 (semantic-lex-token 'semantic-list start end
673 (list 'prefix-fake)))))
674 (setq semantic-lex-end-point (point)))
676 (define-lex-regex-analyzer semantic-lex-c-VC++-end-std-namespace
677 "Handle VC++'s definition of the std namespace."
678 "\\(_STD_END\\)"
679 (goto-char (match-end 0))
680 (setq semantic-lex-end-point (point)))
682 (define-lex-regex-analyzer semantic-lex-c-namespace-begin-nested-macro
683 "Handle G++'s namespace macros which the pre-processor can't handle."
684 "\\(_GLIBCXX_BEGIN_NESTED_NAMESPACE\\)(\\s-*\\(\\(?:\\w\\|\\s_\\)+\\)\\s-*,\\s-*\\(\\(?:\\w\\|\\s_\\)+\\)\\s-*)"
685 (goto-char (match-end 0))
686 (let* ((nsend (match-end 1))
687 (sym-start (match-beginning 2))
688 (sym-end (match-end 2))
689 (ms (buffer-substring-no-properties sym-start sym-end))
690 (sym2-start (match-beginning 3))
691 (sym2-end (match-end 3))
692 (ms2 (buffer-substring-no-properties sym2-start sym2-end)))
693 ;; Push the namespace keyword.
694 (semantic-lex-push-token
695 (semantic-lex-token 'NAMESPACE (match-beginning 0) nsend "namespace"))
696 ;; Push the name.
697 (semantic-lex-push-token
698 (semantic-lex-token 'symbol sym-start sym-end ms))
700 (goto-char (match-end 0))
701 (let ((start (point))
702 (end 0))
703 ;; If we can't find a matching end, then create the fake list.
704 (when (re-search-forward "_GLIBCXX_END_NESTED_NAMESPACE" nil t)
705 (setq end (point))
706 (if semantic-lex-c-nested-namespace-ignore-second
707 ;; The same as _GLIBCXX_BEGIN_NAMESPACE
708 (semantic-lex-push-token
709 (semantic-lex-token 'semantic-list start end
710 (list 'prefix-fake)))
711 ;; Do both the top and second level namespace
712 (semantic-lex-push-token
713 (semantic-lex-token 'semantic-list start end
714 ;; We'll depend on a quick hack
715 (list 'prefix-fake-plus
716 (semantic-lex-token 'NAMESPACE
717 sym-end sym2-start
718 "namespace")
719 (semantic-lex-token 'symbol
720 sym2-start sym2-end
721 ms2)
722 (semantic-lex-token 'semantic-list start end
723 (list 'prefix-fake)))
726 (setq semantic-lex-end-point (point)))
728 (define-lex-regex-analyzer semantic-lex-c-namespace-end-macro
729 "Handle G++'s namespace macros which the pre-processor can't handle."
730 "_GLIBCXX_END_\\(NESTED_\\)?NAMESPACE"
731 (goto-char (match-end 0))
732 (setq semantic-lex-end-point (point)))
734 (define-lex-regex-analyzer semantic-lex-c-string
735 "Detect and create a C string token."
736 "L?\\(\\s\"\\)"
737 ;; Zing to the end of this string.
738 (semantic-lex-push-token
739 (semantic-lex-token
740 'string (point)
741 (save-excursion
742 ;; Skip L prefix if present.
743 (goto-char (match-beginning 1))
744 (semantic-lex-unterminated-syntax-protection 'string
745 (forward-sexp 1)
746 (point))
747 ))))
749 (define-lex-regex-analyzer semantic-c-lex-ignore-newline
750 "Detect and ignore newline tokens.
751 Use this ONLY if newlines are not whitespace characters (such as when
752 they are comment end characters)."
753 ;; Just like semantic-lex-ignore-newline, but also ignores
754 ;; trailing \.
755 "\\s-*\\\\?\\s-*\\(\n\\|\\s>\\)"
756 (setq semantic-lex-end-point (match-end 0)))
759 (define-lex semantic-c-lexer
760 "Lexical Analyzer for C code.
761 Use semantic-cpp-lexer for parsing text inside a CPP macro."
762 ;; C preprocessor features
763 semantic-lex-cpp-define
764 semantic-lex-cpp-undef
765 semantic-lex-c-ifdef
766 semantic-lex-c-if
767 semantic-lex-c-macro-else
768 semantic-lex-c-macrobits
769 semantic-lex-c-include
770 semantic-lex-c-include-system
771 semantic-lex-c-ignore-ending-backslash
772 ;; Whitespace handling
773 semantic-lex-ignore-whitespace
774 semantic-c-lex-ignore-newline
775 ;; Non-preprocessor features
776 semantic-lex-number
777 ;; Must detect C strings before symbols because of possible L prefix!
778 semantic-lex-c-string
779 ;; Custom handlers for some macros come before the macro replacement analyzer.
780 semantic-lex-c-namespace-begin-macro
781 semantic-lex-c-namespace-begin-nested-macro
782 semantic-lex-c-namespace-end-macro
783 semantic-lex-c-VC++-begin-std-namespace
784 semantic-lex-c-VC++-end-std-namespace
785 ;; Handle macros, symbols, and keywords
786 semantic-lex-spp-replace-or-symbol-or-keyword
787 semantic-lex-charquote
788 semantic-lex-paren-or-list
789 semantic-lex-close-paren
790 semantic-lex-ignore-comments
791 semantic-lex-punctuation
792 semantic-lex-default-action)
794 (define-lex-simple-regex-analyzer semantic-lex-cpp-hashhash
795 "Match ## inside a CPP macro as special."
796 "##" 'spp-concat)
798 (define-lex semantic-cpp-lexer
799 "Lexical Analyzer for CPP macros in C code."
800 ;; CPP special
801 semantic-lex-cpp-hashhash
802 ;; C preprocessor features
803 semantic-lex-cpp-define
804 semantic-lex-cpp-undef
805 semantic-lex-c-if
806 semantic-lex-c-macro-else
807 semantic-lex-c-macrobits
808 semantic-lex-c-include
809 semantic-lex-c-include-system
810 semantic-lex-c-ignore-ending-backslash
811 ;; Whitespace handling
812 semantic-lex-ignore-whitespace
813 semantic-c-lex-ignore-newline
814 ;; Non-preprocessor features
815 semantic-lex-number
816 ;; Must detect C strings before symbols because of possible L prefix!
817 semantic-lex-c-string
818 ;; Parsing inside a macro means that we don't do macro replacement.
819 ;; semantic-lex-spp-replace-or-symbol-or-keyword
820 semantic-lex-symbol-or-keyword
821 semantic-lex-charquote
822 semantic-lex-spp-paren-or-list
823 semantic-lex-close-paren
824 semantic-lex-ignore-comments
825 semantic-lex-punctuation
826 semantic-lex-default-action)
828 (define-mode-local-override semantic-parse-region c-mode
829 (start end &optional nonterminal depth returnonerror)
830 "Calls `semantic-parse-region-default', except in a macro expansion.
831 MACRO expansion mode is handled through the nature of Emacs's non-lexical
832 binding of variables.
833 START, END, NONTERMINAL, DEPTH, and RETURNONERRORS are the same
834 as for the parent."
835 (if (and (boundp 'lse) (or (/= start 1) (/= end (point-max))))
836 (let* ((last-lexical-token lse)
837 (llt-class (semantic-lex-token-class last-lexical-token))
838 (llt-fakebits (car (cdr last-lexical-token)))
839 (macroexpand (stringp (car (cdr last-lexical-token)))))
840 (if macroexpand
841 (progn
842 ;; It is a macro expansion. Do something special.
843 ;;(message "MOOSE %S %S, %S : %S" start end nonterminal lse)
844 (semantic-c-parse-lexical-token
845 lse nonterminal depth returnonerror)
847 ;; Not a macro expansion, but perhaps a funny semantic-list
848 ;; is at the start? Remove the depth if our semantic list is not
849 ;; made of list tokens.
850 (if (and depth (= depth 1)
851 (eq llt-class 'semantic-list)
852 (not (null llt-fakebits))
853 (consp llt-fakebits)
854 (symbolp (car llt-fakebits))
856 (progn
857 (setq depth 0)
859 ;; This is a copy of semantic-parse-region-default where we
860 ;; are doing something special with the lexing of the
861 ;; contents of the semantic-list token. Stuff not used by C
862 ;; removed.
863 (let ((tokstream
864 (if (and (consp llt-fakebits)
865 (eq (car llt-fakebits) 'prefix-fake-plus))
866 ;; If our semantic-list is special, then only stick in the
867 ;; fake tokens.
868 (cdr llt-fakebits)
869 ;; Lex up the region with a depth of 0
870 (semantic-lex start end 0))))
872 ;; Do the parse
873 (nreverse
874 (semantic-repeat-parse-whole-stream tokstream
875 nonterminal
876 returnonerror))
880 ;; It was not a macro expansion, nor a special semantic-list.
881 ;; Do old thing.
882 (semantic-parse-region-default start end
883 nonterminal depth
884 returnonerror)
886 ;; Do the parse
887 (semantic-parse-region-default start end nonterminal
888 depth returnonerror)
891 (defvar semantic-c-parse-token-hack-depth 0
892 "Current depth of recursive calls to `semantic-c-parse-lexical-token'.")
894 (defun semantic-c-parse-lexical-token (lexicaltoken nonterminal depth
895 returnonerror)
896 "Do a region parse on the contents of LEXICALTOKEN.
897 Presumably, this token has a string in it from a macro.
898 The text of the token is inserted into a different buffer, and
899 parsed there.
900 Argument NONTERMINAL, DEPTH, and RETURNONERROR are passed into
901 the regular parser."
902 (let* ((semantic-c-parse-token-hack-depth (1+ semantic-c-parse-token-hack-depth))
903 (buf (get-buffer-create (format " *C parse hack %d*"
904 semantic-c-parse-token-hack-depth)))
905 (mode major-mode)
906 (spp-syms semantic-lex-spp-dynamic-macro-symbol-obarray)
907 (stream nil)
908 (start (semantic-lex-token-start lexicaltoken))
909 (end (semantic-lex-token-end lexicaltoken))
910 (symtext (semantic-lex-token-text lexicaltoken))
911 (macros (get-text-property 0 'macros symtext))
913 (if (> semantic-c-parse-token-hack-depth 5)
915 (with-current-buffer buf
916 (erase-buffer)
917 (when (not (eq major-mode mode))
918 (save-match-data
920 ;; Protect against user hooks throwing errors.
921 (condition-case nil
922 (funcall mode)
923 (error
924 (if (y-or-n-p
925 (format "There was an error initializing %s in buffer \"%s\". Debug your hooks? "
926 mode (buffer-name)))
927 (semantic-c-debug-mode-init mode)
928 (message "Macro parsing state may be broken...")
929 (sit-for 1))))
930 ) ; save match data
932 ;; Hack in mode-local
933 (activate-mode-local-bindings)
934 ;; Setup C parser
935 (semantic-default-c-setup)
936 ;; CHEATER! The following 3 lines are from
937 ;; `semantic-new-buffer-fcn', but we don't want to turn
938 ;; on all the other annoying modes for this little task.
939 (setq semantic-new-buffer-fcn-was-run t)
940 (semantic-lex-init)
941 (semantic-clear-toplevel-cache)
942 (remove-hook 'semantic-lex-reset-functions
943 'semantic-lex-spp-reset-hook t)
945 ;; Get the macro symbol table right.
946 (setq semantic-lex-spp-dynamic-macro-symbol-obarray spp-syms)
947 ;; (message "%S" macros)
948 (dolist (sym macros)
949 (semantic-lex-spp-symbol-set (car sym) (cdr sym)))
951 (insert symtext)
953 (setq stream
954 (semantic-parse-region-default
955 (point-min) (point-max) nonterminal depth returnonerror))
957 ;; Clean up macro symbols
958 (dolist (sym macros)
959 (semantic-lex-spp-symbol-remove (car sym)))
961 ;; Convert the text of the stream.
962 (dolist (tag stream)
963 ;; Only do two levels here 'cause I'm lazy.
964 (semantic--tag-set-overlay tag (list start end))
965 (dolist (stag (semantic-tag-components-with-overlays tag))
966 (semantic--tag-set-overlay stag (list start end))
969 stream))
971 (defvar semantic-c-debug-mode-init-last-mode nil
972 "The most recent mode needing debugging.")
974 (defun semantic-c-debug-mode-init (mm)
975 "Debug mode init for major mode MM after we're done parsing now."
976 (interactive (list semantic-c-debug-mode-init-last-mode))
977 (if (called-interactively-p 'interactive)
978 ;; Do the debug.
979 (progn
980 (switch-to-buffer (get-buffer-create "*MODE HACK TEST*"))
981 (let ((debug-on-error t))
982 (funcall mm)))
984 ;; Notify about the debug
985 (setq semantic-c-debug-mode-init-last-mode mm)
987 (add-hook 'post-command-hook 'semantic-c-debug-mode-init-pch)))
989 (defun semantic-c-debug-mode-init-pch ()
990 "Notify user about needing to debug their major mode hooks."
991 (let ((mm semantic-c-debug-mode-init-last-mode))
992 (switch-to-buffer-other-window
993 (get-buffer-create "*MODE HACK TEST*"))
994 (erase-buffer)
995 (insert "A failure occurred while parsing your buffers.
997 The failure occurred while attempting to initialize " (symbol-name mm) " in a
998 buffer not associated with a file. To debug this problem, type
1000 M-x semantic-c-debug-mode-init
1002 now.
1004 (remove-hook 'post-command-hook 'semantic-c-debug-mode-init-pch)))
1006 (defun semantic-expand-c-tag (tag)
1007 "Expand TAG into a list of equivalent tags, or nil."
1008 (let ((return-list nil)
1010 ;; Expand an EXTERN C first.
1011 (when (eq (semantic-tag-class tag) 'extern)
1012 (setq return-list (semantic-expand-c-extern-C tag))
1013 ;; The members will be expanded in the next iteration. The
1014 ;; 'extern' tag itself isn't needed anymore.
1015 (setq tag nil))
1017 ;; Check if we have a complex type
1018 (when (or (semantic-tag-of-class-p tag 'function)
1019 (semantic-tag-of-class-p tag 'variable))
1020 (setq tag (semantic-expand-c-complex-type tag))
1021 ;; Extract new basetag
1022 (setq return-list (car tag))
1023 (setq tag (cdr tag)))
1025 ;; Name of the tag is a list, so expand it. Tag lists occur
1026 ;; for variables like this: int var1, var2, var3;
1028 ;; This will expand that to 3 tags that happen to share the
1029 ;; same overlay information.
1030 (if (consp (semantic-tag-name tag))
1031 (let ((rl (semantic-expand-c-tag-namelist tag)))
1032 (cond
1033 ;; If this returns nothing, then return nil overall
1034 ;; because that will restore the old TAG input.
1035 ((not rl) (setq return-list nil))
1036 ;; If we have a return, append it to the existing list
1037 ;; of returns.
1038 ((consp rl)
1039 (setq return-list (append rl return-list)))
1041 ;; If we didn't have a list, but the return-list is non-empty,
1042 ;; that means we still need to take our existing tag, and glom
1043 ;; it onto our extracted type.
1044 (if (and tag (consp return-list))
1045 (setq return-list (cons tag return-list)))
1048 ;; Default, don't change the tag means returning nil.
1049 return-list))
1051 (defun semantic-expand-c-extern-C (tag)
1052 "Expand TAG containing an 'extern \"C\"' statement.
1053 This will return all members of TAG with 'extern \"C\"' added to
1054 the typemodifiers attribute."
1055 (when (eq (semantic-tag-class tag) 'extern)
1056 (let* ((mb (semantic-tag-get-attribute tag :members))
1057 (ret mb))
1058 (while mb
1059 (let ((mods (semantic-tag-get-attribute (car mb) :typemodifiers)))
1060 (setq mods (cons "extern" (cons "\"C\"" mods)))
1061 (semantic-tag-put-attribute (car mb) :typemodifiers mods))
1062 (setq mb (cdr mb)))
1063 (nreverse ret))))
1065 (defun semantic-expand-c-complex-type (tag)
1066 "Check if TAG has a full :type with a name on its own.
1067 If so, extract it, and replace it with a reference to that type.
1068 Thus, 'struct A { int a; } B;' will create 2 toplevel tags, one
1069 is type A, and the other variable B where the :type of B is just
1070 a type tag A that is a prototype, and the actual struct info of A
1071 is its own toplevel tag. This function will return (cons A B)."
1072 (let* ((basetype (semantic-tag-type tag))
1073 (typeref nil)
1074 (ret nil)
1075 (tname (when (consp basetype)
1076 (semantic-tag-name basetype))))
1077 ;; Make tname be a string.
1078 (when (consp tname) (setq tname (car (car tname))))
1079 ;; Is the basetype a full type with a name of its own?
1080 (when (and basetype (semantic-tag-p basetype)
1081 (not (semantic-tag-prototype-p basetype))
1082 tname
1083 (not (string= tname "")))
1084 ;; a type tag referencing the type we are extracting.
1085 (setq typeref (semantic-tag-new-type
1086 (semantic-tag-name basetype)
1087 (semantic-tag-type basetype)
1088 nil nil
1089 :prototype t))
1090 ;; Convert original tag to only have a reference.
1091 (setq tag (semantic-tag-copy tag))
1092 (semantic-tag-put-attribute tag :type typeref)
1093 ;; Convert basetype to have the location information.
1094 (semantic--tag-copy-properties tag basetype)
1095 (semantic--tag-set-overlay basetype
1096 (semantic-tag-overlay tag))
1097 ;; Store the base tag as part of the return list.
1098 (setq ret (cons basetype ret)))
1099 (cons ret tag)))
1101 (defun semantic-expand-c-tag-namelist (tag)
1102 "Expand TAG whose name is a list into a list of tags, or nil."
1103 (cond ((semantic-tag-of-class-p tag 'variable)
1104 ;; The name part comes back in the form of:
1105 ;; ( NAME NUMSTARS BITS ARRAY ASSIGN )
1106 (let ((vl nil)
1107 (basety (semantic-tag-type tag))
1108 (ty "")
1109 (mods (semantic-tag-get-attribute tag :typemodifiers))
1110 (suffix "")
1111 (lst (semantic-tag-name tag))
1112 (default nil)
1113 (cur nil))
1114 ;; Open up each name in the name list.
1115 (while lst
1116 (setq suffix "" ty "")
1117 (setq cur (car lst))
1118 (if (nth 2 cur)
1119 (setq suffix (concat ":" (nth 2 cur))))
1120 (if (= (length basety) 1)
1121 (setq ty (car basety))
1122 (setq ty basety))
1123 (setq default (nth 4 cur))
1124 (setq vl (cons
1125 (semantic-tag-new-variable
1126 (car cur) ;name
1127 ty ;type
1128 (if (and default
1129 (listp (cdr default)))
1130 (buffer-substring-no-properties
1131 (car default) (car (cdr default))))
1132 :constant-flag (semantic-tag-variable-constant-p tag)
1133 :suffix suffix
1134 :typemodifiers mods
1135 :dereference (length (nth 3 cur))
1136 :pointer (nth 1 cur)
1137 :reference (semantic-tag-get-attribute tag :reference)
1138 :documentation (semantic-tag-docstring tag) ;doc
1140 vl))
1141 (semantic--tag-copy-properties tag (car vl))
1142 (semantic--tag-set-overlay (car vl)
1143 (semantic-tag-overlay tag))
1144 (setq lst (cdr lst)))
1145 ;; Return the list
1146 (nreverse vl)))
1147 ((semantic-tag-of-class-p tag 'type)
1148 ;; We may someday want to add an extra check for a type
1149 ;; of type "typedef".
1150 ;; Each elt of NAME is ( STARS NAME )
1151 (let ((vl nil)
1152 (names (semantic-tag-name tag))
1153 (super (semantic-tag-get-attribute tag :superclasses))
1154 (addlast nil))
1156 (when (and (semantic-tag-of-type-p tag "typedef")
1157 (semantic-tag-of-class-p super 'type)
1158 (semantic-tag-type-members super))
1159 ;; This is a typedef of a real type. Extract
1160 ;; the super class, and stick it into the tags list.
1161 (setq addlast super)
1163 ;; Clone super and remove the members IFF super has a name.
1164 ;; Note: anonymous struct/enums that are typedef'd shouldn't
1165 ;; exist in the top level type list, so they will appear only
1166 ;; in the :typedef slot of the typedef.
1167 (setq super (semantic-tag-clone super))
1168 (if (not (string= (semantic-tag-name super) ""))
1169 (semantic-tag-put-attribute super :members nil)
1170 (setq addlast nil))
1172 ;; Add in props to the full superclass.
1173 (when addlast
1174 (semantic--tag-copy-properties tag addlast)
1175 (semantic--tag-set-overlay addlast (semantic-tag-overlay tag)))
1178 (while names
1180 (setq vl (cons (semantic-tag-new-type
1181 (nth 1 (car names)) ; name
1182 "typedef"
1183 (semantic-tag-type-members tag)
1185 :pointer
1186 (let ((stars (car (car (car names)))))
1187 (if (= stars 0) nil stars))
1188 ;; This specifies what the typedef
1189 ;; is expanded out as. Just the
1190 ;; name shows up as a parent of this
1191 ;; typedef.
1192 :typedef super
1193 ;;(semantic-tag-type-superclasses tag)
1194 :documentation
1195 (semantic-tag-docstring tag))
1196 vl))
1197 (semantic--tag-copy-properties tag (car vl))
1198 (semantic--tag-set-overlay (car vl) (semantic-tag-overlay tag))
1199 (setq names (cdr names)))
1201 ;; Add typedef superclass last.
1202 (when addlast (setq vl (cons addlast vl)))
1204 vl))
1205 ((and (listp (car tag))
1206 (semantic-tag-of-class-p (car tag) 'variable))
1207 ;; Argument lists come in this way. Append all the expansions!
1208 (let ((vl nil))
1209 (while tag
1210 (setq vl (append (semantic-tag-components (car vl))
1212 tag (cdr tag)))
1213 vl))
1214 (t nil)))
1216 (defvar-mode-local c-mode semantic-tag-expand-function 'semantic-expand-c-tag
1217 "Function used to expand tags generated in the C bovine parser.")
1219 (defvar semantic-c-classname nil
1220 "At parse time, assign a class or struct name text here.
1221 It is picked up by `semantic-c-reconstitute-token' to determine
1222 if something is a constructor. Value should be:
1223 (TYPENAME . TYPEOFTYPE)
1224 where typename is the name of the type, and typeoftype is \"class\"
1225 or \"struct\".")
1227 (define-mode-local-override semantic-analyze-split-name c-mode (name)
1228 "Split up tag names on colon (:) boundaries."
1229 (let ((ans (split-string name ":")))
1230 (if (= (length ans) 1)
1231 name
1232 (delete "" ans))))
1234 (define-mode-local-override semantic-analyze-tag-references c-mode (tag &optional db)
1235 "Analyze the references for TAG.
1236 Returns a class with information about TAG.
1238 Optional argument DB is a database. It will be used to help
1239 locate TAG.
1241 Use `semantic-analyze-current-tag' to debug this fcn."
1242 (when (not (semantic-tag-p tag)) (signal 'wrong-type-argument (list 'semantic-tag-p tag)))
1243 (let ((allhits nil)
1244 (scope nil)
1245 (refs nil))
1246 (save-excursion
1247 (semantic-go-to-tag tag db)
1248 (setq scope (semantic-calculate-scope))
1250 (setq allhits (semantic--analyze-refs-full-lookup tag scope t))
1252 (when (or (zerop (semanticdb-find-result-length allhits))
1253 (and (= (semanticdb-find-result-length allhits) 1)
1254 (eq (car (semanticdb-find-result-nth allhits 0)) tag)))
1255 ;; It found nothing or only itself - not good enough. As a
1256 ;; last resort, let's remove all namespaces from the scope and
1257 ;; search again.
1258 (oset scope parents
1259 (let ((parents (oref scope parents))
1260 newparents)
1261 (dolist (cur parents)
1262 (unless (string= (semantic-tag-type cur) "namespace")
1263 (push cur newparents)))
1264 (reverse newparents)))
1265 (setq allhits (semantic--analyze-refs-full-lookup tag scope t)))
1267 (setq refs (semantic-analyze-references (semantic-tag-name tag)
1268 :tag tag
1269 :tagdb db
1270 :scope scope
1271 :rawsearchdata allhits)))))
1273 (defun semantic-c-reconstitute-token (tokenpart declmods typedecl)
1274 "Reconstitute a token TOKENPART with DECLMODS and TYPEDECL.
1275 This is so we don't have to match the same starting text several times.
1276 Optional argument STAR and REF indicate the number of * and & in the typedef."
1277 (when (and (listp typedecl)
1278 (= 1 (length typedecl))
1279 (stringp (car typedecl)))
1280 (setq typedecl (car typedecl)))
1281 (cond ((eq (nth 1 tokenpart) 'variable)
1282 (semantic-tag-new-variable
1283 (car tokenpart)
1284 (or typedecl "int") ;type
1285 nil ;default value (filled with expand)
1286 :constant-flag (if (member "const" declmods) t nil)
1287 :typemodifiers (delete "const" declmods)
1290 ((eq (nth 1 tokenpart) 'function)
1291 ;; We should look at part 4 (the arglist) here, and throw an
1292 ;; error of some sort if it contains parser errors so that we
1293 ;; don't parser function calls, but that is a little beyond what
1294 ;; is available for data here.
1295 (let* ((constructor
1296 (and (or (and semantic-c-classname
1297 (string= (car semantic-c-classname)
1298 (car tokenpart)))
1299 (and (stringp (car (nth 2 tokenpart)))
1300 (string= (car (nth 2 tokenpart)) (car tokenpart)))
1301 (nth 10 tokenpart) ; initializers
1303 (not (car (nth 3 tokenpart)))))
1304 (fcnpointer (and (> (length (car tokenpart)) 0)
1305 (= (aref (car tokenpart) 0) ?*)))
1306 (fnname (if fcnpointer
1307 (substring (car tokenpart) 1)
1308 (car tokenpart)))
1309 (operator (if (string-match "[a-zA-Z]" fnname)
1313 ;; The function
1314 (semantic-tag-new-function
1315 fnname
1316 (or typedecl ;type
1317 (cond ((car (nth 3 tokenpart) )
1318 "void") ; Destructors have no return?
1319 (constructor
1320 ;; Constructors return an object.
1321 (semantic-tag-new-type
1322 ;; name
1323 (or (car semantic-c-classname)
1324 (let ((split (semantic-analyze-split-name-c-mode
1325 (car (nth 2 tokenpart)))))
1326 (if (stringp split) split
1327 (car (last split)))))
1328 ;; type
1329 (or (cdr semantic-c-classname)
1330 "class")
1331 ;; members
1333 ;; parents
1336 (t "int")))
1337 ;; Argument list can contain things like function pointers
1338 (semantic-c-reconstitute-function-arglist (nth 4 tokenpart))
1339 :constant-flag (if (member "const" declmods) t nil)
1340 :typemodifiers (delete "const" declmods)
1341 :parent (car (nth 2 tokenpart))
1342 :destructor-flag (if (car (nth 3 tokenpart) ) t)
1343 :constructor-flag (if constructor t)
1344 :function-pointer fcnpointer
1345 :pointer (nth 7 tokenpart)
1346 :operator-flag operator
1347 ;; Even though it is "throw" in C++, we use
1348 ;; `throws' as a common name for things that toss
1349 ;; exceptions about.
1350 :throws (nth 5 tokenpart)
1351 ;; Reentrant is a C++ thingy. Add it here
1352 :reentrant-flag (if (member "reentrant" (nth 6 tokenpart)) t)
1353 ;; A function post-const is funky. Try stuff
1354 :methodconst-flag (if (member "const" (nth 6 tokenpart)) t)
1355 ;; prototypes are functions w/ no body
1356 :prototype-flag (if (nth 8 tokenpart) t)
1357 ;; Pure virtual
1358 :pure-virtual-flag (if (eq (nth 8 tokenpart) :pure-virtual-flag) t)
1359 ;; Template specifier.
1360 :template-specifier (nth 9 tokenpart))))))
1362 (defun semantic-c-reconstitute-template (tag specifier)
1363 "Reconstitute the token TAG with the template SPECIFIER."
1364 (semantic-tag-put-attribute tag :template (or specifier ""))
1365 tag)
1367 (defun semantic-c-reconstitute-function-arglist (arglist)
1368 "Reconstitute the argument list of a function.
1369 This currently only checks if the function expects a function
1370 pointer as argument."
1371 (let (result)
1372 (dolist (arg arglist)
1373 ;; Names starting with a '*' denote a function pointer
1374 (if (and (> (length (semantic-tag-name arg)) 0)
1375 (= (aref (semantic-tag-name arg) 0) ?*))
1376 (setq result
1377 (append result
1378 (list
1379 (semantic-tag-new-function
1380 (substring (semantic-tag-name arg) 1)
1381 (semantic-tag-type arg)
1382 (cadr (semantic-tag-attributes arg))
1383 :function-pointer t))))
1384 (setq result (append result (list arg)))))
1385 result))
1388 ;;; Override methods & Variables
1390 (define-mode-local-override semantic-format-tag-name
1391 c-mode (tag &optional parent color)
1392 "Convert TAG to a string that is the print name for TAG.
1393 Optional PARENT and COLOR are ignored."
1394 (let ((name (semantic-format-tag-name-default tag parent color))
1395 (fnptr (semantic-tag-get-attribute tag :function-pointer))
1397 (if (not fnptr)
1398 name
1399 (concat "(*" name ")"))
1402 (define-mode-local-override semantic-format-tag-canonical-name
1403 c-mode (tag &optional parent color)
1404 "Create a canonical name for TAG.
1405 PARENT specifies a parent class.
1406 COLOR indicates that the text should be type colorized.
1407 Enhances the base class to search for the entire parent
1408 tree to make the name accurate."
1409 (semantic-format-tag-canonical-name-default tag parent color)
1412 (define-mode-local-override semantic-format-tag-type c-mode (tag color)
1413 "Convert the data type of TAG to a string usable in tag formatting.
1414 Adds pointer and reference symbols to the default.
1415 Argument COLOR adds color to the text."
1416 (let* ((type (semantic-tag-type tag))
1417 (defaulttype nil)
1418 (point (semantic-tag-get-attribute tag :pointer))
1419 (ref (semantic-tag-get-attribute tag :reference))
1421 (if (semantic-tag-p type)
1422 (let ((typetype (semantic-tag-type type))
1423 (typename (semantic-tag-name type)))
1424 ;; Create the string that expresses the type
1425 (if (string= typetype "class")
1426 (setq defaulttype typename)
1427 (setq defaulttype (concat typetype " " typename))))
1428 (setq defaulttype (semantic-format-tag-type-default tag color)))
1430 ;; Colorize
1431 (when color
1432 (setq defaulttype (semantic--format-colorize-text defaulttype 'type)))
1434 ;; Add refs, ptrs, etc
1435 (if ref (setq ref "&"))
1436 (if point (setq point (make-string point ?*)) "")
1437 (when type
1438 (concat defaulttype ref point))
1441 (define-mode-local-override semantic-find-tags-by-scope-protection
1442 c-mode (scopeprotection parent &optional table)
1443 "Override the usual search for protection.
1444 We can be more effective than the default by scanning through once,
1445 and collecting tags based on the labels we see along the way."
1446 (if (not table) (setq table (semantic-tag-type-members parent)))
1447 (if (null scopeprotection)
1448 table
1449 (let ((ans nil)
1450 (curprot 1)
1451 (targetprot (cond ((eq scopeprotection 'public)
1453 ((eq scopeprotection 'protected)
1455 (t 3)
1457 (alist '(("public" . 1)
1458 ("protected" . 2)
1459 ("private" . 3)))
1461 (dolist (tag table)
1462 (cond
1463 ((semantic-tag-of-class-p tag 'label)
1464 (setq curprot (cdr (assoc (semantic-tag-name tag) alist)))
1466 ((>= targetprot curprot)
1467 (setq ans (cons tag ans)))
1469 ans)))
1471 (define-mode-local-override semantic-tag-protection
1472 c-mode (tag &optional parent)
1473 "Return the protection of TAG in PARENT.
1474 Override function for `semantic-tag-protection'."
1475 (let ((mods (semantic-tag-modifiers tag))
1476 (prot nil))
1477 ;; Check the modifiers for protection if we are not a child
1478 ;; of some class type.
1479 (when (or (not parent) (not (eq (semantic-tag-class parent) 'type)))
1480 (while (and (not prot) mods)
1481 (if (stringp (car mods))
1482 (let ((s (car mods)))
1483 ;; A few silly defaults to get things started.
1484 (cond ((or (string= s "extern")
1485 (string= s "export"))
1486 'public)
1487 ((string= s "static")
1488 'private))))
1489 (setq mods (cdr mods))))
1490 ;; If we have a typed parent, look for :public style labels.
1491 (when (and parent (eq (semantic-tag-class parent) 'type))
1492 (let ((pp (semantic-tag-type-members parent)))
1493 (while (and pp (not (semantic-equivalent-tag-p (car pp) tag)))
1494 (when (eq (semantic-tag-class (car pp)) 'label)
1495 (setq prot
1496 (cond ((string= (semantic-tag-name (car pp)) "public")
1497 'public)
1498 ((string= (semantic-tag-name (car pp)) "private")
1499 'private)
1500 ((string= (semantic-tag-name (car pp)) "protected")
1501 'protected)))
1503 (setq pp (cdr pp)))))
1504 (when (and (not prot) (eq (semantic-tag-class parent) 'type))
1505 (setq prot
1506 (cond ((string= (semantic-tag-type parent) "class") 'private)
1507 ((string= (semantic-tag-type parent) "struct") 'public)
1508 (t 'unknown))))
1509 (or prot
1510 (if (and parent (semantic-tag-of-class-p parent 'type))
1511 'public
1512 nil))))
1514 (define-mode-local-override semantic-find-tags-included c-mode
1515 (&optional table)
1516 "Find all tags in TABLE that are of the 'include class.
1517 TABLE is a tag table. See `semantic-something-to-tag-table'.
1518 For C++, we also have to search namespaces for include tags."
1519 (let ((tags (semantic-find-tags-by-class 'include table))
1520 (namespaces (semantic-find-tags-by-type "namespace" table)))
1521 (dolist (cur namespaces)
1522 (setq tags
1523 (append tags
1524 (semantic-find-tags-by-class
1525 'include
1526 (semantic-tag-get-attribute cur :members)))))
1527 tags))
1530 (define-mode-local-override semantic-tag-components c-mode (tag)
1531 "Return components for TAG."
1532 (if (and (eq (semantic-tag-class tag) 'type)
1533 (string= (semantic-tag-type tag) "typedef"))
1534 ;; A typedef can contain a parent who has positional children,
1535 ;; but that parent will not have a position. Do this funny hack
1536 ;; to make sure we can apply overlays properly.
1537 (let ((sc (semantic-tag-get-attribute tag :typedef)))
1538 (when (semantic-tag-p sc) (semantic-tag-components sc)))
1539 (semantic-tag-components-default tag)))
1541 (defun semantic-c-tag-template (tag)
1542 "Return the template specification for TAG, or nil."
1543 (semantic-tag-get-attribute tag :template))
1545 (defun semantic-c-tag-template-specifier (tag)
1546 "Return the template specifier specification for TAG, or nil."
1547 (semantic-tag-get-attribute tag :template-specifier))
1549 (defun semantic-c-template-string-body (templatespec)
1550 "Convert TEMPLATESPEC into a string.
1551 This might be a string, or a list of tokens."
1552 (cond ((stringp templatespec)
1553 templatespec)
1554 ((semantic-tag-p templatespec)
1555 (semantic-format-tag-abbreviate templatespec))
1556 ((listp templatespec)
1557 (mapconcat 'semantic-format-tag-abbreviate templatespec ", "))))
1559 (defun semantic-c-template-string (token &optional parent color)
1560 "Return a string representing the TEMPLATE attribute of TOKEN.
1561 This string is prefixed with a space, or is the empty string.
1562 Argument PARENT specifies a parent type.
1563 Argument COLOR specifies that the string should be colorized."
1564 (let ((t2 (semantic-c-tag-template-specifier token))
1565 (t1 (semantic-c-tag-template token))
1566 ;; @todo - Need to account for a parent that is a template
1567 (pt1 (if parent (semantic-c-tag-template parent)))
1568 (pt2 (if parent (semantic-c-tag-template-specifier parent)))
1570 (cond (t2 ;; we have a template with specifier
1571 (concat " <"
1572 ;; Fill in the parts here
1573 (semantic-c-template-string-body t2)
1574 ">"))
1575 (t1 ;; we have a template without specifier
1576 " <>")
1578 ""))))
1580 (define-mode-local-override semantic-format-tag-concise-prototype
1581 c-mode (token &optional parent color)
1582 "Return an abbreviated string describing TOKEN for C and C++.
1583 Optional PARENT and COLOR as specified with
1584 `semantic-format-tag-abbreviate-default'."
1585 ;; If we have special template things, append.
1586 (concat (semantic-format-tag-concise-prototype-default token parent color)
1587 (semantic-c-template-string token parent color)))
1589 (define-mode-local-override semantic-format-tag-uml-prototype
1590 c-mode (token &optional parent color)
1591 "Return an UML string describing TOKEN for C and C++.
1592 Optional PARENT and COLOR as specified with
1593 `semantic-abbreviate-tag-default'."
1594 ;; If we have special template things, append.
1595 (concat (semantic-format-tag-uml-prototype-default token parent color)
1596 (semantic-c-template-string token parent color)))
1598 (define-mode-local-override semantic-tag-abstract-p
1599 c-mode (tag &optional parent)
1600 "Return non-nil if TAG is considered abstract.
1601 PARENT is tag's parent.
1602 In C, a method is abstract if it is `virtual', which is already
1603 handled. A class is abstract only if its destructor is virtual."
1604 (cond
1605 ((eq (semantic-tag-class tag) 'type)
1606 (require 'semantic/find)
1607 (or (semantic-brute-find-tag-by-attribute :pure-virtual-flag
1608 (semantic-tag-components tag)
1610 (let* ((ds (semantic-brute-find-tag-by-attribute
1611 :destructor-flag
1612 (semantic-tag-components tag)
1614 (cs (semantic-brute-find-tag-by-attribute
1615 :constructor-flag
1616 (semantic-tag-components tag)
1618 (and ds (member "virtual" (semantic-tag-modifiers (car ds)))
1619 cs (eq 'protected (semantic-tag-protection (car cs) tag))
1622 ((eq (semantic-tag-class tag) 'function)
1623 (or (semantic-tag-get-attribute tag :pure-virtual-flag)
1624 (member "virtual" (semantic-tag-modifiers tag))))
1625 (t (semantic-tag-abstract-p-default tag parent))))
1627 (defun semantic-c-dereference-typedef (type scope &optional type-declaration)
1628 "If TYPE is a typedef, get TYPE's type by name or tag, and return.
1629 SCOPE is not used, and TYPE-DECLARATION is used only if TYPE is not a typedef."
1630 (if (and (eq (semantic-tag-class type) 'type)
1631 (string= (semantic-tag-type type) "typedef"))
1632 (let ((dt (semantic-tag-get-attribute type :typedef)))
1633 (cond ((and (semantic-tag-p dt)
1634 (not (semantic-tag-prototype-p dt)))
1635 ;; In this case, DT was declared directly. We need
1636 ;; to clone DT and apply a filename to it.
1637 (let* ((fname (semantic-tag-file-name type))
1638 (def (semantic-tag-copy dt nil fname)))
1639 (list def def)))
1640 ((stringp dt) (list dt (semantic-tag dt 'type)))
1641 ((consp dt) (list (car dt) dt))))
1643 (list type type-declaration)))
1645 (defun semantic-c--instantiate-template (tag def-list spec-list)
1646 "Replace TAG name according to template specification.
1647 DEF-LIST is the template information.
1648 SPEC-LIST is the template specifier of the datatype instantiated."
1649 (when (and (car def-list) (car spec-list))
1651 (when (and (string= (semantic-tag-type (car def-list)) "class")
1652 (string= (semantic-tag-name tag) (semantic-tag-name (car def-list))))
1653 (semantic-tag-set-name tag (semantic-tag-name (car spec-list))))
1655 (semantic-c--instantiate-template tag (cdr def-list) (cdr spec-list))))
1657 (defun semantic-c--template-name-1 (spec-list)
1658 "Return a string used to compute template class name.
1659 Based on SPEC-LIST, for ref<Foo,Bar> it will return 'Foo,Bar'."
1660 (when (car spec-list)
1661 (let* ((endpart (semantic-c--template-name-1 (cdr spec-list)))
1662 (separator (and endpart ",")))
1663 (concat (semantic-tag-name (car spec-list)) separator endpart))))
1665 (defun semantic-c--template-name (type spec-list)
1666 "Return a template class name for TYPE based on SPEC-LIST.
1667 For a type `ref' with a template specifier of (Foo Bar) it will
1668 return 'ref<Foo,Bar>'."
1669 (concat (semantic-tag-name type)
1670 "<" (semantic-c--template-name-1 (cdr spec-list)) ">"))
1672 (defun semantic-c-dereference-template (type scope &optional type-declaration)
1673 "Dereference any template specifiers in TYPE within SCOPE.
1674 If TYPE is a template, return a TYPE copy with the templates types
1675 instantiated as specified in TYPE-DECLARATION."
1676 (when (semantic-tag-p type-declaration)
1677 (let ((def-list (semantic-tag-get-attribute type :template))
1678 (spec-list (semantic-tag-get-attribute type-declaration :template-specifier)))
1679 (when (and def-list spec-list)
1680 (setq type (semantic-tag-deep-copy-one-tag
1681 type
1682 (lambda (tag)
1683 (when (semantic-tag-of-class-p tag 'type)
1684 (semantic-c--instantiate-template
1685 tag def-list spec-list))
1686 tag)
1688 (semantic-tag-set-name type (semantic-c--template-name type spec-list))
1689 (semantic-tag-put-attribute type :template nil)
1690 (semantic-tag-set-faux type))))
1691 (list type type-declaration))
1693 ;;; Patch here by "Raf" for instantiating templates.
1694 (defun semantic-c-dereference-member-of (type scope &optional type-declaration)
1695 "Dereference through the `->' operator of TYPE.
1696 Uses the return type of the '->' operator if it is contained in TYPE.
1697 SCOPE is the current local scope to perform searches in.
1698 TYPE-DECLARATION is passed through."
1699 (if semantic-c-member-of-autocast
1700 (let ((operator (car (semantic-find-tags-by-name "->" (semantic-analyze-scoped-type-parts type)))))
1701 (if operator
1702 (list (semantic-tag-get-attribute operator :type) (semantic-tag-get-attribute operator :type))
1703 (list type type-declaration)))
1704 (list type type-declaration)))
1706 ;; David Engster: The following three functions deal with namespace
1707 ;; aliases and types which are member of a namespace through a using
1708 ;; statement. For examples, see the file semantic/tests/testusing.cpp,
1709 ;; tests 5 and following.
1711 (defun semantic-c-dereference-namespace (type scope &optional type-declaration)
1712 "Dereference namespace which might hold an 'alias' for TYPE.
1713 Such an alias can be created through 'using' statements in a
1714 namespace declaration. This function checks the namespaces in
1715 SCOPE for such statements."
1716 (let ((scopetypes (oref scope scopetypes))
1717 typename currentns tmp usingname result namespaces)
1718 (when (and (semantic-tag-p type-declaration)
1719 (or (null type) (semantic-tag-prototype-p type)))
1720 (setq typename (semantic-analyze-split-name (semantic-tag-name type-declaration)))
1721 ;; If we already have that TYPE in SCOPE, we do nothing
1722 (unless (semantic-deep-find-tags-by-name (or (car-safe typename) typename) scopetypes)
1723 (if (stringp typename)
1724 ;; The type isn't fully qualified, so we have to search in all namespaces in SCOPE.
1725 (setq namespaces (semantic-find-tags-by-type "namespace" scopetypes))
1726 ;; This is a fully qualified name, so we only have to search one namespace.
1727 (setq namespaces (semanticdb-typecache-find (car typename)))
1728 ;; Make sure it's really a namespace.
1729 (if (string= (semantic-tag-type namespaces) "namespace")
1730 (setq namespaces (list namespaces))
1731 (setq namespaces nil)))
1732 (setq result nil)
1733 ;; Iterate over all the namespaces we have to check.
1734 (while (and namespaces
1735 (null result))
1736 (setq currentns (car namespaces))
1737 ;; Check if this is namespace is an alias and dereference it if necessary.
1738 (setq result (semantic-c-dereference-namespace-alias type-declaration currentns))
1739 (unless result
1740 ;; Otherwise, check if we can reach the type through 'using' statements.
1741 (setq result
1742 (semantic-c-check-type-namespace-using type-declaration currentns)))
1743 (setq namespaces (cdr namespaces)))))
1744 (if result
1745 ;; we have found the original type
1746 (list result result)
1747 (list type type-declaration))))
1749 (defun semantic-c-dereference-namespace-alias (type namespace)
1750 "Dereference TYPE in NAMESPACE, given that NAMESPACE is an alias.
1751 Checks if NAMESPACE is an alias and if so, returns a new type
1752 with a fully qualified name in the original namespace. Returns
1753 nil if NAMESPACE is not an alias."
1754 (when (eq (semantic-tag-get-attribute namespace :kind) 'alias)
1755 (let ((typename (semantic-analyze-split-name (semantic-tag-name type)))
1756 ns nstype originaltype newtype)
1757 ;; Make typename unqualified
1758 (if (listp typename)
1759 (setq typename (last typename))
1760 (setq typename (list typename)))
1761 (when
1762 (and
1763 ;; Get original namespace and make sure TYPE exists there.
1764 (setq ns (semantic-tag-name
1765 (car (semantic-tag-get-attribute namespace :members))))
1766 (setq nstype (semanticdb-typecache-find ns))
1767 (setq originaltype (semantic-find-tags-by-name
1768 (car typename)
1769 (semantic-tag-get-attribute nstype :members))))
1770 ;; Construct new type with name in original namespace.
1771 (setq ns (semantic-analyze-split-name ns))
1772 (setq newtype
1773 (semantic-tag-clone
1774 (car originaltype)
1775 (semantic-analyze-unsplit-name
1776 (if (listp ns)
1777 (append ns typename)
1778 (append (list ns) typename)))))))))
1780 ;; This searches a type in a namespace, following through all using
1781 ;; statements.
1782 (defun semantic-c-check-type-namespace-using (type namespace)
1783 "Check if TYPE is accessible in NAMESPACE through a using statement.
1784 Returns the original type from the namespace where it is defined,
1785 or nil if it cannot be found."
1786 (let (usings result usingname usingtype unqualifiedname members shortname tmp)
1787 ;; Get all using statements from NAMESPACE.
1788 (when (and (setq usings (semantic-tag-get-attribute namespace :members))
1789 (setq usings (semantic-find-tags-by-class 'using usings)))
1790 ;; Get unqualified typename.
1791 (when (listp (setq unqualifiedname (semantic-analyze-split-name
1792 (semantic-tag-name type))))
1793 (setq unqualifiedname (car (last unqualifiedname))))
1794 ;; Iterate over all using statements in NAMESPACE.
1795 (while (and usings
1796 (null result))
1797 (setq usingname (semantic-analyze-split-name
1798 (semantic-tag-name (car usings)))
1799 usingtype (semantic-tag-type (semantic-tag-type (car usings))))
1800 (cond
1801 ((or (string= usingtype "namespace")
1802 (stringp usingname))
1803 ;; We are dealing with a 'using [namespace] NAMESPACE;'
1804 ;; Search for TYPE in that namespace
1805 (setq result
1806 (semanticdb-typecache-find usingname))
1807 (if (and result
1808 (setq members (semantic-tag-get-attribute result :members))
1809 (setq members (semantic-find-tags-by-name unqualifiedname members)))
1810 ;; TYPE is member of that namespace, so we are finished
1811 (setq result (car members))
1812 ;; otherwise recursively search in that namespace for an alias
1813 (setq result (semantic-c-check-type-namespace-using type result))
1814 (when result
1815 (setq result (semantic-tag-type result)))))
1816 ((and (string= usingtype "class")
1817 (listp usingname))
1818 ;; We are dealing with a 'using TYPE;'
1819 (when (string= unqualifiedname (car (last usingname)))
1820 ;; We have found the correct tag.
1821 (setq result (semantic-tag-type (car usings))))))
1822 (setq usings (cdr usings))))
1823 result))
1826 (define-mode-local-override semantic-analyze-dereference-metatype
1827 c-mode (type scope &optional type-declaration)
1828 "Dereference TYPE as described in `semantic-analyze-dereference-metatype'.
1829 Handle typedef, template instantiation, and '->' operator."
1830 (let* ((dereferencer-list '(semantic-c-dereference-typedef
1831 semantic-c-dereference-template
1832 semantic-c-dereference-member-of
1833 semantic-c-dereference-namespace))
1834 (dereferencer (pop dereferencer-list))
1835 (type-tuple)
1836 (original-type type))
1837 (while dereferencer
1838 (setq type-tuple (funcall dereferencer type scope type-declaration)
1839 type (car type-tuple)
1840 type-declaration (cadr type-tuple))
1841 (if (not (eq type original-type))
1842 ;; we found a new type so break the dereferencer loop now !
1843 ;; (we will be recalled with the new type expanded by
1844 ;; semantic-analyze-dereference-metatype-stack).
1845 (setq dereferencer nil)
1846 ;; no new type found try the next dereferencer :
1847 (setq dereferencer (pop dereferencer-list)))))
1848 (list type type-declaration))
1850 (define-mode-local-override semantic-analyze-type-constants c-mode (type)
1851 "When TYPE is a tag for an enum, return its parts.
1852 These are constants which are of type TYPE."
1853 (if (and (eq (semantic-tag-class type) 'type)
1854 (string= (semantic-tag-type type) "enum"))
1855 (semantic-tag-type-members type)))
1857 (define-mode-local-override semantic-analyze-unsplit-name c-mode (namelist)
1858 "Assemble the list of names NAMELIST into a namespace name."
1859 (mapconcat 'identity namelist "::"))
1861 (define-mode-local-override semantic-ctxt-scoped-types c++-mode (&optional point)
1862 "Return a list of tags of CLASS type based on POINT.
1863 DO NOT return the list of tags encompassing point."
1864 (when point (goto-char (point)))
1865 (let ((tagsaroundpoint (semantic-find-tag-by-overlay))
1866 (tagreturn nil)
1867 (tmp nil))
1868 ;; In C++, we want to find all the namespaces declared
1869 ;; locally and add them to the list.
1870 (setq tmp (semantic-find-tags-by-class 'type (current-buffer)))
1871 (setq tmp (semantic-find-tags-by-type "namespace" tmp))
1872 (setq tmp (semantic-find-tags-by-name "unnamed" tmp))
1873 (setq tagreturn tmp)
1874 ;; We should also find all "using" type statements and
1875 ;; accept those entities in as well.
1876 (setq tmp (semanticdb-find-tags-by-class 'using))
1877 (let ((idx 0)
1878 (len (semanticdb-find-result-length tmp)))
1879 (while (< idx len)
1880 (setq tagreturn
1881 (append tagreturn (list (semantic-tag-type
1882 (car (semanticdb-find-result-nth tmp idx))))))
1883 (setq idx (1+ idx))))
1884 ;; Use the encompassed types around point to also look for using
1885 ;; statements. If we deal with types, search inside members; for
1886 ;; functions, we have to call `semantic-get-local-variables' to
1887 ;; parse inside the function's body.
1888 (dolist (cur tagsaroundpoint)
1889 (cond
1890 ((and (eq (semantic-tag-class cur) 'type)
1891 (setq tmp (semantic-find-tags-by-class
1892 'using
1893 (semantic-tag-components (car tagsaroundpoint)))))
1894 (dolist (T tmp)
1895 (setq tagreturn (cons (semantic-tag-type T) tagreturn))))
1896 ((and (semantic-tag-of-class-p (car (last tagsaroundpoint)) 'function)
1897 (setq tmp (semantic-find-tags-by-class
1898 'using
1899 (semantic-get-local-variables))))
1900 (setq tagreturn
1901 (append tagreturn
1902 (mapcar 'semantic-tag-type tmp))))))
1903 ;; Return the stuff
1904 tagreturn))
1906 (define-mode-local-override semantic-ctxt-imported-packages c++-mode (&optional point)
1907 "Return the list of using tag types in scope of POINT."
1908 (when point (goto-char (point)))
1909 (let ((tagsaroundpoint (semantic-find-tag-by-overlay))
1910 (namereturn nil)
1911 (tmp nil)
1913 ;; Collect using statements from the top level.
1914 (setq tmp (semantic-find-tags-by-class 'using (current-buffer)))
1915 (dolist (T tmp) (setq namereturn (cons (semantic-tag-type T) namereturn)))
1916 ;; Move through the tags around point looking for more using statements
1917 (while (cdr tagsaroundpoint) ; don't search the last one
1918 (setq tmp (semantic-find-tags-by-class 'using (semantic-tag-components (car tagsaroundpoint))))
1919 (dolist (T tmp) (setq namereturn (cons (semantic-tag-type T) namereturn)))
1920 (setq tagsaroundpoint (cdr tagsaroundpoint))
1922 namereturn))
1924 (define-mode-local-override semanticdb-expand-nested-tag c++-mode (tag)
1925 "Expand TAG if it has a fully qualified name.
1926 For types with a :parent, create faux namespaces to put TAG into."
1927 (let ((p (semantic-tag-get-attribute tag :parent)))
1928 (if (and p (semantic-tag-of-class-p tag 'type))
1929 ;; Expand the tag
1930 (let ((s (semantic-analyze-split-name p))
1931 (newtag (semantic-tag-copy tag nil t)))
1932 ;; Erase the qualified name.
1933 (semantic-tag-put-attribute newtag :parent nil)
1934 ;; Fixup the namespace name
1935 (setq s (if (stringp s) (list s) (nreverse s)))
1936 ;; Loop over all the parents, creating the nested
1937 ;; namespace.
1938 (require 'semantic/db-typecache)
1939 (dolist (namespace s)
1940 (setq newtag (semanticdb-typecache-faux-namespace
1941 namespace (list newtag)))
1943 ;; Return the last created namespace.
1944 newtag)
1945 ;; Else, return tag unmodified.
1946 tag)))
1948 (define-mode-local-override semanticdb-find-table-for-include c-mode
1949 (includetag &optional table)
1950 "For a single INCLUDETAG found in TABLE, find a `semanticdb-table' object
1951 INCLUDETAG is a semantic TAG of class 'include.
1952 TABLE is a semanticdb table that identifies where INCLUDETAG came from.
1953 TABLE is optional if INCLUDETAG has an overlay of :filename attribute.
1955 For C++, we also have to check if the include is inside a
1956 namespace, since this means all tags inside this include will
1957 have to be wrapped in that namespace."
1958 (let ((inctable (semanticdb-find-table-for-include-default includetag table))
1959 (inside-ns (semantic-tag-get-attribute includetag :inside-ns))
1960 tags newtags namespaces prefix parenttable newtable)
1961 (if (or (null inside-ns)
1962 (not inctable)
1963 (not (slot-boundp inctable 'tags)))
1964 inctable
1965 (when (and (eq inside-ns t)
1966 ;; Get the table which has this include.
1967 (setq parenttable
1968 (semanticdb-find-table-for-include-default
1969 (semantic-tag-new-include
1970 (semantic--tag-get-property includetag :filename) nil)))
1971 table)
1972 ;; Find the namespace where this include is located.
1973 (setq namespaces
1974 (semantic-find-tags-by-type "namespace" parenttable))
1975 (when (and namespaces
1976 (slot-boundp inctable 'tags))
1977 (dolist (cur namespaces)
1978 (when (semantic-find-tags-by-name
1979 (semantic-tag-name includetag)
1980 (semantic-tag-get-attribute cur :members))
1981 (setq inside-ns (semantic-tag-name cur))
1982 ;; Cache the namespace value.
1983 (semantic-tag-put-attribute includetag :inside-ns inside-ns)))))
1984 (unless (semantic-find-tags-by-name
1985 inside-ns
1986 (semantic-find-tags-by-type "namespace" inctable))
1987 (setq tags (oref inctable tags))
1988 ;; Wrap tags inside namespace tag
1989 (setq newtags
1990 (list (semantic-tag-new-type inside-ns "namespace" tags nil)))
1991 ;; Create new semantic-table for the wrapped tags, since we don't want
1992 ;; the namespace to actually be a part of the header file.
1993 (setq newtable (semanticdb-table "include with context"))
1994 (oset newtable tags newtags)
1995 (oset newtable parent-db (oref inctable parent-db))
1996 (oset newtable file (oref inctable file)))
1997 newtable)))
2000 (define-mode-local-override semantic-get-local-variables c++-mode ()
2001 "Do what `semantic-get-local-variables' does, plus add `this' if needed."
2002 (let* ((origvar (semantic-get-local-variables-default))
2003 (ct (semantic-current-tag))
2004 (p (when (semantic-tag-of-class-p ct 'function)
2005 (or (semantic-tag-function-parent ct)
2006 (car-safe (semantic-find-tags-by-type
2007 "class" (semantic-find-tag-by-overlay)))))))
2008 ;; If we have a function parent, then that implies we can
2009 (if p
2010 ;; Append a new tag THIS into our space.
2011 (cons (semantic-tag-new-variable "this" p nil :pointer 1)
2012 origvar)
2013 ;; No parent, just return the usual
2014 origvar)))
2016 (define-mode-local-override semantic-idle-summary-current-symbol-info
2017 c-mode ()
2018 "Handle the SPP keywords, then use the default mechanism."
2019 (let* ((sym (car (semantic-ctxt-current-thing)))
2020 (spp-sym (semantic-lex-spp-symbol sym)))
2021 (if spp-sym
2022 (let* ((txt (concat "Macro: " sym))
2023 (sv (symbol-value spp-sym))
2024 (arg (semantic-lex-spp-macro-with-args sv))
2026 (when arg
2027 (setq txt (concat txt (format "%S" arg)))
2028 (setq sv (cdr sv)))
2030 ;; This is optional, and potentially fraught w/ errors.
2031 (condition-case nil
2032 (dolist (lt sv)
2033 (setq txt (concat txt " " (semantic-lex-token-text lt))))
2034 (error (setq txt (concat txt " #error in summary fcn"))))
2036 txt)
2037 (semantic-idle-summary-current-symbol-info-default))))
2039 (define-mode-local-override semantic--tag-similar-names-p c-mode (tag1 tag2 blankok)
2040 "Compare the names of TAG1 and TAG2.
2041 If BLANKOK is false, then the names must exactly match.
2042 If BLANKOK is true, then always return t, as for C, the names don't matter
2043 for arguments compared."
2044 (if blankok t (semantic--tag-similar-names-p-default tag1 tag2 nil)))
2046 (define-mode-local-override semantic--tag-similar-types-p c-mode (tag1 tag2)
2047 "For c-mode, deal with TAG1 and TAG2 being used in different namespaces.
2048 In this case, one type will be shorter than the other. Instead
2049 of fully resolving all namespaces currently in scope for both
2050 types, we simply compare as many elements as the shorter type
2051 provides."
2052 ;; First, we see if the default method fails
2053 (if (semantic--tag-similar-types-p-default tag1 tag2)
2055 (let* ((names
2056 (mapcar
2057 (lambda (tag)
2058 (let ((type (semantic-tag-type tag)))
2059 (unless (stringp type)
2060 (setq type (semantic-tag-name type)))
2061 (setq type (semantic-analyze-split-name type))
2062 (when (stringp type)
2063 (setq type (list type)))
2064 type))
2065 (list tag1 tag2)))
2066 (len1 (length (car names)))
2067 (len2 (length (cadr names))))
2068 (cond
2069 ((<= len1 len2)
2070 (equal (nthcdr len1 (cadr names)) (car names)))
2071 ((< len2 len1)
2072 (equal (nthcdr len2 (car names)) (cadr names)))))))
2075 (define-mode-local-override semantic--tag-attribute-similar-p c-mode
2076 (attr value1 value2 ignorable-attributes)
2077 "For c-mode, allow function :arguments to ignore the :name attributes."
2078 (cond ((eq attr :arguments)
2079 (semantic--tag-attribute-similar-p-default attr value1 value2
2080 (cons :name ignorable-attributes)))
2082 (semantic--tag-attribute-similar-p-default attr value1 value2
2083 ignorable-attributes))))
2085 (defvar-mode-local c-mode semantic-orphaned-member-metaparent-type "struct"
2086 "When lost members are found in the class hierarchy generator, use a struct.")
2088 (defvar-mode-local c-mode semantic-symbol->name-assoc-list
2089 '((type . "Types")
2090 (variable . "Variables")
2091 (function . "Functions")
2092 (include . "Includes")
2094 "List of tag classes, and strings to describe them.")
2096 (defvar-mode-local c-mode semantic-symbol->name-assoc-list-for-type-parts
2097 '((type . "Types")
2098 (variable . "Attributes")
2099 (function . "Methods")
2100 (label . "Labels")
2102 "List of tag classes in a datatype decl, and strings to describe them.")
2104 (defvar-mode-local c-mode imenu-create-index-function 'semantic-create-imenu-index
2105 "Imenu index function for C.")
2107 (defvar-mode-local c-mode semantic-type-relation-separator-character
2108 '("." "->" "::")
2109 "Separator characters between something of a given type, and a field.")
2111 (defvar-mode-local c-mode semantic-command-separation-character ";"
2112 "Command separation character for C.")
2114 (defvar-mode-local c-mode senator-step-at-tag-classes '(function variable)
2115 "Tag classes where senator will stop at the end.")
2117 (defvar-mode-local c-mode semantic-tag-similar-ignorable-attributes
2118 '(:prototype-flag :parent :typemodifiers)
2119 "Tag attributes to ignore during similarity tests.
2120 :parent is here because some tags might specify a parent, while others are
2121 actually in their parent which is not accessible.")
2123 ;;;###autoload
2124 (defun semantic-default-c-setup ()
2125 "Set up a buffer for semantic parsing of the C language."
2126 (semantic-c-by--install-parser)
2127 (setq semantic-lex-syntax-modifications '((?> ".")
2128 (?< ".")
2132 (setq semantic-lex-analyzer #'semantic-c-lexer)
2133 (add-hook 'semantic-lex-reset-functions 'semantic-lex-spp-reset-hook nil t)
2134 (when (eq major-mode 'c++-mode)
2135 (add-to-list 'semantic-lex-c-preprocessor-symbol-map '("__cplusplus" . "")))
2138 ;;;###autoload
2139 (defun semantic-c-add-preprocessor-symbol (sym replacement)
2140 "Add a preprocessor symbol SYM with a REPLACEMENT value."
2141 (interactive "sSymbol: \nsReplacement: ")
2142 (let ((SA (assoc sym semantic-lex-c-preprocessor-symbol-map)))
2143 (if SA
2144 ;; Replace if there is one.
2145 (setcdr SA replacement)
2146 ;; Otherwise, append
2147 (setq semantic-lex-c-preprocessor-symbol-map
2148 (cons (cons sym replacement)
2149 semantic-lex-c-preprocessor-symbol-map))))
2151 (semantic-c-reset-preprocessor-symbol-map)
2154 ;;; SETUP QUERY
2156 (defun semantic-c-describe-environment ()
2157 "Describe the Semantic features of the current C environment."
2158 (interactive)
2159 (if (not (member 'c-mode (mode-local-equivalent-mode-p major-mode)))
2160 (error "Not useful to query C mode in %s mode" major-mode))
2161 (let ((gcc (when (boundp 'semantic-gcc-setup-data)
2162 semantic-gcc-setup-data))
2164 (semantic-fetch-tags)
2166 (with-output-to-temp-buffer "*Semantic C Environment*"
2167 (when gcc
2168 (princ "Calculated GCC Parameters:")
2169 (dolist (P gcc)
2170 (princ "\n ")
2171 (princ (car P))
2172 (princ " = ")
2173 (princ (cdr P))
2177 (princ "\n\nInclude Path Summary:\n")
2178 (when (and (boundp 'ede-object) ede-object)
2179 (princ "\n This file's project include is handled by:\n")
2180 (let ((objs (if (listp ede-object)
2181 ede-object
2182 (list ede-object))))
2183 (dolist (O objs)
2184 (princ " EDE : ")
2185 (princ (object-print O))
2186 (let ((ipath (ede-system-include-path O)))
2187 (if (not ipath)
2188 (princ "\n with NO specified system include path.\n")
2189 (princ "\n with the system path:\n")
2190 (dolist (dir ipath)
2191 (princ " ")
2192 (princ dir)
2193 (princ "\n"))))))
2196 (when semantic-dependency-include-path
2197 (princ "\n This file's generic include path is:\n")
2198 (dolist (dir semantic-dependency-include-path)
2199 (princ " ")
2200 (princ dir)
2201 (princ "\n")))
2203 (when semantic-dependency-system-include-path
2204 (princ "\n This file's system include path is:\n")
2205 (dolist (dir semantic-dependency-system-include-path)
2206 (princ " ")
2207 (princ dir)
2208 (princ "\n")))
2210 (princ "\n\nMacro Summary:\n")
2212 (when semantic-lex-c-preprocessor-symbol-file
2213 (princ "\n Your CPP table is primed from these system files:\n")
2214 (dolist (file semantic-lex-c-preprocessor-symbol-file)
2215 (princ " ")
2216 (princ file)
2217 (princ "\n")
2218 (princ " in table: ")
2219 (let ((fto (semanticdb-file-table-object file)))
2220 (if fto
2221 (princ (object-print fto))
2222 (princ "No Table")))
2223 (princ "\n")
2226 (when semantic-lex-c-preprocessor-symbol-map-builtin
2227 (princ "\n Built-in symbol map:\n")
2228 (dolist (S semantic-lex-c-preprocessor-symbol-map-builtin)
2229 (princ " ")
2230 (princ (car S))
2231 (princ " = ")
2232 (princ (cdr S))
2233 (princ "\n")
2236 (when semantic-lex-c-preprocessor-symbol-map
2237 (princ "\n User symbol map (primed from system files):\n")
2238 (dolist (S semantic-lex-c-preprocessor-symbol-map)
2239 (princ " ")
2240 (princ (car S))
2241 (princ " = ")
2242 (princ (cdr S))
2243 (princ "\n")
2246 (when (and (boundp 'ede-object)
2247 ede-object)
2248 (princ "\n Project symbol map:\n")
2249 (when (and (boundp 'ede-object) ede-object)
2250 (princ " Your project symbol map is also derived from the EDE object:\n ")
2251 (princ (object-print ede-object)))
2252 (princ "\n\n")
2253 (if (arrayp semantic-lex-spp-project-macro-symbol-obarray)
2254 (let ((macros nil))
2255 (mapatoms
2256 #'(lambda (symbol)
2257 (setq macros (cons symbol macros)))
2258 semantic-lex-spp-project-macro-symbol-obarray)
2259 (dolist (S macros)
2260 (princ " ")
2261 (princ (symbol-name S))
2262 (princ " = ")
2263 (princ (symbol-value S))
2264 (princ "\n")
2266 ;; Else, not map
2267 (princ " No Symbols.\n")))
2269 (princ "\n\n Use: M-x semantic-lex-spp-describe RET\n")
2270 (princ "\n to see the complete macro table.\n")
2274 (provide 'semantic/bovine/c)
2276 (semantic-c-reset-preprocessor-symbol-map)
2278 ;; Local variables:
2279 ;; generated-autoload-file: "../loaddefs.el"
2280 ;; generated-autoload-load-name: "semantic/bovine/c"
2281 ;; End:
2283 ;;; semantic/bovine/c.el ends here