1;;; semantic/fw.el --- Framework for Semantic
2
3;;; Copyright (C) 1999-2021 Free Software Foundation, Inc.
4
5;; Author: Eric M. Ludlam <zappo@gnu.org>
6
7;; This file is part of GNU Emacs.
8
9;; GNU Emacs is free software: you can redistribute it and/or modify
10;; it under the terms of the GNU General Public License as published by
11;; the Free Software Foundation, either version 3 of the License, or
12;; (at your option) any later version.
13
14;; GNU Emacs is distributed in the hope that it will be useful,
15;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17;; GNU General Public License for more details.
18
19;; You should have received a copy of the GNU General Public License
20;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
21
22;;; Commentary:
23;;
24;; Semantic has several core features shared across it's lex/parse/util
25;; stages.  This used to clutter semantic.el some.  These routines are all
26;; simple things that are not parser specific, but aid in making
27;; semantic flexible and compatible amongst different Emacs platforms.
28
29;;; Code:
30;;
31(require 'mode-local)
32(require 'eieio)
33(load "semantic/loaddefs" 'noerror 'nomessage)
34
35;;; Compatibility
36;;
37(define-obsolete-function-alias 'semantic-overlay-live-p 'overlay-buffer "27.1")
38(define-obsolete-function-alias 'semantic-make-overlay 'make-overlay "27.1")
39(define-obsolete-function-alias 'semantic-overlay-put 'overlay-put "27.1")
40(define-obsolete-function-alias 'semantic-overlay-get 'overlay-get "27.1")
41(define-obsolete-function-alias 'semantic-overlay-properties
42  'overlay-properties "27.1")
43(define-obsolete-function-alias 'semantic-overlay-move 'move-overlay "27.1")
44(define-obsolete-function-alias 'semantic-overlay-delete 'delete-overlay "27.1")
45(define-obsolete-function-alias 'semantic-overlays-at 'overlays-at "27.1")
46(define-obsolete-function-alias 'semantic-overlays-in 'overlays-in "27.1")
47(define-obsolete-function-alias 'semantic-overlay-buffer 'overlay-buffer "27.1")
48(define-obsolete-function-alias 'semantic-overlay-start 'overlay-start "27.1")
49(define-obsolete-function-alias 'semantic-overlay-end 'overlay-end "27.1")
50(define-obsolete-function-alias 'semantic-overlay-next-change
51  'next-overlay-change "27.1")
52(define-obsolete-function-alias 'semantic-overlay-previous-change
53  'previous-overlay-change "27.1")
54(define-obsolete-function-alias 'semantic-overlay-lists 'overlay-lists "27.1")
55(define-obsolete-function-alias 'semantic-overlay-p 'overlayp "27.1")
56(define-obsolete-function-alias 'semantic-read-event 'read-event "27.1")
57(define-obsolete-function-alias 'semantic-popup-menu 'popup-menu "27.1")
58(define-obsolete-function-alias 'semantic-buffer-local-value
59  'buffer-local-value "27.1")
60
61(defun semantic-event-window (event)
62  "Extract the window from EVENT."
63  (car (car (cdr event))))
64
65(define-obsolete-function-alias 'semantic-make-local-hook #'identity "27.1")
66
67(defalias 'semantic-mode-line-update #'force-mode-line-update)
68
69;; Since Emacs 22 major mode functions should use `run-mode-hooks' to
70;; run major mode hooks.
71(defalias 'semantic-run-mode-hooks
72  (if (fboundp 'run-mode-hooks)
73      'run-mode-hooks
74    'run-hooks))
75
76  ;; Fancy compat usage now handled in cedet-compat
77(defalias 'semantic-subst-char-in-string 'subst-char-in-string)
78
79(defun semantic-delete-overlay-maybe (overlay)
80  "Delete OVERLAY if it is a semantic token overlay."
81  (if (overlay-get overlay 'semantic)
82      (delete-overlay overlay)))
83
84;;; Menu Item compatibility
85;;
86(define-obsolete-function-alias 'semantic-menu-item #'identity "27.1")
87
88;;; Positional Data Cache
89;;
90(defvar semantic-cache-data-overlays nil
91  "List of all overlays waiting to be flushed.")
92
93(defun semantic-cache-data-to-buffer (buffer start end value name &optional lifespan)
94  "In BUFFER over the region START END, remember VALUE.
95NAME specifies a special name that can be searched for later to
96recover the cached data with `semantic-get-cache-data'.
97LIFESPAN indicates how long the data cache will be remembered.
98The default LIFESPAN is `end-of-command'.
99Possible Lifespans are:
100  `end-of-command' - Remove the cache at the end of the currently
101                     executing command.
102  `exit-cache-zone' - Remove when point leaves the overlay at the
103                      end of the currently executing command."
104  ;; Check if LIFESPAN is valid before to create any overlay
105  (or lifespan (setq lifespan 'end-of-command))
106  (or (memq lifespan '(end-of-command exit-cache-zone))
107      (error "semantic-cache-data-to-buffer: Unknown LIFESPAN: %s"
108             lifespan))
109  (let ((o (make-overlay start end buffer)))
110    (overlay-put o 'cache-name   name)
111    (overlay-put o 'cached-value value)
112    (overlay-put o 'lifespan     lifespan)
113    (setq semantic-cache-data-overlays
114          (cons o semantic-cache-data-overlays))
115    ;;(message "Adding to cache: %s" o)
116    (add-hook 'post-command-hook 'semantic-cache-data-post-command-hook)
117    ))
118
119(defun semantic-cache-data-post-command-hook ()
120  "Flush `semantic-cache-data-overlays' based `lifespan' property.
121Remove self from `post-command-hook' if it is empty."
122  (let ((newcache nil)
123        (oldcache semantic-cache-data-overlays))
124    (while oldcache
125      (let* ((o    (car oldcache))
126             (life (overlay-get o 'lifespan))
127             )
128        (if (or (eq life 'end-of-command)
129                (and (eq life 'exit-cache-zone)
130                     (not (member o (overlays-at (point))))))
131            (progn
132              ;;(message "Removing from cache: %s" o)
133              (delete-overlay o)
134              )
135          (setq newcache (cons o newcache))))
136      (setq oldcache (cdr oldcache)))
137    (setq semantic-cache-data-overlays (nreverse newcache)))
138
139  ;; Remove ourselves if we have removed all overlays.
140  (unless semantic-cache-data-overlays
141    (remove-hook 'post-command-hook
142                 'semantic-cache-data-post-command-hook)))
143
144(defun semantic-get-cache-data (name &optional point)
145  "Get cached data with NAME from optional POINT."
146  (save-excursion
147    (if point (goto-char point))
148    (let ((o (overlays-at (point)))
149          (ans nil))
150      (while (and (not ans) o)
151        (if (equal (overlay-get (car o) 'cache-name) name)
152            (setq ans (car o))
153          (setq o (cdr o))))
154      (when ans
155        (overlay-get ans 'cached-value)))))
156
157(defun semantic-test-data-cache ()
158  "Test the data cache."
159  (interactive)
160  (let ((data '(a b c)))
161    (save-current-buffer
162      (set-buffer (get-buffer-create " *semantic-test-data-cache*"))
163      (save-excursion
164	(erase-buffer)
165	(insert "The Moose is Loose")
166	(goto-char (point-min))
167	(semantic-cache-data-to-buffer (current-buffer) (point) (+ (point) 5)
168				       data 'moose 'exit-cache-zone)
169	(if (equal (semantic-get-cache-data 'moose) data)
170	    (message "Successfully retrieved cached data.")
171	  (error "Failed to retrieve cached data"))
172	))))
173
174;;; Obsoleting various functions & variables
175;;
176(defun semantic-overload-symbol-from-function (name)
177  "Return the symbol for overload used by NAME, the defined symbol."
178  (let ((sym-name (symbol-name name)))
179    (if (string-match "^semantic-" sym-name)
180	(intern (substring sym-name (match-end 0)))
181      name)))
182
183(defun semantic-alias-obsolete (oldfnalias newfn when)
184  "Make OLDFNALIAS an alias for NEWFN.
185Mark OLDFNALIAS as obsolete, such that the byte compiler
186will throw a warning when it encounters this symbol."
187  (defalias oldfnalias newfn)
188  (make-obsolete oldfnalias newfn when)
189  (when (and (mode-local--function-overload-p newfn)
190             (not (mode-local--overload-obsoleted-by newfn))
191             ;; Only throw this warning when byte compiling things.
192             (boundp 'byte-compile-current-file)
193             byte-compile-current-file
194	     (not (string-match "cedet" byte-compile-current-file))
195	     )
196    (make-obsolete-overload oldfnalias newfn when)
197    (byte-compile-warn
198     "%s: `%s' obsoletes overload `%s'"
199     byte-compile-current-file
200     newfn
201     (semantic-overload-symbol-from-function oldfnalias))
202    ))
203
204(defun semantic-varalias-obsolete (oldvaralias newvar when)
205  "Make OLDVARALIAS an alias for variable NEWVAR.
206Mark OLDVARALIAS as obsolete, such that the byte compiler
207will throw a warning when it encounters this symbol."
208  (make-obsolete-variable oldvaralias newvar when)
209  (condition-case nil
210      (defvaralias oldvaralias newvar)
211    (error
212     ;; Only throw this warning when byte compiling things.
213     (when (and (boundp 'byte-compile-current-file)
214                byte-compile-current-file)
215       (byte-compile-warn
216        "variable `%s' obsoletes, but isn't alias of `%s'"
217        newvar oldvaralias)
218     ))))
219
220;;; Help debugging
221;;
222(defmacro semantic-safe (format &rest body)
223  "Turn into a FORMAT message any error caught during eval of BODY.
224Return the value of last BODY form or nil if an error occurred.
225FORMAT can have a %s escape which will be replaced with the actual
226error message.
227If `debug-on-error' is set, errors are not caught, so that you can
228debug them.
229Avoid using a large BODY since it is duplicated."
230  (declare (debug t) (indent 1))
231  `(if debug-on-error
232       ;;(let ((inhibit-quit nil)) ,@body)
233       ;; Note to self: Doing the above screws up the wisent parser.
234       (progn ,@body)
235     (condition-case err
236	 (progn ,@body)
237       (error
238        (message ,format (format "%S - %s" (current-buffer)
239                                 (error-message-string err)))
240        nil))))
241
242;;; Misc utilities
243;;
244
245(defvar semantic-new-buffer-fcn-was-run nil
246  "Non-nil after `semantic-new-buffer-fcn' has been executed.")
247(make-variable-buffer-local 'semantic-new-buffer-fcn-was-run)
248
249(defsubst semantic-active-p ()
250  "Return non-nil if the current buffer was set up for parsing."
251  semantic-new-buffer-fcn-was-run)
252
253(defsubst semantic-map-buffers (function)
254  "Run FUNCTION for each Semantic enabled buffer found.
255FUNCTION does not have arguments.  When FUNCTION is entered
256`current-buffer' is a selected Semantic enabled buffer."
257  (mode-local-map-file-buffers function #'semantic-active-p))
258
259(defalias 'semantic-map-mode-buffers 'mode-local-map-mode-buffers)
260
261(semantic-alias-obsolete 'define-mode-overload-implementation
262                         'define-mode-local-override "23.2")
263
264(defun semantic-install-function-overrides (overrides &optional transient)
265  "Install the function OVERRIDES in the specified environment.
266OVERRIDES must be an alist ((OVERLOAD .  FUNCTION) ...) where OVERLOAD
267is a symbol identifying an overloadable entry, and FUNCTION is the
268function to override it with.
269If optional argument TRANSIENT is non-nil, installed overrides can in
270turn be overridden by next installation.
271If optional argument MODE is non-nil, it must be a major mode symbol.
272OVERRIDES will be installed globally for this major mode.  If MODE is
273nil, OVERRIDES will be installed locally in the current buffer.  This
274later installation should be done in MODE hook."
275  (mode-local-bind
276   ;; Add the semantic- prefix to OVERLOAD short names.
277   (mapcar
278    #'(lambda (e)
279        (let ((name (symbol-name (car e))))
280          (if (string-match "^semantic-" name)
281              e
282            (cons (intern (format "semantic-%s" name)) (cdr e)))))
283    overrides)
284   (list 'constant-flag (not transient)
285         'override-flag t)))
286
287;;; User Interrupt handling
288;;
289(defvar semantic-current-input-throw-symbol nil
290  "The current throw symbol for `semantic-exit-on-input'.")
291(defvar semantic--on-input-start-marker nil
292  "The marker when starting a semantic-exit-on-input form.")
293
294(defmacro semantic-exit-on-input (symbol &rest forms)
295  "Using SYMBOL as an argument to `throw', execute FORMS.
296If FORMS includes a call to `semantic-throw-on-input', then
297if a user presses any key during execution, this form macro
298will exit with the value passed to `semantic-throw-on-input'.
299If FORMS completes, then the return value is the same as `progn'."
300  (declare (indent 1) (debug def-body))
301  `(let ((semantic-current-input-throw-symbol ,symbol)
302         (semantic--on-input-start-marker (point-marker)))
303     (catch ,symbol
304       ,@forms)))
305
306(defmacro semantic-throw-on-input (from)
307  "Exit with `throw' when in `semantic-exit-on-input' on user input.
308FROM is an indication of where this function is called from as a value
309to pass to `throw'.  It is recommended to use the name of the function
310calling this one."
311  `(when (and semantic-current-input-throw-symbol
312              (or (input-pending-p)
313                  (with-current-buffer
314                      (marker-buffer semantic--on-input-start-marker)
315                    ;; Timers might run during accept-process-output.
316                    ;; If they redisplay, point must be where the user
317                    ;; expects. (Bug#15045)
318                    (save-excursion
319                      (goto-char semantic--on-input-start-marker)
320                      (accept-process-output)))))
321     (throw semantic-current-input-throw-symbol ,from)))
322
323
324;;; Special versions of Find File
325;;
326(defun semantic-find-file-noselect (file &optional nowarn rawfile wildcards)
327  "Call `find-file-noselect' with various features turned off.
328Use this when referencing a file that will be soon deleted.
329FILE, NOWARN, RAWFILE, and WILDCARDS are passed into `find-file-noselect'."
330  ;; Hack -
331  ;; Check if we are in set-auto-mode, and if so, warn about this.
332  (when (boundp 'keep-mode-if-same)
333    (let ((filename (or (and (boundp 'filename) filename)
334			"(unknown)")))
335      (message "WARNING: semantic-find-file-noselect called for \
336%s while in set-auto-mode for %s.  You should call the responsible function \
337into `mode-local-init-hook'." file filename)
338      (sit-for 1)))
339
340  (let* ((recentf-exclude '( (lambda (f) t) ))
341	 ;; This is a brave statement.  Don't waste time loading in
342	 ;; lots of modes.  Especially decoration mode can waste a lot
343	 ;; of time for a buffer we intend to kill.
344	 (semantic-init-hook nil)
345	 ;; This disables the part of EDE that asks questions
346	 (ede-auto-add-method 'never)
347	 ;; Ask font-lock to not colorize these buffers, nor to
348	 ;; whine about it either.
349	 (global-font-lock-mode nil)
350	 (font-lock-verbose nil)
351	 ;; This forces flymake to ignore this buffer on find-file, and
352	 ;; prevents flymake processes from being started.
353	 (flymake-start-syntax-check-on-find-file nil)
354	 ;; Disable revision control
355	 (vc-handled-backends nil)
356	 ;; Don't prompt to insert a template if we visit an empty file
357	 (auto-insert nil)
358	 ;; We don't want emacs to query about unsafe local variables
359	 (enable-local-variables :safe)
360	 ;; ... or eval variables
361	 (enable-local-eval nil)
362	 )
363    (save-match-data
364      (find-file-noselect file nowarn rawfile wildcards))))
365
366;;; Database restriction settings
367;;
368(defmacro semanticdb-without-unloaded-file-searches (forms)
369  "Execute FORMS with `unloaded' removed from the current throttle."
370  (declare (indent 1))
371  `(let ((semanticdb-find-default-throttle
372	  (if (featurep 'semantic/db-find)
373	      (remq 'unloaded semanticdb-find-default-throttle)
374	    nil)))
375     ,forms))
376
377
378;; ;;; Editor goodies ;-)
379;; ;;
380;; (defconst semantic-fw-font-lock-keywords
381;;   (eval-when-compile
382;;     (let* (
383;;            ;; Variable declarations
384;; 	   (vl nil)
385;;            (kv (if vl (regexp-opt vl t) ""))
386;;            ;; Function declarations
387;; 	   (vf '(
388;; 		 "define-lex"
389;; 		 "define-lex-analyzer"
390;; 		 "define-lex-block-analyzer"
391;; 		 "define-lex-regex-analyzer"
392;; 		 "define-lex-spp-macro-declaration-analyzer"
393;; 		 "define-lex-spp-macro-undeclaration-analyzer"
394;; 		 "define-lex-spp-include-analyzer"
395;; 		 "define-lex-simple-regex-analyzer"
396;; 		 "define-lex-keyword-type-analyzer"
397;; 		 "define-lex-sexp-type-analyzer"
398;; 		 "define-lex-regex-type-analyzer"
399;; 		 "define-lex-string-type-analyzer"
400;; 		 "define-lex-block-type-analyzer"
401;; 		 ;;"define-mode-overload-implementation"
402;; 		 ;;"define-semantic-child-mode"
403;; 		 "define-semantic-idle-service"
404;; 		 "define-semantic-decoration-style"
405;; 		 "define-wisent-lexer"
406;; 		 "semantic-alias-obsolete"
407;; 		 "semantic-varalias-obsolete"
408;; 		 "semantic-make-obsolete-overload"
409;; 		 "defcustom-mode-local-semantic-dependency-system-include-path"
410;; 		 ))
411;;            (kf (if vf (regexp-opt vf t) ""))
412;;            ;; Regexp depths
413;;            (kv-depth (if kv (regexp-opt-depth kv) nil))
414;;            (kf-depth (if kf (regexp-opt-depth kf) nil))
415;;            )
416;;       `((,(concat
417;;            ;; Declarative things
418;;            "(\\(" kv "\\|" kf "\\)"
419;;            ;; Whitespaces & names
420;;            "\\>[ \t]*\\(\\sw+\\)?[ \t]*\\(\\sw+\\)?"
421;;            )
422;;          (1 font-lock-keyword-face)
423;;          (,(+ 1 kv-depth kf-depth 1)
424;;           (cond ((match-beginning 2)
425;;                  font-lock-type-face)
426;;                 ((match-beginning ,(+ 1 kv-depth 1))
427;;                  font-lock-function-name-face)
428;;                 )
429;;           nil t)
430;;          (,(+ 1 kv-depth kf-depth 1 1)
431;;           (cond ((match-beginning 2)
432;;                  font-lock-variable-name-face)
433;;                 )
434;;           nil t)))
435;;       ))
436;;   "Highlighted Semantic keywords.")
437
438;; (when (fboundp 'font-lock-add-keywords)
439;;   (font-lock-add-keywords 'emacs-lisp-mode
440;;                           semantic-fw-font-lock-keywords))
441
442
443(provide 'semantic/fw)
444
445;;; semantic/fw.el ends here
446