1 ;;; hideif.el --- hides selected code within ifdef -*- lexical-binding:t -*-
3 ;; Copyright (C) 1988, 1994, 2001-2014 Free Software Foundation, Inc.
5 ;; Author: Brian Marick
6 ;; Daniel LaLiberte <liberte@holonexus.org>
7 ;; Maintainer: Luke Lee <luke.yx.lee@gmail.com>
8 ;; Keywords: c, outlines
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; To initialize, toggle the hide-ifdef minor mode with
29 ;; M-x hide-ifdef-mode
31 ;; This will set up key bindings and call hide-ifdef-mode-hook if it
32 ;; has a value. To explicitly hide ifdefs using a buffer-local
33 ;; define list (default empty), type
35 ;; M-x hide-ifdefs or C-c @ h
37 ;; Hide-ifdef suppresses the display of code that the preprocessor wouldn't
38 ;; pass through. Support complete C/C++ expression and precedence.
39 ;; It will automatically scan for new #define symbols and macros on the way
42 ;; The hidden code is marked by ellipses (...). Be
43 ;; cautious when editing near ellipses, since the hidden text is
44 ;; still in the buffer, and you can move the point into it and modify
46 ;; You can make your buffer read-only while hide-ifdef-hiding by setting
47 ;; hide-ifdef-read-only to a non-nil value. You can toggle this
48 ;; variable with hide-ifdef-toggle-read-only (C-c @ C-q).
50 ;; You can undo the effect of hide-ifdefs by typing
52 ;; M-x show-ifdefs or C-c @ s
54 ;; Use M-x hide-ifdef-define (C-c @ d) to define a symbol.
55 ;; Use M-x hide-ifdef-undef (C-c @ u) to undefine a symbol.
57 ;; If you define or undefine a symbol while hide-ifdef-mode is in effect,
58 ;; the display will be updated. Only the define list for the current
59 ;; buffer will be affected. You can save changes to the local define
60 ;; list with hide-ifdef-set-define-alist. This adds entries
61 ;; to hide-ifdef-define-alist.
63 ;; If you have defined a hide-ifdef-mode-hook, you can set
64 ;; up a list of symbols that may be used by hide-ifdefs as in the
67 ;; (add-hook 'hide-ifdef-mode-hook
69 ;; (unless hide-ifdef-define-alist
70 ;; (setq hide-ifdef-define-alist
72 ;; (list2 TWO THREE))))
73 ;; (hide-ifdef-use-define-alist 'list2))) ; use list2 by default
75 ;; You can call hide-ifdef-use-define-alist (C-c @ U) at any time to specify
76 ;; another list to use.
78 ;; To cause ifdefs to be hidden as soon as hide-ifdef-mode is called,
79 ;; set hide-ifdef-initially to non-nil.
81 ;; If you set hide-ifdef-lines to t, hide-ifdefs hides all the #ifdef lines.
82 ;; In the absence of highlighting, that might be a bad idea. If you set
83 ;; hide-ifdef-lines to nil (the default), the surrounding preprocessor
84 ;; lines will be displayed. That can be confusing in its own
85 ;; right. Other variations on display are possible, but not much
88 ;; You can explicitly hide or show individual ifdef blocks irrespective
89 ;; of the define list by using hide-ifdef-block and show-ifdef-block.
91 ;; You can move the point between ifdefs with forward-ifdef, backward-ifdef,
92 ;; up-ifdef, down-ifdef, next-ifdef, and previous-ifdef.
94 ;; If you have minor-mode-alist in your mode line (the default) two labels
95 ;; may appear. "Ifdef" will appear when hide-ifdef-mode is active. "Hiding"
96 ;; will appear when text may be hidden ("hide-ifdef-hiding" is non-nil).
98 ;; Written by Brian Marick, at Gould, Computer Systems Division, Urbana IL.
99 ;; Extensively modified by Daniel LaLiberte (while at Gould).
101 ;; Extensively modified by Luke Lee in 2013 to support complete C expression
102 ;; evaluation and argumented macro expansion.
109 (defgroup hide-ifdef nil
110 "Hide selected code within `ifdef'."
113 (defcustom hide-ifdef-initially nil
114 "Non-nil means call `hide-ifdefs' when Hide-Ifdef mode is first activated."
118 (defcustom hide-ifdef-read-only nil
119 "Set to non-nil if you want buffer to be read-only while hiding text."
123 (defcustom hide-ifdef-lines nil
124 "Non-nil means hide the #ifX, #else, and #endif lines."
128 (defcustom hide-ifdef-shadow nil
129 "Non-nil means shadow text instead of hiding it."
134 (defface hide-ifdef-shadow '((t (:inherit shadow)))
135 "Face for shadowing ifdef blocks."
139 (defcustom hide-ifdef-exclude-define-regexp nil
140 "Ignore #define names if those names match this exclusion pattern."
144 (defcustom hide-ifdef-expand-reinclusion-protection t
145 "Non-nil means don't hide an entire header file enclosed by #ifndef...#endif.
146 Most C/C++ headers are usually wrapped with ifdefs to prevent re-inclusion:
148 ----- beginning of file -----
149 #ifndef _XXX_HEADER_FILE_INCLUDED_
150 #define _XXX_HEADER_FILE_INCLUDED_
155 ----- end of file -----
157 The first time we visit such a file, _XXX_HEADER_FILE_INCLUDED_ is
158 undefined, and so nothing is hidden. The next time we visit it, everything will
161 This behavior is generally undesirable. If this option is non-nil, the outermost
162 #if is always visible."
166 (defcustom hide-ifdef-header-regexp
167 "\\.h\\(h\\|xx\\|pp\\)?\\'"
168 "C/C++ header file name patterns to determine if current buffer is a header.
169 Effective only if `hide-ifdef-expand-reinclusion-protection' is t."
174 (defvar hide-ifdef-mode-submap
175 ;; Set up the submap that goes after the prefix key.
176 (let ((map (make-sparse-keymap)))
177 (define-key map "d" 'hide-ifdef-define)
178 (define-key map "u" 'hide-ifdef-undef)
179 (define-key map "D" 'hide-ifdef-set-define-alist)
180 (define-key map "U" 'hide-ifdef-use-define-alist)
182 (define-key map "h" 'hide-ifdefs)
183 (define-key map "s" 'show-ifdefs)
184 (define-key map "\C-d" 'hide-ifdef-block)
185 (define-key map "\C-s" 'show-ifdef-block)
186 (define-key map "e" 'hif-evaluate-macro)
187 (define-key map "C" 'hif-clear-all-ifdef-defined)
189 (define-key map "\C-q" 'hide-ifdef-toggle-read-only)
190 (define-key map "\C-w" 'hide-ifdef-toggle-shadowing)
191 (substitute-key-definition
192 'toggle-read-only 'hide-ifdef-toggle-outside-read-only map)
194 "Keymap used by `hide-ifdef-mode' under `hide-ifdef-mode-prefix-key'.")
196 (defconst hide-ifdef-mode-prefix-key "\C-c@"
197 "Prefix key for all Hide-Ifdef mode commands.")
199 (defvar hide-ifdef-mode-map
200 ;; Set up the mode's main map, which leads via the prefix key to the submap.
201 (let ((map (make-sparse-keymap)))
202 (define-key map hide-ifdef-mode-prefix-key hide-ifdef-mode-submap)
204 "Keymap used with `hide-ifdef-mode'.")
206 (easy-menu-define hide-ifdef-mode-menu hide-ifdef-mode-map
207 "Menu for `hide-ifdef-mode'."
209 ["Hide some ifdefs" hide-ifdefs
210 :help "Hide the contents of some #ifdefs"]
211 ["Show all ifdefs" show-ifdefs
212 :help "Cancel the effects of `hide-ifdef': show the contents of all #ifdefs"]
213 ["Hide ifdef block" hide-ifdef-block
214 :help "Hide the ifdef block (true or false part) enclosing or before the cursor"]
215 ["Show ifdef block" show-ifdef-block
216 :help "Show the ifdef block (true or false part) enclosing or before the cursor"]
217 ["Define a variable..." hide-ifdef-define
218 :help "Define a VAR so that #ifdef VAR would be included"]
219 ["Undefine a variable..." hide-ifdef-undef
220 :help "Undefine a VAR so that #ifdef VAR would not be included"]
221 ["Define an alist..." hide-ifdef-set-define-alist
222 :help "Set the association for NAME to `hide-ifdef-env'"]
223 ["Use an alist..." hide-ifdef-use-define-alist
224 :help "Set `hide-ifdef-env' to the define list specified by NAME"]
225 ["Toggle read only" hide-ifdef-toggle-read-only
226 :style toggle :selected hide-ifdef-read-only
227 :help "Buffer should be read-only while hiding text"]
228 ["Toggle shadowing" hide-ifdef-toggle-shadowing
229 :style toggle :selected hide-ifdef-shadow
230 :help "Text should be shadowed instead of hidden"]))
232 (defvar hide-ifdef-hiding nil
233 "Non-nil when text may be hidden.")
235 (or (assq 'hide-ifdef-hiding minor-mode-alist)
236 (setq minor-mode-alist
237 (cons '(hide-ifdef-hiding " Hiding")
240 ;; Fix c-mode syntax table so we can recognize whole symbols.
241 (defvar hide-ifdef-syntax-table
242 (let ((st (copy-syntax-table c-mode-syntax-table)))
243 (modify-syntax-entry ?_ "w" st)
244 (modify-syntax-entry ?& "." st)
245 (modify-syntax-entry ?\| "." st)
247 "Syntax table used for tokenizing #if expressions.")
249 (defvar hide-ifdef-env nil
250 "An alist of defined symbols and their values.")
252 (defvar hide-ifdef-env-backup nil
253 "This variable is a backup of the previously cleared `hide-ifdef-env'.
254 This backup prevents any accidental clearance of `hide-fidef-env' by
255 `hif-clear-all-ifdef-defined'.")
257 (defvar hif-outside-read-only nil
258 "Internal variable. Saves the value of `buffer-read-only' while hiding.")
261 (define-minor-mode hide-ifdef-mode
262 "Toggle features to hide/show #ifdef blocks (Hide-Ifdef mode).
263 With a prefix argument ARG, enable Hide-Ifdef mode if ARG is
264 positive, and disable it otherwise. If called from Lisp, enable
265 the mode if ARG is omitted or nil.
267 Hide-Ifdef mode is a buffer-local minor mode for use with C and
268 C-like major modes. When enabled, code within #ifdef constructs
269 that the C preprocessor would eliminate may be hidden from view.
270 Several variables affect how the hiding is done:
273 An association list of defined and undefined symbols for the
274 current project. Initially, the global value of `hide-ifdef-env'
275 is used. This variable was a buffer-local variable, which limits
276 hideif to parse only one C/C++ file at a time. We've extended
277 hideif to support parsing a C/C++ project containing multiple C/C++
278 source files opened simultaneously in different buffers. Therefore
279 `hide-ifdef-env' can no longer be buffer local but must be global.
281 `hide-ifdef-define-alist'
282 An association list of defined symbol lists.
283 Use `hide-ifdef-set-define-alist' to save the current `hide-ifdef-env'
284 and `hide-ifdef-use-define-alist' to set the current `hide-ifdef-env'
285 from one of the lists in `hide-ifdef-define-alist'.
288 Set to non-nil to not show #if, #ifdef, #ifndef, #else, and
289 #endif lines when hiding.
291 `hide-ifdef-initially'
292 Indicates whether `hide-ifdefs' should be called when Hide-Ifdef mode
295 `hide-ifdef-read-only'
296 Set to non-nil if you want to make buffers read only while hiding.
297 After `show-ifdefs', read-only status is restored to previous value.
299 \\{hide-ifdef-mode-map}"
300 :group 'hide-ifdef :lighter " Ifdef"
303 ;; inherit global values
305 ;; `hide-ifdef-env' is now a global variable.
306 ;; We can still simulate the behavior of older hideif versions (i.e.
307 ;; `hide-ifdef-env' being buffer local) by clearing this variable
308 ;; (C-c @ C) everytime before hiding current buffer.
309 ;; (set (make-local-variable 'hide-ifdef-env)
310 ;; (default-value 'hide-ifdef-env))
311 (set 'hide-ifdef-env (default-value 'hide-ifdef-env))
312 ;; Some C/C++ headers might have other ways to prevent reinclusion and
313 ;; thus would like `hide-ifdef-expand-reinclusion-protection' to be nil.
314 (set (make-local-variable 'hide-ifdef-expand-reinclusion-protection)
315 (default-value 'hide-ifdef-expand-reinclusion-protection))
316 (set (make-local-variable 'hide-ifdef-hiding)
317 (default-value 'hide-ifdef-hiding))
318 (set (make-local-variable 'hif-outside-read-only) buffer-read-only)
319 (set (make-local-variable 'line-move-ignore-invisible) t)
320 (add-hook 'change-major-mode-hook
321 (lambda () (hide-ifdef-mode -1)) nil t)
323 (add-to-invisibility-spec '(hide-ifdef . t))
325 (if hide-ifdef-initially
328 ;; else end hide-ifdef-mode
329 (kill-local-variable 'line-move-ignore-invisible)
330 (remove-from-invisibility-spec '(hide-ifdef . t))
331 (when hide-ifdef-hiding
334 (defun hif-clear-all-ifdef-defined ()
335 "Clears all symbols defined in `hide-ifdef-env'.
336 It will backup this variable to `hide-ifdef-env-backup' before clearing to
337 prevent accidental clearance."
339 (when (y-or-n-p "Clear all #defined symbols? ")
340 (setq hide-ifdef-env-backup hide-ifdef-env)
341 (setq hide-ifdef-env nil)))
343 (defun hif-show-all ()
344 "Show all of the text in the current buffer."
346 (hif-show-ifdef-region (point-min) (point-max)))
348 ;; By putting this on after-revert-hook, we arrange that it only
349 ;; does anything when revert-buffer avoids turning off the mode.
350 ;; (That can happen in VC.)
351 (defun hif-after-revert-function ()
352 (and hide-ifdef-mode hide-ifdef-hiding
354 (add-hook 'after-revert-hook 'hif-after-revert-function)
356 (defun hif-end-of-line ()
358 (while (= (logand 1 (skip-chars-backward "\\\\")) 1)
361 (defun hif-merge-ifdef-region (start end)
362 "This function merges nearby ifdef regions to form a bigger overlay.
363 The region is defined by START and END. This will decrease the number of
365 ;; Generally there is no need to call itself recursively since there should
366 ;; originally exists no un-merged regions; however, if a part of the file is
367 ;; hidden with `hide-ifdef-lines' equals to nil while another part with 't,
368 ;; this case happens.
369 ;; TODO: Should we merge? or just create a container overlay? -- this can
370 ;; prevent `hideif-show-ifdef' expanding too many hidden contents since there
371 ;; is only a big overlay exists there without any smaller overlays.
373 (widen) ; Otherwise `point-min' and `point-max' will be restricted and thus
374 ; fail to find neighbor overlays
375 (let ((begovrs (overlays-in
376 (max (- start 2) (point-min))
377 (max (- start 1) (point-min))))
378 (endovrs (overlays-in
379 (min (+ end 1) (point-max))
380 (min (+ end 2) (point-max))))
384 ;; Merge overlays before START
386 (when (overlay-get o 'hide-ifdef)
387 (setq b (min start (overlay-start o))
388 e (max end (overlay-end o)))
390 (hif-merge-ifdef-region b e)
392 ;; Merge overlays after END
394 (when (overlay-get o 'hide-ifdef)
395 (setq b (min start (overlay-start o))
396 e (max end (overlay-end o)))
398 (hif-merge-ifdef-region b e)
400 ;; If both START and END merging happens, merge into bigger one
402 (let ((b (min (overlay-start ob) (overlay-start oe)))
403 (e (max (overlay-end ob) (overlay-end oe))))
405 (move-overlay ob b e)
406 (hif-merge-ifdef-region b e)))
409 (defun hide-ifdef-region-internal (start end)
410 (unless (hif-merge-ifdef-region start end)
411 (let ((o (make-overlay start end)))
412 (overlay-put o 'hide-ifdef t)
413 (if hide-ifdef-shadow
414 (overlay-put o 'face 'hide-ifdef-shadow)
415 (overlay-put o 'invisible 'hide-ifdef)))))
417 (defun hide-ifdef-region (start end)
418 "START is the start of a #if, #elif, or #else form. END is the ending part.
419 Everything including these lines is made invisible."
421 (goto-char start) (hif-end-of-line) (setq start (point))
422 (goto-char end) (hif-end-of-line) (setq end (point))
423 (hide-ifdef-region-internal start end)))
425 (defun hif-show-ifdef-region (start end)
426 "Everything between START and END is made visible."
427 (let ((onum (length (overlays-in start end))))
428 (remove-overlays start end 'hide-ifdef t)
429 (/= onum (length (overlays-in start end)))))
432 ;;===%%SF%% evaluation (Start) ===
434 ;; It is not useful to set this to anything but `eval'.
435 ;; In fact, the variable might as well be eliminated.
436 (defvar hide-ifdef-evaluator 'eval
437 "The function to use to evaluate a form.
438 The evaluator is given a canonical form and returns t if text under
439 that form should be displayed.")
441 (defvar hif-undefined-symbol nil
442 "...is by default considered to be false.")
445 (defun hif-set-var (var value)
446 "Prepend (VAR VALUE) pair to `hide-ifdef-env'."
447 (setq hide-ifdef-env (cons (cons var value) hide-ifdef-env)))
449 (declare-function semantic-c-hideif-lookup "semantic/bovine/c" (var))
450 (declare-function semantic-c-hideif-defined "semantic/bovine/c" (var))
452 (defun hif-lookup (var)
453 (or (when (bound-and-true-p semantic-c-takeover-hideif)
454 (semantic-c-hideif-lookup var))
455 (let ((val (assoc var hide-ifdef-env)))
458 hif-undefined-symbol))))
460 (defun hif-defined (var)
462 ((bound-and-true-p semantic-c-takeover-hideif)
463 (semantic-c-hideif-defined var))
464 ((assoc var hide-ifdef-env) 1)
467 ;;===%%SF%% evaluation (End) ===
471 ;;===%%SF%% parsing (Start) ===
472 ;;; The code that understands what ifs and ifdef in files look like.
474 (defconst hif-cpp-prefix "\\(^\\|\r\\)[ \t]*#[ \t]*")
475 (defconst hif-ifxdef-regexp (concat hif-cpp-prefix "if\\(n\\)?def"))
476 (defconst hif-ifndef-regexp (concat hif-cpp-prefix "ifndef"))
477 (defconst hif-ifx-regexp (concat hif-cpp-prefix "if\\(n?def\\)?[ \t]+"))
478 (defconst hif-elif-regexp (concat hif-cpp-prefix "elif"))
479 (defconst hif-else-regexp (concat hif-cpp-prefix "else"))
480 (defconst hif-endif-regexp (concat hif-cpp-prefix "endif"))
481 (defconst hif-ifx-else-endif-regexp
482 (concat hif-ifx-regexp "\\|" hif-elif-regexp "\\|" hif-else-regexp "\\|"
484 (defconst hif-macro-expr-prefix-regexp
485 (concat hif-cpp-prefix "\\(if\\(n?def\\)?\\|elif\\|define\\)[ \t]+"))
487 (defconst hif-white-regexp "[ \t]*")
488 (defconst hif-define-regexp (concat hif-cpp-prefix "\\(define\\|undef\\)"))
489 (defconst hif-id-regexp (concat "[[:alpha:]_][[:alnum:]_]*"))
490 (defconst hif-macroref-regexp
491 (concat hif-white-regexp "\\(" hif-id-regexp "\\)" hif-white-regexp
494 "\\(" hif-id-regexp "\\)?" hif-white-regexp
495 "\\(" "," hif-white-regexp hif-id-regexp hif-white-regexp "\\)*"
496 "\\(\\.\\.\\.\\)?" hif-white-regexp
500 ;; Store the current token and the whole token list during parsing.
501 ;; Bound dynamically.
503 (defvar hif-token-list)
505 (defconst hif-token-alist
511 ("<<" . hif-shiftleft)
512 (">>" . hif-shiftright)
514 ;; Note: we include tokens like `=' which aren't supported by CPP's
515 ;; expression syntax, because they are still relevant for the tokenizer,
516 ;; especially in conjunction with ##.
518 ("!=" . hif-notequal)
519 ("##" . hif-token-concat)
526 (">=" . hif-greater-equal)
527 ("<=" . hif-less-equal)
533 ("?" . hif-conditional)
536 ("#" . hif-stringify)
539 (defconst hif-valid-token-list (mapcar 'cdr hif-token-alist))
541 (defconst hif-token-regexp
542 (concat (regexp-opt (mapcar 'car hif-token-alist))
543 "\\|0x[0-9a-fA-F]+\\.?[0-9a-fA-F]*"
544 "\\|[0-9]+\\.?[0-9]*" ;; decimal/octal
547 (defconst hif-string-literal-regexp "\\(\"\\(?:[^\"\\]\\|\\\\.\\)*\"\\)")
549 (defun hif-string-to-number (string &optional base)
550 "Like `string-to-number', but it understands non-decimal floats."
551 (if (or (not base) (= base 10))
552 (string-to-number string base)
553 (let* ((parts (split-string string "\\." t "[ \t]+"))
555 (fraclen (length frac))
556 (quot (expt (if (zerop fraclen)
558 (* base 1.0)) fraclen)))
559 (/ (string-to-number (concat (car parts) frac) base) quot))))
561 ;; The dynamic binding variable `hif-simple-token-only' is shared only by
562 ;; `hif-tokenize' and `hif-find-define'. The purpose is to prevent `hif-tokenize'
563 ;; from returning one more value to indicate a simple token is scanned. This help
564 ;; speeding up macro evaluation on those very simple cases like integers or
566 ;; Check the long comments before `hif-find-define' for more details. [lukelee]
567 (defvar hif-simple-token-only)
569 (defun hif-tokenize (start end)
570 "Separate string between START and END into a list of tokens."
571 (let ((token-list nil))
572 (setq hif-simple-token-only t)
573 (with-syntax-table hide-ifdef-syntax-table
576 (while (progn (forward-comment (point-max)) (< (point) end))
577 ;; (message "expr-start = %d" expr-start) (sit-for 1)
579 ((looking-at "\\\\\n")
582 ((looking-at hif-string-literal-regexp)
583 (push (substring-no-properties (match-string 1)) token-list)
584 (goto-char (match-end 0)))
586 ((looking-at hif-token-regexp)
587 (let ((token (buffer-substring-no-properties
588 (point) (match-end 0))))
589 (goto-char (match-end 0))
590 ;; (message "token: %s" token) (sit-for 1)
592 (or (cdr (assoc token hif-token-alist))
593 (if (string-equal token "defined") 'hif-defined)
595 ;; 1. postfix 'l', 'll', 'ul' and 'ull'
596 ;; 2. floating number formats (like 1.23e4)
597 ;; 3. 098 is interpreted as octal conversion error
598 (if (string-match "0x\\([0-9a-fA-F]+\\.?[0-9a-fA-F]*\\)"
600 (hif-string-to-number (match-string 1 token) 16)) ;; hex
601 (if (string-match "\\`0[0-9]+\\(\\.[0-9]+\\)?\\'" token)
602 (hif-string-to-number token 8)) ;; octal
603 (if (string-match "\\`[1-9][0-9]*\\(\\.[0-9]+\\)?\\'"
605 (string-to-number token)) ;; decimal
606 (prog1 (intern token)
607 (setq hif-simple-token-only nil)))
610 ((looking-at "\r") ; Sometimes MS-Windows user will leave CR in
611 (forward-char 1)) ; the source code. Let's not get stuck here.
612 (t (error "Bad #if expression: %s" (buffer-string)))))))
614 (nreverse token-list)))
616 ;;------------------------------------------------------------------------
617 ;; Translate C preprocessor #if expressions using recursive descent.
618 ;; This parser was limited to the operators &&, ||, !, and "defined".
619 ;; Added ==, !=, +, and -. Gary Oberbrunner, garyo@avs.com, 8/9/94
621 ;; Implement the C language operator precedence table. Add all those
622 ;; missing operators that could be used in macros. Luke Lee 2013-09-04
624 ;; | Operator Type | Operator | Associativity |
625 ;; +----------------------+-----------------------------+---------------+
626 ;; | Primary Expression | () [] . -> expr++ expr-- | left-to-right |
627 ;; | Unary Operators | * & + - ! ~ ++expr --expr | right-to-left |
628 ;; | | (typecast) sizeof | |
629 ;; | Binary Operators | * / % | left-to-right |
639 ;; | Ternary Operator | ?: | right-to-left |
640 ;; x| Assignment Operators | = += -= *= /= %= >>= <<= &= | right-to-left |
642 ;; | Comma | , | left-to-right |
644 (defsubst hif-nexttoken ()
645 "Pop the next token from token-list into the let variable `hif-token'."
646 (setq hif-token (pop hif-token-list)))
648 (defsubst hif-if-valid-identifier-p (id)
649 (not (or (numberp id)
652 (defun hif-define-operator (tokens)
653 "`Upgrade' hif-define xxx to '(hif-define xxx)' so it won't be subsitituted."
656 (while (setq tok (pop tokens))
658 (if (eq tok 'hif-defined)
660 (setq tok (cadr tokens))
661 (if (eq (car tokens) 'hif-lparen)
662 (if (and (hif-if-valid-identifier-p tok)
663 (eq (cl-caddr tokens) 'hif-rparen))
664 (setq tokens (cl-cdddr tokens))
665 (error "#define followed by non-identifier: %S" tok))
666 (setq tok (car tokens)
668 (unless (hif-if-valid-identifier-p tok)
669 (error "#define followed by non-identifier: %S" tok)))
670 (list 'hif-defined 'hif-lparen tok 'hif-rparen))
675 (defun hif-flatten (l)
678 (mapcar (lambda (x) (if (listp x)
682 (defun hif-expand-token-list (tokens &optional macroname expand_list)
683 "Perform expansion on TOKENS till everything expanded.
684 Self-reference (directly or indirectly) tokens are not expanded.
685 EXPAND_LIST is the list of macro names currently being expanded, used for
686 detecting self-reference."
687 (catch 'self-referencing
689 (remains (hif-define-operator
690 (hif-token-concatenation
691 (hif-token-stringification tokens))))
694 (setq expand_list (cons macroname expand_list)))
695 ;; Expanding all tokens till list exhausted
696 (while (setq tok (pop remains))
697 (if (memq tok expand_list)
698 ;; For self-referencing tokens, don't expand it
699 (throw 'self-referencing tokens))
702 ((or (memq tok hif-valid-token-list)
707 ((setq rep (hif-lookup tok))
709 (eq (car rep) 'hif-define-macro)) ; A defined macro
710 ;; Recursively expand it
711 (if (cadr rep) ; Argument list is not nil
712 (if (not (eq (car remains) 'hif-lparen))
713 ;; No argument, no invocation
715 ;; Argumented macro, get arguments and invoke it.
716 ;; Dynamically bind hif-token-list and hif-token
717 ;; for hif-macro-supply-arguments
718 (let* ((hif-token-list (cdr remains))
720 (parmlist (mapcar #'hif-expand-token-list
721 (hif-get-argument-list)))
723 (hif-expand-token-list
724 (hif-macro-supply-arguments tok parmlist)
726 (setq remains (cons hif-token hif-token-list))
728 ;; Argument list is nil, direct expansion
729 (setq rep (hif-expand-token-list
730 (cl-caddr rep) ; Macro's token list
732 ;; Replace all remaining references immediately
733 (setq remains (cl-substitute tok rep remains))
735 ;; Lookup tok returns an atom
738 ;;[2013-10-22 16:06:12 +0800] Must keep the token, removing
739 ;; this token might results in an incomplete expression that
740 ;; cannot be parsed further.
741 ;;((= 1 (hif-defined tok)) ; defined (hif-defined tok)=1,
742 ;; ;;but empty (hif-lookup tok)=nil, thus remove this token
743 ;; (setq remains (delete tok remains))
751 (hif-flatten (nreverse expanded)))))
753 (defun hif-parse-exp (token-list &optional macroname)
754 "Parse the TOKEN-LIST.
755 Return translated list in prefix form. MACRONAME is applied when invoking
756 macros to prevent self-reference."
757 (let ((hif-token-list (hif-expand-token-list token-list macroname)))
762 (if hif-token ; is there still a token?
763 (error "Error: unexpected token: %s" hif-token)))))
765 (defun hif-exprlist ()
766 "Parse an exprlist: expr { ',' expr}."
767 (let ((result (hif-expr)))
768 (if (eq hif-token 'hif-comma)
769 (let ((temp (list result)))
773 (push (hif-expr) temp)
774 (eq hif-token 'hif-comma)))
775 (cons 'hif-comma (nreverse temp)))
779 "Parse an expression as found in #if.
780 expr : or-expr | or-expr '?' expr ':' expr."
781 (let ((result (hif-or-expr))
783 (while (eq hif-token 'hif-conditional)
785 (setq middle (hif-expr))
786 (if (eq hif-token 'hif-colon)
789 (setq result (list 'hif-conditional result middle (hif-expr))))
790 (error "Error: unexpected token: %s" hif-token)))
793 (defun hif-or-expr ()
794 "Parse an or-expr : and-expr | or-expr '||' and-expr."
795 (let ((result (hif-and-expr)))
796 (while (eq hif-token 'hif-or)
798 (setq result (list 'hif-or result (hif-and-expr))))
801 (defun hif-and-expr ()
802 "Parse an and-expr : logior-expr | and-expr '&&' logior-expr."
803 (let ((result (hif-logior-expr)))
804 (while (eq hif-token 'hif-and)
806 (setq result (list 'hif-and result (hif-logior-expr))))
809 (defun hif-logior-expr ()
810 "Parse a logor-expr : logxor-expr | logor-expr '|' logxor-expr."
811 (let ((result (hif-logxor-expr)))
812 (while (eq hif-token 'hif-logior)
814 (setq result (list 'hif-logior result (hif-logxor-expr))))
817 (defun hif-logxor-expr ()
818 "Parse a logxor-expr : logand-expr | logxor-expr '^' logand-expr."
819 (let ((result (hif-logand-expr)))
820 (while (eq hif-token 'hif-logxor)
822 (setq result (list 'hif-logxor result (hif-logand-expr))))
825 (defun hif-logand-expr ()
826 "Parse a logand-expr : eq-expr | logand-expr '&' eq-expr."
827 (let ((result (hif-eq-expr)))
828 (while (eq hif-token 'hif-logand)
830 (setq result (list 'hif-logand result (hif-eq-expr))))
833 (defun hif-eq-expr ()
834 "Parse an eq-expr : comp | eq-expr `=='|`!=' comp."
835 (let ((result (hif-comp-expr))
837 (while (memq hif-token '(hif-equal hif-notequal))
838 (setq eq-token hif-token)
840 (setq result (list eq-token result (hif-comp-expr))))
843 (defun hif-comp-expr ()
844 "Parse a comp-expr : logshift | comp-expr `<'|`>'|`>='|`<=' logshift."
845 (let ((result (hif-logshift-expr))
847 (while (memq hif-token '(hif-greater hif-less hif-greater-equal
849 (setq comp-token hif-token)
851 (setq result (list comp-token result (hif-logshift-expr))))
854 (defun hif-logshift-expr ()
855 "Parse a logshift : math | logshift `<<'|`>>' math."
856 (let ((result (hif-math))
858 (while (memq hif-token '(hif-shiftleft hif-shiftright))
859 (setq shift-token hif-token)
861 (setq result (list shift-token result (hif-math))))
865 "Parse an expression with + or -.
866 math : muldiv | math '+|-' muldiv."
867 (let ((result (hif-muldiv-expr))
869 (while (memq hif-token '(hif-plus hif-minus))
870 (setq math-op hif-token)
872 (setq result (list math-op result (hif-muldiv-expr))))
875 (defun hif-muldiv-expr ()
876 "Parse an expression with *,/,%.
877 muldiv : factor | muldiv '*|/|%' factor."
878 (let ((result (hif-factor))
880 (while (memq hif-token '(hif-multiply hif-divide hif-modulo))
881 (setq math-op hif-token)
883 (setq result (list math-op result (hif-factor))))
888 factor : '!' factor | '~' factor | '(' expr ')' | 'defined(' id ')' |
889 'id(parmlist)' | strings | id."
891 ((eq hif-token 'hif-not)
893 (list 'hif-not (hif-factor)))
895 ((eq hif-token 'hif-lognot)
897 (list 'hif-lognot (hif-factor)))
899 ((eq hif-token 'hif-lparen)
901 (let ((result (hif-exprlist)))
902 (if (not (eq hif-token 'hif-rparen))
903 (error "Bad token in parenthesized expression: %s" hif-token)
907 ((eq hif-token 'hif-defined)
909 (let ((paren (when (eq hif-token 'hif-lparen) (hif-nexttoken) t))
911 (if (memq hif-token '(or and not hif-defined hif-lparen hif-rparen))
912 (error "Error: unexpected token: %s" hif-token))
915 (unless (eq hif-token 'hif-rparen)
916 (error "Error: expected \")\" after identifier")))
918 `(hif-defined (quote ,ident))))
921 (prog1 hif-token (hif-nexttoken)))
923 (hif-string-concatenation))
926 ((memq hif-token '(hif-minus hif-plus))
927 (list (prog1 hif-token (hif-nexttoken)) 0 (hif-factor)))
930 (let ((ident hif-token))
932 (if (eq hif-token 'hif-lparen)
933 (hif-place-macro-invocation ident)
934 `(hif-lookup (quote ,ident)))))))
936 (defun hif-get-argument-list ()
938 (parmlist nil) ; A "token" list of parameters, will later be parsed
941 (while (or (not (eq (hif-nexttoken) 'hif-rparen))
943 (if (eq (car (last parm)) 'hif-comma)
946 ((eq hif-token 'hif-lparen)
947 (setq nest (1+ nest)))
948 ((eq hif-token 'hif-rparen)
949 (setq nest (1- nest)))
950 ((and (eq hif-token 'hif-comma)
952 (push (nreverse parm) parmlist)
954 (push hif-token parm))
956 (push (nreverse parm) parmlist) ; Okay even if PARM is nil
957 (hif-nexttoken) ; Drop the `hif-rparen', get next token
958 (nreverse parmlist)))
960 (defun hif-place-macro-invocation (ident)
961 (let ((parmlist (hif-get-argument-list)))
962 `(hif-invoke (quote ,ident) (quote ,parmlist))))
964 (defun hif-string-concatenation ()
965 "Parse concatenated strings: string | strings string."
966 (let ((result (substring-no-properties hif-token)))
967 (while (stringp (hif-nexttoken))
969 (substring result 0 -1) ; remove trailing '"'
970 (substring hif-token 1)))) ; remove leading '"'
973 (defun hif-define-macro (_parmlist _token-body)
974 "A marker for defined macro with arguments.
975 This macro cannot be evaluated alone without parameters inputed."
976 ;;TODO: input arguments at run time, use minibuffer to query all arguments
978 "Argumented macro cannot be evaluated without passing any parameter"))
980 (defun hif-stringify (a)
981 "Stringify a number, string or symbol."
984 (number-to-string a))
988 (concat "\"" a "\""))
990 (error "Invalid token to stringify"))))
992 (defun intern-safe (str)
996 (defun hif-token-concat (a b)
997 "Concatenate two tokens into a longer token.
998 Currently support only simple token concatenation. Also support weird (but
999 valid) token concatenation like '>' ## '>' becomes '>>'. Here we take care only
1000 those that can be evaluated during preprocessing time and ignore all those that
1001 can only be evaluated at C(++) runtime (like '++', '--' and '+='...)."
1002 (if (or (memq a hif-valid-token-list)
1003 (memq b hif-valid-token-list))
1004 (let* ((ra (car (rassq a hif-token-alist)))
1005 (rb (car (rassq b hif-token-alist)))
1007 (cdr (assoc (concat ra rb) hif-token-alist)))))
1009 ;;(error "Invalid token to concatenate")
1010 (error "Concatenating \"%s\" and \"%s\" does not give a valid \
1011 preprocessing token"
1012 (or ra (symbol-name a))
1013 (or rb (symbol-name b)))))
1014 (intern-safe (concat (hif-stringify a)
1015 (hif-stringify b)))))
1017 (defun hif-mathify (val)
1018 "Treat VAL as a number: if it's t or nil, use 1 or 0."
1019 (cond ((eq val t) 1)
1023 (defun hif-conditional (a b c)
1024 (if (not (zerop (hif-mathify a))) (hif-mathify b) (hif-mathify c)))
1025 (defun hif-and (a b)
1026 (and (not (zerop (hif-mathify a))) (not (zerop (hif-mathify b)))))
1028 (or (not (zerop (hif-mathify a))) (not (zerop (hif-mathify b)))))
1030 (zerop (hif-mathify a)))
1031 (defun hif-lognot (a)
1032 (lognot (hif-mathify a)))
1034 (defmacro hif-mathify-binop (fun)
1036 ,(format "Like `%s' but treat t and nil as 1 and 0." fun)
1037 (,fun (hif-mathify a) (hif-mathify b))))
1039 (defun hif-shiftleft (a b)
1040 (setq a (hif-mathify a))
1041 (setq b (hif-mathify b))
1046 (defun hif-shiftright (a b)
1047 (setq a (hif-mathify a))
1048 (setq b (hif-mathify b))
1054 (defalias 'hif-multiply (hif-mathify-binop *))
1055 (defalias 'hif-divide (hif-mathify-binop /))
1056 (defalias 'hif-modulo (hif-mathify-binop %))
1057 (defalias 'hif-plus (hif-mathify-binop +))
1058 (defalias 'hif-minus (hif-mathify-binop -))
1059 (defalias 'hif-equal (hif-mathify-binop =))
1060 (defalias 'hif-notequal (hif-mathify-binop /=))
1061 (defalias 'hif-greater (hif-mathify-binop >))
1062 (defalias 'hif-less (hif-mathify-binop <))
1063 (defalias 'hif-greater-equal (hif-mathify-binop >=))
1064 (defalias 'hif-less-equal (hif-mathify-binop <=))
1065 (defalias 'hif-logior (hif-mathify-binop logior))
1066 (defalias 'hif-logxor (hif-mathify-binop logxor))
1067 (defalias 'hif-logand (hif-mathify-binop logand))
1070 (defun hif-comma (&rest expr)
1071 "Evaluate a list of EXPR, return the result of the last item."
1075 (setq result (funcall hide-ifdef-evaluator e))))
1078 (defun hif-token-stringification (l)
1079 "Scan token list for `hif-stringify' ('#') token and stringify the next token."
1082 (push (if (eq (car l) 'hif-stringify)
1085 (hif-stringify (cadr l))
1086 (error "No token to stringify"))
1093 (defun hif-token-concatenation (l)
1094 "Scan token list for `hif-token-concat' ('##') token and concatenate two tokens."
1098 (while (eq (car l) 'hif-token-concat)
1100 (error "No token before ## to concatenate"))
1102 (error "No token after ## to concatenate"))
1103 (setq prev (hif-token-concat prev (cadr l)))
1106 (setq result (append result (list prev))))
1110 (append result (list prev))
1113 (defun hif-delimit (lis atom)
1114 (nconc (cl-mapcan (lambda (l) (list l atom))
1118 ;; Perform token replacement:
1119 (defun hif-macro-supply-arguments (macro-name actual-parms)
1120 "Expand a macro call, replace ACTUAL-PARMS in the macro body."
1121 (let* ((SA (assoc macro-name hide-ifdef-env))
1124 (eq (cadr SA) 'hif-define-macro)
1126 (formal-parms (and macro (car macro)))
1127 (macro-body (and macro (cadr macro)))
1133 (when (and actual-parms formal-parms macro-body)
1134 ;; For each actual parameter, evaluate each one and associate it
1135 ;; with an actual parameter, put it into local table and finally
1136 ;; evaluate the macro body.
1137 (if (setq etc (eq (car formal-parms) 'hif-etc))
1138 ;; Take care of `hif-etc' first. Prefix `hif-comma' back if needed.
1139 (setq formal-parms (cdr formal-parms)))
1140 (setq formal-count (length formal-parms)
1141 actual-count (length actual-parms))
1143 (if (> formal-count actual-count)
1144 (error "Too few parmameter for macro %S" macro-name)
1145 (if (< formal-count actual-count)
1147 (error "Too many parameters for macro %S" macro-name))))
1149 ;; Perform token replacement on the MACRO-BODY with the parameters
1150 (while (setq formal (pop formal-parms))
1151 ;; Prevent repetitive substitutation, thus cannot use `subst'
1153 ;; #define mac(a,b) (a+b)
1154 ;; #define testmac mac(b,y)
1155 ;; testmac should expand to (b+y): replace of argument a and b
1156 ;; occurs simultaneously, not sequentially. If sequentially,
1157 ;; according to the argument order, it will become:
1158 ;; 1. formal parm #1 'a' replaced by actual parm 'b', thus (a+b)
1160 ;; 2. formal parm #2 'b' replaced by actual parm 'y', thus (b+b)
1163 ;; Unlike `subst', `substitute' replace only the top level
1164 ;; instead of the whole tree; more importantly, it's not
1166 (cl-substitute (if (and etc (null formal-parms))
1167 (hif-delimit actual-parms 'hif-comma)
1170 (setq actual-parms (cdr actual-parms)))
1172 ;; Replacement completed, flatten the whole token list
1173 (setq macro-body (hif-flatten macro-body))
1175 ;; Stringification and token concatenation happens here
1176 (hif-token-concatenation (hif-token-stringification macro-body)))))
1178 (defun hif-invoke (macro-name actual-parms)
1179 "Invoke a macro by expanding it, reparse macro-body and finally invoke it."
1180 ;; Reparse the macro body and evaluate it
1181 (funcall hide-ifdef-evaluator
1183 (hif-macro-supply-arguments macro-name actual-parms)
1186 ;;;----------- end of parser -----------------------
1189 (defun hif-canonicalize-tokens (regexp) ; For debugging
1190 "Return the expanded result of the scanned tokens."
1192 (re-search-forward regexp)
1193 (let* ((curr-regexp (match-string 0))
1194 (defined (string-match hif-ifxdef-regexp curr-regexp))
1195 (negate (and defined
1196 (string= (match-string 2 curr-regexp) "n")))
1197 (hif-simple-token-only nil) ;; Dynamic binding var for `hif-tokenize'
1198 (tokens (hif-tokenize (point)
1199 (progn (hif-end-of-line) (point)))))
1201 (setq tokens (list 'hif-defined tokens)))
1203 (setq tokens (list 'hif-not tokens)))
1206 (defun hif-canonicalize (regexp)
1207 "Return a Lisp expression for its condition by scanning current buffer.
1208 Do this when cursor is at the beginning of `regexp' (i.e. #ifX)."
1209 (let ((case-fold-search nil))
1211 (re-search-forward regexp)
1212 (let* ((curr-regexp (match-string 0))
1213 (defined (string-match hif-ifxdef-regexp curr-regexp))
1214 (negate (and defined
1215 (string= (match-string 2 curr-regexp) "n")))
1216 (hif-simple-token-only nil) ; Dynamic binding for `hif-tokenize'
1217 (tokens (hif-tokenize (point)
1218 (progn (hif-end-of-line) (point)))))
1220 (setq tokens (list 'hif-defined tokens)))
1222 (setq tokens (list 'hif-not tokens)))
1223 (hif-parse-exp tokens)))))
1225 (defun hif-find-any-ifX ()
1226 "Move to next #if..., or #ifndef, at point or after."
1227 ;; (message "find ifX at %d" (point))
1229 (re-search-forward hif-ifx-regexp (point-max) t)
1230 (beginning-of-line)))
1233 (defun hif-find-next-relevant ()
1234 "Move to next #if..., #elif..., #else, or #endif, after the current line."
1235 ;; (message "hif-find-next-relevant at %d" (point))
1237 ;; Avoid infinite recursion by only going to line-beginning if match found
1238 (if (re-search-forward hif-ifx-else-endif-regexp (point-max) t)
1239 (beginning-of-line)))
1241 (defun hif-find-previous-relevant ()
1242 "Move to previous #if..., #else, or #endif, before the current line."
1243 ;; (message "hif-find-previous-relevant at %d" (point))
1245 ;; Avoid infinite recursion by only going to line-beginning if match found
1246 (if (re-search-backward hif-ifx-else-endif-regexp (point-min) t)
1247 (beginning-of-line)))
1250 (defun hif-looking-at-ifX ()
1251 (looking-at hif-ifx-regexp)) ; Should eventually see #if
1252 (defun hif-looking-at-endif ()
1253 (looking-at hif-endif-regexp))
1254 (defun hif-looking-at-else ()
1255 (looking-at hif-else-regexp))
1257 (defun hif-looking-at-elif ()
1258 (looking-at hif-elif-regexp))
1261 (defun hif-ifdef-to-endif ()
1262 "If positioned at #ifX, #elif, or #else form, skip to corresponding #endif."
1263 ;; (message "hif-ifdef-to-endif at %d" (point)) (sit-for 1)
1264 (hif-find-next-relevant)
1265 (cond ((hif-looking-at-ifX)
1266 (hif-ifdef-to-endif) ; Find endif of nested if
1267 (hif-ifdef-to-endif)) ; Find outer endif or else
1268 ((hif-looking-at-elif)
1269 (hif-ifdef-to-endif))
1270 ((hif-looking-at-else)
1271 (hif-ifdef-to-endif)) ; Find endif following else
1272 ((hif-looking-at-endif)
1275 (error "Mismatched #ifdef #endif pair"))))
1278 (defun hif-endif-to-ifdef ()
1279 "If positioned at #endif form, skip backward to corresponding #ifX."
1280 ;; (message "hif-endif-to-ifdef at %d" (point))
1281 (let ((start (point)))
1282 (hif-find-previous-relevant)
1283 (if (= start (point))
1284 (error "Mismatched #ifdef #endif pair")))
1285 (cond ((hif-looking-at-endif)
1286 (hif-endif-to-ifdef) ; Find beginning of nested if
1287 (hif-endif-to-ifdef)) ; Find beginning of outer if or else
1288 ((hif-looking-at-elif)
1289 (hif-endif-to-ifdef))
1290 ((hif-looking-at-else)
1291 (hif-endif-to-ifdef))
1292 ((hif-looking-at-ifX)
1295 (error "Mismatched #endif")))) ; never gets here
1298 (defun forward-ifdef (&optional arg)
1299 "Move point to beginning of line of the next ifdef-endif.
1300 With argument, do this that many times."
1302 (or arg (setq arg 1))
1303 (if (< arg 0) (backward-ifdef (- arg))
1306 (let ((start (point)))
1307 (unless (hif-looking-at-ifX)
1308 (hif-find-next-relevant))
1309 (if (hif-looking-at-ifX)
1310 (hif-ifdef-to-endif)
1312 (error "No following #ifdef"))))))
1315 (defun backward-ifdef (&optional arg)
1316 "Move point to beginning of the previous ifdef-endif.
1317 With argument, do this that many times."
1319 (or arg (setq arg 1))
1320 (if (< arg 0) (forward-ifdef (- arg))
1324 (let ((start (point)))
1325 (unless (hif-looking-at-endif)
1326 (hif-find-previous-relevant))
1327 (if (hif-looking-at-endif)
1328 (hif-endif-to-ifdef)
1330 (error "No previous #ifdef"))))))
1333 (defun down-ifdef ()
1334 "Move point to beginning of nested ifdef or else-part."
1336 (let ((start (point)))
1337 (hif-find-next-relevant)
1338 (if (or (hif-looking-at-ifX) (hif-looking-at-else))
1341 (error "No following #ifdef"))))
1345 "Move point to beginning of enclosing ifdef or else-part."
1348 (let ((start (point)))
1349 (unless (hif-looking-at-endif)
1350 (hif-find-previous-relevant))
1351 (if (hif-looking-at-endif)
1352 (hif-endif-to-ifdef))
1353 (if (= start (point))
1354 (error "No previous #ifdef"))))
1356 (defun next-ifdef (&optional arg)
1357 "Move to the beginning of the next #ifX, #else, or #endif.
1358 With argument, do this that many times."
1360 (or arg (setq arg 1))
1361 (if (< arg 0) (previous-ifdef (- arg))
1364 (hif-find-next-relevant)
1367 (error "No following #ifdefs, #elses, or #endifs")))))
1369 (defun previous-ifdef (&optional arg)
1370 "Move to the beginning of the previous #ifX, #else, or #endif.
1371 With argument, do this that many times."
1373 (or arg (setq arg 1))
1374 (if (< arg 0) (next-ifdef (- arg))
1377 (let ((start (point)))
1378 (hif-find-previous-relevant)
1379 (if (= start (point))
1380 (error "No previous #ifdefs, #elses, or #endifs"))))))
1383 ;;===%%SF%% parsing (End) ===
1386 ;;===%%SF%% hide-ifdef-hiding (Start) ===
1389 ;; A range is a structure with four components:
1390 ;; START The start of the range. (beginning of line)
1391 ;; ELSE The else marker (beginning of line)
1392 ;; END The end of the range. (beginning of line)
1393 ;; ELIF A sequence of #elif markers (beginning of line)
1395 (defsubst hif-make-range (start end &optional else elif)
1396 (list start else end elif))
1398 (defsubst hif-range-start (range) (elt range 0))
1399 (defsubst hif-range-else (range) (elt range 1))
1400 (defsubst hif-range-end (range) (elt range 2))
1401 (defsubst hif-range-elif (range) (elt range 3))
1405 ;; The workhorse, it delimits the #if region. Reasonably simple:
1406 ;; Skip until an #else or #endif is found, remembering positions. If
1407 ;; an #else was found, skip some more, looking for the true #endif.
1409 (defun hif-find-range ()
1410 "Return a Range structure describing the current #if region.
1411 Point is left unchanged."
1412 ;; (message "hif-find-range at %d" (point))
1415 (let ((start (point))
1419 ;; Part one. Look for either #elif, #else or #endif.
1420 ;; This loop-and-a-half dedicated to E. Dijkstra.
1421 (while (and (not else) (not end))
1423 (hif-find-next-relevant)
1424 (hif-looking-at-ifX)) ; Skip nested ifdef
1425 (hif-ifdef-to-endif))
1426 ;; Found either a #else, #elif, or an #endif.
1427 (cond ((hif-looking-at-elif)
1428 (setq elif (nconc elif (list (point)))))
1429 ((hif-looking-at-else)
1430 (setq else (point)))
1432 (setq end (point)))))
1433 ;; If found #else, look for #endif.
1436 (hif-find-next-relevant)
1437 (hif-looking-at-ifX)) ; Skip nested ifdef
1438 (hif-ifdef-to-endif))
1439 (if (hif-looking-at-else)
1440 (error "Found two elses in a row? Broken!"))
1441 (setq end (point))) ; (line-end-position)
1442 (hif-make-range start end else elif))))
1447 (defun hif-hide-line (point)
1448 "Hide the line containing point.
1449 Does nothing if `hide-ifdef-lines' is nil."
1450 (when hide-ifdef-lines
1453 (hide-ifdef-region-internal
1454 (line-beginning-position) (progn (hif-end-of-line) (point))))))
1457 ;; Hif-Possibly-Hide
1458 ;; There are four cases. The #ifX expression is "taken" if it
1459 ;; the hide-ifdef-evaluator returns T. Presumably, this means the code
1460 ;; inside the #ifdef would be included when the program was
1463 ;; Case 1: #ifX taken, and there's an #else.
1464 ;; The #else part must be hidden. The #if (then) part must be
1465 ;; processed for nested #ifX's.
1466 ;; Case 2: #ifX taken, and there's no #else.
1467 ;; The #if part must be processed for nested #ifX's.
1468 ;; Case 3: #ifX not taken, and there's an #elif
1469 ;; The #if part must be hidden, and then evaluate
1470 ;; the #elif condition like a new #ifX.
1471 ;; Case 4: #ifX not taken, and there's just an #else.
1472 ;; The #if part must be hidden. The #else part must be processed
1474 ;; Case 5: #ifX not taken, and there's no #else.
1475 ;; The #ifX part must be hidden.
1477 ;; Further processing is done by narrowing to the relevant region
1478 ;; and just recursively calling hide-ifdef-guts.
1480 ;; When hif-possibly-hide returns, point is at the end of the
1481 ;; possibly-hidden range.
1483 (defvar hif-recurse-level 0)
1485 (defun hif-recurse-on (start end &optional dont-go-eol)
1486 "Call `hide-ifdef-guts' after narrowing to end of START line and END line."
1492 (narrow-to-region (point) end)
1493 (let ((hif-recurse-level (1+ hif-recurse-level)))
1494 (hide-ifdef-guts)))))
1496 (defun hif-possibly-hide (expand-reinclusion)
1497 "Called at #ifX expression, this hides those parts that should be hidden.
1498 It uses the judgment of `hide-ifdef-evaluator'. EXPAND-REINCLUSION is a flag
1499 indicating that we should expand the #ifdef even if it should be hidden.
1500 Refer to `hide-ifdef-expand-reinclusion-protection' for more details."
1501 ;; (message "hif-possibly-hide") (sit-for 1)
1502 (let* ((case-fold-search nil)
1503 (test (hif-canonicalize hif-ifx-regexp))
1504 (range (hif-find-range))
1505 (elifs (hif-range-elif range))
1506 (if-part t) ; Everytime we start from if-part
1508 ;; (message "test = %s" test) (sit-for 1)
1510 (hif-hide-line (hif-range-end range))
1511 (while (not complete)
1512 (if (and (not (and expand-reinclusion if-part))
1513 (hif-not (funcall hide-ifdef-evaluator test)))
1514 ;; ifX/elif is FALSE
1516 ;; Case 3 - Hide the #ifX and eval #elif
1517 (let ((newstart (car elifs)))
1518 (hif-hide-line (hif-range-start range))
1519 (hide-ifdef-region (hif-range-start range)
1521 (setcar range newstart)
1522 (goto-char newstart)
1523 (setq elifs (cdr elifs))
1524 (setq test (hif-canonicalize hif-elif-regexp)))
1527 (cond ((hif-range-else range)
1528 ;; Case 4 - #else block visible
1529 (hif-hide-line (hif-range-else range))
1530 (hide-ifdef-region (hif-range-start range)
1531 (1- (hif-range-else range)))
1532 (hif-recurse-on (hif-range-else range)
1533 (hif-range-end range)))
1535 ;; Case 5 - No #else block, hide #ifX
1536 (hide-ifdef-region (point)
1537 (1- (hif-range-end range)))))
1542 ;; Luke fix: distinguish from #elif..#elif to #elif..#else
1543 (let ((elif (car elifs)))
1545 (hif-hide-line elif)
1546 (hide-ifdef-region elif (1- (hif-range-end range)))
1547 (hif-recurse-on (hif-range-start range)
1549 ((hif-range-else range)
1550 ;; Case 1 - Hide #elif and #else blocks, recurse #ifX
1551 (hif-hide-line (hif-range-else range))
1552 (hide-ifdef-region (hif-range-else range)
1553 (1- (hif-range-end range)))
1554 (hif-recurse-on (hif-range-start range)
1555 (hif-range-else range)))
1557 ;; Case 2 - No #else, just recurse #ifX
1558 (hif-recurse-on (hif-range-start range)
1559 (hif-range-end range))))
1564 (hif-hide-line (hif-range-start range)) ; Always hide start.
1565 (goto-char (hif-range-end range))
1568 (defun hif-evaluate-region (start end)
1569 (let* ((tokens (ignore-errors ; Prevent C statement things like
1570 ; 'do { ... } while (0)'
1571 (hif-tokenize start end)))
1574 (hif-parse-exp tokens)
1577 (result (funcall hide-ifdef-evaluator expr)))
1580 (defun hif-evaluate-macro (rstart rend)
1581 "Evaluate the macro expansion result for a region.
1582 If no region active, find the current #ifdefs and evaluate the result.
1583 Currently it supports only math calculations, strings or argumented macros can
1586 (let ((case-fold-search nil))
1589 (setq rstart nil rend nil)
1591 (when (and (re-search-forward hif-macro-expr-prefix-regexp nil t)
1592 (string= "define" (match-string 2)))
1593 (re-search-forward hif-macroref-regexp nil t)))
1594 (let* ((start (or rstart (point)))
1595 (end (or rend (progn (hif-end-of-line) (point))))
1598 (tokens (ignore-errors ; Prevent C statement things like
1599 ; 'do { ... } while (0)'
1600 (hif-tokenize start end)))
1601 (expr (or (and (<= (length tokens) 1) ; Simple token
1602 (setq defined (assoc (car tokens) hide-ifdef-env))
1603 (setq simple (atom (hif-lookup (car tokens))))
1604 (hif-lookup (car tokens)))
1607 (hif-parse-exp tokens)
1610 (result (funcall hide-ifdef-evaluator expr))
1611 (exprstring (replace-regexp-in-string
1612 ;; Trim off leading/trailing whites
1613 "^[ \t]*\\([^ \t]+\\)[ \t]*" "\\1"
1614 (replace-regexp-in-string
1615 "\\(//.*\\)" "" ; Trim off end-of-line comments
1616 (buffer-substring-no-properties start end)))))
1618 ((and (<= (length tokens) 1) simple) ; Simple token
1620 (message "%S <= `%s'" result exprstring)
1621 (message "`%s' is not defined" exprstring)))
1623 (if (or (= 0 result) (= 1 result))
1624 (message "%S <= `%s'" result exprstring)
1625 (message "%S (0x%x) <= `%s'" result result exprstring)))
1626 ((null result) (message "%S <= `%s'" 'false exprstring))
1627 ((eq t result) (message "%S <= `%s'" 'true exprstring))
1628 (t (message "%S <= `%s'" result exprstring)))
1631 (defun hif-parse-macro-arglist (str)
1632 "Parse argument list formatted as '( arg1 [ , argn] [...] )'.
1633 The '...' is also included. Return a list of the arguments, if '...' exists the
1634 first arg will be `hif-etc'."
1635 (let* ((hif-simple-token-only nil) ; Dynamic binding var for `hif-tokenize'
1638 (- (point) (length str)) (point)))) ; Remove `hif-lparen'
1640 (while (not (eq (setq token (pop tokenlist)) 'hif-rparen))
1642 ((eq token 'hif-etc)
1644 ((eq token 'hif-comma)
1647 (push token result))))
1649 (cons 'hif-etc (nreverse result))
1650 (nreverse result))))
1652 ;; The original version of hideif evaluates the macro early and store the
1653 ;; final values for the defined macro into the symbol database (aka
1654 ;; `hide-ifdef-env'). The evaluation process is "strings -> tokens -> parsed
1655 ;; tree -> [value]". (The square bracket refers to what's stored in in our
1656 ;; `hide-ifdef-env'.)
1658 ;; This forbids the evaluation of an argumented macro since the parameters
1659 ;; are applied at run time. In order to support argumented macro I then
1660 ;; postponed the evaluation process one stage and store the "parsed tree"
1661 ;; into symbol database. The evaluation process was then "strings -> tokens
1662 ;; -> [parsed tree] -> value". Hideif therefore run slower since it need to
1663 ;; evaluate the parsed tree everytime when trying to expand the symbol. These
1664 ;; temporarily code changes are obsolete and not in Emacs source repository.
1666 ;; Furthermore, CPP did allow partial expression to be defined in several
1667 ;; macros and later got concatenated into a complete expression and then
1668 ;; evaluate it. In order to match this behavior I had to postpone one stage
1669 ;; further, otherwise those partial expression will be fail on parsing and
1670 ;; we'll miss all macros that reference it. The evaluation process thus
1671 ;; became "strings -> [tokens] -> parsed tree -> value." This degraded the
1672 ;; performance since we need to parse tokens and evaluate them everytime
1673 ;; when that symbol is referenced.
1675 ;; In real cases I found a lot portion of macros are "simple macros" that
1676 ;; expand to literals like integers or other symbols. In order to enhance
1677 ;; the performance I use this `hif-simple-token-only' to notify my code and
1678 ;; save the final [value] into symbol database. [lukelee]
1680 (defun hif-find-define (&optional min max)
1681 "Parse texts and retrieve all defines within the region MIN and MAX."
1683 (and min (goto-char min))
1684 (and (re-search-forward hif-define-regexp max t)
1686 (let* ((defining (string= "define" (match-string 2)))
1687 (name (and (re-search-forward hif-macroref-regexp max t)
1689 (parmlist (and (match-string 3) ; First arg id found
1690 (hif-parse-macro-arglist (match-string 2)))))
1692 ;; Ignore name (still need to return 't), or define the name
1693 (or (and hide-ifdef-exclude-define-regexp
1694 (string-match hide-ifdef-exclude-define-regexp
1697 (let* ((start (point))
1698 (end (progn (hif-end-of-line) (point)))
1699 (hif-simple-token-only nil) ; Dynamic binding
1702 ;; `hif-simple-token-only' is set/clear
1703 ;; only in this block
1705 ;; Prevent C statements like
1706 ;; 'do { ... } while (0)'
1707 (hif-tokenize start end)
1709 ;; We can't just return nil here since
1710 ;; this will stop hideif from searching
1711 ;; for more #defines.
1712 (setq hif-simple-token-only t)
1713 (buffer-substring-no-properties
1715 ;; For simple tokens we save only the parsed result;
1716 ;; otherwise we save the tokens and parse it after
1717 ;; parameter replacement
1719 ;; `hif-simple-token-only' is checked only
1721 (or (and hif-simple-token-only
1723 (= (length tokens) 1)
1724 (hif-parse-exp tokens))
1725 `(hif-define-macro ,parmlist
1728 (assoc (intern name) hide-ifdef-env))))
1731 (or (setcdr SA expr) t)
1732 ;; Lazy evaluation, eval only if hif-lookup find it.
1733 ;; Define it anyway, even if nil it's still in list
1734 ;; and therefore considerred defined
1735 (push (cons (intern name) expr) hide-ifdef-env)))))
1738 (hif-undefine-symbol (intern name))))))
1742 (defun hif-add-new-defines (&optional min max)
1743 "Scan and add all #define macros between MIN and MAX."
1747 ;; (mark-region min max) ;; for debugging
1748 (while (hif-find-define min max)
1750 (if max (goto-char max)
1751 (goto-char (point-max))))))
1753 (defun hide-ifdef-guts ()
1754 "Does most of the work of `hide-ifdefs'.
1755 It does not do the work that's pointless to redo on a recursive entry."
1756 ;; (message "hide-ifdef-guts")
1758 (let* ((case-fold-search t) ; Ignore case for `hide-ifdef-header-regexp'
1759 (expand-header (and hide-ifdef-expand-reinclusion-protection
1760 (string-match hide-ifdef-header-regexp
1762 (zerop hif-recurse-level)))
1763 (case-fold-search nil)
1765 (goto-char (point-min))
1768 (setf max (hif-find-any-ifX))
1769 (hif-add-new-defines min max)
1771 (hif-possibly-hide expand-header))
1775 ;;===%%SF%% hide-ifdef-hiding (End) ===
1778 ;;===%%SF%% exports (Start) ===
1780 (defun hide-ifdef-toggle-read-only ()
1781 "Toggle `hide-ifdef-read-only'."
1783 (setq hide-ifdef-read-only (not hide-ifdef-read-only))
1784 (message "Hide-Read-Only %s"
1785 (if hide-ifdef-read-only "ON" "OFF"))
1786 (if hide-ifdef-hiding
1787 (setq buffer-read-only (or hide-ifdef-read-only
1788 hif-outside-read-only)))
1789 (force-mode-line-update))
1791 (defun hide-ifdef-toggle-outside-read-only ()
1792 "Replacement for `toggle-read-only' within Hide-Ifdef mode."
1794 (setq hif-outside-read-only (not hif-outside-read-only))
1795 (message "Read only %s"
1796 (if hif-outside-read-only "ON" "OFF"))
1797 (setq buffer-read-only
1798 (or (and hide-ifdef-hiding hide-ifdef-read-only)
1799 hif-outside-read-only))
1800 (force-mode-line-update))
1802 (defun hide-ifdef-toggle-shadowing ()
1805 (set (make-local-variable 'hide-ifdef-shadow) (not hide-ifdef-shadow))
1806 (message "Shadowing %s" (if hide-ifdef-shadow "ON" "OFF"))
1809 (dolist (overlay (overlays-in (point-min) (point-max)))
1810 (when (overlay-get overlay 'hide-ifdef)
1811 (if hide-ifdef-shadow
1813 (overlay-put overlay 'invisible nil)
1814 (overlay-put overlay 'face 'hide-ifdef-shadow))
1815 (overlay-put overlay 'face nil)
1816 (overlay-put overlay 'invisible 'hide-ifdef))))))
1818 (defun hide-ifdef-define (var &optional val)
1819 "Define a VAR to VAL (default 1) in `hide-ifdef-env'.
1820 This allows #ifdef VAR to be hidden."
1822 (let* ((default (save-excursion
1824 (cond ((looking-at hif-ifx-else-endif-regexp)
1826 (current-word 'strict))
1829 (var (read-minibuffer "Define what? " default))
1830 (val (read-from-minibuffer (format "Set %s to? (default 1): " var)
1831 nil nil t nil "1")))
1833 (hif-set-var var (or val 1))
1834 (message "%s set to %s" var (or val 1))
1836 (if hide-ifdef-hiding (hide-ifdefs)))
1838 (defun hif-undefine-symbol (var)
1839 (setq hide-ifdef-env
1840 (delete (assoc var hide-ifdef-env) hide-ifdef-env)))
1842 (defun hide-ifdef-undef (start end)
1843 "Undefine a VAR so that #ifdef VAR would not be included."
1846 (or (and mark-active
1847 (buffer-substring-no-properties start end))
1848 (read-string "Undefine what? " (current-word))))
1851 (if (zerop (hif-defined sym))
1852 (message "`%s' not defined, no need to undefine it" symstr)
1853 (hif-undefine-symbol sym)
1854 (if hide-ifdef-hiding (hide-ifdefs))
1855 (message "`%S' undefined" sym))))
1857 (defun hide-ifdefs (&optional nomsg)
1858 "Hide the contents of some #ifdefs.
1859 Assume that defined symbols have been added to `hide-ifdef-env'.
1860 The text hidden is the text that would not be included by the C
1861 preprocessor if it were given the file with those symbols defined.
1862 With prefix command presents it will also hide the #ifdefs themselves.
1864 Turn off hiding by calling `show-ifdefs'."
1867 (let ((hide-ifdef-lines current-prefix-arg))
1869 (message "Hiding..."))
1870 (setq hif-outside-read-only buffer-read-only)
1871 (unless hide-ifdef-mode (hide-ifdef-mode 1)) ; Turn on hide-ifdef-mode
1872 (if hide-ifdef-hiding
1873 (show-ifdefs)) ; Otherwise, deep confusion.
1874 (setq hide-ifdef-hiding t)
1876 (setq buffer-read-only (or hide-ifdef-read-only hif-outside-read-only))
1878 (message "Hiding done"))))
1881 (defun show-ifdefs ()
1882 "Cancel the effects of `hide-ifdef': show the contents of all #ifdefs."
1884 (setq buffer-read-only hif-outside-read-only)
1886 (setq hide-ifdef-hiding nil))
1889 (defun hif-find-ifdef-block ()
1890 "Utility to hide and show ifdef block.
1891 Return as (TOP . BOTTOM) the extent of ifdef block."
1893 (cons (save-excursion
1895 (unless (or (hif-looking-at-else) (hif-looking-at-ifX))
1898 (hif-ifdef-to-endif)
1899 (setq max-bottom (1- (point)))))
1902 (unless (hif-looking-at-endif)
1903 (hif-find-next-relevant))
1904 (while (hif-looking-at-ifX)
1905 (hif-ifdef-to-endif)
1906 (hif-find-next-relevant))
1907 (min max-bottom (1- (point)))))))
1910 (defun hide-ifdef-block (&optional arg start end)
1911 "Hide the ifdef block (true or false part) enclosing or before the cursor.
1912 With optional prefix agument ARG, also hide the #ifdefs themselves."
1913 (interactive "P\nr")
1914 (let ((hide-ifdef-lines arg))
1916 (let ((hif-recurse-level (1+ hif-recurse-level)))
1917 (hif-recurse-on start end t)
1918 (setq mark-active nil))
1919 (unless hide-ifdef-mode (hide-ifdef-mode 1))
1920 (let ((top-bottom (hif-find-ifdef-block)))
1921 (hide-ifdef-region (car top-bottom) (cdr top-bottom))
1922 (when hide-ifdef-lines
1923 (hif-hide-line (car top-bottom))
1924 (hif-hide-line (1+ (cdr top-bottom))))
1925 (setq hide-ifdef-hiding t))
1926 (setq buffer-read-only
1927 (or hide-ifdef-read-only hif-outside-read-only)))))
1929 (defun show-ifdef-block (&optional start end)
1930 "Show the ifdef block (true or false part) enclosing or before the cursor."
1934 (dolist (o (overlays-in start end))
1935 (if (overlay-get o 'hide-ifdef)
1936 (delete-overlay o)))
1937 (setq mark-active nil))
1938 (let ((top-bottom (condition-case nil
1939 (hif-find-ifdef-block)
1942 (ovrs (overlays-in (max (point-min) (1- (point)))
1943 (min (point-max) (1+ (point)))))
1946 (if hide-ifdef-lines
1947 (hif-show-ifdef-region
1949 (goto-char (car top-bottom)) (line-beginning-position))
1951 (goto-char (1+ (cdr top-bottom)))
1952 (hif-end-of-line) (point)))
1953 (setf del (hif-show-ifdef-region
1954 (1- (car top-bottom)) (cdr top-bottom)))))
1955 (if (not (and top-bottom
1958 ;;(dolist (o (overlays-in (1- (point)) (1+ (point))))
1959 ;; (if (overlay-get o 'hide-ifdef) (message "%S" o)))
1960 (if (overlay-get o 'hide-ifdef)
1961 (delete-overlay o)))))))
1964 ;;; definition alist support
1966 (defvar hide-ifdef-define-alist nil
1967 "A global assoc list of pre-defined symbol lists.")
1969 (defun hif-compress-define-list (env)
1970 "Compress the define list ENV into a list of defined symbols only."
1971 (let ((new-defs nil))
1972 (dolist (def env new-defs)
1973 (if (hif-lookup (car def)) (push (car def) new-defs)))))
1975 (defun hide-ifdef-set-define-alist (name)
1976 "Set the association for NAME to `hide-ifdef-env'."
1977 (interactive "SSet define list: ")
1978 (push (cons name (hif-compress-define-list hide-ifdef-env))
1979 hide-ifdef-define-alist))
1981 (defun hide-ifdef-use-define-alist (name)
1982 "Set `hide-ifdef-env' to the define list specified by NAME."
1984 (list (completing-read "Use define list: "
1985 (mapcar (lambda (x) (symbol-name (car x)))
1986 hide-ifdef-define-alist)
1988 (if (stringp name) (setq name (intern name)))
1989 (let ((define-list (assoc name hide-ifdef-define-alist)))
1991 (setq hide-ifdef-env
1992 (mapcar (lambda (arg) (cons arg t))
1994 (error "No define list for %s" name))
1995 (if hide-ifdef-hiding (hide-ifdefs))))
1999 ;;; hideif.el ends here