]> code.delx.au - gnu-emacs/blob - lisp/progmodes/hideif.el
Merge from emacs-24; up to 2014-06-23T06:25:47Z!rgm@gnu.org
[gnu-emacs] / lisp / progmodes / hideif.el
1 ;;; hideif.el --- hides selected code within ifdef -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 1988, 1994, 2001-2014 Free Software Foundation, Inc.
4
5 ;; Author: Brian Marick
6 ;; Daniel LaLiberte <liberte@holonexus.org>
7 ;; Maintainer: Luke Lee <luke.yx.lee@gmail.com>
8 ;; Keywords: c, outlines
9
10 ;; This file is part of GNU Emacs.
11
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.
16
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.
21
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/>.
24
25 ;;; Commentary:
26
27 ;; To initialize, toggle the hide-ifdef minor mode with
28 ;;
29 ;; M-x hide-ifdef-mode
30 ;;
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
34 ;;
35 ;; M-x hide-ifdefs or C-c @ h
36 ;;
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
40 ;; parsing.
41 ;;
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
45 ;; text unawares.
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).
49 ;;
50 ;; You can undo the effect of hide-ifdefs by typing
51 ;;
52 ;; M-x show-ifdefs or C-c @ s
53 ;;
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.
56 ;;
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.
62 ;;
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
65 ;; following example:
66 ;;
67 ;; (add-hook 'hide-ifdef-mode-hook
68 ;; (lambda ()
69 ;; (unless hide-ifdef-define-alist
70 ;; (setq hide-ifdef-define-alist
71 ;; '((list1 ONE TWO)
72 ;; (list2 TWO THREE))))
73 ;; (hide-ifdef-use-define-alist 'list2))) ; use list2 by default
74 ;;
75 ;; You can call hide-ifdef-use-define-alist (C-c @ U) at any time to specify
76 ;; another list to use.
77 ;;
78 ;; To cause ifdefs to be hidden as soon as hide-ifdef-mode is called,
79 ;; set hide-ifdef-initially to non-nil.
80 ;;
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
86 ;; better.
87 ;;
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.
90 ;;
91 ;; You can move the point between ifdefs with forward-ifdef, backward-ifdef,
92 ;; up-ifdef, down-ifdef, next-ifdef, and previous-ifdef.
93 ;;
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).
97 ;;
98 ;; Written by Brian Marick, at Gould, Computer Systems Division, Urbana IL.
99 ;; Extensively modified by Daniel LaLiberte (while at Gould).
100 ;;
101 ;; Extensively modified by Luke Lee in 2013 to support complete C expression
102 ;; evaluation and argumented macro expansion.
103
104 ;;; Code:
105
106 (require 'cc-mode)
107 (require 'cl-lib)
108
109 (defgroup hide-ifdef nil
110 "Hide selected code within `ifdef'."
111 :group 'c)
112
113 (defcustom hide-ifdef-initially nil
114 "Non-nil means call `hide-ifdefs' when Hide-Ifdef mode is first activated."
115 :type 'boolean
116 :group 'hide-ifdef)
117
118 (defcustom hide-ifdef-read-only nil
119 "Set to non-nil if you want buffer to be read-only while hiding text."
120 :type 'boolean
121 :group 'hide-ifdef)
122
123 (defcustom hide-ifdef-lines nil
124 "Non-nil means hide the #ifX, #else, and #endif lines."
125 :type 'boolean
126 :group 'hide-ifdef)
127
128 (defcustom hide-ifdef-shadow nil
129 "Non-nil means shadow text instead of hiding it."
130 :type 'boolean
131 :group 'hide-ifdef
132 :version "23.1")
133
134 (defface hide-ifdef-shadow '((t (:inherit shadow)))
135 "Face for shadowing ifdef blocks."
136 :group 'hide-ifdef
137 :version "23.1")
138
139 (defcustom hide-ifdef-exclude-define-regexp nil
140 "Ignore #define names if those names match this exclusion pattern."
141 :type 'string
142 :version "24.5")
143
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:
147
148 ----- beginning of file -----
149 #ifndef _XXX_HEADER_FILE_INCLUDED_
150 #define _XXX_HEADER_FILE_INCLUDED_
151 xxx
152 xxx
153 xxx...
154 #endif
155 ----- end of file -----
156
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
159 be hidden.
160
161 This behavior is generally undesirable. If this option is non-nil, the outermost
162 #if is always visible."
163 :type 'boolean
164 :version "24.5")
165
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."
170 :type 'string
171 :group 'hide-ifdef
172 :version "24.5")
173
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)
181
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)
188
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)
193 map)
194 "Keymap used by `hide-ifdef-mode' under `hide-ifdef-mode-prefix-key'.")
195
196 (defconst hide-ifdef-mode-prefix-key "\C-c@"
197 "Prefix key for all Hide-Ifdef mode commands.")
198
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)
203 map)
204 "Keymap used with `hide-ifdef-mode'.")
205
206 (easy-menu-define hide-ifdef-mode-menu hide-ifdef-mode-map
207 "Menu for `hide-ifdef-mode'."
208 '("Hide-Ifdef"
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"]))
231
232 (defvar hide-ifdef-hiding nil
233 "Non-nil when text may be hidden.")
234
235 (or (assq 'hide-ifdef-hiding minor-mode-alist)
236 (setq minor-mode-alist
237 (cons '(hide-ifdef-hiding " Hiding")
238 minor-mode-alist)))
239
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)
246 st)
247 "Syntax table used for tokenizing #if expressions.")
248
249 (defvar hide-ifdef-env nil
250 "An alist of defined symbols and their values.")
251
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'.")
256
257 (defvar hif-outside-read-only nil
258 "Internal variable. Saves the value of `buffer-read-only' while hiding.")
259
260 ;;;###autoload
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.
266
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:
271
272 `hide-ifdef-env'
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.
280
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'.
286
287 `hide-ifdef-lines'
288 Set to non-nil to not show #if, #ifdef, #ifndef, #else, and
289 #endif lines when hiding.
290
291 `hide-ifdef-initially'
292 Indicates whether `hide-ifdefs' should be called when Hide-Ifdef mode
293 is activated.
294
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.
298
299 \\{hide-ifdef-mode-map}"
300 :group 'hide-ifdef :lighter " Ifdef"
301 (if hide-ifdef-mode
302 (progn
303 ;; inherit global values
304
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)
322
323 (add-to-invisibility-spec '(hide-ifdef . t))
324
325 (if hide-ifdef-initially
326 (hide-ifdefs)
327 (show-ifdefs)))
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
332 (show-ifdefs))))
333
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."
338 (interactive)
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)))
342
343 (defun hif-show-all ()
344 "Show all of the text in the current buffer."
345 (interactive)
346 (hif-show-ifdef-region (point-min) (point-max)))
347
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
353 (hide-ifdefs t)))
354 (add-hook 'after-revert-hook 'hif-after-revert-function)
355
356 (defun hif-end-of-line ()
357 (end-of-line)
358 (while (= (logand 1 (skip-chars-backward "\\\\")) 1)
359 (end-of-line 2)))
360
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
364 overlays created."
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.
372 (save-restriction
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))))
381 (ob nil)
382 (oe nil)
383 b e)
384 ;; Merge overlays before START
385 (dolist (o begovrs)
386 (when (overlay-get o 'hide-ifdef)
387 (setq b (min start (overlay-start o))
388 e (max end (overlay-end o)))
389 (move-overlay o b e)
390 (hif-merge-ifdef-region b e)
391 (setq ob o)))
392 ;; Merge overlays after END
393 (dolist (o endovrs)
394 (when (overlay-get o 'hide-ifdef)
395 (setq b (min start (overlay-start o))
396 e (max end (overlay-end o)))
397 (move-overlay o b e)
398 (hif-merge-ifdef-region b e)
399 (setf oe o)))
400 ;; If both START and END merging happens, merge into bigger one
401 (when (and ob oe)
402 (let ((b (min (overlay-start ob) (overlay-start oe)))
403 (e (max (overlay-end ob) (overlay-end oe))))
404 (delete-overlay oe)
405 (move-overlay ob b e)
406 (hif-merge-ifdef-region b e)))
407 (or ob oe))))
408
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)))))
416
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."
420 (save-excursion
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)))
424
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)))))
430
431
432 ;;===%%SF%% evaluation (Start) ===
433
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.")
440
441 (defvar hif-undefined-symbol nil
442 "...is by default considered to be false.")
443
444
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)))
448
449 (declare-function semantic-c-hideif-lookup "semantic/bovine/c" (var))
450 (declare-function semantic-c-hideif-defined "semantic/bovine/c" (var))
451
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)))
456 (if val
457 (cdr val)
458 hif-undefined-symbol))))
459
460 (defun hif-defined (var)
461 (cond
462 ((bound-and-true-p semantic-c-takeover-hideif)
463 (semantic-c-hideif-defined var))
464 ((assoc var hide-ifdef-env) 1)
465 (t 0)))
466
467 ;;===%%SF%% evaluation (End) ===
468
469
470
471 ;;===%%SF%% parsing (Start) ===
472 ;;; The code that understands what ifs and ifdef in files look like.
473
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 "\\|"
483 hif-endif-regexp))
484 (defconst hif-macro-expr-prefix-regexp
485 (concat hif-cpp-prefix "\\(if\\(n?def\\)?\\|elif\\|define\\)[ \t]+"))
486
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
492 "\\("
493 "(" hif-white-regexp
494 "\\(" hif-id-regexp "\\)?" hif-white-regexp
495 "\\(" "," hif-white-regexp hif-id-regexp hif-white-regexp "\\)*"
496 "\\(\\.\\.\\.\\)?" hif-white-regexp
497 ")"
498 "\\)?" ))
499
500 ;; Store the current token and the whole token list during parsing.
501 ;; Bound dynamically.
502 (defvar hif-token)
503 (defvar hif-token-list)
504
505 (defconst hif-token-alist
506 '(("||" . hif-or)
507 ("&&" . hif-and)
508 ("|" . hif-logior)
509 ("^" . hif-logxor)
510 ("&" . hif-logand)
511 ("<<" . hif-shiftleft)
512 (">>" . hif-shiftright)
513 ("==" . hif-equal)
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 ##.
517 ("=" . hif-assign)
518 ("!=" . hif-notequal)
519 ("##" . hif-token-concat)
520 ("!" . hif-not)
521 ("~" . hif-lognot)
522 ("(" . hif-lparen)
523 (")" . hif-rparen)
524 (">" . hif-greater)
525 ("<" . hif-less)
526 (">=" . hif-greater-equal)
527 ("<=" . hif-less-equal)
528 ("+" . hif-plus)
529 ("-" . hif-minus)
530 ("*" . hif-multiply)
531 ("/" . hif-divide)
532 ("%" . hif-modulo)
533 ("?" . hif-conditional)
534 (":" . hif-colon)
535 ("," . hif-comma)
536 ("#" . hif-stringify)
537 ("..." . hif-etc)))
538
539 (defconst hif-valid-token-list (mapcar 'cdr hif-token-alist))
540
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
545 "\\|\\w+"))
546
547 (defconst hif-string-literal-regexp "\\(\"\\(?:[^\"\\]\\|\\\\.\\)*\"\\)")
548
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]+"))
554 (frac (cadr parts))
555 (fraclen (length frac))
556 (quot (expt (if (zerop fraclen)
557 base
558 (* base 1.0)) fraclen)))
559 (/ (string-to-number (concat (car parts) frac) base) quot))))
560
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
565 ;; literals.
566 ;; Check the long comments before `hif-find-define' for more details. [lukelee]
567 (defvar hif-simple-token-only)
568
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
574 (save-excursion
575 (goto-char start)
576 (while (progn (forward-comment (point-max)) (< (point) end))
577 ;; (message "expr-start = %d" expr-start) (sit-for 1)
578 (cond
579 ((looking-at "\\\\\n")
580 (forward-char 2))
581
582 ((looking-at hif-string-literal-regexp)
583 (push (substring-no-properties (match-string 1)) token-list)
584 (goto-char (match-end 0)))
585
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)
591 (push
592 (or (cdr (assoc token hif-token-alist))
593 (if (string-equal token "defined") 'hif-defined)
594 ;; TODO:
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]*\\)"
599 token)
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]+\\)?\\'"
604 token)
605 (string-to-number token)) ;; decimal
606 (prog1 (intern token)
607 (setq hif-simple-token-only nil)))
608 token-list)))
609
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)))))))
613
614 (nreverse token-list)))
615
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
620 ;;
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
623
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 |
630 ;; | | + - | |
631 ;; | | >> << | |
632 ;; | | < > <= >= | |
633 ;; | | == != | |
634 ;; | | & | |
635 ;; | | ^ | |
636 ;; | | | | |
637 ;; | | && | |
638 ;; | | || | |
639 ;; | Ternary Operator | ?: | right-to-left |
640 ;; x| Assignment Operators | = += -= *= /= %= >>= <<= &= | right-to-left |
641 ;; | | ^= = | |
642 ;; | Comma | , | left-to-right |
643
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)))
647
648 (defsubst hif-if-valid-identifier-p (id)
649 (not (or (numberp id)
650 (stringp id))))
651
652 (defun hif-define-operator (tokens)
653 "`Upgrade' hif-define xxx to '(hif-define xxx)' so it won't be subsitituted."
654 (let ((result nil)
655 (tok nil))
656 (while (setq tok (pop tokens))
657 (push
658 (if (eq tok 'hif-defined)
659 (progn
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)
667 tokens (cdr 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))
671 tok)
672 result))
673 (nreverse result)))
674
675 (defun hif-flatten (l)
676 "Flatten a tree."
677 (apply #'nconc
678 (mapcar (lambda (x) (if (listp x)
679 (hif-flatten x)
680 (list x))) l)))
681
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
688 (let ((expanded nil)
689 (remains (hif-define-operator
690 (hif-token-concatenation
691 (hif-token-stringification tokens))))
692 tok rep)
693 (if macroname
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))
700 (push
701 (cond
702 ((or (memq tok hif-valid-token-list)
703 (numberp tok)
704 (stringp tok))
705 tok)
706
707 ((setq rep (hif-lookup tok))
708 (if (and (listp rep)
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
714 tok
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))
719 (hif-token nil)
720 (parmlist (mapcar #'hif-expand-token-list
721 (hif-get-argument-list)))
722 (result
723 (hif-expand-token-list
724 (hif-macro-supply-arguments tok parmlist)
725 tok expand_list)))
726 (setq remains (cons hif-token hif-token-list))
727 result))
728 ;; Argument list is nil, direct expansion
729 (setq rep (hif-expand-token-list
730 (cl-caddr rep) ; Macro's token list
731 tok expand_list))
732 ;; Replace all remaining references immediately
733 (setq remains (cl-substitute tok rep remains))
734 rep)
735 ;; Lookup tok returns an atom
736 rep))
737
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))
744 ;; nil)
745
746 (t ; Usual IDs
747 tok))
748
749 expanded))
750
751 (hif-flatten (nreverse expanded)))))
752
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)))
758 (hif-nexttoken)
759 (prog1
760 (and hif-token
761 (hif-exprlist))
762 (if hif-token ; is there still a token?
763 (error "Error: unexpected token: %s" hif-token)))))
764
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)))
770 (while
771 (progn
772 (hif-nexttoken)
773 (push (hif-expr) temp)
774 (eq hif-token 'hif-comma)))
775 (cons 'hif-comma (nreverse temp)))
776 result)))
777
778 (defun hif-expr ()
779 "Parse an expression as found in #if.
780 expr : or-expr | or-expr '?' expr ':' expr."
781 (let ((result (hif-or-expr))
782 middle)
783 (while (eq hif-token 'hif-conditional)
784 (hif-nexttoken)
785 (setq middle (hif-expr))
786 (if (eq hif-token 'hif-colon)
787 (progn
788 (hif-nexttoken)
789 (setq result (list 'hif-conditional result middle (hif-expr))))
790 (error "Error: unexpected token: %s" hif-token)))
791 result))
792
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)
797 (hif-nexttoken)
798 (setq result (list 'hif-or result (hif-and-expr))))
799 result))
800
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)
805 (hif-nexttoken)
806 (setq result (list 'hif-and result (hif-logior-expr))))
807 result))
808
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)
813 (hif-nexttoken)
814 (setq result (list 'hif-logior result (hif-logxor-expr))))
815 result))
816
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)
821 (hif-nexttoken)
822 (setq result (list 'hif-logxor result (hif-logand-expr))))
823 result))
824
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)
829 (hif-nexttoken)
830 (setq result (list 'hif-logand result (hif-eq-expr))))
831 result))
832
833 (defun hif-eq-expr ()
834 "Parse an eq-expr : comp | eq-expr `=='|`!=' comp."
835 (let ((result (hif-comp-expr))
836 (eq-token nil))
837 (while (memq hif-token '(hif-equal hif-notequal))
838 (setq eq-token hif-token)
839 (hif-nexttoken)
840 (setq result (list eq-token result (hif-comp-expr))))
841 result))
842
843 (defun hif-comp-expr ()
844 "Parse a comp-expr : logshift | comp-expr `<'|`>'|`>='|`<=' logshift."
845 (let ((result (hif-logshift-expr))
846 (comp-token nil))
847 (while (memq hif-token '(hif-greater hif-less hif-greater-equal
848 hif-less-equal))
849 (setq comp-token hif-token)
850 (hif-nexttoken)
851 (setq result (list comp-token result (hif-logshift-expr))))
852 result))
853
854 (defun hif-logshift-expr ()
855 "Parse a logshift : math | logshift `<<'|`>>' math."
856 (let ((result (hif-math))
857 (shift-token nil))
858 (while (memq hif-token '(hif-shiftleft hif-shiftright))
859 (setq shift-token hif-token)
860 (hif-nexttoken)
861 (setq result (list shift-token result (hif-math))))
862 result))
863
864 (defun hif-math ()
865 "Parse an expression with + or -.
866 math : muldiv | math '+|-' muldiv."
867 (let ((result (hif-muldiv-expr))
868 (math-op nil))
869 (while (memq hif-token '(hif-plus hif-minus))
870 (setq math-op hif-token)
871 (hif-nexttoken)
872 (setq result (list math-op result (hif-muldiv-expr))))
873 result))
874
875 (defun hif-muldiv-expr ()
876 "Parse an expression with *,/,%.
877 muldiv : factor | muldiv '*|/|%' factor."
878 (let ((result (hif-factor))
879 (math-op nil))
880 (while (memq hif-token '(hif-multiply hif-divide hif-modulo))
881 (setq math-op hif-token)
882 (hif-nexttoken)
883 (setq result (list math-op result (hif-factor))))
884 result))
885
886 (defun hif-factor ()
887 "Parse a factor.
888 factor : '!' factor | '~' factor | '(' expr ')' | 'defined(' id ')' |
889 'id(parmlist)' | strings | id."
890 (cond
891 ((eq hif-token 'hif-not)
892 (hif-nexttoken)
893 (list 'hif-not (hif-factor)))
894
895 ((eq hif-token 'hif-lognot)
896 (hif-nexttoken)
897 (list 'hif-lognot (hif-factor)))
898
899 ((eq hif-token 'hif-lparen)
900 (hif-nexttoken)
901 (let ((result (hif-exprlist)))
902 (if (not (eq hif-token 'hif-rparen))
903 (error "Bad token in parenthesized expression: %s" hif-token)
904 (hif-nexttoken)
905 result)))
906
907 ((eq hif-token 'hif-defined)
908 (hif-nexttoken)
909 (let ((paren (when (eq hif-token 'hif-lparen) (hif-nexttoken) t))
910 (ident hif-token))
911 (if (memq hif-token '(or and not hif-defined hif-lparen hif-rparen))
912 (error "Error: unexpected token: %s" hif-token))
913 (when paren
914 (hif-nexttoken)
915 (unless (eq hif-token 'hif-rparen)
916 (error "Error: expected \")\" after identifier")))
917 (hif-nexttoken)
918 `(hif-defined (quote ,ident))))
919
920 ((numberp hif-token)
921 (prog1 hif-token (hif-nexttoken)))
922 ((stringp hif-token)
923 (hif-string-concatenation))
924
925 ;; Unary plus/minus.
926 ((memq hif-token '(hif-minus hif-plus))
927 (list (prog1 hif-token (hif-nexttoken)) 0 (hif-factor)))
928
929 (t ; identifier
930 (let ((ident hif-token))
931 (hif-nexttoken)
932 (if (eq hif-token 'hif-lparen)
933 (hif-place-macro-invocation ident)
934 `(hif-lookup (quote ,ident)))))))
935
936 (defun hif-get-argument-list ()
937 (let ((nest 0)
938 (parmlist nil) ; A "token" list of parameters, will later be parsed
939 (parm nil))
940
941 (while (or (not (eq (hif-nexttoken) 'hif-rparen))
942 (/= nest 0))
943 (if (eq (car (last parm)) 'hif-comma)
944 (setq parm nil))
945 (cond
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)
951 (= nest 0))
952 (push (nreverse parm) parmlist)
953 (setq parm nil)))
954 (push hif-token parm))
955
956 (push (nreverse parm) parmlist) ; Okay even if PARM is nil
957 (hif-nexttoken) ; Drop the `hif-rparen', get next token
958 (nreverse parmlist)))
959
960 (defun hif-place-macro-invocation (ident)
961 (let ((parmlist (hif-get-argument-list)))
962 `(hif-invoke (quote ,ident) (quote ,parmlist))))
963
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))
968 (setq result (concat
969 (substring result 0 -1) ; remove trailing '"'
970 (substring hif-token 1)))) ; remove leading '"'
971 result))
972
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
977 (error
978 "Argumented macro cannot be evaluated without passing any parameter"))
979
980 (defun hif-stringify (a)
981 "Stringify a number, string or symbol."
982 (cond
983 ((numberp a)
984 (number-to-string a))
985 ((atom a)
986 (symbol-name a))
987 ((stringp a)
988 (concat "\"" a "\""))
989 (t
990 (error "Invalid token to stringify"))))
991
992 (defun intern-safe (str)
993 (if (stringp str)
994 (intern str)))
995
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)))
1006 (result (and ra rb
1007 (cdr (assoc (concat ra rb) hif-token-alist)))))
1008 (or result
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)))))
1016
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)
1020 ((null val) 0)
1021 (t val)))
1022
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)))))
1027 (defun hif-or (a b)
1028 (or (not (zerop (hif-mathify a))) (not (zerop (hif-mathify b)))))
1029 (defun hif-not (a)
1030 (zerop (hif-mathify a)))
1031 (defun hif-lognot (a)
1032 (lognot (hif-mathify a)))
1033
1034 (defmacro hif-mathify-binop (fun)
1035 `(lambda (a b)
1036 ,(format "Like `%s' but treat t and nil as 1 and 0." fun)
1037 (,fun (hif-mathify a) (hif-mathify b))))
1038
1039 (defun hif-shiftleft (a b)
1040 (setq a (hif-mathify a))
1041 (setq b (hif-mathify b))
1042 (if (< a 0)
1043 (ash a b)
1044 (lsh a b)))
1045
1046 (defun hif-shiftright (a b)
1047 (setq a (hif-mathify a))
1048 (setq b (hif-mathify b))
1049 (if (< a 0)
1050 (ash a (- b))
1051 (lsh a (- b))))
1052
1053
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))
1068
1069
1070 (defun hif-comma (&rest expr)
1071 "Evaluate a list of EXPR, return the result of the last item."
1072 (let ((result nil))
1073 (dolist (e expr)
1074 (ignore-errors
1075 (setq result (funcall hide-ifdef-evaluator e))))
1076 result))
1077
1078 (defun hif-token-stringification (l)
1079 "Scan token list for `hif-stringify' ('#') token and stringify the next token."
1080 (let (result)
1081 (while l
1082 (push (if (eq (car l) 'hif-stringify)
1083 (prog1
1084 (if (cadr l)
1085 (hif-stringify (cadr l))
1086 (error "No token to stringify"))
1087 (setq l (cdr l)))
1088 (car l))
1089 result)
1090 (setq l (cdr l)))
1091 (nreverse result)))
1092
1093 (defun hif-token-concatenation (l)
1094 "Scan token list for `hif-token-concat' ('##') token and concatenate two tokens."
1095 (let ((prev nil)
1096 result)
1097 (while l
1098 (while (eq (car l) 'hif-token-concat)
1099 (unless prev
1100 (error "No token before ## to concatenate"))
1101 (unless (cdr l)
1102 (error "No token after ## to concatenate"))
1103 (setq prev (hif-token-concat prev (cadr l)))
1104 (setq l (cddr l)))
1105 (if prev
1106 (setq result (append result (list prev))))
1107 (setq prev (car l)
1108 l (cdr l)))
1109 (if prev
1110 (append result (list prev))
1111 result)))
1112
1113 (defun hif-delimit (lis atom)
1114 (nconc (cl-mapcan (lambda (l) (list l atom))
1115 (butlast lis))
1116 (last lis)))
1117
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))
1122 (macro (and SA
1123 (cdr SA)
1124 (eq (cadr SA) 'hif-define-macro)
1125 (cddr SA)))
1126 (formal-parms (and macro (car macro)))
1127 (macro-body (and macro (cadr macro)))
1128 actual-count
1129 formal-count
1130 formal
1131 etc)
1132
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))
1142
1143 (if (> formal-count actual-count)
1144 (error "Too few parmameter for macro %S" macro-name)
1145 (if (< formal-count actual-count)
1146 (or etc
1147 (error "Too many parameters for macro %S" macro-name))))
1148
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'
1152 ;; for example:
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)
1159 ;; becomes (b+b)
1160 ;; 2. formal parm #2 'b' replaced by actual parm 'y', thus (b+b)
1161 ;; becomes (y+y).
1162 (setq macro-body
1163 ;; Unlike `subst', `substitute' replace only the top level
1164 ;; instead of the whole tree; more importantly, it's not
1165 ;; destructive.
1166 (cl-substitute (if (and etc (null formal-parms))
1167 (hif-delimit actual-parms 'hif-comma)
1168 (car actual-parms))
1169 formal macro-body))
1170 (setq actual-parms (cdr actual-parms)))
1171
1172 ;; Replacement completed, flatten the whole token list
1173 (setq macro-body (hif-flatten macro-body))
1174
1175 ;; Stringification and token concatenation happens here
1176 (hif-token-concatenation (hif-token-stringification macro-body)))))
1177
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
1182 (hif-parse-exp
1183 (hif-macro-supply-arguments macro-name actual-parms)
1184 macro-name)))
1185
1186 ;;;----------- end of parser -----------------------
1187
1188
1189 (defun hif-canonicalize-tokens (regexp) ; For debugging
1190 "Return the expanded result of the scanned tokens."
1191 (save-excursion
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)))))
1200 (if defined
1201 (setq tokens (list 'hif-defined tokens)))
1202 (if negate
1203 (setq tokens (list 'hif-not tokens)))
1204 tokens)))
1205
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))
1210 (save-excursion
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)))))
1219 (if defined
1220 (setq tokens (list 'hif-defined tokens)))
1221 (if negate
1222 (setq tokens (list 'hif-not tokens)))
1223 (hif-parse-exp tokens)))))
1224
1225 (defun hif-find-any-ifX ()
1226 "Move to next #if..., or #ifndef, at point or after."
1227 ;; (message "find ifX at %d" (point))
1228 (prog1
1229 (re-search-forward hif-ifx-regexp (point-max) t)
1230 (beginning-of-line)))
1231
1232
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))
1236 (end-of-line)
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)))
1240
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))
1244 (beginning-of-line)
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)))
1248
1249
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))
1256
1257 (defun hif-looking-at-elif ()
1258 (looking-at hif-elif-regexp))
1259
1260
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)
1273 'done)
1274 (t
1275 (error "Mismatched #ifdef #endif pair"))))
1276
1277
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)
1293 'done)
1294 (t
1295 (error "Mismatched #endif")))) ; never gets here
1296
1297
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."
1301 (interactive "p")
1302 (or arg (setq arg 1))
1303 (if (< arg 0) (backward-ifdef (- arg))
1304 (while (< 0 arg)
1305 (setq arg (- 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)
1311 (goto-char start)
1312 (error "No following #ifdef"))))))
1313
1314
1315 (defun backward-ifdef (&optional arg)
1316 "Move point to beginning of the previous ifdef-endif.
1317 With argument, do this that many times."
1318 (interactive "p")
1319 (or arg (setq arg 1))
1320 (if (< arg 0) (forward-ifdef (- arg))
1321 (while (< 0 arg)
1322 (setq arg (1- arg))
1323 (beginning-of-line)
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)
1329 (goto-char start)
1330 (error "No previous #ifdef"))))))
1331
1332
1333 (defun down-ifdef ()
1334 "Move point to beginning of nested ifdef or else-part."
1335 (interactive)
1336 (let ((start (point)))
1337 (hif-find-next-relevant)
1338 (if (or (hif-looking-at-ifX) (hif-looking-at-else))
1339 ()
1340 (goto-char start)
1341 (error "No following #ifdef"))))
1342
1343
1344 (defun up-ifdef ()
1345 "Move point to beginning of enclosing ifdef or else-part."
1346 (interactive)
1347 (beginning-of-line)
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"))))
1355
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."
1359 (interactive "p")
1360 (or arg (setq arg 1))
1361 (if (< arg 0) (previous-ifdef (- arg))
1362 (while (< 0 arg)
1363 (setq arg (1- arg))
1364 (hif-find-next-relevant)
1365 (when (eolp)
1366 (beginning-of-line)
1367 (error "No following #ifdefs, #elses, or #endifs")))))
1368
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."
1372 (interactive "p")
1373 (or arg (setq arg 1))
1374 (if (< arg 0) (next-ifdef (- arg))
1375 (while (< 0 arg)
1376 (setq arg (1- arg))
1377 (let ((start (point)))
1378 (hif-find-previous-relevant)
1379 (if (= start (point))
1380 (error "No previous #ifdefs, #elses, or #endifs"))))))
1381
1382
1383 ;;===%%SF%% parsing (End) ===
1384
1385
1386 ;;===%%SF%% hide-ifdef-hiding (Start) ===
1387
1388
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)
1394
1395 (defsubst hif-make-range (start end &optional else elif)
1396 (list start else end elif))
1397
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))
1402
1403
1404 ;; Find-Range
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.
1408
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))
1413 (save-excursion
1414 (beginning-of-line)
1415 (let ((start (point))
1416 (elif nil)
1417 (else nil)
1418 (end nil))
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))
1422 (while (progn
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)))
1431 (t
1432 (setq end (point)))))
1433 ;; If found #else, look for #endif.
1434 (when else
1435 (while (progn
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))))
1443
1444
1445 ;; A bit slimy.
1446
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
1451 (save-excursion
1452 (goto-char point)
1453 (hide-ifdef-region-internal
1454 (line-beginning-position) (progn (hif-end-of-line) (point))))))
1455
1456
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
1461 ;; compiled.
1462 ;;
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
1473 ;; for nested #ifs.
1474 ;; Case 5: #ifX not taken, and there's no #else.
1475 ;; The #ifX part must be hidden.
1476 ;;
1477 ;; Further processing is done by narrowing to the relevant region
1478 ;; and just recursively calling hide-ifdef-guts.
1479 ;;
1480 ;; When hif-possibly-hide returns, point is at the end of the
1481 ;; possibly-hidden range.
1482
1483 (defvar hif-recurse-level 0)
1484
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."
1487 (save-excursion
1488 (save-restriction
1489 (goto-char start)
1490 (unless dont-go-eol
1491 (end-of-line))
1492 (narrow-to-region (point) end)
1493 (let ((hif-recurse-level (1+ hif-recurse-level)))
1494 (hide-ifdef-guts)))))
1495
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
1507 (complete nil))
1508 ;; (message "test = %s" test) (sit-for 1)
1509
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
1515 (if elifs
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)
1520 (1- newstart))
1521 (setcar range newstart)
1522 (goto-char newstart)
1523 (setq elifs (cdr elifs))
1524 (setq test (hif-canonicalize hif-elif-regexp)))
1525
1526 ;; Check for #else
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)))
1534 (t
1535 ;; Case 5 - No #else block, hide #ifX
1536 (hide-ifdef-region (point)
1537 (1- (hif-range-end range)))))
1538 (setq complete t))
1539
1540 ;; ifX/elif is TRUE
1541 (cond (elifs
1542 ;; Luke fix: distinguish from #elif..#elif to #elif..#else
1543 (let ((elif (car elifs)))
1544 ;; hide all elifs
1545 (hif-hide-line elif)
1546 (hide-ifdef-region elif (1- (hif-range-end range)))
1547 (hif-recurse-on (hif-range-start range)
1548 elif)))
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)))
1556 (t
1557 ;; Case 2 - No #else, just recurse #ifX
1558 (hif-recurse-on (hif-range-start range)
1559 (hif-range-end range))))
1560 (setq complete t))
1561 (setq if-part nil))
1562
1563 ;; complete = t
1564 (hif-hide-line (hif-range-start range)) ; Always hide start.
1565 (goto-char (hif-range-end range))
1566 (end-of-line)))
1567
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)))
1572 (expr (and tokens
1573 (condition-case nil
1574 (hif-parse-exp tokens)
1575 (error
1576 tokens))))
1577 (result (funcall hide-ifdef-evaluator expr)))
1578 result))
1579
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
1584 not be expanded."
1585 (interactive "r")
1586 (let ((case-fold-search nil))
1587 (save-excursion
1588 (unless mark-active
1589 (setq rstart nil rend nil)
1590 (beginning-of-line)
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))))
1596 (defined nil)
1597 (simple 't)
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)))
1605 (and tokens
1606 (condition-case nil
1607 (hif-parse-exp tokens)
1608 (error
1609 nil)))))
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)))))
1617 (cond
1618 ((and (<= (length tokens) 1) simple) ; Simple token
1619 (if defined
1620 (message "%S <= `%s'" result exprstring)
1621 (message "`%s' is not defined" exprstring)))
1622 ((integerp result)
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)))
1629 result))))
1630
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'
1636 (tokenlist
1637 (cdr (hif-tokenize
1638 (- (point) (length str)) (point)))) ; Remove `hif-lparen'
1639 etc result token)
1640 (while (not (eq (setq token (pop tokenlist)) 'hif-rparen))
1641 (cond
1642 ((eq token 'hif-etc)
1643 (setq etc t))
1644 ((eq token 'hif-comma)
1645 t)
1646 (t
1647 (push token result))))
1648 (if etc
1649 (cons 'hif-etc (nreverse result))
1650 (nreverse result))))
1651
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'.)
1657 ;;
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.
1665 ;;
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.
1674 ;;
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]
1679
1680 (defun hif-find-define (&optional min max)
1681 "Parse texts and retrieve all defines within the region MIN and MAX."
1682 (interactive)
1683 (and min (goto-char min))
1684 (and (re-search-forward hif-define-regexp max t)
1685 (or
1686 (let* ((defining (string= "define" (match-string 2)))
1687 (name (and (re-search-forward hif-macroref-regexp max t)
1688 (match-string 1)))
1689 (parmlist (and (match-string 3) ; First arg id found
1690 (hif-parse-macro-arglist (match-string 2)))))
1691 (if defining
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
1695 name))
1696
1697 (let* ((start (point))
1698 (end (progn (hif-end-of-line) (point)))
1699 (hif-simple-token-only nil) ; Dynamic binding
1700 (tokens
1701 (and name
1702 ;; `hif-simple-token-only' is set/clear
1703 ;; only in this block
1704 (condition-case nil
1705 ;; Prevent C statements like
1706 ;; 'do { ... } while (0)'
1707 (hif-tokenize start end)
1708 (error
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
1714 start end)))))
1715 ;; For simple tokens we save only the parsed result;
1716 ;; otherwise we save the tokens and parse it after
1717 ;; parameter replacement
1718 (expr (and tokens
1719 ;; `hif-simple-token-only' is checked only
1720 ;; here.
1721 (or (and hif-simple-token-only
1722 (listp tokens)
1723 (= (length tokens) 1)
1724 (hif-parse-exp tokens))
1725 `(hif-define-macro ,parmlist
1726 ,tokens))))
1727 (SA (and name
1728 (assoc (intern name) hide-ifdef-env))))
1729 (and name
1730 (if SA
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)))))
1736 ;; #undef
1737 (and name
1738 (hif-undefine-symbol (intern name))))))
1739 t))
1740
1741
1742 (defun hif-add-new-defines (&optional min max)
1743 "Scan and add all #define macros between MIN and MAX."
1744 (interactive)
1745 (save-excursion
1746 (save-restriction
1747 ;; (mark-region min max) ;; for debugging
1748 (while (hif-find-define min max)
1749 (setf min (point)))
1750 (if max (goto-char max)
1751 (goto-char (point-max))))))
1752
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")
1757 (save-excursion
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
1761 (buffer-file-name))
1762 (zerop hif-recurse-level)))
1763 (case-fold-search nil)
1764 min max)
1765 (goto-char (point-min))
1766 (setf min (point))
1767 (cl-loop do
1768 (setf max (hif-find-any-ifX))
1769 (hif-add-new-defines min max)
1770 (if max
1771 (hif-possibly-hide expand-header))
1772 (setf min (point))
1773 while max))))
1774
1775 ;;===%%SF%% hide-ifdef-hiding (End) ===
1776
1777
1778 ;;===%%SF%% exports (Start) ===
1779
1780 (defun hide-ifdef-toggle-read-only ()
1781 "Toggle `hide-ifdef-read-only'."
1782 (interactive)
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))
1790
1791 (defun hide-ifdef-toggle-outside-read-only ()
1792 "Replacement for `toggle-read-only' within Hide-Ifdef mode."
1793 (interactive)
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))
1801
1802 (defun hide-ifdef-toggle-shadowing ()
1803 "Toggle shadowing."
1804 (interactive)
1805 (set (make-local-variable 'hide-ifdef-shadow) (not hide-ifdef-shadow))
1806 (message "Shadowing %s" (if hide-ifdef-shadow "ON" "OFF"))
1807 (save-restriction
1808 (widen)
1809 (dolist (overlay (overlays-in (point-min) (point-max)))
1810 (when (overlay-get overlay 'hide-ifdef)
1811 (if hide-ifdef-shadow
1812 (progn
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))))))
1817
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."
1821 (interactive
1822 (let* ((default (save-excursion
1823 (beginning-of-line)
1824 (cond ((looking-at hif-ifx-else-endif-regexp)
1825 (forward-word 2)
1826 (current-word 'strict))
1827 (t
1828 nil))))
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")))
1832 (list var val)))
1833 (hif-set-var var (or val 1))
1834 (message "%s set to %s" var (or val 1))
1835 (sleep-for 1)
1836 (if hide-ifdef-hiding (hide-ifdefs)))
1837
1838 (defun hif-undefine-symbol (var)
1839 (setq hide-ifdef-env
1840 (delete (assoc var hide-ifdef-env) hide-ifdef-env)))
1841
1842 (defun hide-ifdef-undef (start end)
1843 "Undefine a VAR so that #ifdef VAR would not be included."
1844 (interactive "r")
1845 (let* ((symstr
1846 (or (and mark-active
1847 (buffer-substring-no-properties start end))
1848 (read-string "Undefine what? " (current-word))))
1849 (sym (and symstr
1850 (intern symstr))))
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))))
1856
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.
1863
1864 Turn off hiding by calling `show-ifdefs'."
1865
1866 (interactive)
1867 (let ((hide-ifdef-lines current-prefix-arg))
1868 (or nomsg
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)
1875 (hide-ifdef-guts)
1876 (setq buffer-read-only (or hide-ifdef-read-only hif-outside-read-only))
1877 (or nomsg
1878 (message "Hiding done"))))
1879
1880
1881 (defun show-ifdefs ()
1882 "Cancel the effects of `hide-ifdef': show the contents of all #ifdefs."
1883 (interactive)
1884 (setq buffer-read-only hif-outside-read-only)
1885 (hif-show-all)
1886 (setq hide-ifdef-hiding nil))
1887
1888
1889 (defun hif-find-ifdef-block ()
1890 "Utility to hide and show ifdef block.
1891 Return as (TOP . BOTTOM) the extent of ifdef block."
1892 (let (max-bottom)
1893 (cons (save-excursion
1894 (beginning-of-line)
1895 (unless (or (hif-looking-at-else) (hif-looking-at-ifX))
1896 (up-ifdef))
1897 (prog1 (point)
1898 (hif-ifdef-to-endif)
1899 (setq max-bottom (1- (point)))))
1900 (save-excursion
1901 (beginning-of-line)
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)))))))
1908
1909
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))
1915 (if mark-active
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)))))
1928
1929 (defun show-ifdef-block (&optional start end)
1930 "Show the ifdef block (true or false part) enclosing or before the cursor."
1931 (interactive "r")
1932 (if mark-active
1933 (progn
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)
1940 (error
1941 nil)))
1942 (ovrs (overlays-in (max (point-min) (1- (point)))
1943 (min (point-max) (1+ (point)))))
1944 (del nil))
1945 (if top-bottom
1946 (if hide-ifdef-lines
1947 (hif-show-ifdef-region
1948 (save-excursion
1949 (goto-char (car top-bottom)) (line-beginning-position))
1950 (save-excursion
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
1956 del))
1957 (dolist (o ovrs)
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)))))))
1962
1963
1964 ;;; definition alist support
1965
1966 (defvar hide-ifdef-define-alist nil
1967 "A global assoc list of pre-defined symbol lists.")
1968
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)))))
1974
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))
1980
1981 (defun hide-ifdef-use-define-alist (name)
1982 "Set `hide-ifdef-env' to the define list specified by NAME."
1983 (interactive
1984 (list (completing-read "Use define list: "
1985 (mapcar (lambda (x) (symbol-name (car x)))
1986 hide-ifdef-define-alist)
1987 nil t)))
1988 (if (stringp name) (setq name (intern name)))
1989 (let ((define-list (assoc name hide-ifdef-define-alist)))
1990 (if define-list
1991 (setq hide-ifdef-env
1992 (mapcar (lambda (arg) (cons arg t))
1993 (cdr define-list)))
1994 (error "No define list for %s" name))
1995 (if hide-ifdef-hiding (hide-ifdefs))))
1996
1997 (provide 'hideif)
1998
1999 ;;; hideif.el ends here