Remove some function declarations, no longer needed or correct
[bpt/emacs.git] / lisp / progmodes / verilog-mode.el
CommitLineData
ea89ff08 1;;; verilog-mode.el --- major mode for editing verilog source in Emacs
6341f357 2
ba318903 3;; Copyright (C) 1996-2014 Free Software Foundation, Inc.
6341f357 4
ea89ff08
WS
5;; Author: Michael McNamara <mac@verilog.com>
6;; Wilson Snyder <wsnyder@wsnyder.org>
a03c2342
WS
7;; http://www.verilog.com
8;; http://www.veripool.org
ea89ff08 9;; Created: 3 Jan 1996
6341f357
DN
10;; Keywords: languages
11
241760a3
SM
12;; Yoni Rabkin <yoni@rabkins.net> contacted the maintainer of this
13;; file on 19/3/2008, and the maintainer agreed that when a bug is
14;; filed in the Emacs bug reporting system against this file, a copy
15;; of the bug report be sent to the maintainer's email address.
16
60618039
DN
17;; This code supports Emacs 21.1 and later
18;; And XEmacs 21.1 and later
19;; Please do not make changes that break Emacs 21. Thanks!
20;;
21;;
22
637b4d38
GM
23;; This file is part of GNU Emacs.
24
b1fc2b50 25;; GNU Emacs is free software: you can redistribute it and/or modify
6341f357 26;; it under the terms of the GNU General Public License as published by
b1fc2b50
GM
27;; the Free Software Foundation, either version 3 of the License, or
28;; (at your option) any later version.
6341f357 29
637b4d38 30;; GNU Emacs is distributed in the hope that it will be useful,
6341f357
DN
31;; but WITHOUT ANY WARRANTY; without even the implied warranty of
32;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33;; GNU General Public License for more details.
34
35;; You should have received a copy of the GNU General Public License
b1fc2b50 36;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
6341f357
DN
37
38;;; Commentary:
39
6341f357
DN
40;; USAGE
41;; =====
42
ea89ff08
WS
43;; A major mode for editing Verilog and SystemVerilog HDL source code (IEEE
44;; 1364-2005 and IEEE 1800-2012 standards). When you have entered Verilog
45;; mode, you may get more info by pressing C-h m. You may also get online
46;; help describing various functions by: C-h f <Name of function you want
47;; described>
6341f357
DN
48
49;; KNOWN BUGS / BUG REPORTS
50;; =======================
51
ea89ff08
WS
52;; SystemVerilog is a rapidly evolving language, and hence this mode is
53;; under continuous development. Please report any issues to the issue
54;; tracker at
55;;
56;; http://www.veripool.org/verilog-mode
57;;
6341f357 58;; Please use verilog-submit-bug-report to submit a report; type C-c
ea89ff08 59;; C-b to invoke this and as a result we will have a much easier time
6341f357
DN
60;; of reproducing the bug you find, and hence fixing it.
61
62;; INSTALLING THE MODE
63;; ===================
64
65;; An older version of this mode may be already installed as a part of
66;; your environment, and one method of updating would be to update
60618039 67;; your Emacs environment. Sometimes this is difficult for local
6341f357
DN
68;; political/control reasons, and hence you can always install a
69;; private copy (or even a shared copy) which overrides the system
70;; default.
71
72;; You can get step by step help in installing this file by going to
73;; <http://www.verilog.com/emacs_install.html>
74
75;; The short list of installation instructions are: To set up
37ea4b9b 76;; automatic Verilog mode, put this file in your load path, and put
6341f357
DN
77;; the following in code (please un comment it first!) in your
78;; .emacs, or in your site's site-load.el
79
80; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
fd9ea9d3 81; (add-to-list 'auto-mode-alist '("\\.[ds]?vh?\\'" . verilog-mode))
6341f357 82
a03c2342
WS
83;; Be sure to examine at the help for verilog-auto, and the other
84;; verilog-auto-* functions for some major coding time savers.
85;;
6341f357 86;; If you want to customize Verilog mode to fit your needs better,
a03c2342 87;; you may add the below lines (the values of the variables presented
60618039 88;; here are the defaults). Note also that if you use an Emacs that
6341f357 89;; supports custom, it's probably better to use the custom menu to
9489a450 90;; edit these. If working as a member of a large team these settings
a03c2342
WS
91;; should be common across all users (in a site-start file), or set
92;; in Local Variables in every file. Otherwise, different people's
93;; AUTO expansion may result different whitespace changes.
6341f357 94;;
a03c2342
WS
95; ;; Enable syntax highlighting of **all** languages
96; (global-font-lock-mode t)
97;
6341f357
DN
98; ;; User customization for Verilog mode
99; (setq verilog-indent-level 3
100; verilog-indent-level-module 3
101; verilog-indent-level-declaration 3
102; verilog-indent-level-behavioral 3
103; verilog-indent-level-directive 1
104; verilog-case-indent 2
105; verilog-auto-newline t
106; verilog-auto-indent-on-newline t
107; verilog-tab-always-indent t
108; verilog-auto-endcomments t
109; verilog-minimum-comment-distance 40
110; verilog-indent-begin-after-if t
a3a8b002 111; verilog-auto-lineup 'declarations
6341f357 112; verilog-highlight-p1800-keywords nil
ea89ff08
WS
113; verilog-linter "my_lint_shell_command"
114; )
6341f357
DN
115
116;; \f
117
118;;; History:
37ea4b9b 119;;
7cb1c4d7 120;; See commit history at http://www.veripool.org/verilog-mode.html
60618039
DN
121;; (This section is required to appease checkdoc.)
122
6341f357
DN
123;;; Code:
124
6341f357 125;; This variable will always hold the version number of the mode
0f137a73 126(defconst verilog-mode-version "2013-11-05-78e66ba-vpo"
1418c701 127 "Version of this Verilog mode.")
b7f42161 128(defconst verilog-mode-release-emacs t
1418c701 129 "If non-nil, this version of Verilog mode was released with Emacs itself.")
6341f357
DN
130
131(defun verilog-version ()
132 "Inform caller of the version of this file."
133 (interactive)
7ea26faf 134 (message "Using verilog-mode version %s" verilog-mode-version))
6341f357
DN
135
136;; Insure we have certain packages, and deal with it if we don't
60618039 137;; Be sure to note which Emacs flavor and version added each feature.
6edb5716 138(eval-when-compile
7cb1c4d7 139 ;; Provide stuff if we are XEmacs
7ea26faf
DN
140 (when (featurep 'xemacs)
141 (condition-case nil
142 (require 'easymenu)
143 (error nil))
144 (condition-case nil
145 (require 'regexp-opt)
146 (error nil))
147 ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
148 (condition-case nil
149 (load "skeleton")
150 (error nil))
151 (condition-case nil
152 (if (fboundp 'when)
153 nil ;; fab
154 (defmacro when (cond &rest body)
155 (list 'if cond (cons 'progn body))))
156 (error nil))
157 (condition-case nil
158 (if (fboundp 'unless)
159 nil ;; fab
160 (defmacro unless (cond &rest body)
161 (cons 'if (cons cond (cons nil body)))))
162 (error nil))
163 (condition-case nil
164 (if (fboundp 'store-match-data)
165 nil ;; fab
0f137a73 166 (defmacro store-match-data (&rest _args) nil))
7ea26faf 167 (error nil))
7ea26faf
DN
168 (condition-case nil
169 (if (fboundp 'char-before)
170 nil ;; great
0f137a73 171 (defmacro char-before (&rest _body)
7ea26faf
DN
172 (char-after (1- (point)))))
173 (error nil))
9489a450
MM
174 (condition-case nil
175 (if (fboundp 'when)
176 nil ;; fab
177 (defsubst point-at-bol (&optional N)
178 (save-excursion (beginning-of-line N) (point))))
179 (error nil))
180 (condition-case nil
181 (if (fboundp 'when)
182 nil ;; fab
183 (defsubst point-at-eol (&optional N)
184 (save-excursion (end-of-line N) (point))))
185 (error nil))
7ea26faf
DN
186 (condition-case nil
187 (require 'custom)
188 (error nil))
189 (condition-case nil
190 (if (fboundp 'match-string-no-properties)
191 nil ;; great
192 (defsubst match-string-no-properties (num &optional string)
193 "Return string of text matched by last search, without text properties.
6341f357
DN
194NUM specifies which parenthesized expression in the last regexp.
195 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
196Zero means the entire text matched by the whole regexp or whole string.
197STRING should be given if the last search was by `string-match' on STRING."
7ea26faf
DN
198 (if (match-beginning num)
199 (if string
200 (let ((result
201 (substring string
202 (match-beginning num) (match-end num))))
203 (set-text-properties 0 (length result) nil result)
204 result)
205 (buffer-substring-no-properties (match-beginning num)
206 (match-end num)
60618039
DN
207 (current-buffer)))))
208 )
7ea26faf
DN
209 (error nil))
210 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
211 nil ;; We've got what we needed
212 ;; We have the old custom-library, hack around it!
0f137a73
SM
213 (defmacro defgroup (&rest _args) nil)
214 (defmacro customize (&rest _args)
7ea26faf 215 (message
37ea4b9b 216 "Sorry, Customize is not available with this version of Emacs"))
0f137a73 217 (defmacro defcustom (var value doc &rest _args)
7ea26faf
DN
218 `(defvar ,var ,value ,doc))
219 )
220 (if (fboundp 'defface)
221 nil ; great!
0f137a73 222 (defmacro defface (var values doc &rest _args)
7ea26faf
DN
223 `(make-face ,var))
224 )
6341f357 225
7ea26faf
DN
226 (if (and (featurep 'custom) (fboundp 'customize-group))
227 nil ;; We've got what we needed
228 ;; We have an intermediate custom-library, hack around it!
0f137a73 229 (defmacro customize-group (var &rest _args)
7ea26faf 230 `(customize ,var))
a03c2342
WS
231 )
232
233 (unless (boundp 'inhibit-point-motion-hooks)
234 (defvar inhibit-point-motion-hooks nil))
235 (unless (boundp 'deactivate-mark)
236 (defvar deactivate-mark nil))
237 )
238 ;;
7cb1c4d7
DN
239 ;; OK, do this stuff if we are NOT XEmacs:
240 (unless (featurep 'xemacs)
241 (unless (fboundp 'region-active-p)
242 (defmacro region-active-p ()
243 `(and transient-mark-mode mark-active))))
244 )
6341f357 245
6341f357
DN
246;; Provide a regular expression optimization routine, using regexp-opt
247;; if provided by the user's elisp libraries
248(eval-and-compile
60618039
DN
249 ;; The below were disabled when GNU Emacs 22 was released;
250 ;; perhaps some still need to be there to support Emacs 21.
7ea26faf
DN
251 (if (featurep 'xemacs)
252 (if (fboundp 'regexp-opt)
253 ;; regexp-opt is defined, does it take 3 or 2 arguments?
254 (if (fboundp 'function-max-args)
255 (let ((args (function-max-args `regexp-opt)))
256 (cond
257 ((eq args 3) ;; It takes 3
258 (condition-case nil ; Hide this defun from emacses
6341f357 259 ;with just a two input regexp
7ea26faf
DN
260 (defun verilog-regexp-opt (a b)
261 "Deal with differing number of required arguments for `regexp-opt'.
0f137a73
SM
262 Call `regexp-opt' on A and B."
263 (regexp-opt a b t))
7ea26faf
DN
264 (error nil))
265 )
266 ((eq args 2) ;; It takes 2
267 (defun verilog-regexp-opt (a b)
0f137a73 268 "Call `regexp-opt' on A and B."
7ea26faf
DN
269 (regexp-opt a b))
270 )
271 (t nil)))
272 ;; We can't tell; assume it takes 2
273 (defun verilog-regexp-opt (a b)
0f137a73 274 "Call `regexp-opt' on A and B."
7ea26faf
DN
275 (regexp-opt a b))
276 )
277 ;; There is no regexp-opt, provide our own
0f137a73 278 (defun verilog-regexp-opt (strings &optional paren _shy)
7ea26faf
DN
279 (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
280 (concat open (mapconcat 'regexp-quote strings "\\|") close)))
281 )
282 ;; Emacs.
283 (defalias 'verilog-regexp-opt 'regexp-opt)))
6341f357 284
a03c2342
WS
285(eval-and-compile
286 ;; Both xemacs and emacs
9489a450
MM
287 (condition-case nil
288 (require 'diff) ;; diff-command and diff-switches
289 (error nil))
290 (condition-case nil
291 (require 'compile) ;; compilation-error-regexp-alist-alist
292 (error nil))
a03c2342
WS
293 (condition-case nil
294 (unless (fboundp 'buffer-chars-modified-tick) ;; Emacs 22 added
295 (defmacro buffer-chars-modified-tick () (buffer-modified-tick)))
9489a450
MM
296 (error nil))
297 ;; Added in Emacs 24.1
298 (condition-case nil
299 (unless (fboundp 'prog-mode)
300 (define-derived-mode prog-mode fundamental-mode "Prog"))
a03c2342
WS
301 (error nil)))
302
38f584e9
DN
303(eval-when-compile
304 (defun verilog-regexp-words (a)
305 "Call 'regexp-opt' with word delimiters for the words A."
306 (concat "\\<" (verilog-regexp-opt a t) "\\>")))
a03c2342
WS
307(defun verilog-regexp-words (a)
308 "Call 'regexp-opt' with word delimiters for the words A."
309 ;; The FAQ references this function, so user LISP sometimes calls it
310 (concat "\\<" (verilog-regexp-opt a t) "\\>"))
6341f357 311
495ab0d5 312(defun verilog-easy-menu-filter (menu)
a3a8b002 313 "Filter `easy-menu-define' MENU to support new features."
495ab0d5
DN
314 (cond ((not (featurep 'xemacs))
315 menu) ;; GNU Emacs - passthru
0d26e0b6 316 ;; XEmacs doesn't support :help. Strip it.
495ab0d5
DN
317 ;; Recursively filter the a submenu
318 ((listp menu)
319 (mapcar 'verilog-easy-menu-filter menu))
320 ;; Look for [:help "blah"] and remove
321 ((vectorp menu)
322 (let ((i 0) (out []))
323 (while (< i (length menu))
324 (if (equal `:help (aref menu i))
325 (setq i (+ 2 i))
326 (setq out (vconcat out (vector (aref menu i)))
327 i (1+ i))))
328 out))
329 (t menu))) ;; Default - ok
330;;(verilog-easy-menu-filter
331;; `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
332;; "----" ["MB" nil :help "Help MB"]))
333
9489a450
MM
334(defun verilog-define-abbrev (table name expansion &optional hook)
335 "Filter `define-abbrev' TABLE NAME EXPANSION and call HOOK.
336Provides SYSTEM-FLAG in newer Emacs."
337 (condition-case nil
338 (define-abbrev table name expansion hook 0 t)
339 (error
340 (define-abbrev table name expansion hook))))
341
6341f357 342(defun verilog-customize ()
495ab0d5 343 "Customize variables and other settings used by Verilog-Mode."
6341f357
DN
344 (interactive)
345 (customize-group 'verilog-mode))
346
347(defun verilog-font-customize ()
495ab0d5 348 "Customize fonts used by Verilog-Mode."
6341f357 349 (interactive)
7ea26faf
DN
350 (if (fboundp 'customize-apropos)
351 (customize-apropos "font-lock-*" 'faces)))
6341f357 352
eaf7efe9
DN
353(defun verilog-booleanp (value)
354 "Return t if VALUE is boolean.
a3a8b002
DN
355This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
356This function may be removed when Emacs 21 is no longer supported."
eaf7efe9
DN
357 (or (equal value t) (equal value nil)))
358
a3a8b002
DN
359(defun verilog-insert-last-command-event ()
360 "Insert the `last-command-event'."
361 (insert (if (featurep 'xemacs)
362 ;; XEmacs 21.5 doesn't like last-command-event
363 last-command-char
364 ;; And GNU Emacs 22 has obsoleted last-command-char
365 last-command-event)))
366
9489a450
MM
367(defvar verilog-no-change-functions nil
368 "True if `after-change-functions' is disabled.
369Use of `syntax-ppss' may break, as ppss's cache may get corrupted.")
370
371(defvar verilog-in-hooks nil
372 "True when within a `verilog-run-hooks' block.")
373
374(defmacro verilog-run-hooks (&rest hooks)
375 "Run each hook in HOOKS using `run-hooks'.
376Set `verilog-in-hooks' during this time, to assist AUTO caches."
377 `(let ((verilog-in-hooks t))
378 (run-hooks ,@hooks)))
379
380(defun verilog-syntax-ppss (&optional pos)
381 (when verilog-no-change-functions
382 (if verilog-in-hooks
383 (verilog-scan-cache-flush)
384 ;; else don't let the AUTO code itself get away with flushing the cache,
385 ;; as that'll make things very slow
386 (backtrace)
387 (error "%s: Internal problem; use of syntax-ppss when cache may be corrupt"
388 (verilog-point-text))))
389 (if (fboundp 'syntax-ppss)
390 (syntax-ppss pos)
391 (parse-partial-sexp (point-min) (or pos (point)))))
d63b01e1 392
6341f357 393(defgroup verilog-mode nil
cf20dee0 394 "Major mode for Verilog source code."
8e788369 395 :version "22.2"
6341f357
DN
396 :group 'languages)
397
398; (defgroup verilog-mode-fonts nil
399; "Facilitates easy customization fonts used in Verilog source text"
400; :link '(customize-apropos "font-lock-*" 'faces)
401; :group 'verilog-mode)
402
403(defgroup verilog-mode-indent nil
37ea4b9b 404 "Customize indentation and highlighting of Verilog source text."
6341f357
DN
405 :group 'verilog-mode)
406
407(defgroup verilog-mode-actions nil
37ea4b9b 408 "Customize actions on Verilog source text."
6341f357
DN
409 :group 'verilog-mode)
410
411(defgroup verilog-mode-auto nil
37ea4b9b 412 "Customize AUTO actions when expanding Verilog source text."
6341f357
DN
413 :group 'verilog-mode)
414
a03c2342 415(defvar verilog-debug nil
47086495
WS
416 "Non-nil means enable debug messages for `verilog-mode' internals.")
417
418(defvar verilog-warn-fatal nil
419 "Non-nil means `verilog-warn-error' warnings are fatal `error's.")
a03c2342 420
6341f357
DN
421(defcustom verilog-linter
422 "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
fb7ada5f 423 "Unix program and arguments to call to run a lint checker on Verilog source.
6341f357
DN
424Depending on the `verilog-set-compile-command', this may be invoked when
425you type \\[compile]. When the compile completes, \\[next-error] will take
426you to the next lint error."
427 :type 'string
428 :group 'verilog-mode-actions)
60618039 429;; We don't mark it safe, as it's used as a shell command
6341f357
DN
430
431(defcustom verilog-coverage
432 "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
fb7ada5f 433 "Program and arguments to use to annotate for coverage Verilog source.
6341f357
DN
434Depending on the `verilog-set-compile-command', this may be invoked when
435you type \\[compile]. When the compile completes, \\[next-error] will take
436you to the next lint error."
437 :type 'string
438 :group 'verilog-mode-actions)
60618039 439;; We don't mark it safe, as it's used as a shell command
6341f357
DN
440
441(defcustom verilog-simulator
442 "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
fb7ada5f 443 "Program and arguments to use to interpret Verilog source.
6341f357
DN
444Depending on the `verilog-set-compile-command', this may be invoked when
445you type \\[compile]. When the compile completes, \\[next-error] will take
446you to the next lint error."
447 :type 'string
448 :group 'verilog-mode-actions)
60618039 449;; We don't mark it safe, as it's used as a shell command
6341f357
DN
450
451(defcustom verilog-compiler
452 "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
fb7ada5f 453 "Program and arguments to use to compile Verilog source.
6341f357
DN
454Depending on the `verilog-set-compile-command', this may be invoked when
455you type \\[compile]. When the compile completes, \\[next-error] will take
456you to the next lint error."
457 :type 'string
458 :group 'verilog-mode-actions)
60618039 459;; We don't mark it safe, as it's used as a shell command
6341f357 460
a03c2342
WS
461(defcustom verilog-preprocessor
462 ;; Very few tools give preprocessed output, so we'll default to Verilog-Perl
463 "vppreproc __FLAGS__ __FILE__"
fb7ada5f 464 "Program and arguments to use to preprocess Verilog source.
a03c2342
WS
465This is invoked with `verilog-preprocess', and depending on the
466`verilog-set-compile-command', may also be invoked when you type
467\\[compile]. When the compile completes, \\[next-error] will
468take you to the next lint error."
469 :type 'string
470 :group 'verilog-mode-actions)
471;; We don't mark it safe, as it's used as a shell command
472
473(defvar verilog-preprocess-history nil
474 "History for `verilog-preprocess'.")
475
6341f357
DN
476(defvar verilog-tool 'verilog-linter
477 "Which tool to use for building compiler-command.
a03c2342
WS
478Either nil, `verilog-linter, `verilog-compiler,
479`verilog-coverage, `verilog-preprocessor, or `verilog-simulator.
480Alternatively use the \"Choose Compilation Action\" menu. See
481`verilog-set-compile-command' for more information.")
6341f357
DN
482
483(defcustom verilog-highlight-translate-off nil
fb7ada5f 484 "Non-nil means background-highlight code excluded from translation.
6341f357
DN
485That is, all code between \"// synopsys translate_off\" and
486\"// synopsys translate_on\" is highlighted using a different background color
487\(face `verilog-font-lock-translate-off-face').
488
489Note: This will slow down on-the-fly fontification (and thus editing).
490
491Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
492entry \"Fontify Buffer\"). XEmacs: turn off and on font locking."
493 :type 'boolean
494 :group 'verilog-mode-indent)
60618039 495;; Note we don't use :safe, as that would break on Emacsen before 22.0.
eaf7efe9 496(put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
6341f357 497
a3a8b002 498(defcustom verilog-auto-lineup 'declarations
fb7ada5f 499 "Type of statements to lineup across multiple lines.
a3a8b002
DN
500If 'all' is selected, then all line ups described below are done.
501
bc8bc17d 502If 'declarations', then just declarations are lined up with any
a3a8b002
DN
503preceding declarations, taking into account widths and the like,
504so or example the code:
ea89ff08
WS
505 reg [31:0] a;
506 reg b;
a3a8b002 507would become
ea89ff08
WS
508 reg [31:0] a;
509 reg b;
a3a8b002
DN
510
511If 'assignment', then assignments are lined up with any preceding
512assignments, so for example the code
513 a_long_variable <= b + c;
514 d = e + f;
515would become
516 a_long_variable <= b + c;
517 d = e + f;
518
519In order to speed up editing, large blocks of statements are lined up
520only when a \\[verilog-pretty-expr] is typed; and large blocks of declarations
521are lineup only when \\[verilog-pretty-declarations] is typed."
522
523 :type '(radio (const :tag "Line up Assignments and Declarations" all)
524 (const :tag "Line up Assignment statements" assignments )
86a4c7ac 525 (const :tag "Line up Declarations" declarations)
a3a8b002
DN
526 (function :tag "Other"))
527 :group 'verilog-mode-indent )
47086495
WS
528(put 'verilog-auto-lineup 'safe-local-variable
529 '(lambda (x) (memq x '(nil all assignments declarations))))
a3a8b002 530
6341f357 531(defcustom verilog-indent-level 3
fb7ada5f 532 "Indentation of Verilog statements with respect to containing block."
6341f357
DN
533 :group 'verilog-mode-indent
534 :type 'integer)
60618039 535(put 'verilog-indent-level 'safe-local-variable 'integerp)
6341f357
DN
536
537(defcustom verilog-indent-level-module 3
fb7ada5f 538 "Indentation of Module level Verilog statements (eg always, initial).
6341f357
DN
539Set to 0 to get initial and always statements lined up on the left side of
540your screen."
541 :group 'verilog-mode-indent
542 :type 'integer)
60618039 543(put 'verilog-indent-level-module 'safe-local-variable 'integerp)
6341f357
DN
544
545(defcustom verilog-indent-level-declaration 3
fb7ada5f 546 "Indentation of declarations with respect to containing block.
6341f357
DN
547Set to 0 to get them list right under containing block."
548 :group 'verilog-mode-indent
549 :type 'integer)
60618039 550(put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
6341f357
DN
551
552(defcustom verilog-indent-declaration-macros nil
fb7ada5f 553 "How to treat macro expansions in a declaration.
6341f357
DN
554If nil, indent as:
555 input [31:0] a;
556 input `CP;
557 output c;
558If non nil, treat as:
559 input [31:0] a;
560 input `CP ;
561 output c;"
562 :group 'verilog-mode-indent
563 :type 'boolean)
eaf7efe9 564(put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
6341f357
DN
565
566(defcustom verilog-indent-lists t
fb7ada5f 567 "How to treat indenting items in a list.
6341f357
DN
568If t (the default), indent as:
569 always @( posedge a or
570 reset ) begin
571
572If nil, treat as:
573 always @( posedge a or
574 reset ) begin"
575 :group 'verilog-mode-indent
576 :type 'boolean)
eaf7efe9 577(put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
6341f357
DN
578
579(defcustom verilog-indent-level-behavioral 3
fb7ada5f 580 "Absolute indentation of first begin in a task or function block.
6341f357
DN
581Set to 0 to get such code to start at the left side of the screen."
582 :group 'verilog-mode-indent
583 :type 'integer)
60618039 584(put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
6341f357
DN
585
586(defcustom verilog-indent-level-directive 1
fb7ada5f 587 "Indentation to add to each level of `ifdef declarations.
6341f357
DN
588Set to 0 to have all directives start at the left side of the screen."
589 :group 'verilog-mode-indent
590 :type 'integer)
60618039 591(put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
6341f357
DN
592
593(defcustom verilog-cexp-indent 2
fb7ada5f 594 "Indentation of Verilog statements split across lines."
6341f357
DN
595 :group 'verilog-mode-indent
596 :type 'integer)
60618039 597(put 'verilog-cexp-indent 'safe-local-variable 'integerp)
6341f357
DN
598
599(defcustom verilog-case-indent 2
fb7ada5f 600 "Indentation for case statements."
6341f357
DN
601 :group 'verilog-mode-indent
602 :type 'integer)
60618039 603(put 'verilog-case-indent 'safe-local-variable 'integerp)
6341f357
DN
604
605(defcustom verilog-auto-newline t
47086495 606 "Non-nil means automatically newline after semicolons."
6341f357
DN
607 :group 'verilog-mode-indent
608 :type 'boolean)
eaf7efe9 609(put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
6341f357
DN
610
611(defcustom verilog-auto-indent-on-newline t
47086495 612 "Non-nil means automatically indent line after newline."
6341f357
DN
613 :group 'verilog-mode-indent
614 :type 'boolean)
eaf7efe9 615(put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
6341f357
DN
616
617(defcustom verilog-tab-always-indent t
47086495 618 "Non-nil means TAB should always re-indent the current line.
37ea4b9b 619A nil value means TAB will only reindent when at the beginning of the line."
6341f357
DN
620 :group 'verilog-mode-indent
621 :type 'boolean)
eaf7efe9 622(put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
6341f357
DN
623
624(defcustom verilog-tab-to-comment nil
47086495 625 "Non-nil means TAB moves to the right hand column in preparation for a comment."
6341f357
DN
626 :group 'verilog-mode-actions
627 :type 'boolean)
eaf7efe9 628(put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
6341f357
DN
629
630(defcustom verilog-indent-begin-after-if t
47086495 631 "Non-nil means indent begin statements following if, else, while, etc.
6341f357
DN
632Otherwise, line them up."
633 :group 'verilog-mode-indent
60618039 634 :type 'boolean)
eaf7efe9 635(put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
6341f357 636
6341f357 637(defcustom verilog-align-ifelse nil
47086495 638 "Non-nil means align `else' under matching `if'.
6341f357
DN
639Otherwise else is lined up with first character on line holding matching if."
640 :group 'verilog-mode-indent
60618039 641 :type 'boolean)
eaf7efe9 642(put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
6341f357
DN
643
644(defcustom verilog-minimum-comment-distance 10
fb7ada5f 645 "Minimum distance (in lines) between begin and end required before a comment.
6341f357 646Setting this variable to zero results in every end acquiring a comment; the
37ea4b9b 647default avoids too many redundant comments in tight quarters."
6341f357
DN
648 :group 'verilog-mode-indent
649 :type 'integer)
60618039 650(put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
6341f357 651
6341f357 652(defcustom verilog-highlight-p1800-keywords nil
47086495 653 "Non-nil means highlight words newly reserved by IEEE-1800.
60618039
DN
654These will appear in `verilog-font-lock-p1800-face' in order to gently
655suggest changing where these words are used as variables to something else.
37ea4b9b 656A nil value means highlight these words as appropriate for the SystemVerilog
60618039 657IEEE-1800 standard. Note that changing this will require restarting Emacs
37ea4b9b 658to see the effect as font color choices are cached by Emacs."
6341f357
DN
659 :group 'verilog-mode-indent
660 :type 'boolean)
eaf7efe9 661(put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
6341f357 662
a1ebd734 663(defcustom verilog-highlight-grouping-keywords nil
ea89ff08 664 "Non-nil means highlight grouping keywords more dramatically.
a3a8b002
DN
665If false, these words are in the `font-lock-type-face'; if True then they are in
666`verilog-font-lock-ams-face'. Some find that special highlighting on these
a1ebd734
DN
667grouping constructs allow the structure of the code to be understood at a glance."
668 :group 'verilog-mode-indent
669 :type 'boolean)
b1d0fc86 670(put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
a1ebd734 671
a03c2342 672(defcustom verilog-highlight-modules nil
47086495 673 "Non-nil means highlight module statements for `verilog-load-file-at-point'.
a03c2342
WS
674When true, mousing over module names will allow jumping to the
675module definition. If false, this is not supported. Setting
676this is experimental, and may lead to bad performance."
677 :group 'verilog-mode-indent
678 :type 'boolean)
679(put 'verilog-highlight-modules 'safe-local-variable 'verilog-booleanp)
680
681(defcustom verilog-highlight-includes t
47086495 682 "Non-nil means highlight module statements for `verilog-load-file-at-point'.
a03c2342
WS
683When true, mousing over include file names will allow jumping to the
684file referenced. If false, this is not supported."
685 :group 'verilog-mode-indent
686 :type 'boolean)
687(put 'verilog-highlight-includes 'safe-local-variable 'verilog-booleanp)
688
9489a450 689(defcustom verilog-auto-declare-nettype nil
fb7ada5f 690 "Non-nil specifies the data type to use with `verilog-auto-input' etc.
9489a450
MM
691Set this to \"wire\" if the Verilog code uses \"`default_nettype
692none\". Note using `default_nettype none isn't recommended practice; this
693mode is experimental."
47086495 694 :version "24.1" ;; rev670
9489a450
MM
695 :group 'verilog-mode-actions
696 :type 'boolean)
697(put 'verilog-auto-declare-nettype 'safe-local-variable `stringp)
698
699(defcustom verilog-auto-wire-type nil
fb7ada5f 700 "Non-nil specifies the data type to use with `verilog-auto-wire' etc.
9489a450 701Set this to \"logic\" for SystemVerilog code, or use `verilog-auto-logic'."
47086495 702 :version "24.1" ;; rev673
9489a450
MM
703 :group 'verilog-mode-actions
704 :type 'boolean)
705(put 'verilog-auto-wire-type 'safe-local-variable `stringp)
706
6341f357 707(defcustom verilog-auto-endcomments t
47086495 708 "Non-nil means insert a comment /* ... */ after 'end's.
6341f357
DN
709The name of the function or case will be set between the braces."
710 :group 'verilog-mode-actions
60618039 711 :type 'boolean)
eaf7efe9 712(put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
6341f357 713
9489a450 714(defcustom verilog-auto-delete-trailing-whitespace nil
47086495
WS
715 "Non-nil means to `delete-trailing-whitespace' in `verilog-auto'."
716 :version "24.1" ;; rev703
9489a450
MM
717 :group 'verilog-mode-actions
718 :type 'boolean)
719(put 'verilog-auto-delete-trailing-whitespace 'safe-local-variable 'verilog-booleanp)
720
14862301 721(defcustom verilog-auto-ignore-concat nil
47086495 722 "Non-nil means ignore signals in {...} concatenations for AUTOWIRE etc.
14862301
SM
723This will exclude signals referenced as pin connections in {...}
724from AUTOWIRE, AUTOOUTPUT and friends. This flag should be set
725for backward compatibility only and not set in new designs; it
726may be removed in future versions."
727 :group 'verilog-mode-actions
728 :type 'boolean)
729(put 'verilog-auto-ignore-concat 'safe-local-variable 'verilog-booleanp)
730
6341f357 731(defcustom verilog-auto-read-includes nil
47086495 732 "Non-nil means to automatically read includes before AUTOs.
6341f357
DN
733This will do a `verilog-read-defines' and `verilog-read-includes' before
734each AUTO expansion. This makes it easier to embed defines and includes,
735but can result in very slow reading times if there are many or large
736include files."
737 :group 'verilog-mode-actions
60618039 738 :type 'boolean)
eaf7efe9 739(put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
6341f357
DN
740
741(defcustom verilog-auto-save-policy nil
fb7ada5f 742 "Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
6341f357
DN
743A value of `force' will always do a \\[verilog-auto] automatically if
744needed on every save. A value of `detect' will do \\[verilog-auto]
745automatically when it thinks necessary. A value of `ask' will query the
746user when it thinks updating is needed.
747
748You should not rely on the 'ask or 'detect policies, they are safeguards
749only. They do not detect when AUTOINSTs need to be updated because a
750sub-module's port list has changed."
751 :group 'verilog-mode-actions
752 :type '(choice (const nil) (const ask) (const detect) (const force)))
753
754(defcustom verilog-auto-star-expand t
47086495
WS
755 "Non-nil means to expand SystemVerilog .* instance ports.
756They will be expanded in the same way as if there was an AUTOINST in the
6341f357
DN
757instantiation. See also `verilog-auto-star' and `verilog-auto-star-save'."
758 :group 'verilog-mode-actions
759 :type 'boolean)
eaf7efe9 760(put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
6341f357
DN
761
762(defcustom verilog-auto-star-save nil
47086495 763 "Non-nil means save to disk SystemVerilog .* instance expansions.
37ea4b9b
JB
764A nil value indicates direct connections will be removed before saving.
765Only meaningful to those created due to `verilog-auto-star-expand' being set.
6341f357
DN
766
767Instead of setting this, you may want to use /*AUTOINST*/, which will
768always be saved."
769 :group 'verilog-mode-actions
770 :type 'boolean)
eaf7efe9 771(put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
6341f357
DN
772
773(defvar verilog-auto-update-tick nil
774 "Modification tick at which autos were last performed.")
775
776(defvar verilog-auto-last-file-locals nil
777 "Text from file-local-variables during last evaluation.")
778
9489a450 779(defvar verilog-diff-function 'verilog-diff-report
fb7ada5f 780 "Function to run when `verilog-diff-auto' detects differences.
9489a450
MM
781Function takes three arguments, the original buffer, the
782difference buffer, and the point in original buffer with the
783first difference.")
784
a3a8b002
DN
785;;; Compile support
786(require 'compile)
d88782c3 787(defvar verilog-error-regexp-added nil)
a03c2342 788
d88782c3
DN
789(defvar verilog-error-regexp-emacs-alist
790 '(
791 (verilog-xl-1
792 "\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
793 (verilog-xl-2
794 "([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 3)
795 (verilog-IES
a03c2342 796 ".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)" 2 3)
d88782c3
DN
797 (verilog-surefire-1
798 "[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
799 (verilog-surefire-2
800 "\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\),\\s-+\\(line \\)?\\([0-9]+\\):" 2 4 )
801 (verilog-verbose
802 "\
803\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
804:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
805 (verilog-xsim
806 "\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
807 (verilog-vcs-1
808 "\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
809 (verilog-vcs-2
810 "Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
811 (verilog-vcs-3
812 "\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
813 (verilog-vcs-4
814 "syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
815 (verilog-verilator
816 "%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
817 (verilog-leda
a03c2342 818 "^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 2)
d88782c3 819 )
a03c2342
WS
820 "List of regexps for Verilog compilers.
821See `compilation-error-regexp-alist' for the formatting. For Emacs 22+.")
822
823(defvar verilog-error-regexp-xemacs-alist
824 ;; Emacs form is '((v-tool "re" 1 2) ...)
825 ;; XEmacs form is '(verilog ("re" 1 2) ...)
0d26e0b6 826 ;; So we can just map from Emacs to XEmacs
a03c2342
WS
827 (cons 'verilog (mapcar 'cdr verilog-error-regexp-emacs-alist))
828 "List of regexps for Verilog compilers.
829See `compilation-error-regexp-alist-alist' for the formatting. For XEmacs.")
6341f357
DN
830
831(defvar verilog-error-font-lock-keywords
832 '(
a03c2342
WS
833 ;; verilog-xl-1
834 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
835 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
836 ;; verilog-xl-2
837 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 bold t)
838 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 3 bold t)
839 ;; verilog-IES (nc-verilog)
840 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
841 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 3 bold t)
842 ;; verilog-surefire-1
6341f357
DN
843 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
844 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
a03c2342 845 ;; verilog-surefire-2
6341f357
DN
846 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
847 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
a03c2342 848 ;; verilog-verbose
6341f357
DN
849 ("\
850\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
851:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
852 ("\
853\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
854:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
a03c2342 855 ;; verilog-vcs-1
6341f357
DN
856 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
857 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
a03c2342 858 ;; verilog-vcs-2
6341f357
DN
859 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
860 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
a03c2342 861 ;; verilog-vcs-3
6341f357
DN
862 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
863 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
a03c2342 864 ;; verilog-vcs-4
6341f357
DN
865 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
866 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
a03c2342
WS
867 ;; verilog-verilator
868 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
869 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
870 ;; verilog-leda
871 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 bold t)
872 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 2 bold t)
6341f357 873 )
fb7ada5f 874 "Keywords to also highlight in Verilog *compilation* buffers.
a03c2342 875Only used in XEmacs; GNU Emacs uses `verilog-error-regexp-emacs-alist'.")
6341f357
DN
876
877(defcustom verilog-library-flags '("")
fb7ada5f 878 "List of standard Verilog arguments to use for /*AUTOINST*/.
6341f357
DN
879These arguments are used to find files for `verilog-auto', and match
880the flags accepted by a standard Verilog-XL simulator.
881
882 -f filename Reads more `verilog-library-flags' from the filename.
883 +incdir+dir Adds the directory to `verilog-library-directories'.
884 -Idir Adds the directory to `verilog-library-directories'.
885 -y dir Adds the directory to `verilog-library-directories'.
886 +libext+.v Adds the extensions to `verilog-library-extensions'.
887 -v filename Adds the filename to `verilog-library-files'.
888
889 filename Adds the filename to `verilog-library-files'.
890 This is not recommended, -v is a better choice.
891
892You might want these defined in each file; put at the *END* of your file
893something like:
894
895 // Local Variables:
896 // verilog-library-flags:(\"-y dir -y otherdir\")
897 // End:
898
899Verilog-mode attempts to detect changes to this local variable, but they
37ea4b9b 900are only insured to be correct when the file is first visited. Thus if you
6341f357
DN
901have problems, use \\[find-alternate-file] RET to have these take effect.
902
903See also the variables mentioned above."
904 :group 'verilog-mode-auto
905 :type '(repeat string))
60618039 906(put 'verilog-library-flags 'safe-local-variable 'listp)
6341f357
DN
907
908(defcustom verilog-library-directories '(".")
fb7ada5f 909 "List of directories when looking for files for /*AUTOINST*/.
6341f357
DN
910The directory may be relative to the current file, or absolute.
911Environment variables are also expanded in the directory names.
912Having at least the current directory is a good idea.
913
914You might want these defined in each file; put at the *END* of your file
915something like:
916
917 // Local Variables:
918 // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
919 // End:
920
921Verilog-mode attempts to detect changes to this local variable, but they
37ea4b9b 922are only insured to be correct when the file is first visited. Thus if you
6341f357
DN
923have problems, use \\[find-alternate-file] RET to have these take effect.
924
925See also `verilog-library-flags', `verilog-library-files'
926and `verilog-library-extensions'."
927 :group 'verilog-mode-auto
928 :type '(repeat file))
60618039 929(put 'verilog-library-directories 'safe-local-variable 'listp)
6341f357
DN
930
931(defcustom verilog-library-files '()
fb7ada5f 932 "List of files to search for modules.
60618039 933AUTOINST will use this when it needs to resolve a module name.
6341f357
DN
934This is a complete path, usually to a technology file with many standard
935cells defined in it.
936
937You might want these defined in each file; put at the *END* of your file
938something like:
939
940 // Local Variables:
941 // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
942 // End:
943
944Verilog-mode attempts to detect changes to this local variable, but they
37ea4b9b 945are only insured to be correct when the file is first visited. Thus if you
6341f357
DN
946have problems, use \\[find-alternate-file] RET to have these take effect.
947
948See also `verilog-library-flags', `verilog-library-directories'."
949 :group 'verilog-mode-auto
950 :type '(repeat directory))
60618039 951(put 'verilog-library-files 'safe-local-variable 'listp)
6341f357 952
7cb1c4d7 953(defcustom verilog-library-extensions '(".v" ".sv")
fb7ada5f 954 "List of extensions to use when looking for files for /*AUTOINST*/.
6341f357
DN
955See also `verilog-library-flags', `verilog-library-directories'."
956 :type '(repeat string)
957 :group 'verilog-mode-auto)
60618039 958(put 'verilog-library-extensions 'safe-local-variable 'listp)
6341f357
DN
959
960(defcustom verilog-active-low-regexp nil
ea89ff08 961 "If true, treat signals matching this regexp as active low.
6341f357
DN
962This is used for AUTORESET and AUTOTIEOFF. For proper behavior,
963you will probably also need `verilog-auto-reset-widths' set."
964 :group 'verilog-mode-auto
a931698a 965 :type '(choice (const nil) regexp))
60618039 966(put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
6341f357
DN
967
968(defcustom verilog-auto-sense-include-inputs nil
47086495 969 "Non-nil means AUTOSENSE should include all inputs.
6341f357
DN
970If nil, only inputs that are NOT output signals in the same block are
971included."
60618039
DN
972 :group 'verilog-mode-auto
973 :type 'boolean)
eaf7efe9 974(put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
6341f357
DN
975
976(defcustom verilog-auto-sense-defines-constant nil
47086495 977 "Non-nil means AUTOSENSE should assume all defines represent constants.
6341f357
DN
978When true, the defines will not be included in sensitivity lists. To
979maintain compatibility with other sites, this should be set at the bottom
37ea4b9b 980of each Verilog file that requires it, rather than being set globally."
60618039
DN
981 :group 'verilog-mode-auto
982 :type 'boolean)
eaf7efe9 983(put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
6341f357 984
9489a450 985(defcustom verilog-auto-reset-blocking-in-non t
47086495
WS
986 "Non-nil means AUTORESET will reset blocking statements.
987When true, AUTORESET will reset in blocking statements those
988signals which were assigned with blocking assignments (=) even in
989a block with non-blocking assignments (<=).
301b181a 990
9489a450
MM
991If nil, all blocking assigned signals are ignored when any
992non-blocking assignment is in the AUTORESET block. This allows
993blocking assignments to be used for temporary values and not have
994those temporaries reset. See example in `verilog-auto-reset'."
47086495 995 :version "24.1" ;; rev718
9489a450
MM
996 :type 'boolean
997 :group 'verilog-mode-auto)
998(put 'verilog-auto-reset-blocking-in-non 'safe-local-variable 'verilog-booleanp)
999
6341f357 1000(defcustom verilog-auto-reset-widths t
47086495 1001 "True means AUTORESET should determine the width of signals.
6341f357
DN
1002This is then used to set the width of the zero (32'h0 for example). This
1003is required by some lint tools that aren't smart enough to ignore widths of
ea89ff08 1004the constant zero. This may result in ugly code when parameters determine
47086495
WS
1005the MSB or LSB of a signal inside an AUTORESET.
1006
1007If nil, AUTORESET uses \"0\" as the constant.
1008
1009If 'unbased', AUTORESET used the unbased unsized literal \"'0\"
1010as the constant. This setting is strongly recommended for
1011SystemVerilog designs."
6341f357
DN
1012 :type 'boolean
1013 :group 'verilog-mode-auto)
47086495
WS
1014(put 'verilog-auto-reset-widths 'safe-local-variable
1015 '(lambda (x) (memq x '(nil t unbased))))
6341f357
DN
1016
1017(defcustom verilog-assignment-delay ""
fb7ada5f 1018 "Text used for delays in delayed assignments. Add a trailing space if set."
60618039
DN
1019 :group 'verilog-mode-auto
1020 :type 'string)
1021(put 'verilog-assignment-delay 'safe-local-variable 'stringp)
6341f357 1022
a3a8b002 1023(defcustom verilog-auto-arg-sort nil
47086495 1024 "Non-nil means AUTOARG signal names will be sorted, not in declaration order.
14862301
SM
1025Declaration order is advantageous with order based instantiations
1026and is the default for backward compatibility. Sorted order
1027reduces changes when declarations are moved around in a file, and
9489a450
MM
1028it's bad practice to rely on order based instantiations anyhow.
1029
1030See also `verilog-auto-inst-sort'."
a3a8b002
DN
1031 :group 'verilog-mode-auto
1032 :type 'boolean)
1033(put 'verilog-auto-arg-sort 'safe-local-variable 'verilog-booleanp)
1034
a03c2342 1035(defcustom verilog-auto-inst-dot-name nil
47086495 1036 "Non-nil means when creating ports with AUTOINST, use .name syntax.
a03c2342
WS
1037This will use \".port\" instead of \".port(port)\" when possible.
1038This is only legal in SystemVerilog files, and will confuse older
1039simulators. Setting `verilog-auto-inst-vector' to nil may also
1040be desirable to increase how often .name will be used."
1041 :group 'verilog-mode-auto
1042 :type 'boolean)
1043(put 'verilog-auto-inst-dot-name 'safe-local-variable 'verilog-booleanp)
1044
4c5e69c6 1045(defcustom verilog-auto-inst-param-value nil
47086495 1046 "Non-nil means AUTOINST will replace parameters with the parameter value.
4c5e69c6
DN
1047If nil, leave parameters as symbolic names.
1048
1049Parameters must be in Verilog 2001 format #(...), and if a parameter is not
1050listed as such there (as when the default value is acceptable), it will not
1051be replaced, and will remain symbolic.
1052
1053For example, imagine a submodule uses parameters to declare the size of its
47086495 1054inputs. This is then used by an upper module:
4c5e69c6 1055
a03c2342 1056 module InstModule (o,i);
4c5e69c6
DN
1057 parameter WIDTH;
1058 input [WIDTH-1:0] i;
1059 endmodule
1060
1061 module ExampInst;
1062 InstModule
ea89ff08 1063 #(.PARAM(10))
4c5e69c6
DN
1064 instName
1065 (/*AUTOINST*/
1066 .i (i[PARAM-1:0]));
1067
1068Note even though PARAM=10, the AUTOINST has left the parameter as a
1069symbolic name. If `verilog-auto-inst-param-value' is set, this will
1070instead expand to:
1071
1072 module ExampInst;
1073 InstModule
ea89ff08 1074 #(.PARAM(10))
4c5e69c6
DN
1075 instName
1076 (/*AUTOINST*/
1077 .i (i[9:0]));"
1078 :group 'verilog-mode-auto
1079 :type 'boolean)
7cb1c4d7 1080(put 'verilog-auto-inst-param-value 'safe-local-variable 'verilog-booleanp)
4c5e69c6 1081
9489a450 1082(defcustom verilog-auto-inst-sort nil
47086495 1083 "Non-nil means AUTOINST signals will be sorted, not in declaration order.
9489a450
MM
1084Also affects AUTOINSTPARAM. Declaration order is the default for
1085backward compatibility, and as some teams prefer signals that are
1086declared together to remain together. Sorted order reduces
1087changes when declarations are moved around in a file.
1088
1089See also `verilog-auto-arg-sort'."
47086495 1090 :version "24.1" ;; rev688
9489a450
MM
1091 :group 'verilog-mode-auto
1092 :type 'boolean)
1093(put 'verilog-auto-inst-sort 'safe-local-variable 'verilog-booleanp)
1094
6341f357 1095(defcustom verilog-auto-inst-vector t
47086495 1096 "Non-nil means when creating default ports with AUTOINST, use bus subscripts.
6341f357
DN
1097If nil, skip the subscript when it matches the entire bus as declared in
1098the module (AUTOWIRE signals always are subscripted, you must manually
37ea4b9b
JB
1099declare the wire to have the subscripts removed.) Setting this to nil may
1100speed up some simulators, but is less general and harder to read, so avoid."
6341f357 1101 :group 'verilog-mode-auto
60618039 1102 :type 'boolean)
eaf7efe9 1103(put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
6341f357
DN
1104
1105(defcustom verilog-auto-inst-template-numbers nil
fb7ada5f 1106 "If true, when creating templated ports with AUTOINST, add a comment.
9489a450
MM
1107
1108If t, the comment will add the line number of the template that
1109was used for that port declaration. This setting is suggested
1110only for debugging use, as regular use may cause a large numbers
1111of merge conflicts.
1112
1113If 'lhs', the comment will show the left hand side of the
1114AUTO_TEMPLATE rule that is matched. This is less precise than
1115numbering (t) when multiple rules have the same pin name, but
1116won't merge conflict."
6341f357 1117 :group 'verilog-mode-auto
9489a450
MM
1118 :type '(choice (const nil) (const t) (const lhs)))
1119(put 'verilog-auto-inst-template-numbers 'safe-local-variable
1120 '(lambda (x) (memq x '(nil t lhs))))
6341f357 1121
4c5e69c6 1122(defcustom verilog-auto-inst-column 40
fb7ada5f 1123 "Indent-to column number for net name part of AUTOINST created pin."
4c5e69c6
DN
1124 :group 'verilog-mode-indent
1125 :type 'integer)
1126(put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
6341f357 1127
179f044b 1128(defcustom verilog-auto-inst-interfaced-ports nil
47086495 1129 "Non-nil means include interfaced ports in AUTOINST expansions."
bc8bc17d 1130 :version "24.3" ;; rev773, default change rev815
47086495 1131 :group 'verilog-mode-auto
bc8bc17d 1132 :type 'boolean)
47086495
WS
1133(put 'verilog-auto-inst-interfaced-ports 'safe-local-variable 'verilog-booleanp)
1134
6341f357 1135(defcustom verilog-auto-input-ignore-regexp nil
ea89ff08 1136 "If non-nil, when creating AUTOINPUT, ignore signals matching this regexp.
6341f357
DN
1137See the \\[verilog-faq] for examples on using this."
1138 :group 'verilog-mode-auto
a931698a 1139 :type '(choice (const nil) regexp))
60618039 1140(put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
6341f357
DN
1141
1142(defcustom verilog-auto-inout-ignore-regexp nil
ea89ff08 1143 "If non-nil, when creating AUTOINOUT, ignore signals matching this regexp.
6341f357
DN
1144See the \\[verilog-faq] for examples on using this."
1145 :group 'verilog-mode-auto
a931698a 1146 :type '(choice (const nil) regexp))
60618039 1147(put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
6341f357
DN
1148
1149(defcustom verilog-auto-output-ignore-regexp nil
ea89ff08 1150 "If non-nil, when creating AUTOOUTPUT, ignore signals matching this regexp.
6341f357
DN
1151See the \\[verilog-faq] for examples on using this."
1152 :group 'verilog-mode-auto
a931698a 1153 :type '(choice (const nil) regexp))
60618039 1154(put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
6341f357 1155
47086495
WS
1156(defcustom verilog-auto-template-warn-unused nil
1157 "Non-nil means report warning if an AUTO_TEMPLATE line is not used.
1158This feature is not supported before Emacs 21.1 or XEmacs 21.4."
bc8bc17d 1159 :version "24.3" ;;rev787
47086495
WS
1160 :group 'verilog-mode-auto
1161 :type 'boolean)
1162(put 'verilog-auto-template-warn-unused 'safe-local-variable 'verilog-booleanp)
1163
9489a450 1164(defcustom verilog-auto-tieoff-declaration "wire"
47086495
WS
1165 "Data type used for the declaration for AUTOTIEOFF.
1166If \"wire\" then create a wire, if \"assign\" create an
1167assignment, else the data type for variable creation."
1168 :version "24.1" ;; rev713
9489a450
MM
1169 :group 'verilog-mode-auto
1170 :type 'string)
1171(put 'verilog-auto-tieoff-declaration 'safe-local-variable 'stringp)
1172
a03c2342 1173(defcustom verilog-auto-tieoff-ignore-regexp nil
ea89ff08 1174 "If non-nil, when creating AUTOTIEOFF, ignore signals matching this regexp.
a03c2342
WS
1175See the \\[verilog-faq] for examples on using this."
1176 :group 'verilog-mode-auto
a931698a 1177 :type '(choice (const nil) regexp))
a03c2342
WS
1178(put 'verilog-auto-tieoff-ignore-regexp 'safe-local-variable 'stringp)
1179
6341f357 1180(defcustom verilog-auto-unused-ignore-regexp nil
ea89ff08 1181 "If non-nil, when creating AUTOUNUSED, ignore signals matching this regexp.
6341f357
DN
1182See the \\[verilog-faq] for examples on using this."
1183 :group 'verilog-mode-auto
a931698a 1184 :type '(choice (const nil) regexp))
60618039 1185(put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
6341f357 1186
ea89ff08
WS
1187(defcustom verilog-case-fold t
1188 "Non-nil means `verilog-mode' regexps should ignore case.
1189This variable is t for backward compatibility; nil is suggested."
d64da4b7 1190 :version "24.4"
ea89ff08
WS
1191 :group 'verilog-mode
1192 :type 'boolean)
1193(put 'verilog-case-fold 'safe-local-variable 'verilog-booleanp)
1194
6341f357 1195(defcustom verilog-typedef-regexp nil
fb7ada5f 1196 "If non-nil, regular expression that matches Verilog-2001 typedef names.
ea89ff08
WS
1197For example, \"_t$\" matches typedefs named with _t, as in the C language.
1198See also `verilog-case-fold'."
6341f357 1199 :group 'verilog-mode-auto
a931698a 1200 :type '(choice (const nil) regexp))
60618039 1201(put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
6341f357
DN
1202
1203(defcustom verilog-mode-hook 'verilog-set-compile-command
fb7ada5f 1204 "Hook run after Verilog mode is loaded."
6341f357
DN
1205 :type 'hook
1206 :group 'verilog-mode)
1207
1208(defcustom verilog-auto-hook nil
fb7ada5f 1209 "Hook run after `verilog-mode' updates AUTOs."
60618039
DN
1210 :group 'verilog-mode-auto
1211 :type 'hook)
6341f357
DN
1212
1213(defcustom verilog-before-auto-hook nil
fb7ada5f 1214 "Hook run before `verilog-mode' updates AUTOs."
60618039
DN
1215 :group 'verilog-mode-auto
1216 :type 'hook)
6341f357
DN
1217
1218(defcustom verilog-delete-auto-hook nil
fb7ada5f 1219 "Hook run after `verilog-mode' deletes AUTOs."
60618039
DN
1220 :group 'verilog-mode-auto
1221 :type 'hook)
6341f357
DN
1222
1223(defcustom verilog-before-delete-auto-hook nil
fb7ada5f 1224 "Hook run before `verilog-mode' deletes AUTOs."
60618039
DN
1225 :group 'verilog-mode-auto
1226 :type 'hook)
6341f357
DN
1227
1228(defcustom verilog-getopt-flags-hook nil
fb7ada5f 1229 "Hook run after `verilog-getopt-flags' determines the Verilog option lists."
60618039
DN
1230 :group 'verilog-mode-auto
1231 :type 'hook)
6341f357
DN
1232
1233(defcustom verilog-before-getopt-flags-hook nil
fb7ada5f 1234 "Hook run before `verilog-getopt-flags' determines the Verilog option lists."
60618039
DN
1235 :group 'verilog-mode-auto
1236 :type 'hook)
6341f357 1237
47086495
WS
1238(defcustom verilog-before-save-font-hook nil
1239 "Hook run before `verilog-save-font-mods' removes highlighting."
bc8bc17d 1240 :version "24.3" ;;rev735
47086495
WS
1241 :group 'verilog-mode-auto
1242 :type 'hook)
1243
1244(defcustom verilog-after-save-font-hook nil
1245 "Hook run after `verilog-save-font-mods' restores highlighting."
bc8bc17d 1246 :version "24.3" ;;rev735
47086495
WS
1247 :group 'verilog-mode-auto
1248 :type 'hook)
1249
6341f357
DN
1250(defvar verilog-imenu-generic-expression
1251 '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
1252 ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
37ea4b9b 1253 "Imenu expression for Verilog mode. See `imenu-generic-expression'.")
6341f357
DN
1254
1255;;
1256;; provide a verilog-header function.
1257;; Customization variables:
1258;;
1259(defvar verilog-date-scientific-format nil
fb7ada5f 1260 "If non-nil, dates are written in scientific format (e.g. 1997/09/17).
6341f357
DN
1261If nil, in European format (e.g. 17.09.1997). The brain-dead American
1262format (e.g. 09/17/1997) is not supported.")
1263
1264(defvar verilog-company nil
fb7ada5f 1265 "Default name of Company for Verilog header.
6341f357 1266If set will become buffer local.")
7ea26faf
DN
1267(make-variable-buffer-local 'verilog-company)
1268
6341f357 1269(defvar verilog-project nil
fb7ada5f 1270 "Default name of Project for Verilog header.
6341f357 1271If set will become buffer local.")
7ea26faf
DN
1272(make-variable-buffer-local 'verilog-project)
1273
7d49d8e1 1274(defvar verilog-mode-map
6edb5716
DN
1275 (let ((map (make-sparse-keymap)))
1276 (define-key map ";" 'electric-verilog-semi)
1277 (define-key map [(control 59)] 'electric-verilog-semi-with-comment)
1278 (define-key map ":" 'electric-verilog-colon)
1279 ;;(define-key map "=" 'electric-verilog-equal)
1280 (define-key map "\`" 'electric-verilog-tick)
1281 (define-key map "\t" 'electric-verilog-tab)
1282 (define-key map "\r" 'electric-verilog-terminate-line)
1283 ;; backspace/delete key bindings
1284 (define-key map [backspace] 'backward-delete-char-untabify)
1285 (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
1286 (define-key map [delete] 'delete-char)
1287 (define-key map [(meta delete)] 'kill-word))
1288 (define-key map "\M-\C-b" 'electric-verilog-backward-sexp)
1289 (define-key map "\M-\C-f" 'electric-verilog-forward-sexp)
1290 (define-key map "\M-\r" `electric-verilog-terminate-and-indent)
1291 (define-key map "\M-\t" 'verilog-complete-word)
1292 (define-key map "\M-?" 'verilog-show-completions)
9489a450 1293 ;; Note \C-c and letter are reserved for users
6edb5716
DN
1294 (define-key map "\C-c\`" 'verilog-lint-off)
1295 (define-key map "\C-c\*" 'verilog-delete-auto-star-implicit)
9489a450 1296 (define-key map "\C-c\?" 'verilog-diff-auto)
6edb5716
DN
1297 (define-key map "\C-c\C-r" 'verilog-label-be)
1298 (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
1299 (define-key map "\C-c=" 'verilog-pretty-expr)
1300 (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
1301 (define-key map "\M-*" 'verilog-star-comment)
1302 (define-key map "\C-c\C-c" 'verilog-comment-region)
1303 (define-key map "\C-c\C-u" 'verilog-uncomment-region)
e1776067
DN
1304 (when (featurep 'xemacs)
1305 (define-key map [(meta control h)] 'verilog-mark-defun)
1306 (define-key map "\M-\C-a" 'verilog-beg-of-defun)
1307 (define-key map "\M-\C-e" 'verilog-end-of-defun))
6edb5716
DN
1308 (define-key map "\C-c\C-d" 'verilog-goto-defun)
1309 (define-key map "\C-c\C-k" 'verilog-delete-auto)
1310 (define-key map "\C-c\C-a" 'verilog-auto)
1311 (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
a03c2342 1312 (define-key map "\C-c\C-p" 'verilog-preprocess)
6edb5716
DN
1313 (define-key map "\C-c\C-z" 'verilog-inject-auto)
1314 (define-key map "\C-c\C-e" 'verilog-expand-vector)
30d48f20
DN
1315 (define-key map "\C-c\C-h" 'verilog-header)
1316 map)
6341f357 1317 "Keymap used in Verilog mode.")
6341f357
DN
1318
1319;; menus
7d55bf04
DN
1320(easy-menu-define
1321 verilog-menu verilog-mode-map "Menu for Verilog mode"
495ab0d5
DN
1322 (verilog-easy-menu-filter
1323 '("Verilog"
1324 ("Choose Compilation Action"
1325 ["None"
1326 (progn
1327 (setq verilog-tool nil)
1328 (verilog-set-compile-command))
1329 :style radio
1330 :selected (equal verilog-tool nil)
1331 :help "When invoking compilation, use compile-command"]
1332 ["Lint"
1333 (progn
1334 (setq verilog-tool 'verilog-linter)
1335 (verilog-set-compile-command))
1336 :style radio
1337 :selected (equal verilog-tool `verilog-linter)
1338 :help "When invoking compilation, use lint checker"]
1339 ["Coverage"
1340 (progn
1341 (setq verilog-tool 'verilog-coverage)
1342 (verilog-set-compile-command))
1343 :style radio
1344 :selected (equal verilog-tool `verilog-coverage)
1345 :help "When invoking compilation, annotate for coverage"]
1346 ["Simulator"
1347 (progn
1348 (setq verilog-tool 'verilog-simulator)
1349 (verilog-set-compile-command))
1350 :style radio
1351 :selected (equal verilog-tool `verilog-simulator)
1352 :help "When invoking compilation, interpret Verilog source"]
1353 ["Compiler"
1354 (progn
1355 (setq verilog-tool 'verilog-compiler)
1356 (verilog-set-compile-command))
1357 :style radio
1358 :selected (equal verilog-tool `verilog-compiler)
1359 :help "When invoking compilation, compile Verilog source"]
a03c2342
WS
1360 ["Preprocessor"
1361 (progn
1362 (setq verilog-tool 'verilog-preprocessor)
1363 (verilog-set-compile-command))
1364 :style radio
1365 :selected (equal verilog-tool `verilog-preprocessor)
1366 :help "When invoking compilation, preprocess Verilog source, see also `verilog-preprocess'"]
495ab0d5
DN
1367 )
1368 ("Move"
1369 ["Beginning of function" verilog-beg-of-defun
1370 :keys "C-M-a"
1371 :help "Move backward to the beginning of the current function or procedure"]
1372 ["End of function" verilog-end-of-defun
1373 :keys "C-M-e"
1374 :help "Move forward to the end of the current function or procedure"]
1375 ["Mark function" verilog-mark-defun
1376 :keys "C-M-h"
1377 :help "Mark the current Verilog function or procedure"]
1378 ["Goto function/module" verilog-goto-defun
1379 :help "Move to specified Verilog module/task/function"]
1380 ["Move to beginning of block" electric-verilog-backward-sexp
1381 :help "Move backward over one balanced expression"]
1382 ["Move to end of block" electric-verilog-forward-sexp
1383 :help "Move forward over one balanced expression"]
1384 )
1385 ("Comments"
1386 ["Comment Region" verilog-comment-region
1387 :help "Put marked area into a comment"]
1388 ["UnComment Region" verilog-uncomment-region
1389 :help "Uncomment an area commented with Comment Region"]
1390 ["Multi-line comment insert" verilog-star-comment
1391 :help "Insert Verilog /* */ comment at point"]
1392 ["Lint error to comment" verilog-lint-off
1393 :help "Convert a Verilog linter warning line into a disable statement"]
1394 )
1395 "----"
1396 ["Compile" compile
1397 :help "Perform compilation-action (above) on the current buffer"]
1398 ["AUTO, Save, Compile" verilog-auto-save-compile
1399 :help "Recompute AUTOs, save buffer, and compile"]
1400 ["Next Compile Error" next-error
1401 :help "Visit next compilation error message and corresponding source code"]
1402 ["Ignore Lint Warning at point" verilog-lint-off
1403 :help "Convert a Verilog linter warning line into a disable statement"]
1404 "----"
1405 ["Line up declarations around point" verilog-pretty-declarations
1406 :help "Line up declarations around point"]
1407 ["Line up equations around point" verilog-pretty-expr
1408 :help "Line up expressions around point"]
1409 ["Redo/insert comments on every end" verilog-label-be
1410 :help "Label matching begin ... end statements"]
1411 ["Expand [x:y] vector line" verilog-expand-vector
1412 :help "Take a signal vector on the current line and expand it to multiple lines"]
1413 ["Insert begin-end block" verilog-insert-block
1414 :help "Insert begin ... end"]
1415 ["Complete word" verilog-complete-word
1416 :help "Complete word at point"]
1417 "----"
1418 ["Recompute AUTOs" verilog-auto
1419 :help "Expand AUTO meta-comment statements"]
1420 ["Kill AUTOs" verilog-delete-auto
1421 :help "Remove AUTO expansions"]
9489a450
MM
1422 ["Diff AUTOs" verilog-diff-auto
1423 :help "Show differences in AUTO expansions"]
495ab0d5
DN
1424 ["Inject AUTOs" verilog-inject-auto
1425 :help "Inject AUTOs into legacy non-AUTO buffer"]
1426 ("AUTO Help..."
1427 ["AUTO General" (describe-function 'verilog-auto)
1428 :help "Help introduction on AUTOs"]
1429 ["AUTO Library Flags" (describe-variable 'verilog-library-flags)
1430 :help "Help on verilog-library-flags"]
1431 ["AUTO Library Path" (describe-variable 'verilog-library-directories)
1432 :help "Help on verilog-library-directories"]
1433 ["AUTO Library Files" (describe-variable 'verilog-library-files)
1434 :help "Help on verilog-library-files"]
1435 ["AUTO Library Extensions" (describe-variable 'verilog-library-extensions)
1436 :help "Help on verilog-library-extensions"]
1437 ["AUTO `define Reading" (describe-function 'verilog-read-defines)
1438 :help "Help on reading `defines"]
1439 ["AUTO `include Reading" (describe-function 'verilog-read-includes)
1440 :help "Help on parsing `includes"]
1441 ["AUTOARG" (describe-function 'verilog-auto-arg)
1442 :help "Help on AUTOARG - declaring module port list"]
1443 ["AUTOASCIIENUM" (describe-function 'verilog-auto-ascii-enum)
1444 :help "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
179f044b
WS
1445 ["AUTOASSIGNMODPORT" (describe-function 'verilog-auto-assign-modport)
1446 :help "Help on AUTOASSIGNMODPORT - creating assignments to/from modports"]
ea89ff08
WS
1447 ["AUTOINOUT" (describe-function 'verilog-auto-inout)
1448 :help "Help on AUTOINOUT - adding inouts from cells"]
86a4c7ac 1449 ["AUTOINOUTCOMP" (describe-function 'verilog-auto-inout-comp)
7cb1c4d7 1450 :help "Help on AUTOINOUTCOMP - copying complemented i/o from another file"]
9489a450 1451 ["AUTOINOUTIN" (describe-function 'verilog-auto-inout-in)
179f044b
WS
1452 :help "Help on AUTOINOUTIN - copying i/o from another file as all inputs"]
1453 ["AUTOINOUTMODPORT" (describe-function 'verilog-auto-inout-modport)
1454 :help "Help on AUTOINOUTMODPORT - copying i/o from an interface modport"]
495ab0d5
DN
1455 ["AUTOINOUTMODULE" (describe-function 'verilog-auto-inout-module)
1456 :help "Help on AUTOINOUTMODULE - copying i/o from another file"]
179f044b
WS
1457 ["AUTOINOUTPARAM" (describe-function 'verilog-auto-inout-param)
1458 :help "Help on AUTOINOUTPARAM - copying parameters from another file"]
495ab0d5
DN
1459 ["AUTOINPUT" (describe-function 'verilog-auto-input)
1460 :help "Help on AUTOINPUT - adding inputs from cells"]
ea89ff08
WS
1461 ["AUTOINSERTLISP" (describe-function 'verilog-auto-insert-lisp)
1462 :help "Help on AUTOINSERTLISP - insert text from a lisp function"]
495ab0d5
DN
1463 ["AUTOINST" (describe-function 'verilog-auto-inst)
1464 :help "Help on AUTOINST - adding pins for cells"]
1465 ["AUTOINST (.*)" (describe-function 'verilog-auto-star)
1466 :help "Help on expanding Verilog-2001 .* pins"]
1467 ["AUTOINSTPARAM" (describe-function 'verilog-auto-inst-param)
1468 :help "Help on AUTOINSTPARAM - adding parameter pins to cells"]
9489a450
MM
1469 ["AUTOLOGIC" (describe-function 'verilog-auto-logic)
1470 :help "Help on AUTOLOGIC - declaring logic signals"]
495ab0d5
DN
1471 ["AUTOOUTPUT" (describe-function 'verilog-auto-output)
1472 :help "Help on AUTOOUTPUT - adding outputs from cells"]
1473 ["AUTOOUTPUTEVERY" (describe-function 'verilog-auto-output-every)
1474 :help "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
1475 ["AUTOREG" (describe-function 'verilog-auto-reg)
1476 :help "Help on AUTOREG - declaring registers for non-wires"]
1477 ["AUTOREGINPUT" (describe-function 'verilog-auto-reg-input)
1478 :help "Help on AUTOREGINPUT - declaring inputs for non-wires"]
1479 ["AUTORESET" (describe-function 'verilog-auto-reset)
1480 :help "Help on AUTORESET - resetting always blocks"]
ea89ff08 1481 ["AUTOSENSE or AS" (describe-function 'verilog-auto-sense)
495ab0d5
DN
1482 :help "Help on AUTOSENSE - sensitivity lists for always blocks"]
1483 ["AUTOTIEOFF" (describe-function 'verilog-auto-tieoff)
22bcf204 1484 :help "Help on AUTOTIEOFF - tying off unused outputs"]
47086495
WS
1485 ["AUTOUNDEF" (describe-function 'verilog-auto-undef)
1486 :help "Help on AUTOUNDEF - undefine all local defines"]
495ab0d5
DN
1487 ["AUTOUNUSED" (describe-function 'verilog-auto-unused)
1488 :help "Help on AUTOUNUSED - terminating unused inputs"]
1489 ["AUTOWIRE" (describe-function 'verilog-auto-wire)
1490 :help "Help on AUTOWIRE - declaring wires for cells"]
1491 )
1492 "----"
1493 ["Submit bug report" verilog-submit-bug-report
1494 :help "Submit via mail a bug report on verilog-mode.el"]
1495 ["Version and FAQ" verilog-faq
1496 :help "Show the current version, and where to get the FAQ etc"]
1497 ["Customize Verilog Mode..." verilog-customize
1498 :help "Customize variables and other settings used by Verilog-Mode"]
1499 ["Customize Verilog Fonts & Colors" verilog-font-customize
1500 :help "Customize fonts used by Verilog-Mode."])))
7d55bf04
DN
1501
1502(easy-menu-define
1503 verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
495ab0d5
DN
1504 (verilog-easy-menu-filter
1505 '("Statements"
1506 ["Header" verilog-sk-header
1507 :help "Insert a header block at the top of file"]
1508 ["Comment" verilog-sk-comment
1509 :help "Insert a comment block"]
1510 "----"
1511 ["Module" verilog-sk-module
1512 :help "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
9489a450
MM
1513 ["OVM Class" verilog-sk-ovm-class
1514 :help "Insert an OVM class block"]
ea89ff08
WS
1515 ["UVM Object" verilog-sk-uvm-object
1516 :help "Insert an UVM object block"]
1517 ["UVM Component" verilog-sk-uvm-component
1518 :help "Insert an UVM component block"]
495ab0d5
DN
1519 ["Primitive" verilog-sk-primitive
1520 :help "Insert a primitive .. (.. );.. endprimitive block"]
1521 "----"
1522 ["Input" verilog-sk-input
1523 :help "Insert an input declaration"]
1524 ["Output" verilog-sk-output
1525 :help "Insert an output declaration"]
1526 ["Inout" verilog-sk-inout
1527 :help "Insert an inout declaration"]
1528 ["Wire" verilog-sk-wire
1529 :help "Insert a wire declaration"]
1530 ["Reg" verilog-sk-reg
1531 :help "Insert a register declaration"]
1532 ["Define thing under point as a register" verilog-sk-define-signal
1533 :help "Define signal under point as a register at the top of the module"]
1534 "----"
1535 ["Initial" verilog-sk-initial
1536 :help "Insert an initial begin .. end block"]
1537 ["Always" verilog-sk-always
1538 :help "Insert an always @(AS) begin .. end block"]
1539 ["Function" verilog-sk-function
1540 :help "Insert a function .. begin .. end endfunction block"]
1541 ["Task" verilog-sk-task
1542 :help "Insert a task .. begin .. end endtask block"]
1543 ["Specify" verilog-sk-specify
1544 :help "Insert a specify .. endspecify block"]
1545 ["Generate" verilog-sk-generate
1546 :help "Insert a generate .. endgenerate block"]
1547 "----"
1548 ["Begin" verilog-sk-begin
1549 :help "Insert a begin .. end block"]
1550 ["If" verilog-sk-if
1551 :help "Insert an if (..) begin .. end block"]
1552 ["(if) else" verilog-sk-else-if
1553 :help "Insert an else if (..) begin .. end block"]
1554 ["For" verilog-sk-for
1555 :help "Insert a for (...) begin .. end block"]
1556 ["While" verilog-sk-while
1557 :help "Insert a while (...) begin .. end block"]
1558 ["Fork" verilog-sk-fork
1559 :help "Insert a fork begin .. end .. join block"]
1560 ["Repeat" verilog-sk-repeat
1561 :help "Insert a repeat (..) begin .. end block"]
1562 ["Case" verilog-sk-case
1563 :help "Insert a case block, prompting for details"]
1564 ["Casex" verilog-sk-casex
1565 :help "Insert a casex (...) item: begin.. end endcase block"]
1566 ["Casez" verilog-sk-casez
1567 :help "Insert a casez (...) item: begin.. end endcase block"])))
6341f357
DN
1568
1569(defvar verilog-mode-abbrev-table nil
1570 "Abbrev table in use in Verilog-mode buffers.")
1571
1572(define-abbrev-table 'verilog-mode-abbrev-table ())
9489a450
MM
1573(verilog-define-abbrev verilog-mode-abbrev-table "class" "" 'verilog-sk-ovm-class)
1574(verilog-define-abbrev verilog-mode-abbrev-table "always" "" 'verilog-sk-always)
1575(verilog-define-abbrev verilog-mode-abbrev-table "begin" nil `verilog-sk-begin)
1576(verilog-define-abbrev verilog-mode-abbrev-table "case" "" `verilog-sk-case)
1577(verilog-define-abbrev verilog-mode-abbrev-table "for" "" `verilog-sk-for)
1578(verilog-define-abbrev verilog-mode-abbrev-table "generate" "" `verilog-sk-generate)
1579(verilog-define-abbrev verilog-mode-abbrev-table "initial" "" `verilog-sk-initial)
1580(verilog-define-abbrev verilog-mode-abbrev-table "fork" "" `verilog-sk-fork)
1581(verilog-define-abbrev verilog-mode-abbrev-table "module" "" `verilog-sk-module)
1582(verilog-define-abbrev verilog-mode-abbrev-table "primitive" "" `verilog-sk-primitive)
1583(verilog-define-abbrev verilog-mode-abbrev-table "repeat" "" `verilog-sk-repeat)
1584(verilog-define-abbrev verilog-mode-abbrev-table "specify" "" `verilog-sk-specify)
1585(verilog-define-abbrev verilog-mode-abbrev-table "task" "" `verilog-sk-task)
1586(verilog-define-abbrev verilog-mode-abbrev-table "while" "" `verilog-sk-while)
1587(verilog-define-abbrev verilog-mode-abbrev-table "casex" "" `verilog-sk-casex)
1588(verilog-define-abbrev verilog-mode-abbrev-table "casez" "" `verilog-sk-casez)
1589(verilog-define-abbrev verilog-mode-abbrev-table "if" "" `verilog-sk-if)
1590(verilog-define-abbrev verilog-mode-abbrev-table "else if" "" `verilog-sk-else-if)
1591(verilog-define-abbrev verilog-mode-abbrev-table "assign" "" `verilog-sk-assign)
1592(verilog-define-abbrev verilog-mode-abbrev-table "function" "" `verilog-sk-function)
1593(verilog-define-abbrev verilog-mode-abbrev-table "input" "" `verilog-sk-input)
1594(verilog-define-abbrev verilog-mode-abbrev-table "output" "" `verilog-sk-output)
1595(verilog-define-abbrev verilog-mode-abbrev-table "inout" "" `verilog-sk-inout)
1596(verilog-define-abbrev verilog-mode-abbrev-table "wire" "" `verilog-sk-wire)
1597(verilog-define-abbrev verilog-mode-abbrev-table "reg" "" `verilog-sk-reg)
6341f357 1598
b68a96b9
DN
1599;;
1600;; Macros
1601;;
1602
a03c2342 1603(defsubst verilog-within-string ()
3ba6b2ee 1604 (nth 3 (parse-partial-sexp (point-at-bol) (point))))
a03c2342 1605
ea89ff08
WS
1606(defsubst verilog-string-match-fold (regexp string &optional start)
1607 "Like `string-match', but use `verilog-case-fold'.
1608Return index of start of first match for REGEXP in STRING, or nil.
1609Matching ignores case if `verilog-case-fold' is non-nil.
1610If third arg START is non-nil, start search at that index in STRING."
1611 (let ((case-fold-search verilog-case-fold))
1612 (string-match regexp string start)))
1613
b68a96b9
DN
1614(defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1615 "Replace occurrences of FROM-STRING with TO-STRING.
1616FIXEDCASE and LITERAL as in `replace-match`. STRING is what to replace.
1617The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1618will break, as the o's continuously replace. xa -> x works ok though."
47086495 1619 ;; Hopefully soon to an Emacs built-in
9489a450
MM
1620 ;; Also note \ in the replacement prevent multiple replacements; IE
1621 ;; (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil "wire@_@")
1622 ;; Gives "wire\([0-9]+\)_@" not "wire\([0-9]+\)_\([0-9]+\)"
b68a96b9
DN
1623 (let ((start 0))
1624 (while (string-match from-string string start)
1625 (setq string (replace-match to-string fixedcase literal string)
4c5e69c6 1626 start (min (length string) (+ (match-beginning 0) (length to-string)))))
b68a96b9
DN
1627 string))
1628
1629(defsubst verilog-string-remove-spaces (string)
1630 "Remove spaces surrounding STRING."
1631 (save-match-data
1632 (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1633 (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1634 string))
1635
1636(defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1637 ; checkdoc-params: (REGEXP BOUND NOERROR)
1638 "Like `re-search-forward', but skips over match in comments or strings."
7cb1c4d7
DN
1639 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1640 (while (and
1641 (re-search-forward REGEXP BOUND NOERROR)
1642 (setq mdata (match-data))
1643 (and (verilog-skip-forward-comment-or-string)
1644 (progn
1645 (setq mdata '(nil nil))
1646 (if BOUND
1647 (< (point) BOUND)
1648 t)))))
1649 (store-match-data mdata)
1650 (match-end 0)))
b68a96b9
DN
1651
1652(defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1653 ; checkdoc-params: (REGEXP BOUND NOERROR)
1654 "Like `re-search-backward', but skips over match in comments or strings."
7cb1c4d7
DN
1655 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1656 (while (and
1657 (re-search-backward REGEXP BOUND NOERROR)
1658 (setq mdata (match-data))
1659 (and (verilog-skip-backward-comment-or-string)
1660 (progn
1661 (setq mdata '(nil nil))
1662 (if BOUND
1663 (> (point) BOUND)
1664 t)))))
1665 (store-match-data mdata)
1666 (match-end 0)))
b68a96b9
DN
1667
1668(defsubst verilog-re-search-forward-quick (regexp bound noerror)
1669 "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1670but trashes match data and is faster for REGEXP that doesn't match often.
9489a450 1671This uses `verilog-scan' and text properties to ignore comments,
b68a96b9
DN
1672so there may be a large up front penalty for the first search."
1673 (let (pt)
1674 (while (and (not pt)
1675 (re-search-forward regexp bound noerror))
9489a450
MM
1676 (if (verilog-inside-comment-or-string-p)
1677 (re-search-forward "[/\"\n]" nil t) ;; Only way a comment or quote can end
1678 (setq pt (match-end 0))))
b68a96b9
DN
1679 pt))
1680
1681(defsubst verilog-re-search-backward-quick (regexp bound noerror)
1682 ; checkdoc-params: (REGEXP BOUND NOERROR)
1683 "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1684but trashes match data and is faster for REGEXP that doesn't match often.
9489a450 1685This uses `verilog-scan' and text properties to ignore comments,
b68a96b9
DN
1686so there may be a large up front penalty for the first search."
1687 (let (pt)
1688 (while (and (not pt)
1689 (re-search-backward regexp bound noerror))
9489a450
MM
1690 (if (verilog-inside-comment-or-string-p)
1691 (re-search-backward "[/\"]" nil t) ;; Only way a comment or quote can begin
1692 (setq pt (match-beginning 0))))
b68a96b9
DN
1693 pt))
1694
a03c2342
WS
1695(defsubst verilog-re-search-forward-substr (substr regexp bound noerror)
1696 "Like `re-search-forward', but first search for SUBSTR constant.
1697Then searched for the normal REGEXP (which contains SUBSTR), with given
1698BOUND and NOERROR. The REGEXP must fit within a single line.
1699This speeds up complicated regexp matches."
1700 ;; Problem with overlap: search-forward BAR then FOOBARBAZ won't match.
1701 ;; thus require matches to be on one line, and use beginning-of-line.
1702 (let (done)
1703 (while (and (not done)
1704 (search-forward substr bound noerror))
1705 (save-excursion
1706 (beginning-of-line)
3ba6b2ee 1707 (setq done (re-search-forward regexp (point-at-eol) noerror)))
a03c2342
WS
1708 (unless (and (<= (match-beginning 0) (point))
1709 (>= (match-end 0) (point)))
1710 (setq done nil)))
1711 (when done (goto-char done))
1712 done))
1713;;(verilog-re-search-forward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1714
1715(defsubst verilog-re-search-backward-substr (substr regexp bound noerror)
1716 "Like `re-search-backward', but first search for SUBSTR constant.
1717Then searched for the normal REGEXP (which contains SUBSTR), with given
1718BOUND and NOERROR. The REGEXP must fit within a single line.
1719This speeds up complicated regexp matches."
1720 ;; Problem with overlap: search-backward BAR then FOOBARBAZ won't match.
1721 ;; thus require matches to be on one line, and use beginning-of-line.
1722 (let (done)
1723 (while (and (not done)
1724 (search-backward substr bound noerror))
1725 (save-excursion
1726 (end-of-line)
3ba6b2ee 1727 (setq done (re-search-backward regexp (point-at-bol) noerror)))
a03c2342
WS
1728 (unless (and (<= (match-beginning 0) (point))
1729 (>= (match-end 0) (point)))
1730 (setq done nil)))
1731 (when done (goto-char done))
1732 done))
1733;;(verilog-re-search-backward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
b68a96b9 1734
9489a450 1735(defun verilog-delete-trailing-whitespace ()
179f044b
WS
1736 "Delete trailing spaces or tabs, but not newlines nor linefeeds.
1737Also add missing final newline.
1738
1739To call this from the command line, see \\[verilog-batch-diff-auto].
1740
1741To call on \\[verilog-auto], set `verilog-auto-delete-trailing-whitespace'."
9489a450
MM
1742 ;; Similar to `delete-trailing-whitespace' but that's not present in XEmacs
1743 (save-excursion
1744 (goto-char (point-min))
22bcf204 1745 (while (re-search-forward "[ \t]+$" nil t) ;; Not syntactic WS as no formfeed
179f044b
WS
1746 (replace-match "" nil nil))
1747 (goto-char (point-max))
1748 (unless (bolp) (insert "\n"))))
9489a450 1749
60618039
DN
1750(defvar compile-command)
1751
6341f357
DN
1752;; compilation program
1753(defun verilog-set-compile-command ()
37ea4b9b 1754 "Function to compute shell command to compile Verilog.
6341f357
DN
1755
1756This reads `verilog-tool' and sets `compile-command'. This specifies the
1757program that executes when you type \\[compile] or
1758\\[verilog-auto-save-compile].
1759
a03c2342
WS
1760By default `verilog-tool' uses a Makefile if one exists in the
1761current directory. If not, it is set to the `verilog-linter',
1762`verilog-compiler', `verilog-coverage', `verilog-preprocessor',
1763or `verilog-simulator' variables, as selected with the Verilog ->
1764\"Choose Compilation Action\" menu.
6341f357
DN
1765
1766You should set `verilog-tool' or the other variables to the path and
1767arguments for your Verilog simulator. For example:
1768 \"vcs -p123 -O\"
1769or a string like:
1770 \"(cd /tmp; surecov %s)\".
1771
1772In the former case, the path to the current buffer is concat'ed to the
1773value of `verilog-tool'; in the later, the path to the current buffer is
1774substituted for the %s.
1775
a03c2342
WS
1776Where __FLAGS__ appears in the string `verilog-current-flags'
1777will be substituted.
1778
1779Where __FILE__ appears in the string, the variable
1780`buffer-file-name' of the current buffer, without the directory
1781portion, will be substituted."
6341f357
DN
1782 (interactive)
1783 (cond
1784 ((or (file-exists-p "makefile") ;If there is a makefile, use it
1785 (file-exists-p "Makefile"))
175069ef 1786 (set (make-local-variable 'compile-command) "make "))
6341f357 1787 (t
175069ef 1788 (set (make-local-variable 'compile-command)
9489a450
MM
1789 (if verilog-tool
1790 (if (string-match "%s" (eval verilog-tool))
1791 (format (eval verilog-tool) (or buffer-file-name ""))
1792 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1793 ""))))
6341f357
DN
1794 (verilog-modify-compile-command))
1795
a03c2342
WS
1796(defun verilog-expand-command (command)
1797 "Replace meta-information in COMMAND and return it.
1798Where __FLAGS__ appears in the string `verilog-current-flags'
1799will be substituted. Where __FILE__ appears in the string, the
1800current buffer's file-name, without the directory portion, will
1801be substituted."
1802 (setq command (verilog-string-replace-matches
1803 ;; Note \\b only works if under verilog syntax table
1804 "\\b__FLAGS__\\b" (verilog-current-flags)
1805 t t command))
1806 (setq command (verilog-string-replace-matches
1807 "\\b__FILE__\\b" (file-name-nondirectory
1808 (or (buffer-file-name) ""))
1809 t t command))
1810 command)
1811
6341f357 1812(defun verilog-modify-compile-command ()
a03c2342 1813 "Update `compile-command' using `verilog-expand-command'."
6341f357
DN
1814 (when (and
1815 (stringp compile-command)
a03c2342 1816 (string-match "\\b\\(__FLAGS__\\|__FILE__\\)\\b" compile-command))
175069ef 1817 (set (make-local-variable 'compile-command)
9489a450 1818 (verilog-expand-command compile-command))))
6341f357 1819
d9e8a018
GM
1820(if (featurep 'xemacs)
1821 ;; Following code only gets called from compilation-mode-hook on XEmacs to add error handling.
1822 (defun verilog-error-regexp-add-xemacs ()
1823 "Teach XEmacs about verilog errors.
7ea26faf
DN
1824Called by `compilation-mode-hook'. This allows \\[next-error] to
1825find the errors."
d9e8a018
GM
1826 (interactive)
1827 (if (boundp 'compilation-error-regexp-systems-alist)
1828 (if (and
1829 (not (equal compilation-error-regexp-systems-list 'all))
1830 (not (member compilation-error-regexp-systems-list 'verilog)))
1831 (push 'verilog compilation-error-regexp-systems-list)))
1832 (if (boundp 'compilation-error-regexp-alist-alist)
1833 (if (not (assoc 'verilog compilation-error-regexp-alist-alist))
1834 (setcdr compilation-error-regexp-alist-alist
1835 (cons verilog-error-regexp-xemacs-alist
1836 (cdr compilation-error-regexp-alist-alist)))))
1837 (if (boundp 'compilation-font-lock-keywords)
1838 (progn
9489a450
MM
1839 (set (make-local-variable 'compilation-font-lock-keywords)
1840 verilog-error-font-lock-keywords)
d9e8a018
GM
1841 (font-lock-set-defaults)))
1842 ;; Need to re-run compilation-error-regexp builder
1843 (if (fboundp 'compilation-build-compilation-error-regexp-alist)
1844 (compilation-build-compilation-error-regexp-alist))
1845 ))
d88782c3
DN
1846
1847;; Following code only gets called from compilation-mode-hook on Emacs to add error handling.
a3a8b002
DN
1848(defun verilog-error-regexp-add-emacs ()
1849 "Tell Emacs compile that we are Verilog.
1850Called by `compilation-mode-hook'. This allows \\[next-error] to
1851find the errors."
1852 (interactive)
d88782c3
DN
1853 (if (boundp 'compilation-error-regexp-alist-alist)
1854 (progn
1855 (if (not (assoc 'verilog-xl-1 compilation-error-regexp-alist-alist))
1856 (mapcar
1857 (lambda (item)
1858 (push (car item) compilation-error-regexp-alist)
1859 (push item compilation-error-regexp-alist-alist)
1860 )
1861 verilog-error-regexp-emacs-alist)))))
1862
1863(if (featurep 'xemacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-xemacs))
1864(if (featurep 'emacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-emacs))
6341f357
DN
1865
1866(defconst verilog-directive-re
a03c2342
WS
1867 (eval-when-compile
1868 (verilog-regexp-words
1869 '(
1870 "`case" "`default" "`define" "`else" "`elsif" "`endfor" "`endif"
1871 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1872 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1873 "`time_scale" "`undef" "`while" ))))
6341f357 1874
a3a8b002
DN
1875(defconst verilog-directive-re-1
1876 (concat "[ \t]*" verilog-directive-re))
1877
6341f357
DN
1878(defconst verilog-directive-begin
1879 "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1880
1881(defconst verilog-directive-middle
a03c2342 1882 "\\<`\\(else\\|elsif\\|default\\|case\\)\\>")
6341f357
DN
1883
1884(defconst verilog-directive-end
1885 "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1886
a3a8b002
DN
1887(defconst verilog-ovm-begin-re
1888 (eval-when-compile
1889 (verilog-regexp-opt
1890 '(
1891 "`ovm_component_utils_begin"
14862301 1892 "`ovm_component_param_utils_begin"
a3a8b002
DN
1893 "`ovm_field_utils_begin"
1894 "`ovm_object_utils_begin"
14862301 1895 "`ovm_object_param_utils_begin"
a3a8b002
DN
1896 "`ovm_sequence_utils_begin"
1897 "`ovm_sequencer_utils_begin"
1898 ) nil )))
1899
1900(defconst verilog-ovm-end-re
1901 (eval-when-compile
1902 (verilog-regexp-opt
1903 '(
1904 "`ovm_component_utils_end"
1905 "`ovm_field_utils_end"
1906 "`ovm_object_utils_end"
1907 "`ovm_sequence_utils_end"
1908 "`ovm_sequencer_utils_end"
1909 ) nil )))
1910
9489a450
MM
1911(defconst verilog-uvm-begin-re
1912 (eval-when-compile
1913 (verilog-regexp-opt
1914 '(
1915 "`uvm_component_utils_begin"
1916 "`uvm_component_param_utils_begin"
1917 "`uvm_field_utils_begin"
1918 "`uvm_object_utils_begin"
1919 "`uvm_object_param_utils_begin"
1920 "`uvm_sequence_utils_begin"
1921 "`uvm_sequencer_utils_begin"
1922 ) nil )))
1923
1924(defconst verilog-uvm-end-re
1925 (eval-when-compile
1926 (verilog-regexp-opt
1927 '(
1928 "`uvm_component_utils_end"
1929 "`uvm_field_utils_end"
1930 "`uvm_object_utils_end"
1931 "`uvm_sequence_utils_end"
1932 "`uvm_sequencer_utils_end"
1933 ) nil )))
1934
86a4c7ac
DN
1935(defconst verilog-vmm-begin-re
1936 (eval-when-compile
1937 (verilog-regexp-opt
1938 '(
1939 "`vmm_data_member_begin"
1940 "`vmm_env_member_begin"
1941 "`vmm_scenario_member_begin"
1942 "`vmm_subenv_member_begin"
1943 "`vmm_xactor_member_begin"
1944 ) nil ) ) )
1945
1946(defconst verilog-vmm-end-re
1947 (eval-when-compile
1948 (verilog-regexp-opt
1949 '(
1950 "`vmm_data_member_end"
1951 "`vmm_env_member_end"
1952 "`vmm_scenario_member_end"
1953 "`vmm_subenv_member_end"
1954 "`vmm_xactor_member_end"
1955 ) nil ) ) )
1956
1957(defconst verilog-vmm-statement-re
1958 (eval-when-compile
1959 (verilog-regexp-opt
1960 '(
1961;; "`vmm_xactor_member_enum_array"
1962 "`vmm_\\(data\\|env\\|scenario\\|subenv\\|xactor\\)_member_\\(scalar\\|string\\|enum\\|vmm_data\\|channel\\|xactor\\|subenv\\|user_defined\\)\\(_array\\)?"
1963;; "`vmm_xactor_member_scalar_array"
1964;; "`vmm_xactor_member_scalar"
1965 ) nil )))
1966
a3a8b002
DN
1967(defconst verilog-ovm-statement-re
1968 (eval-when-compile
1969 (verilog-regexp-opt
1970 '(
1971 ;; Statements
1972 "`DUT_ERROR"
1973 "`MESSAGE"
1974 "`dut_error"
1975 "`message"
1976 "`ovm_analysis_imp_decl"
1977 "`ovm_blocking_get_imp_decl"
1978 "`ovm_blocking_get_peek_imp_decl"
1979 "`ovm_blocking_master_imp_decl"
1980 "`ovm_blocking_peek_imp_decl"
1981 "`ovm_blocking_put_imp_decl"
1982 "`ovm_blocking_slave_imp_decl"
1983 "`ovm_blocking_transport_imp_decl"
1984 "`ovm_component_registry"
1985 "`ovm_component_registry_param"
1986 "`ovm_component_utils"
1987 "`ovm_create"
1988 "`ovm_create_seq"
1989 "`ovm_declare_sequence_lib"
1990 "`ovm_do"
1991 "`ovm_do_seq"
1992 "`ovm_do_seq_with"
1993 "`ovm_do_with"
1994 "`ovm_error"
1995 "`ovm_fatal"
1996 "`ovm_field_aa_int_byte"
1997 "`ovm_field_aa_int_byte_unsigned"
1998 "`ovm_field_aa_int_int"
1999 "`ovm_field_aa_int_int_unsigned"
2000 "`ovm_field_aa_int_integer"
2001 "`ovm_field_aa_int_integer_unsigned"
2002 "`ovm_field_aa_int_key"
2003 "`ovm_field_aa_int_longint"
2004 "`ovm_field_aa_int_longint_unsigned"
2005 "`ovm_field_aa_int_shortint"
2006 "`ovm_field_aa_int_shortint_unsigned"
2007 "`ovm_field_aa_int_string"
2008 "`ovm_field_aa_object_int"
2009 "`ovm_field_aa_object_string"
2010 "`ovm_field_aa_string_int"
2011 "`ovm_field_aa_string_string"
2012 "`ovm_field_array_int"
2013 "`ovm_field_array_object"
2014 "`ovm_field_array_string"
2015 "`ovm_field_enum"
2016 "`ovm_field_event"
2017 "`ovm_field_int"
2018 "`ovm_field_object"
2019 "`ovm_field_queue_int"
2020 "`ovm_field_queue_object"
2021 "`ovm_field_queue_string"
2022 "`ovm_field_sarray_int"
2023 "`ovm_field_string"
2024 "`ovm_field_utils"
2025 "`ovm_file"
2026 "`ovm_get_imp_decl"
2027 "`ovm_get_peek_imp_decl"
2028 "`ovm_info"
2029 "`ovm_info1"
2030 "`ovm_info2"
2031 "`ovm_info3"
2032 "`ovm_info4"
2033 "`ovm_line"
2034 "`ovm_master_imp_decl"
2035 "`ovm_msg_detail"
2036 "`ovm_non_blocking_transport_imp_decl"
2037 "`ovm_nonblocking_get_imp_decl"
2038 "`ovm_nonblocking_get_peek_imp_decl"
2039 "`ovm_nonblocking_master_imp_decl"
2040 "`ovm_nonblocking_peek_imp_decl"
2041 "`ovm_nonblocking_put_imp_decl"
2042 "`ovm_nonblocking_slave_imp_decl"
2043 "`ovm_object_registry"
2044 "`ovm_object_registry_param"
2045 "`ovm_object_utils"
2046 "`ovm_peek_imp_decl"
2047 "`ovm_phase_func_decl"
2048 "`ovm_phase_task_decl"
2049 "`ovm_print_aa_int_object"
2050 "`ovm_print_aa_string_int"
2051 "`ovm_print_aa_string_object"
2052 "`ovm_print_aa_string_string"
2053 "`ovm_print_array_int"
2054 "`ovm_print_array_object"
2055 "`ovm_print_array_string"
2056 "`ovm_print_object_queue"
2057 "`ovm_print_queue_int"
2058 "`ovm_print_string_queue"
2059 "`ovm_put_imp_decl"
2060 "`ovm_rand_send"
2061 "`ovm_rand_send_with"
2062 "`ovm_send"
2063 "`ovm_sequence_utils"
2064 "`ovm_slave_imp_decl"
2065 "`ovm_transport_imp_decl"
2066 "`ovm_update_sequence_lib"
2067 "`ovm_update_sequence_lib_and_item"
2068 "`ovm_warning"
2069 "`static_dut_error"
2070 "`static_message") nil )))
2071
9489a450
MM
2072(defconst verilog-uvm-statement-re
2073 (eval-when-compile
2074 (verilog-regexp-opt
2075 '(
2076 ;; Statements
2077 "`uvm_analysis_imp_decl"
2078 "`uvm_blocking_get_imp_decl"
2079 "`uvm_blocking_get_peek_imp_decl"
2080 "`uvm_blocking_master_imp_decl"
2081 "`uvm_blocking_peek_imp_decl"
2082 "`uvm_blocking_put_imp_decl"
2083 "`uvm_blocking_slave_imp_decl"
2084 "`uvm_blocking_transport_imp_decl"
2085 "`uvm_component_param_utils"
2086 "`uvm_component_registry"
2087 "`uvm_component_registry_param"
2088 "`uvm_component_utils"
2089 "`uvm_create"
2090 "`uvm_create_on"
301b181a 2091 "`uvm_create_seq" ;; Undocumented in 1.1
9489a450
MM
2092 "`uvm_declare_p_sequencer"
2093 "`uvm_declare_sequence_lib" ;; Deprecated in 1.1
2094 "`uvm_do"
2095 "`uvm_do_callbacks"
2096 "`uvm_do_callbacks_exit_on"
2097 "`uvm_do_obj_callbacks"
2098 "`uvm_do_obj_callbacks_exit_on"
2099 "`uvm_do_on"
2100 "`uvm_do_on_pri"
2101 "`uvm_do_on_pri_with"
2102 "`uvm_do_on_with"
2103 "`uvm_do_pri"
2104 "`uvm_do_pri_with"
2105 "`uvm_do_seq" ;; Undocumented in 1.1
2106 "`uvm_do_seq_with" ;; Undocumented in 1.1
2107 "`uvm_do_with"
2108 "`uvm_error"
2109 "`uvm_error_context"
2110 "`uvm_fatal"
2111 "`uvm_fatal_context"
2112 "`uvm_field_aa_int_byte"
2113 "`uvm_field_aa_int_byte_unsigned"
2114 "`uvm_field_aa_int_enum"
2115 "`uvm_field_aa_int_int"
2116 "`uvm_field_aa_int_int_unsigned"
2117 "`uvm_field_aa_int_integer"
2118 "`uvm_field_aa_int_integer_unsigned"
2119 "`uvm_field_aa_int_key"
2120 "`uvm_field_aa_int_longint"
2121 "`uvm_field_aa_int_longint_unsigned"
2122 "`uvm_field_aa_int_shortint"
2123 "`uvm_field_aa_int_shortint_unsigned"
2124 "`uvm_field_aa_int_string"
2125 "`uvm_field_aa_object_int"
2126 "`uvm_field_aa_object_string"
2127 "`uvm_field_aa_string_int"
2128 "`uvm_field_aa_string_string"
2129 "`uvm_field_array_enum"
2130 "`uvm_field_array_int"
2131 "`uvm_field_array_object"
2132 "`uvm_field_array_string"
2133 "`uvm_field_enum"
2134 "`uvm_field_event"
2135 "`uvm_field_int"
2136 "`uvm_field_object"
2137 "`uvm_field_queue_enum"
2138 "`uvm_field_queue_int"
2139 "`uvm_field_queue_object"
2140 "`uvm_field_queue_string"
2141 "`uvm_field_real"
2142 "`uvm_field_sarray_enum"
2143 "`uvm_field_sarray_int"
2144 "`uvm_field_sarray_object"
2145 "`uvm_field_sarray_string"
2146 "`uvm_field_string"
2147 "`uvm_field_utils"
2148 "`uvm_file" ;; Undocumented in 1.1, use `__FILE__
2149 "`uvm_get_imp_decl"
2150 "`uvm_get_peek_imp_decl"
2151 "`uvm_info"
2152 "`uvm_info_context"
2153 "`uvm_line" ;; Undocumented in 1.1, use `__LINE__
2154 "`uvm_master_imp_decl"
2155 "`uvm_non_blocking_transport_imp_decl" ;; Deprecated in 1.1
2156 "`uvm_nonblocking_get_imp_decl"
2157 "`uvm_nonblocking_get_peek_imp_decl"
2158 "`uvm_nonblocking_master_imp_decl"
2159 "`uvm_nonblocking_peek_imp_decl"
2160 "`uvm_nonblocking_put_imp_decl"
2161 "`uvm_nonblocking_slave_imp_decl"
2162 "`uvm_nonblocking_transport_imp_decl"
2163 "`uvm_object_param_utils"
2164 "`uvm_object_registry"
2165 "`uvm_object_registry_param" ;; Undocumented in 1.1
2166 "`uvm_object_utils"
2167 "`uvm_pack_array"
2168 "`uvm_pack_arrayN"
2169 "`uvm_pack_enum"
2170 "`uvm_pack_enumN"
2171 "`uvm_pack_int"
2172 "`uvm_pack_intN"
2173 "`uvm_pack_queue"
2174 "`uvm_pack_queueN"
2175 "`uvm_pack_real"
2176 "`uvm_pack_sarray"
2177 "`uvm_pack_sarrayN"
2178 "`uvm_pack_string"
2179 "`uvm_peek_imp_decl"
2180 "`uvm_put_imp_decl"
2181 "`uvm_rand_send"
2182 "`uvm_rand_send_pri"
2183 "`uvm_rand_send_pri_with"
2184 "`uvm_rand_send_with"
2185 "`uvm_record_attribute"
2186 "`uvm_record_field"
2187 "`uvm_register_cb"
2188 "`uvm_send"
2189 "`uvm_send_pri"
2190 "`uvm_sequence_utils" ;; Deprecated in 1.1
2191 "`uvm_set_super_type"
2192 "`uvm_slave_imp_decl"
2193 "`uvm_transport_imp_decl"
2194 "`uvm_unpack_array"
2195 "`uvm_unpack_arrayN"
2196 "`uvm_unpack_enum"
2197 "`uvm_unpack_enumN"
2198 "`uvm_unpack_int"
2199 "`uvm_unpack_intN"
2200 "`uvm_unpack_queue"
2201 "`uvm_unpack_queueN"
2202 "`uvm_unpack_real"
2203 "`uvm_unpack_sarray"
2204 "`uvm_unpack_sarrayN"
2205 "`uvm_unpack_string"
2206 "`uvm_update_sequence_lib" ;; Deprecated in 1.1
2207 "`uvm_update_sequence_lib_and_item" ;; Deprecated in 1.1
2208 "`uvm_warning"
2209 "`uvm_warning_context") nil )))
2210
6341f357
DN
2211
2212;;
2213;; Regular expressions used to calculate indent, etc.
2214;;
2215(defconst verilog-symbol-re "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
6341f357
DN
2216;; Want to match
2217;; aa :
2218;; aa,bb :
2219;; a[34:32] :
2220;; a,
2221;; b :
9489a450
MM
2222(defconst verilog-assignment-operator-re
2223 (eval-when-compile
2224 (verilog-regexp-opt
2225 `(
2226 ;; blocking assignment_operator
2227 "=" "+=" "-=" "*=" "/=" "%=" "&=" "|=" "^=" "<<=" ">>=" "<<<=" ">>>="
2228 ;; non blocking assignment operator
2229 "<="
2230 ;; comparison
2231 "==" "!=" "===" "!===" "<=" ">=" "==\?" "!=\?"
2232 ;; event_trigger
2233 "->" "->>"
2234 ;; property_expr
2235 "|->" "|=>"
2236 ;; Is this a legal verilog operator?
2237 ":="
2238 ) 't
2239 )))
2240(defconst verilog-assignment-operation-re
2241 (concat
2242; "\\(^\\s-*[A-Za-z0-9_]+\\(\\[\\([A-Za-z0-9_]+\\)\\]\\)*\\s-*\\)"
2243; "\\(^\\s-*[^=<>+-*/%&|^:\\s-]+[^=<>+-*/%&|^\n]*?\\)"
2244 "\\(^.*?\\)" "\\B" verilog-assignment-operator-re "\\B" ))
6341f357 2245
14862301 2246(defconst verilog-label-re (concat verilog-symbol-re "\\s-*:\\s-*"))
a03c2342
WS
2247(defconst verilog-property-re
2248 (concat "\\(" verilog-label-re "\\)?"
2249 "\\(\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(assert\\)"))
2250 ;; "\\(assert\\|assume\\|cover\\)\\s-+property\\>"
2251
6341f357
DN
2252(defconst verilog-no-indent-begin-re
2253 "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
2254
2255(defconst verilog-ends-re
2256 ;; Parenthesis indicate type of keyword found
2257 (concat
2258 "\\(\\<else\\>\\)\\|" ; 1
2259 "\\(\\<if\\>\\)\\|" ; 2
86a4c7ac
DN
2260 "\\(\\<assert\\>\\)\\|" ; 3
2261 "\\(\\<end\\>\\)\\|" ; 3.1
6341f357
DN
2262 "\\(\\<endcase\\>\\)\\|" ; 4
2263 "\\(\\<endfunction\\>\\)\\|" ; 5
2264 "\\(\\<endtask\\>\\)\\|" ; 6
2265 "\\(\\<endspecify\\>\\)\\|" ; 7
2266 "\\(\\<endtable\\>\\)\\|" ; 8
2267 "\\(\\<endgenerate\\>\\)\\|" ; 9
2268 "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
2269 "\\(\\<endclass\\>\\)\\|" ; 11
a3a8b002 2270 "\\(\\<endgroup\\>\\)\\|" ; 12
86a4c7ac
DN
2271 ;; VMM
2272 "\\(\\<`vmm_data_member_end\\>\\)\\|"
2273 "\\(\\<`vmm_env_member_end\\>\\)\\|"
2274 "\\(\\<`vmm_scenario_member_end\\>\\)\\|"
2275 "\\(\\<`vmm_subenv_member_end\\>\\)\\|"
2276 "\\(\\<`vmm_xactor_member_end\\>\\)\\|"
a3a8b002
DN
2277 ;; OVM
2278 "\\(\\<`ovm_component_utils_end\\>\\)\\|"
2279 "\\(\\<`ovm_field_utils_end\\>\\)\\|"
2280 "\\(\\<`ovm_object_utils_end\\>\\)\\|"
2281 "\\(\\<`ovm_sequence_utils_end\\>\\)\\|"
2282 "\\(\\<`ovm_sequencer_utils_end\\>\\)"
9489a450
MM
2283 ;; UVM
2284 "\\(\\<`uvm_component_utils_end\\>\\)\\|"
2285 "\\(\\<`uvm_field_utils_end\\>\\)\\|"
2286 "\\(\\<`uvm_object_utils_end\\>\\)\\|"
2287 "\\(\\<`uvm_sequence_utils_end\\>\\)\\|"
2288 "\\(\\<`uvm_sequencer_utils_end\\>\\)"
6341f357
DN
2289 ))
2290
2291(defconst verilog-auto-end-comment-lines-re
da6062e6 2292 ;; Matches to names in this list cause auto-end-commenting
6341f357
DN
2293 (concat "\\("
2294 verilog-directive-re "\\)\\|\\("
2295 (eval-when-compile
2296 (verilog-regexp-words
2297 `( "begin"
2298 "else"
2299 "end"
2300 "endcase"
2301 "endclass"
2302 "endclocking"
2303 "endgroup"
2304 "endfunction"
2305 "endmodule"
2306 "endprogram"
2307 "endprimitive"
2308 "endinterface"
2309 "endpackage"
2310 "endsequence"
2311 "endspecify"
2312 "endtable"
2313 "endtask"
2314 "join"
2315 "join_any"
2316 "join_none"
2317 "module"
2318 "macromodule"
2319 "primitive"
2320 "interface"
2321 "package")))
2322 "\\)"))
2323
2324;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
2325;;; verilog-end-block-ordered-re matches exactly the same strings.
2326(defconst verilog-end-block-ordered-re
2327 ;; Parenthesis indicate type of keyword found
2328 (concat "\\(\\<endcase\\>\\)\\|" ; 1
2329 "\\(\\<end\\>\\)\\|" ; 2
2330 "\\(\\<end" ; 3, but not used
2331 "\\(" ; 4, but not used
2332 "\\(function\\)\\|" ; 5
2333 "\\(task\\)\\|" ; 6
2334 "\\(module\\)\\|" ; 7
2335 "\\(primitive\\)\\|" ; 8
2336 "\\(interface\\)\\|" ; 9
2337 "\\(package\\)\\|" ; 10
2338 "\\(class\\)\\|" ; 11
2339 "\\(group\\)\\|" ; 12
2340 "\\(program\\)\\|" ; 13
2341 "\\(sequence\\)\\|" ; 14
2342 "\\(clocking\\)\\|" ; 15
2343 "\\)\\>\\)"))
2344(defconst verilog-end-block-re
2345 (eval-when-compile
2346 (verilog-regexp-words
2347
2348 `("end" ;; closes begin
2349 "endcase" ;; closes any of case, casex casez or randcase
2350 "join" "join_any" "join_none" ;; closes fork
2351 "endclass"
2352 "endtable"
2353 "endspecify"
2354 "endfunction"
2355 "endgenerate"
2356 "endtask"
2357 "endgroup"
2358 "endproperty"
2359 "endinterface"
2360 "endpackage"
2361 "endprogram"
2362 "endsequence"
2363 "endclocking"
a3a8b002
DN
2364 ;; OVM
2365 "`ovm_component_utils_end"
2366 "`ovm_field_utils_end"
2367 "`ovm_object_utils_end"
2368 "`ovm_sequence_utils_end"
2369 "`ovm_sequencer_utils_end"
9489a450
MM
2370 ;; UVM
2371 "`uvm_component_utils_end"
2372 "`uvm_field_utils_end"
2373 "`uvm_object_utils_end"
2374 "`uvm_sequence_utils_end"
2375 "`uvm_sequencer_utils_end"
86a4c7ac
DN
2376 ;; VMM
2377 "`vmm_data_member_end"
2378 "`vmm_env_member_end"
2379 "`vmm_scenario_member_end"
2380 "`vmm_subenv_member_end"
2381 "`vmm_xactor_member_end"
60618039 2382 ))))
6341f357
DN
2383
2384
2385(defconst verilog-endcomment-reason-re
2386 ;; Parenthesis indicate type of keyword found
2387 (concat
a3a8b002
DN
2388 "\\(\\<begin\\>\\)\\|" ; 1
2389 "\\(\\<else\\>\\)\\|" ; 2
2390 "\\(\\<end\\>\\s-+\\<else\\>\\)\\|" ; 3
2391 "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|" ; 4
2392 "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|" ; 5
2393 "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|" ; 6
2394 "\\(\\<fork\\>\\)\\|" ; 7
14862301 2395 "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
6341f357 2396 "\\(\\<if\\>\\)\\|"
a03c2342
WS
2397 verilog-property-re "\\|"
2398 "\\(\\(" verilog-label-re "\\)?\\<assert\\>\\)\\|"
6341f357 2399 "\\(\\<clocking\\>\\)\\|"
14862301
SM
2400 "\\(\\<task\\>\\)\\|"
2401 "\\(\\<function\\>\\)\\|"
6341f357
DN
2402 "\\(\\<initial\\>\\)\\|"
2403 "\\(\\<interface\\>\\)\\|"
2404 "\\(\\<package\\>\\)\\|"
2405 "\\(\\<final\\>\\)\\|"
6341f357
DN
2406 "\\(@\\)\\|"
2407 "\\(\\<while\\>\\)\\|"
2408 "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
2409 "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
2410 "#"))
2411
2412(defconst verilog-named-block-re "begin[ \t]*:")
2413
2414;; These words begin a block which can occur inside a module which should be indented,
2415;; and closed with the respective word from the end-block list
2416
2417(defconst verilog-beg-block-re
2418 (eval-when-compile
2419 (verilog-regexp-words
2420 `("begin"
2421 "case" "casex" "casez" "randcase"
2422 "clocking"
2423 "generate"
2424 "fork"
2425 "function"
2426 "property"
2427 "specify"
2428 "table"
2429 "task"
9489a450 2430 ;; OVM
a3a8b002 2431 "`ovm_component_utils_begin"
14862301 2432 "`ovm_component_param_utils_begin"
a3a8b002
DN
2433 "`ovm_field_utils_begin"
2434 "`ovm_object_utils_begin"
14862301 2435 "`ovm_object_param_utils_begin"
a3a8b002
DN
2436 "`ovm_sequence_utils_begin"
2437 "`ovm_sequencer_utils_begin"
9489a450
MM
2438 ;; UVM
2439 "`uvm_component_utils_begin"
2440 "`uvm_component_param_utils_begin"
2441 "`uvm_field_utils_begin"
2442 "`uvm_object_utils_begin"
2443 "`uvm_object_param_utils_begin"
2444 "`uvm_sequence_utils_begin"
2445 "`uvm_sequencer_utils_begin"
86a4c7ac
DN
2446 ;; VMM
2447 "`vmm_data_member_begin"
2448 "`vmm_env_member_begin"
2449 "`vmm_scenario_member_begin"
2450 "`vmm_subenv_member_begin"
2451 "`vmm_xactor_member_begin"
6341f357
DN
2452 ))))
2453;; These are the same words, in a specific order in the regular
2454;; expression so that matching will work nicely for
2455;; verilog-forward-sexp and verilog-calc-indent
6341f357 2456(defconst verilog-beg-block-re-ordered
4c5e69c6 2457 ( concat "\\(\\<begin\\>\\)" ;1
ea89ff08 2458 "\\|\\(\\<randcase\\>\\|\\(\\<unique0?\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
9489a450 2459 "\\|\\(\\(\\<disable\\>\\s-+\\|\\<wait\\>\\s-+\\)?fork\\>\\)" ;4,5
4c5e69c6
DN
2460 "\\|\\(\\<class\\>\\)" ;6
2461 "\\|\\(\\<table\\>\\)" ;7
2462 "\\|\\(\\<specify\\>\\)" ;8
2463 "\\|\\(\\<function\\>\\)" ;9
a3a8b002
DN
2464 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<function\\>\\)" ;10
2465 "\\|\\(\\<task\\>\\)" ;14
2466 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)" ;15
2467 "\\|\\(\\<generate\\>\\)" ;18
2468 "\\|\\(\\<covergroup\\>\\)" ;16 20
2469 "\\|\\(\\(\\(\\<cover\\>\\s-+\\)\\|\\(\\<assert\\>\\s-+\\)\\)*\\<property\\>\\)" ;17 21
2470 "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;21 25
2471 "\\|\\(\\<clocking\\>\\)" ;22 27
9489a450 2472 "\\|\\(\\<`[ou]vm_[a-z_]+_begin\\>\\)" ;28
86a4c7ac 2473 "\\|\\(\\<`vmm_[a-z_]+_member_begin\\>\\)"
a3a8b002 2474 ;;
4c5e69c6 2475 ))
6341f357
DN
2476
2477(defconst verilog-end-block-ordered-rry
2478 [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2479 "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
2480 "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2481 "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
2482 "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
2483 "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
2484 "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
2485 "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
2486 "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
2487 "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
2488 "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
2489 "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
2490 "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
2491 ] )
2492
2493(defconst verilog-nameable-item-re
2494 (eval-when-compile
2495 (verilog-regexp-words
2496 `("begin"
2497 "fork"
2498 "join" "join_any" "join_none"
2499 "end"
2500 "endcase"
2501 "endconfig"
2502 "endclass"
2503 "endclocking"
2504 "endfunction"
2505 "endgenerate"
2506 "endmodule"
86a4c7ac 2507 "endprimitive"
6341f357
DN
2508 "endinterface"
2509 "endpackage"
2510 "endspecify"
2511 "endtable"
2512 "endtask" )
2513 )))
2514
2515(defconst verilog-declaration-opener
2516 (eval-when-compile
2517 (verilog-regexp-words
2518 `("module" "begin" "task" "function"))))
2519
2520(defconst verilog-declaration-prefix-re
2521 (eval-when-compile
2522 (verilog-regexp-words
2523 `(
2524 ;; port direction
6edb5716 2525 "inout" "input" "output" "ref"
6341f357
DN
2526 ;; changeableness
2527 "const" "static" "protected" "local"
2528 ;; parameters
6edb5716 2529 "localparam" "parameter" "var"
6341f357
DN
2530 ;; type creation
2531 "typedef"
2532 ))))
2533(defconst verilog-declaration-core-re
2534 (eval-when-compile
2535 (verilog-regexp-words
2536 `(
7e2a6000 2537 ;; port direction (by themselves)
871c637e 2538 "inout" "input" "output"
6341f357
DN
2539 ;; integer_atom_type
2540 "byte" "shortint" "int" "longint" "integer" "time"
2541 ;; integer_vector_type
2542 "bit" "logic" "reg"
2543 ;; non_integer_type
2544 "shortreal" "real" "realtime"
2545 ;; net_type
2546 "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
2547 ;; misc
2548 "string" "event" "chandle" "virtual" "enum" "genvar"
2549 "struct" "union"
2550 ;; builtin classes
6edb5716 2551 "mailbox" "semaphore"
6341f357 2552 ))))
6edb5716 2553(defconst verilog-declaration-re
6341f357
DN
2554 (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
2555(defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
2556(defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
2557(defconst verilog-optional-signed-range-re
2558 (concat
2559 "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
2560(defconst verilog-macroexp-re "`\\sw+")
2561
2562(defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
2563(defconst verilog-declaration-re-2-no-macro
2564 (concat "\\s-*" verilog-declaration-re
2565 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2566 "\\)?"))
2567(defconst verilog-declaration-re-2-macro
2568 (concat "\\s-*" verilog-declaration-re
2569 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2570 "\\|\\(" verilog-macroexp-re "\\)"
2571 "\\)?"))
2572(defconst verilog-declaration-re-1-macro
2573 (concat "^" verilog-declaration-re-2-macro))
2574
2575(defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
2576
2577(defconst verilog-defun-re
2578 (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
2579(defconst verilog-end-defun-re
2580 (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
2581(defconst verilog-zero-indent-re
2582 (concat verilog-defun-re "\\|" verilog-end-defun-re))
9489a450
MM
2583(defconst verilog-inst-comment-re
2584 (eval-when-compile (verilog-regexp-words `("Outputs" "Inouts" "Inputs" "Interfaces" "Interfaced"))))
6341f357
DN
2585
2586(defconst verilog-behavioral-block-beg-re
2a9eb3f5
DN
2587 (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
2588 "function" "task"))))
a3a8b002 2589(defconst verilog-coverpoint-re "\\w+\\s*:\\s*\\(coverpoint\\|cross\\constraint\\)" )
ea89ff08
WS
2590(defconst verilog-in-constraint-re ;; keywords legal in constraint blocks starting a statement/block
2591 (eval-when-compile (verilog-regexp-words `("if" "else" "solve" "foreach"))))
2592
6341f357
DN
2593(defconst verilog-indent-re
2594 (eval-when-compile
2595 (verilog-regexp-words
2596 `(
2597 "{"
2598 "always" "always_latch" "always_ff" "always_comb"
2599 "begin" "end"
2600; "unique" "priority"
2601 "case" "casex" "casez" "randcase" "endcase"
2602 "class" "endclass"
2603 "clocking" "endclocking"
2604 "config" "endconfig"
2605 "covergroup" "endgroup"
2606 "fork" "join" "join_any" "join_none"
2607 "function" "endfunction"
2608 "final"
2609 "generate" "endgenerate"
2610 "initial"
2611 "interface" "endinterface"
2612 "module" "macromodule" "endmodule"
2613 "package" "endpackage"
4c36be58 2614 "primitive" "endprimitive"
6341f357
DN
2615 "program" "endprogram"
2616 "property" "endproperty"
2617 "sequence" "randsequence" "endsequence"
2618 "specify" "endspecify"
2619 "table" "endtable"
2620 "task" "endtask"
4c5e69c6 2621 "virtual"
6341f357
DN
2622 "`case"
2623 "`default"
2624 "`define" "`undef"
a03c2342 2625 "`if" "`ifdef" "`ifndef" "`else" "`elsif" "`endif"
6341f357
DN
2626 "`while" "`endwhile"
2627 "`for" "`endfor"
2628 "`format"
2629 "`include"
2630 "`let"
2631 "`protect" "`endprotect"
2632 "`switch" "`endswitch"
2633 "`timescale"
2634 "`time_scale"
a3a8b002
DN
2635 ;; OVM Begin tokens
2636 "`ovm_component_utils_begin"
14862301 2637 "`ovm_component_param_utils_begin"
a3a8b002
DN
2638 "`ovm_field_utils_begin"
2639 "`ovm_object_utils_begin"
14862301 2640 "`ovm_object_param_utils_begin"
a3a8b002
DN
2641 "`ovm_sequence_utils_begin"
2642 "`ovm_sequencer_utils_begin"
2643 ;; OVM End tokens
2644 "`ovm_component_utils_end"
2645 "`ovm_field_utils_end"
2646 "`ovm_object_utils_end"
2647 "`ovm_sequence_utils_end"
2648 "`ovm_sequencer_utils_end"
9489a450
MM
2649 ;; UVM Begin tokens
2650 "`uvm_component_utils_begin"
2651 "`uvm_component_param_utils_begin"
2652 "`uvm_field_utils_begin"
2653 "`uvm_object_utils_begin"
2654 "`uvm_object_param_utils_begin"
2655 "`uvm_sequence_utils_begin"
2656 "`uvm_sequencer_utils_begin"
2657 ;; UVM End tokens
2658 "`uvm_component_utils_end" ;; Typo in spec, it's not uvm_component_end
2659 "`uvm_field_utils_end"
2660 "`uvm_object_utils_end"
2661 "`uvm_sequence_utils_end"
2662 "`uvm_sequencer_utils_end"
86a4c7ac
DN
2663 ;; VMM Begin tokens
2664 "`vmm_data_member_begin"
2665 "`vmm_env_member_begin"
2666 "`vmm_scenario_member_begin"
2667 "`vmm_subenv_member_begin"
2668 "`vmm_xactor_member_begin"
2669 ;; VMM End tokens
2670 "`vmm_data_member_end"
2671 "`vmm_env_member_end"
2672 "`vmm_scenario_member_end"
2673 "`vmm_subenv_member_end"
2674 "`vmm_xactor_member_end"
6341f357
DN
2675 ))))
2676
a3a8b002
DN
2677(defconst verilog-defun-level-not-generate-re
2678 (eval-when-compile
2679 (verilog-regexp-words
2680 `( "module" "macromodule" "primitive" "class" "program"
2681 "interface" "package" "config"))))
2682
6341f357
DN
2683(defconst verilog-defun-level-re
2684 (eval-when-compile
2685 (verilog-regexp-words
a3a8b002
DN
2686 (append
2687 `( "module" "macromodule" "primitive" "class" "program"
2688 "interface" "package" "config")
2689 `( "initial" "final" "always" "always_comb" "always_ff"
2690 "always_latch" "endtask" "endfunction" )))))
6341f357 2691
a3a8b002 2692(defconst verilog-defun-level-generate-only-re
6341f357
DN
2693 (eval-when-compile
2694 (verilog-regexp-words
a3a8b002
DN
2695 `( "initial" "final" "always" "always_comb" "always_ff"
2696 "always_latch" "endtask" "endfunction" ))))
6341f357
DN
2697
2698(defconst verilog-cpp-level-re
2699 (eval-when-compile
2700 (verilog-regexp-words
2701 `(
2702 "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
2703 ))))
9489a450 2704(defconst verilog-disable-fork-re "\\(disable\\|wait\\)\\s-+fork\\>")
ea89ff08 2705(defconst verilog-extended-case-re "\\(\\(unique0?\\s-+\\|priority\\s-+\\)?case[xz]?\\)")
6341f357 2706(defconst verilog-extended-complete-re
47086495
WS
2707 (concat "\\(\\(\\<extern\\s-+\\|\\<\\(\\<pure\\>\\s-+\\)?virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)\\)"
2708 "\\|\\(\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)\\)"
2709 "\\|\\(\\(\\<import\\>\\s-+\\)?\\(\"DPI-C\"\\s-+\\)?\\(\\<pure\\>\\s-+\\)?\\(function\\>\\|task\\>\\)\\)"
6341f357
DN
2710 "\\|" verilog-extended-case-re ))
2711(defconst verilog-basic-complete-re
2712 (eval-when-compile
2713 (verilog-regexp-words
2714 `(
2715 "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
2716 "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
14862301 2717 "if" "for" "forever" "foreach" "else" "parameter" "do" "localparam" "assert"
6341f357
DN
2718 ))))
2719(defconst verilog-complete-reg
2720 (concat
47086495 2721 verilog-extended-complete-re "\\|\\(" verilog-basic-complete-re "\\)"))
6341f357
DN
2722
2723(defconst verilog-end-statement-re
2724 (concat "\\(" verilog-beg-block-re "\\)\\|\\("
2725 verilog-end-block-re "\\)"))
2726
2727(defconst verilog-endcase-re
a3a8b002 2728 (concat verilog-extended-case-re "\\|"
6341f357
DN
2729 "\\(endcase\\)\\|"
2730 verilog-defun-re
2731 ))
2732
2733(defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
2734 "String used to mark beginning of excluded text.")
2735(defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
2736 "String used to mark end of excluded text.")
2737(defconst verilog-preprocessor-re
2738 (eval-when-compile
2739 (verilog-regexp-words
2740 `(
2741 "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
2742 ))))
2743
2744(defconst verilog-keywords
2745 '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
2746 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
2747 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
2748 "`time_scale" "`undef" "`while"
2749
2750 "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
2751 "assert" "assign" "assume" "automatic" "before" "begin" "bind"
2752 "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
2753 "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
2754 "config" "const" "constraint" "context" "continue" "cover"
2755 "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
2756 "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
2757 "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
2758 "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
2759 "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
2760 "endtask" "enum" "event" "expect" "export" "extends" "extern"
2761 "final" "first_match" "for" "force" "foreach" "forever" "fork"
2762 "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
2763 "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
2764 "include" "initial" "inout" "input" "inside" "instance" "int"
2765 "integer" "interface" "intersect" "join" "join_any" "join_none"
2766 "large" "liblist" "library" "local" "localparam" "logic"
2767 "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
2768 "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
2769 "notif0" "notif1" "null" "or" "output" "package" "packed"
2770 "parameter" "pmos" "posedge" "primitive" "priority" "program"
2771 "property" "protected" "pull0" "pull1" "pulldown" "pullup"
2772 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2773 "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
2774 "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
2775 "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
2776 "showcancelled" "signed" "small" "solve" "specify" "specparam"
2777 "static" "string" "strong0" "strong1" "struct" "super" "supply0"
2778 "supply1" "table" "tagged" "task" "this" "throughout" "time"
2779 "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
2780 "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
2781 "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
2782 "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
2783 "wire" "with" "within" "wor" "xnor" "xor"
fd9ea9d3
WS
2784 ;; 1800-2009
2785 "accept_on" "checker" "endchecker" "eventually" "global" "implies"
2786 "let" "nexttime" "reject_on" "restrict" "s_always" "s_eventually"
2787 "s_nexttime" "s_until" "s_until_with" "strong" "sync_accept_on"
2788 "sync_reject_on" "unique0" "until" "until_with" "untyped" "weak"
ea89ff08
WS
2789 ;; 1800-2012
2790 "implements" "interconnect" "nettype" "soft"
6341f357
DN
2791 )
2792 "List of Verilog keywords.")
2793
6341f357
DN
2794(defconst verilog-comment-start-regexp "//\\|/\\*"
2795 "Dual comment value for `comment-start-regexp'.")
2796
e1776067
DN
2797(defvar verilog-mode-syntax-table
2798 (let ((table (make-syntax-table)))
2799 ;; Populate the syntax TABLE.
2800 (modify-syntax-entry ?\\ "\\" table)
2801 (modify-syntax-entry ?+ "." table)
2802 (modify-syntax-entry ?- "." table)
2803 (modify-syntax-entry ?= "." table)
2804 (modify-syntax-entry ?% "." table)
2805 (modify-syntax-entry ?< "." table)
2806 (modify-syntax-entry ?> "." table)
2807 (modify-syntax-entry ?& "." table)
2808 (modify-syntax-entry ?| "." table)
1d5963cc
SM
2809 ;; FIXME: This goes against Emacs conventions. Use "_" syntax instead and
2810 ;; then use regexps with things like "\\_<...\\_>".
ea89ff08 2811 (modify-syntax-entry ?` "w" table) ;; ` is part of definition symbols in Verilog
e1776067
DN
2812 (modify-syntax-entry ?_ "w" table)
2813 (modify-syntax-entry ?\' "." table)
2814
2815 ;; Set up TABLE to handle block and line style comments.
2816 (if (featurep 'xemacs)
2817 (progn
2818 ;; XEmacs (formerly Lucid) has the best implementation
2819 (modify-syntax-entry ?/ ". 1456" table)
2820 (modify-syntax-entry ?* ". 23" table)
2821 (modify-syntax-entry ?\n "> b" table))
d63b01e1 2822 ;; Emacs does things differently, but we can work with it
e1776067
DN
2823 (modify-syntax-entry ?/ ". 124b" table)
2824 (modify-syntax-entry ?* ". 23" table)
2825 (modify-syntax-entry ?\n "> b" table))
2826 table)
37ea4b9b 2827 "Syntax table used in Verilog mode buffers.")
6341f357 2828
7ea26faf 2829(defvar verilog-font-lock-keywords nil
6341f357
DN
2830 "Default highlighting for Verilog mode.")
2831
7ea26faf 2832(defvar verilog-font-lock-keywords-1 nil
6341f357
DN
2833 "Subdued level highlighting for Verilog mode.")
2834
7ea26faf 2835(defvar verilog-font-lock-keywords-2 nil
6341f357
DN
2836 "Medium level highlighting for Verilog mode.
2837See also `verilog-font-lock-extra-types'.")
2838
7ea26faf 2839(defvar verilog-font-lock-keywords-3 nil
6341f357
DN
2840 "Gaudy level highlighting for Verilog mode.
2841See also `verilog-font-lock-extra-types'.")
47086495
WS
2842
2843(defvar verilog-font-lock-translate-off-face
6341f357
DN
2844 'verilog-font-lock-translate-off-face
2845 "Font to use for translated off regions.")
2846(defface verilog-font-lock-translate-off-face
2847 '((((class color)
2848 (background light))
2849 (:background "gray90" :italic t ))
2850 (((class color)
2851 (background dark))
2852 (:background "gray10" :italic t ))
2853 (((class grayscale) (background light))
2854 (:foreground "DimGray" :italic t))
2855 (((class grayscale) (background dark))
2856 (:foreground "LightGray" :italic t))
2857 (t (:italis t)))
2858 "Font lock mode face used to background highlight translate-off regions."
2859 :group 'font-lock-highlighting-faces)
2860
2861(defvar verilog-font-lock-p1800-face
2862 'verilog-font-lock-p1800-face
2863 "Font to use for p1800 keywords.")
2864(defface verilog-font-lock-p1800-face
2865 '((((class color)
2866 (background light))
2867 (:foreground "DarkOrange3" :bold t ))
2868 (((class color)
2869 (background dark))
2870 (:foreground "orange1" :bold t ))
2871 (t (:italic t)))
2872 "Font lock mode face used to highlight P1800 keywords."
2873 :group 'font-lock-highlighting-faces)
2874
2875(defvar verilog-font-lock-ams-face
2876 'verilog-font-lock-ams-face
2877 "Font to use for Analog/Mixed Signal keywords.")
2878(defface verilog-font-lock-ams-face
2879 '((((class color)
2880 (background light))
2881 (:foreground "Purple" :bold t ))
2882 (((class color)
2883 (background dark))
2884 (:foreground "orange1" :bold t ))
2885 (t (:italic t)))
2886 "Font lock mode face used to highlight AMS keywords."
2887 :group 'font-lock-highlighting-faces)
2888
2a9eb3f5
DN
2889(defvar verilog-font-grouping-keywords-face
2890 'verilog-font-lock-grouping-keywords-face
2891 "Font to use for Verilog Grouping Keywords (such as begin..end).")
2892(defface verilog-font-lock-grouping-keywords-face
2893 '((((class color)
2894 (background light))
2895 (:foreground "red4" :bold t ))
2896 (((class color)
2897 (background dark))
2898 (:foreground "red4" :bold t ))
2899 (t (:italic t)))
2900 "Font lock mode face used to highlight verilog grouping keywords."
2901 :group 'font-lock-highlighting-faces)
2902
6341f357
DN
2903(let* ((verilog-type-font-keywords
2904 (eval-when-compile
2905 (verilog-regexp-opt
2906 '(
2907 "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
2908 "event" "genvar" "inout" "input" "integer" "localparam"
2909 "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
fd9ea9d3 2910 "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
6341f357
DN
2911 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
2912 "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
2913 "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
2914 "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
2915 "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
2916 ) nil )))
2917
2918 (verilog-pragma-keywords
2919 (eval-when-compile
2920 (verilog-regexp-opt
47086495
WS
2921 '("surefire" "auto" "synopsys" "rtl_synthesis" "verilint" "leda" "0in"
2922 ) nil )))
6341f357 2923
fd9ea9d3 2924 (verilog-1800-2005-keywords
6341f357
DN
2925 (eval-when-compile
2926 (verilog-regexp-opt
2927 '("alias" "assert" "assume" "automatic" "before" "bind"
2928 "bins" "binsof" "break" "byte" "cell" "chandle" "class"
2929 "clocking" "config" "const" "constraint" "context" "continue"
2930 "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
2931 "dist" "do" "edge" "endclass" "endclocking" "endconfig"
2932 "endgroup" "endprogram" "endproperty" "endsequence" "enum"
2933 "expect" "export" "extends" "extern" "first_match" "foreach"
2934 "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
2935 "illegal_bins" "import" "incdir" "include" "inside" "instance"
2936 "int" "intersect" "large" "liblist" "library" "local" "longint"
2937 "matches" "medium" "modport" "new" "noshowcancelled" "null"
2938 "packed" "program" "property" "protected" "pull0" "pull1"
2939 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2940 "randcase" "randsequence" "ref" "release" "return" "scalared"
2941 "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
2942 "specparam" "static" "string" "strong0" "strong1" "struct"
2943 "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
2944 "type" "union" "unsigned" "use" "var" "virtual" "void"
2945 "wait_order" "weak0" "weak1" "wildcard" "with" "within"
2946 ) nil )))
2947
fd9ea9d3
WS
2948 (verilog-1800-2009-keywords
2949 (eval-when-compile
2950 (verilog-regexp-opt
2951 '("accept_on" "checker" "endchecker" "eventually" "global"
2952 "implies" "let" "nexttime" "reject_on" "restrict" "s_always"
2953 "s_eventually" "s_nexttime" "s_until" "s_until_with" "strong"
2954 "sync_accept_on" "sync_reject_on" "unique0" "until"
2955 "until_with" "untyped" "weak" ) nil )))
2956
ea89ff08
WS
2957 (verilog-1800-2012-keywords
2958 (eval-when-compile
2959 (verilog-regexp-opt
2960 '("implements" "interconnect" "nettype" "soft" ) nil )))
2961
6341f357
DN
2962 (verilog-ams-keywords
2963 (eval-when-compile
2964 (verilog-regexp-opt
2965 '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
2966 "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
2967 "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
2968 "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
2969 "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
2970 "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
2971 "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
2972 "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
2973 "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
2974 "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
2975 "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
2976
2977 (verilog-font-keywords
2978 (eval-when-compile
2979 (verilog-regexp-opt
2980 '(
2a9eb3f5
DN
2981 "assign" "case" "casex" "casez" "randcase" "deassign"
2982 "default" "disable" "else" "endcase" "endfunction"
6341f357
DN
2983 "endgenerate" "endinterface" "endmodule" "endprimitive"
2984 "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
2985 "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
2986 "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
2987 "package" "endpackage" "always" "always_comb" "always_ff"
2988 "always_latch" "posedge" "primitive" "priority" "release"
2989 "repeat" "specify" "table" "task" "unique" "wait" "while"
2990 "class" "program" "endclass" "endprogram"
2a9eb3f5
DN
2991 ) nil )))
2992
2993 (verilog-font-grouping-keywords
2994 (eval-when-compile
2995 (verilog-regexp-opt
2996 '( "begin" "end" ) nil ))))
6341f357
DN
2997
2998 (setq verilog-font-lock-keywords
2999 (list
3000 ;; Fontify all builtin keywords
3001 (concat "\\<\\(" verilog-font-keywords "\\|"
3002 ;; And user/system tasks and functions
a1ebd734
DN
3003 "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
3004 "\\)\\>")
b1d0fc86
DN
3005 ;; Fontify all types
3006 (if verilog-highlight-grouping-keywords
3007 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
3008 'verilog-font-lock-ams-face)
3009 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
3010 'font-lock-type-face))
3011 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
a1ebd734 3012 'font-lock-type-face)
fd9ea9d3 3013 ;; Fontify IEEE-1800-2005 keywords appropriately
6341f357 3014 (if verilog-highlight-p1800-keywords
fd9ea9d3 3015 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
6341f357 3016 'verilog-font-lock-p1800-face)
fd9ea9d3
WS
3017 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
3018 'font-lock-type-face))
3019 ;; Fontify IEEE-1800-2009 keywords appropriately
3020 (if verilog-highlight-p1800-keywords
3021 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
3022 'verilog-font-lock-p1800-face)
3023 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
6341f357 3024 'font-lock-type-face))
ea89ff08
WS
3025 ;; Fontify IEEE-1800-2012 keywords appropriately
3026 (if verilog-highlight-p1800-keywords
3027 (cons (concat "\\<\\(" verilog-1800-2012-keywords "\\)\\>")
3028 'verilog-font-lock-p1800-face)
3029 (cons (concat "\\<\\(" verilog-1800-2012-keywords "\\)\\>")
3030 'font-lock-type-face))
6341f357
DN
3031 ;; Fontify Verilog-AMS keywords
3032 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
60618039 3033 'verilog-font-lock-ams-face)))
6341f357
DN
3034
3035 (setq verilog-font-lock-keywords-1
3036 (append verilog-font-lock-keywords
3037 (list
3038 ;; Fontify module definitions
3039 (list
3040 "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
3041 '(1 font-lock-keyword-face)
3042 '(3 font-lock-function-name-face 'prepend))
3043 ;; Fontify function definitions
3044 (list
3045 (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
3046 '(1 font-lock-keyword-face)
ecb0ab90 3047 '(3 font-lock-constant-face prepend))
6341f357
DN
3048 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
3049 (1 font-lock-keyword-face)
ecb0ab90 3050 (2 font-lock-constant-face append))
6341f357 3051 '("\\<function\\>\\s-+\\(\\sw+\\)"
ecb0ab90 3052 1 'font-lock-constant-face append))))
6341f357
DN
3053
3054 (setq verilog-font-lock-keywords-2
3055 (append verilog-font-lock-keywords-1
3056 (list
3057 ;; Fontify pragmas
47086495 3058 (concat "\\(//\\s-*\\(" verilog-pragma-keywords "\\)\\s-.*\\)")
6341f357
DN
3059 ;; Fontify escaped names
3060 '("\\(\\\\\\S-*\\s-\\)" 0 font-lock-function-name-face)
3061 ;; Fontify macro definitions/ uses
3062 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
3063 'font-lock-preprocessor-face
3064 'font-lock-type-face))
3065 ;; Fontify delays/numbers
3066 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
3067 0 font-lock-type-face append)
3068 ;; Fontify instantiation names
a03c2342 3069 '("\\([A-Za-z][A-Za-z0-9_]*\\)\\s-*(" 1 font-lock-function-name-face)
6341f357
DN
3070 )))
3071
3072 (setq verilog-font-lock-keywords-3
3073 (append verilog-font-lock-keywords-2
3074 (when verilog-highlight-translate-off
3075 (list
3076 ;; Fontify things in translate off regions
7ea26faf
DN
3077 '(verilog-match-translate-off
3078 (0 'verilog-font-lock-translate-off-face prepend))
3079 )))))
6341f357 3080
a03c2342
WS
3081;;
3082;; Buffer state preservation
3083
3084(defmacro verilog-save-buffer-state (&rest body)
3085 "Execute BODY forms, saving state around insignificant change.
3086Changes in text properties like `face' or `syntax-table' are
3087considered insignificant. This macro allows text properties to
3088be changed, even in a read-only buffer.
3089
3090A change is considered significant if it affects the buffer text
3091in any way that isn't completely restored again. Any
3092user-visible changes to the buffer must not be within a
3093`verilog-save-buffer-state'."
3094 ;; From c-save-buffer-state
3095 `(let* ((modified (buffer-modified-p))
3096 (buffer-undo-list t)
3097 (inhibit-read-only t)
3098 (inhibit-point-motion-hooks t)
9489a450 3099 (verilog-no-change-functions t)
a03c2342
WS
3100 before-change-functions
3101 after-change-functions
3102 deactivate-mark
3103 buffer-file-name ; Prevent primitives checking
3104 buffer-file-truename) ; for file modification
3105 (unwind-protect
3106 (progn ,@body)
3107 (and (not modified)
3108 (buffer-modified-p)
3109 (set-buffer-modified-p nil)))))
3110
3111(defmacro verilog-save-no-change-functions (&rest body)
3112 "Execute BODY forms, disabling all change hooks in BODY.
53964682 3113For insignificant changes, see instead `verilog-save-buffer-state'."
a03c2342 3114 `(let* ((inhibit-point-motion-hooks t)
9489a450 3115 (verilog-no-change-functions t)
a03c2342
WS
3116 before-change-functions
3117 after-change-functions)
3118 (progn ,@body)))
6341f357 3119
47086495
WS
3120(defvar verilog-save-font-mod-hooked nil
3121 "Local variable when inside a `verilog-save-font-mods' block.")
3122(make-variable-buffer-local 'verilog-save-font-mod-hooked)
3123
3124(defmacro verilog-save-font-mods (&rest body)
3125 "Execute BODY forms, disabling text modifications to allow performing BODY.
3126Includes temporary disabling of `font-lock' to restore the buffer
3127to full text form for parsing. Additional actions may be specified with
3128`verilog-before-save-font-hook' and `verilog-after-save-font-hook'."
3129 ;; Before version 20, match-string with font-lock returns a
3130 ;; vector that is not equal to the string. IE if on "input"
3131 ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
3132 `(let* ((hooked (unless verilog-save-font-mod-hooked
3133 (verilog-run-hooks 'verilog-before-save-font-hook)
3134 t))
3135 (verilog-save-font-mod-hooked t)
3136 (fontlocked (when (and (boundp 'font-lock-mode) font-lock-mode)
3137 (font-lock-mode 0)
3138 t)))
3139 (unwind-protect
3140 (progn ,@body)
3141 ;; Unwind forms
3142 (when fontlocked (font-lock-mode t))
3143 (when hooked (verilog-run-hooks 'verilog-after-save-font-hook)))))
3144
a03c2342
WS
3145;;
3146;; Comment detection and caching
3147
3148(defvar verilog-scan-cache-preserving nil
ea89ff08 3149 "If true, the specified buffer's comment properties are static.
9489a450 3150Buffer changes will be ignored. See `verilog-inside-comment-or-string-p'
a03c2342
WS
3151and `verilog-scan'.")
3152
3153(defvar verilog-scan-cache-tick nil
3154 "Modification tick at which `verilog-scan' was last completed.")
3155(make-variable-buffer-local 'verilog-scan-cache-tick)
3156
9489a450
MM
3157(defun verilog-scan-cache-flush ()
3158 "Flush the `verilog-scan' cache."
3159 (setq verilog-scan-cache-tick nil))
3160
a03c2342 3161(defun verilog-scan-cache-ok-p ()
d136f184 3162 "Return t if the scan cache is up to date."
a03c2342
WS
3163 (or (and verilog-scan-cache-preserving
3164 (eq verilog-scan-cache-preserving (current-buffer))
3165 verilog-scan-cache-tick)
3166 (equal verilog-scan-cache-tick (buffer-chars-modified-tick))))
3167
3168(defmacro verilog-save-scan-cache (&rest body)
3169 "Execute the BODY forms, allowing scan cache preservation within BODY.
3170This requires that insertions must use `verilog-insert'."
3171 ;; If the buffer is out of date, trash it, as we'll not check later the tick
3172 ;; Note this must work properly if there's multiple layers of calls
3173 ;; to verilog-save-scan-cache even with differing ticks.
3174 `(progn
3175 (unless (verilog-scan-cache-ok-p) ;; Must be before let
3176 (setq verilog-scan-cache-tick nil))
3177 (let* ((verilog-scan-cache-preserving (current-buffer)))
3178 (progn ,@body))))
3179
3180(defun verilog-scan-region (beg end)
9489a450
MM
3181 "Parse between BEG and END for `verilog-inside-comment-or-string-p'.
3182This creates v-cmts properties where comments are in force."
a03c2342
WS
3183 ;; Why properties and not overlays? Overlays have much slower non O(1)
3184 ;; lookup times.
3185 ;; This function is warm - called on every verilog-insert
6341f357 3186 (save-excursion
a03c2342
WS
3187 (save-match-data
3188 (verilog-save-buffer-state
3189 (let (pt)
3190 (goto-char beg)
3191 (while (< (point) end)
3192 (cond ((looking-at "//")
3193 (setq pt (point))
3194 (or (search-forward "\n" end t)
3195 (goto-char end))
3196 ;; "1+": The leading // or /* itself isn't considered as
3197 ;; being "inside" the comment, so that a (search-backward)
3198 ;; that lands at the start of the // won't mis-indicate
9489a450
MM
3199 ;; it's inside a comment. Also otherwise it would be
3200 ;; hard to find a commented out /*AS*/ vs one that isn't
3201 (put-text-property (1+ pt) (point) 'v-cmts t))
a03c2342
WS
3202 ((looking-at "/\\*")
3203 (setq pt (point))
3204 (or (search-forward "*/" end t)
3205 ;; No error - let later code indicate it so we can
3206 ;; use inside functions on-the-fly
3207 ;;(error "%s: Unmatched /* */, at char %d"
3208 ;; (verilog-point-text) (point))
3209 (goto-char end))
9489a450
MM
3210 (put-text-property (1+ pt) (point) 'v-cmts t))
3211 ((looking-at "\"")
3212 (setq pt (point))
3213 (or (re-search-forward "[^\\]\"" end t) ;; don't forward-char first, since we look for a non backslash first
3214 ;; No error - let later code indicate it so we can
3215 (goto-char end))
3216 (put-text-property (1+ pt) (point) 'v-cmts t))
a03c2342
WS
3217 (t
3218 (forward-char 1)
9489a450
MM
3219 (if (re-search-forward "[/\"]" end t)
3220 (backward-char 1)
a03c2342
WS
3221 (goto-char end))))))))))
3222
3223(defun verilog-scan ()
3224 "Parse the buffer, marking all comments with properties.
3225Also assumes any text inserted since `verilog-scan-cache-tick'
3226either is ok to parse as a non-comment, or `verilog-insert' was used."
9489a450 3227 ;; See also `verilog-scan-debug' and `verilog-scan-and-debug'
a03c2342
WS
3228 (unless (verilog-scan-cache-ok-p)
3229 (save-excursion
3230 (verilog-save-buffer-state
3231 (when verilog-debug
3232 (message "Scanning %s cache=%s cachetick=%S tick=%S" (current-buffer)
3233 verilog-scan-cache-preserving verilog-scan-cache-tick
3234 (buffer-chars-modified-tick)))
9489a450 3235 (remove-text-properties (point-min) (point-max) '(v-cmts nil))
a03c2342
WS
3236 (verilog-scan-region (point-min) (point-max))
3237 (setq verilog-scan-cache-tick (buffer-chars-modified-tick))
8350f087 3238 (when verilog-debug (message "Scanning... done"))))))
6341f357 3239
9489a450
MM
3240(defun verilog-scan-debug ()
3241 "For debugging, show with display face results of `verilog-scan'."
3242 (font-lock-mode 0)
3243 ;;(if dbg (setq dbg (concat dbg (format "verilog-scan-debug\n"))))
3244 (save-excursion
3245 (goto-char (point-min))
3246 (remove-text-properties (point-min) (point-max) '(face nil))
3247 (while (not (eobp))
3248 (cond ((get-text-property (point) 'v-cmts)
3249 (put-text-property (point) (1+ (point)) `face 'underline)
3250 ;;(if dbg (setq dbg (concat dbg (format " v-cmts at %S\n" (point)))))
3251 (forward-char 1))
3252 (t
3253 (goto-char (or (next-property-change (point)) (point-max))))))))
3254
3255(defun verilog-scan-and-debug ()
3256 "For debugging, run `verilog-scan' and `verilog-scan-debug'."
3257 (let (verilog-scan-cache-preserving
3258 verilog-scan-cache-tick)
3259 (goto-char (point-min))
3260 (verilog-scan)
3261 (verilog-scan-debug)))
3262
3263(defun verilog-inside-comment-or-string-p (&optional pos)
3264 "Check if optional point POS is inside a comment.
a03c2342
WS
3265This may require a slow pre-parse of the buffer with `verilog-scan'
3266to establish comment properties on all text."
3267 ;; This function is very hot
3268 (verilog-scan)
9489a450
MM
3269 (if pos
3270 (and (>= pos (point-min))
3271 (get-text-property pos 'v-cmts))
3272 (get-text-property (point) 'v-cmts)))
a03c2342
WS
3273
3274(defun verilog-insert (&rest stuff)
9489a450 3275 "Insert STUFF arguments, tracking for `verilog-inside-comment-or-string-p'.
47086495 3276Any insert that includes a comment must have the entire comment
a03c2342
WS
3277inserted using a single call to `verilog-insert'."
3278 (let ((pt (point)))
3279 (while stuff
3280 (insert (car stuff))
3281 (setq stuff (cdr stuff)))
3282 (verilog-scan-region pt (point))))
3283
3284;; More searching
6341f357
DN
3285
3286(defun verilog-declaration-end ()
3287 (search-forward ";"))
3288
3289(defun verilog-point-text (&optional pointnum)
3290 "Return text describing where POINTNUM or current point is (for errors).
3291Use filename, if current buffer being edited shorten to just buffer name."
290d5b58 3292 (concat (or (and (equal (window-buffer) (current-buffer))
6341f357
DN
3293 (buffer-name))
3294 buffer-file-name
3295 (buffer-name))
9489a450 3296 ":" (int-to-string (1+ (count-lines (point-min) (or pointnum (point)))))))
6341f357
DN
3297
3298(defun electric-verilog-backward-sexp ()
495ab0d5 3299 "Move backward over one balanced expression."
6341f357
DN
3300 (interactive)
3301 ;; before that see if we are in a comment
60618039
DN
3302 (verilog-backward-sexp))
3303
6341f357 3304(defun electric-verilog-forward-sexp ()
495ab0d5 3305 "Move forward over one balanced expression."
6341f357
DN
3306 (interactive)
3307 ;; before that see if we are in a comment
60618039
DN
3308 (verilog-forward-sexp))
3309
6341f357
DN
3310;;;used by hs-minor-mode
3311(defun verilog-forward-sexp-function (arg)
3312 (if (< arg 0)
3313 (verilog-backward-sexp)
3314 (verilog-forward-sexp)))
3315
3316
3317(defun verilog-backward-sexp ()
3318 (let ((reg)
3319 (elsec 1)
3320 (found nil)
60618039 3321 (st (point)))
6341f357
DN
3322 (if (not (looking-at "\\<"))
3323 (forward-word -1))
3324 (cond
60618039 3325 ((verilog-skip-backward-comment-or-string))
6341f357
DN
3326 ((looking-at "\\<else\\>")
3327 (setq reg (concat
3328 verilog-end-block-re
3329 "\\|\\(\\<else\\>\\)"
60618039 3330 "\\|\\(\\<if\\>\\)"))
6341f357
DN
3331 (while (and (not found)
3332 (verilog-re-search-backward reg nil 'move))
3333 (cond
3334 ((match-end 1) ; matched verilog-end-block-re
3335 ; try to leap back to matching outward block by striding across
3336 ; indent level changing tokens then immediately
3337 ; previous line governs indentation.
3338 (verilog-leap-to-head))
3339 ((match-end 2) ; else, we're in deep
3340 (setq elsec (1+ elsec)))
3341 ((match-end 3) ; found it
3342 (setq elsec (1- elsec))
3343 (if (= 0 elsec)
3344 ;; Now previous line describes syntax
60618039 3345 (setq found 't))))))
6341f357
DN
3346 ((looking-at verilog-end-block-re)
3347 (verilog-leap-to-head))
3348 ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
3349 (cond
3350 ((match-end 1)
3351 (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
3352 ((match-end 2)
3353 (verilog-re-search-backward "\\<primitive\\>" nil 'move))
3354 ((match-end 3)
3355 (verilog-re-search-backward "\\<class\\>" nil 'move))
3356 ((match-end 4)
3357 (verilog-re-search-backward "\\<program\\>" nil 'move))
3358 ((match-end 5)
3359 (verilog-re-search-backward "\\<interface\\>" nil 'move))
3360 ((match-end 6)
3361 (verilog-re-search-backward "\\<package\\>" nil 'move))
3362 (t
3363 (goto-char st)
3364 (backward-sexp 1))))
3365 (t
3366 (goto-char st)
60618039 3367 (backward-sexp)))))
6341f357
DN
3368
3369(defun verilog-forward-sexp ()
3370 (let ((reg)
3371 (md 2)
4c5e69c6
DN
3372 (st (point))
3373 (nest 'yes))
6341f357
DN
3374 (if (not (looking-at "\\<"))
3375 (forward-word -1))
3376 (cond
3377 ((verilog-skip-forward-comment-or-string)
60618039 3378 (verilog-forward-syntactic-ws))
4c5e69c6 3379 ((looking-at verilog-beg-block-re-ordered)
6341f357 3380 (cond
4c5e69c6
DN
3381 ((match-end 1);
3382 ;; Search forward for matching end
6341f357 3383 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
4c5e69c6
DN
3384 ((match-end 2)
3385 ;; Search forward for matching endcase
ea89ff08 3386 (setq reg "\\(\\<randcase\\>\\|\\(\\<unique0?\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2a9eb3f5
DN
3387 (setq md 3) ;; ender is third item in regexp
3388 )
4c5e69c6 3389 ((match-end 4)
9489a450 3390 ;; might be "disable fork" or "wait fork"
fd9ea9d3
WS
3391 (let
3392 (here)
9489a450
MM
3393 (if (or
3394 (looking-at verilog-disable-fork-re)
3395 (and (looking-at "fork")
3396 (progn
3397 (setq here (point)) ;; sometimes a fork is just a fork
3398 (forward-word -1)
3399 (looking-at verilog-disable-fork-re))))
3400 (progn ;; it is a disable fork; ignore it
fd9ea9d3 3401 (goto-char (match-end 0))
9489a450 3402 (forward-word 1)
fd9ea9d3 3403 (setq reg nil))
9489a450
MM
3404 (progn ;; it is a nice simple fork
3405 (goto-char here) ;; return from looking for "disable fork"
3406 ;; Search forward for matching join
3407 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))))
4c5e69c6
DN
3408 ((match-end 6)
3409 ;; Search forward for matching endclass
6341f357 3410 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
a3a8b002 3411
4c5e69c6
DN
3412 ((match-end 7)
3413 ;; Search forward for matching endtable
3414 (setq reg "\\<endtable\\>" )
3415 (setq nest 'no))
3416 ((match-end 8)
3417 ;; Search forward for matching endspecify
3418 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
3419 ((match-end 9)
3420 ;; Search forward for matching endfunction
3421 (setq reg "\\<endfunction\\>" )
3422 (setq nest 'no))
3423 ((match-end 10)
a3a8b002
DN
3424 ;; Search forward for matching endfunction
3425 (setq reg "\\<endfunction\\>" )
3426 (setq nest 'no))
3427 ((match-end 14)
4c5e69c6
DN
3428 ;; Search forward for matching endtask
3429 (setq reg "\\<endtask\\>" )
3430 (setq nest 'no))
a3a8b002 3431 ((match-end 15)
4c5e69c6
DN
3432 ;; Search forward for matching endtask
3433 (setq reg "\\<endtask\\>" )
3434 (setq nest 'no))
a3a8b002 3435 ((match-end 19)
4c5e69c6
DN
3436 ;; Search forward for matching endgenerate
3437 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
a3a8b002 3438 ((match-end 20)
4c5e69c6
DN
3439 ;; Search forward for matching endgroup
3440 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
a3a8b002 3441 ((match-end 21)
4c5e69c6
DN
3442 ;; Search forward for matching endproperty
3443 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
a3a8b002 3444 ((match-end 25)
4c5e69c6
DN
3445 ;; Search forward for matching endsequence
3446 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
3447 (setq md 3)) ; 3 to get to endsequence in the reg above
a3a8b002 3448 ((match-end 27)
4c5e69c6
DN
3449 ;; Search forward for matching endclocking
3450 (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
2a9eb3f5
DN
3451 (if (and reg
3452 (forward-word 1))
6341f357 3453 (catch 'skip
a3a8b002 3454 (if (eq nest 'yes)
82883f0a
GM
3455 (let ((depth 1)
3456 here)
4c5e69c6
DN
3457 (while (verilog-re-search-forward reg nil 'move)
3458 (cond
fd9ea9d3 3459 ((match-end md) ; a closer in regular expression, so we are climbing out
4c5e69c6
DN
3460 (setq depth (1- depth))
3461 (if (= 0 depth) ; we are out!
3462 (throw 'skip 1)))
fd9ea9d3
WS
3463 ((match-end 1) ; an opener in the r-e, so we are in deeper now
3464 (setq here (point)) ; remember where we started
3465 (goto-char (match-beginning 1))
3466 (cond
fd9ea9d3
WS
3467 ((if (or
3468 (looking-at verilog-disable-fork-re)
3469 (and (looking-at "fork")
82883f0a 3470 (progn
fd9ea9d3
WS
3471 (forward-word -1)
3472 (looking-at verilog-disable-fork-re))))
3473 (progn ;; it is a disable fork; another false alarm
3474 (goto-char (match-end 0)))
3475 (progn ;; it is a simple fork (or has nothing to do with fork)
3476 (goto-char here)
3477 (setq depth (1+ depth))))))))))
4c5e69c6
DN
3478 (if (verilog-re-search-forward reg nil 'move)
3479 (throw 'skip 1))))))
a3a8b002 3480
6341f357
DN
3481 ((looking-at (concat
3482 "\\(\\<\\(macro\\)?module\\>\\)\\|"
3483 "\\(\\<primitive\\>\\)\\|"
3484 "\\(\\<class\\>\\)\\|"
3485 "\\(\\<program\\>\\)\\|"
3486 "\\(\\<interface\\>\\)\\|"
3487 "\\(\\<package\\>\\)"))
3488 (cond
3489 ((match-end 1)
3490 (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
3491 ((match-end 2)
3492 (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
3493 ((match-end 3)
3494 (verilog-re-search-forward "\\<endclass\\>" nil 'move))
3495 ((match-end 4)
3496 (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
3497 ((match-end 5)
3498 (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
3499 ((match-end 6)
3500 (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
3501 (t
3502 (goto-char st)
3503 (if (= (following-char) ?\) )
3504 (forward-char 1)
3505 (forward-sexp 1)))))
3506 (t
3507 (goto-char st)
3508 (if (= (following-char) ?\) )
3509 (forward-char 1)
60618039 3510 (forward-sexp 1))))))
6341f357
DN
3511
3512(defun verilog-declaration-beg ()
3513 (verilog-re-search-backward verilog-declaration-re (bobp) t))
3514
6341f357
DN
3515;;
3516;;
3517;; Mode
3518;;
3519(defvar verilog-which-tool 1)
6edb5716 3520;;;###autoload
175069ef 3521(define-derived-mode verilog-mode prog-mode "Verilog"
6341f357
DN
3522 "Major mode for editing Verilog code.
3523\\<verilog-mode-map>
3524See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
3525AUTOs can improve coding efficiency.
3526
3527Use \\[verilog-faq] for a pointer to frequently asked questions.
3528
3529NEWLINE, TAB indents for Verilog code.
3530Delete converts tabs to spaces as it moves back.
3531
3532Supports highlighting.
3533
3534Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
3535with no args, if that value is non-nil.
3536
3537Variables controlling indentation/edit style:
3538
3539 variable `verilog-indent-level' (default 3)
3540 Indentation of Verilog statements with respect to containing block.
3541 `verilog-indent-level-module' (default 3)
3542 Absolute indentation of Module level Verilog statements.
3543 Set to 0 to get initial and always statements lined up
3544 on the left side of your screen.
3545 `verilog-indent-level-declaration' (default 3)
3546 Indentation of declarations with respect to containing block.
3547 Set to 0 to get them list right under containing block.
3548 `verilog-indent-level-behavioral' (default 3)
3549 Indentation of first begin in a task or function block
37ea4b9b
JB
3550 Set to 0 to get such code to lined up underneath the task or
3551 function keyword.
6341f357 3552 `verilog-indent-level-directive' (default 1)
37ea4b9b 3553 Indentation of `ifdef/`endif blocks.
6341f357
DN
3554 `verilog-cexp-indent' (default 1)
3555 Indentation of Verilog statements broken across lines i.e.:
3556 if (a)
3557 begin
3558 `verilog-case-indent' (default 2)
3559 Indentation for case statements.
3560 `verilog-auto-newline' (default nil)
3561 Non-nil means automatically newline after semicolons and the punctuation
3562 mark after an end.
3563 `verilog-auto-indent-on-newline' (default t)
37ea4b9b 3564 Non-nil means automatically indent line after newline.
6341f357
DN
3565 `verilog-tab-always-indent' (default t)
3566 Non-nil means TAB in Verilog mode should always reindent the current line,
3567 regardless of where in the line point is when the TAB command is used.
3568 `verilog-indent-begin-after-if' (default t)
3569 Non-nil means to indent begin statements following a preceding
37ea4b9b 3570 if, else, while, for and repeat statements, if any. Otherwise,
6341f357
DN
3571 the begin is lined up with the preceding token. If t, you get:
3572 if (a)
3573 begin // amount of indent based on `verilog-cexp-indent'
3574 otherwise you get:
3575 if (a)
3576 begin
3577 `verilog-auto-endcomments' (default t)
3578 Non-nil means a comment /* ... */ is set after the ends which ends
3579 cases, tasks, functions and modules.
3580 The type and name of the object will be set between the braces.
3581 `verilog-minimum-comment-distance' (default 10)
3582 Minimum distance (in lines) between begin and end required before a comment
3583 will be inserted. Setting this variable to zero results in every
3584 end acquiring a comment; the default avoids too many redundant
3585 comments in tight quarters.
a3a8b002 3586 `verilog-auto-lineup' (default 'declarations)
6341f357
DN
3587 List of contexts where auto lineup of code should be done.
3588
3589Variables controlling other actions:
3590
3591 `verilog-linter' (default surelint)
3592 Unix program to call to run the lint checker. This is the default
3593 command for \\[compile-command] and \\[verilog-auto-save-compile].
3594
3595See \\[customize] for the complete list of variables.
3596
3597AUTO expansion functions are, in part:
3598
3599 \\[verilog-auto] Expand AUTO statements.
3600 \\[verilog-delete-auto] Remove the AUTOs.
3601 \\[verilog-inject-auto] Insert AUTOs for the first time.
3602
3603Some other functions are:
3604
3605 \\[verilog-complete-word] Complete word with appropriate possibilities.
3606 \\[verilog-mark-defun] Mark function.
3607 \\[verilog-beg-of-defun] Move to beginning of current function.
3608 \\[verilog-end-of-defun] Move to end of current function.
3609 \\[verilog-label-be] Label matching begin ... end, fork ... join, etc statements.
3610
3611 \\[verilog-comment-region] Put marked area in a comment.
3612 \\[verilog-uncomment-region] Uncomment an area commented with \\[verilog-comment-region].
495ab0d5 3613 \\[verilog-insert-block] Insert begin ... end.
6341f357
DN
3614 \\[verilog-star-comment] Insert /* ... */.
3615
495ab0d5 3616 \\[verilog-sk-always] Insert an always @(AS) begin .. end block.
6341f357
DN
3617 \\[verilog-sk-begin] Insert a begin .. end block.
3618 \\[verilog-sk-case] Insert a case block, prompting for details.
3619 \\[verilog-sk-for] Insert a for (...) begin .. end block, prompting for details.
3620 \\[verilog-sk-generate] Insert a generate .. endgenerate block.
495ab0d5 3621 \\[verilog-sk-header] Insert a header block at the top of file.
6341f357
DN
3622 \\[verilog-sk-initial] Insert an initial begin .. end block.
3623 \\[verilog-sk-fork] Insert a fork begin .. end .. join block.
3624 \\[verilog-sk-module] Insert a module .. (/*AUTOARG*/);.. endmodule block.
9489a450 3625 \\[verilog-sk-ovm-class] Insert an OVM Class block.
ea89ff08
WS
3626 \\[verilog-sk-uvm-object] Insert an UVM Object block.
3627 \\[verilog-sk-uvm-component] Insert an UVM Component block.
6341f357
DN
3628 \\[verilog-sk-primitive] Insert a primitive .. (.. );.. endprimitive block.
3629 \\[verilog-sk-repeat] Insert a repeat (..) begin .. end block.
3630 \\[verilog-sk-specify] Insert a specify .. endspecify block.
3631 \\[verilog-sk-task] Insert a task .. begin .. end endtask block.
3632 \\[verilog-sk-while] Insert a while (...) begin .. end block, prompting for details.
3633 \\[verilog-sk-casex] Insert a casex (...) item: begin.. end endcase block, prompting for details.
3634 \\[verilog-sk-casez] Insert a casez (...) item: begin.. end endcase block, prompting for details.
3635 \\[verilog-sk-if] Insert an if (..) begin .. end block.
3636 \\[verilog-sk-else-if] Insert an else if (..) begin .. end block.
3637 \\[verilog-sk-comment] Insert a comment block.
3638 \\[verilog-sk-assign] Insert an assign .. = ..; statement.
3639 \\[verilog-sk-function] Insert a function .. begin .. end endfunction block.
3640 \\[verilog-sk-input] Insert an input declaration, prompting for details.
3641 \\[verilog-sk-output] Insert an output declaration, prompting for details.
3642 \\[verilog-sk-state-machine] Insert a state machine definition, prompting for details.
3643 \\[verilog-sk-inout] Insert an inout declaration, prompting for details.
3644 \\[verilog-sk-wire] Insert a wire declaration, prompting for details.
3645 \\[verilog-sk-reg] Insert a register declaration, prompting for details.
3646 \\[verilog-sk-define-signal] Define signal under point as a register at the top of the module.
3647
3648All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
3649Key bindings specific to `verilog-mode-map' are:
3650
3651\\{verilog-mode-map}"
175069ef 3652 :abbrev-table verilog-mode-abbrev-table
60618039 3653 (set (make-local-variable 'beginning-of-defun-function)
6edb5716 3654 'verilog-beg-of-defun)
60618039 3655 (set (make-local-variable 'end-of-defun-function)
6edb5716 3656 'verilog-end-of-defun)
6341f357 3657 (set-syntax-table verilog-mode-syntax-table)
175069ef
SM
3658 (set (make-local-variable 'indent-line-function)
3659 #'verilog-indent-line-relative)
c25f8957 3660 (set (make-local-variable 'comment-indent-function) 'verilog-comment-indent)
175069ef 3661 (set (make-local-variable 'parse-sexp-ignore-comments) nil)
175069ef
SM
3662 (set (make-local-variable 'comment-start) "// ")
3663 (set (make-local-variable 'comment-end) "")
3664 (set (make-local-variable 'comment-start-skip) "/\\*+ *\\|// *")
3665 (set (make-local-variable 'comment-multi-line) nil)
6341f357
DN
3666 ;; Set up for compilation
3667 (setq verilog-which-tool 1)
3668 (setq verilog-tool 'verilog-linter)
3669 (verilog-set-compile-command)
3670 (when (boundp 'hack-local-variables-hook) ;; Also modify any file-local-variables
3671 (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
3672
3673 ;; Setting up menus
6edb5716 3674 (when (featurep 'xemacs)
7d55bf04
DN
3675 (easy-menu-add verilog-stmt-menu)
3676 (easy-menu-add verilog-menu)
3677 (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
60618039 3678
d63b01e1 3679 ;; Stuff for GNU Emacs
7ea26faf 3680 (set (make-local-variable 'font-lock-defaults)
47086495
WS
3681 `((verilog-font-lock-keywords
3682 verilog-font-lock-keywords-1
3683 verilog-font-lock-keywords-2
3684 verilog-font-lock-keywords-3)
7664ec44 3685 nil nil nil
a3a8b002
DN
3686 ,(if (functionp 'syntax-ppss)
3687 ;; verilog-beg-of-defun uses syntax-ppss, and syntax-ppss uses
3688 ;; font-lock-beginning-of-syntax-function, so
3689 ;; font-lock-beginning-of-syntax-function, can't use
7664ec44 3690 ;; verilog-beg-of-defun.
a3a8b002
DN
3691 nil
3692 'verilog-beg-of-defun)))
6341f357 3693 ;;------------------------------------------------------------
a03c2342 3694 ;; now hook in 'verilog-highlight-include-files (eldo-mode.el&spice-mode.el)
6341f357 3695 ;; all buffer local:
a03c2342
WS
3696 (unless noninteractive ;; Else can't see the result, and change hooks are slow
3697 (when (featurep 'xemacs)
3698 (make-local-hook 'font-lock-mode-hook)
3699 (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
3700 (make-local-hook 'after-change-functions))
3701 (add-hook 'font-lock-mode-hook 'verilog-highlight-buffer t t)
3702 (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-highlight-buffer t t) ; not in Emacs
3703 (add-hook 'after-change-functions 'verilog-highlight-region t t))
6341f357 3704
37ea4b9b 3705 ;; Tell imenu how to handle Verilog.
175069ef
SM
3706 (set (make-local-variable 'imenu-generic-expression)
3707 verilog-imenu-generic-expression)
9c059794 3708 ;; Tell which-func-modes that imenu knows about verilog
7dd51bf1 3709 (when (and (boundp 'which-func-modes) (listp which-func-modes))
9c059794 3710 (add-to-list 'which-func-modes 'verilog-mode))
6341f357 3711 ;; hideshow support
9c059794
DN
3712 (when (boundp 'hs-special-modes-alist)
3713 (unless (assq 'verilog-mode hs-special-modes-alist)
3714 (setq hs-special-modes-alist
3715 (cons '(verilog-mode-mode "\\<begin\\>" "\\<end\\>" nil
3716 verilog-forward-sexp-function)
3717 hs-special-modes-alist))))
6341f357
DN
3718
3719 ;; Stuff for autos
9489a450
MM
3720 (add-hook 'write-contents-hooks 'verilog-auto-save-check nil 'local)
3721 ;; verilog-mode-hook call added by define-derived-mode
3722 )
6341f357
DN
3723\f
3724
3725;;
3726;; Electric functions
3727;;
3728(defun electric-verilog-terminate-line (&optional arg)
3729 "Terminate line and indent next line.
3730With optional ARG, remove existing end of line comments."
3731 (interactive)
3732 ;; before that see if we are in a comment
d63b01e1 3733 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
3734 (cond
3735 ((nth 7 state) ; Inside // comment
3736 (if (eolp)
3737 (progn
3738 (delete-horizontal-space)
3739 (newline))
3740 (progn
3741 (newline)
7ea26faf 3742 (insert "// ")
6341f357
DN
3743 (beginning-of-line)))
3744 (verilog-indent-line))
3745 ((nth 4 state) ; Inside any comment (hence /**/)
3746 (newline)
3747 (verilog-more-comment))
3748 ((eolp)
3749 ;; First, check if current line should be indented
3750 (if (save-excursion
3751 (delete-horizontal-space)
3752 (beginning-of-line)
3753 (skip-chars-forward " \t")
3754 (if (looking-at verilog-auto-end-comment-lines-re)
3755 (let ((indent-str (verilog-indent-line)))
3756 ;; Maybe we should set some endcomments
3757 (if verilog-auto-endcomments
3758 (verilog-set-auto-endcomments indent-str arg))
3759 (end-of-line)
3760 (delete-horizontal-space)
3761 (if arg
3762 ()
3763 (newline))
3764 nil)
3765 (progn
3766 (end-of-line)
3767 (delete-horizontal-space)
60618039 3768 't)))
6341f357
DN
3769 ;; see if we should line up assignments
3770 (progn
a3a8b002
DN
3771 (if (or (eq 'all verilog-auto-lineup)
3772 (eq 'assignments verilog-auto-lineup))
3773 (verilog-pretty-expr t "\\(<\\|:\\)?=" ))
60618039
DN
3774 (newline))
3775 (forward-line 1))
6341f357
DN
3776 ;; Indent next line
3777 (if verilog-auto-indent-on-newline
60618039 3778 (verilog-indent-line)))
6341f357 3779 (t
60618039 3780 (newline)))))
6341f357
DN
3781
3782(defun electric-verilog-terminate-and-indent ()
3783 "Insert a newline and indent for the next statement."
3784 (interactive)
3785 (electric-verilog-terminate-line 1))
3786
3787(defun electric-verilog-semi ()
3788 "Insert `;' character and reindent the line."
3789 (interactive)
a3a8b002 3790 (verilog-insert-last-command-event)
6341f357
DN
3791
3792 (if (or (verilog-in-comment-or-string-p)
3793 (verilog-in-escaped-name-p))
3794 ()
3795 (save-excursion
3796 (beginning-of-line)
3797 (verilog-forward-ws&directives)
60618039 3798 (verilog-indent-line))
6341f357
DN
3799 (if (and verilog-auto-newline
3800 (not (verilog-parenthesis-depth)))
3801 (electric-verilog-terminate-line))))
3802
3803(defun electric-verilog-semi-with-comment ()
3804 "Insert `;' character, reindent the line and indent for comment."
3805 (interactive)
3806 (insert "\;")
3807 (save-excursion
3808 (beginning-of-line)
3809 (verilog-indent-line))
3810 (indent-for-comment))
3811
3812(defun electric-verilog-colon ()
3813 "Insert `:' and do all indentations except line indent on this line."
3814 (interactive)
a3a8b002 3815 (verilog-insert-last-command-event)
6341f357
DN
3816 ;; Do nothing if within string.
3817 (if (or
3818 (verilog-within-string)
3819 (not (verilog-in-case-region-p)))
3820 ()
3821 (save-excursion
3822 (let ((p (point))
3823 (lim (progn (verilog-beg-of-statement) (point))))
3824 (goto-char p)
3825 (verilog-backward-case-item lim)
3826 (verilog-indent-line)))
3827;; (let ((verilog-tab-always-indent nil))
3828;; (verilog-indent-line))
3829 ))
3830
3831;;(defun electric-verilog-equal ()
3832;; "Insert `=', and do indentation if within block."
3833;; (interactive)
a3a8b002 3834;; (verilog-insert-last-command-event)
6341f357
DN
3835;; Could auto line up expressions, but not yet
3836;; (if (eq (car (verilog-calculate-indent)) 'block)
3837;; (let ((verilog-tab-always-indent nil))
3838;; (verilog-indent-command)))
3839;; )
3840
3841(defun electric-verilog-tick ()
3842 "Insert back-tick, and indent to column 0 if this is a CPP directive."
3843 (interactive)
a3a8b002 3844 (verilog-insert-last-command-event)
6341f357 3845 (save-excursion
a3a8b002
DN
3846 (if (verilog-in-directive-p)
3847 (verilog-indent-line))))
6341f357
DN
3848
3849(defun electric-verilog-tab ()
3850 "Function called when TAB is pressed in Verilog mode."
3851 (interactive)
3852 ;; If verilog-tab-always-indent, indent the beginning of the line.
7cb1c4d7
DN
3853 (cond
3854 ;; The region is active, indent it.
3855 ((and (region-active-p)
3856 (not (eq (region-beginning) (region-end))))
3857 (indent-region (region-beginning) (region-end) nil))
3858 ((or verilog-tab-always-indent
3859 (save-excursion
3860 (skip-chars-backward " \t")
3861 (bolp)))
3862 (let* ((oldpnt (point))
3863 (boi-point
3864 (save-excursion
3865 (beginning-of-line)
3866 (skip-chars-forward " \t")
3867 (verilog-indent-line)
3868 (back-to-indentation)
3869 (point))))
3870 (if (< (point) boi-point)
3871 (back-to-indentation)
3872 (cond ((not verilog-tab-to-comment))
3873 ((not (eolp))
3874 (end-of-line))
3875 (t
3876 (indent-for-comment)
3877 (when (and (eolp) (= oldpnt (point)))
6341f357 3878 ; kill existing comment
7cb1c4d7
DN
3879 (beginning-of-line)
3880 (re-search-forward comment-start-skip oldpnt 'move)
3881 (goto-char (match-beginning 0))
3882 (skip-chars-backward " \t")
3883 (kill-region (point) oldpnt)))))))
3884 (t (progn (insert "\t")))))
a3a8b002 3885
6341f357
DN
3886\f
3887
3888;;
3889;; Interactive functions
3890;;
3891
3892(defun verilog-indent-buffer ()
3893 "Indent-region the entire buffer as Verilog code.
3894To call this from the command line, see \\[verilog-batch-indent]."
3895 (interactive)
3896 (verilog-mode)
3897 (indent-region (point-min) (point-max) nil))
3898
3899(defun verilog-insert-block ()
3900 "Insert Verilog begin ... end; block in the code with right indentation."
3901 (interactive)
3902 (verilog-indent-line)
3903 (insert "begin")
3904 (electric-verilog-terminate-line)
3905 (save-excursion
3906 (electric-verilog-terminate-line)
3907 (insert "end")
3908 (beginning-of-line)
3909 (verilog-indent-line)))
3910
3911(defun verilog-star-comment ()
3912 "Insert Verilog star comment at point."
3913 (interactive)
3914 (verilog-indent-line)
3915 (insert "/*")
3916 (save-excursion
3917 (newline)
3918 (insert " */"))
3919 (newline)
3920 (insert " * "))
3921
7ea26faf 3922(defun verilog-insert-1 (fmt max)
60618039 3923 "Use format string FMT to insert integers 0 to MAX - 1.
7ea26faf
DN
3924Inserts one integer per line, at the current column. Stops early
3925if it reaches the end of the buffer."
3926 (let ((col (current-column))
3927 (n 0))
3928 (save-excursion
3929 (while (< n max)
3930 (insert (format fmt n))
3931 (forward-line 1)
3932 ;; Note that this function does not bother to check for lines
3933 ;; shorter than col.
3934 (if (eobp)
3935 (setq n max)
3936 (setq n (1+ n))
3937 (move-to-column col))))))
3938
3939(defun verilog-insert-indices (max)
3940 "Insert a set of indices into a rectangle.
3941The upper left corner is defined by point. Indices begin with 0
3942and extend to the MAX - 1. If no prefix arg is given, the user
3943is prompted for a value. The indices are surrounded by square
3944brackets \[]. For example, the following code with the point
3945located after the first 'a' gives:
6341f357
DN
3946
3947 a = b a[ 0] = b
3948 a = b a[ 1] = b
3949 a = b a[ 2] = b
3950 a = b a[ 3] = b
3951 a = b ==> insert-indices ==> a[ 4] = b
3952 a = b a[ 5] = b
3953 a = b a[ 6] = b
3954 a = b a[ 7] = b
3955 a = b a[ 8] = b"
3956
60618039 3957 (interactive "NMAX: ")
7ea26faf 3958 (verilog-insert-1 "[%3d]" max))
6341f357 3959
7ea26faf 3960(defun verilog-generate-numbers (max)
6341f357
DN
3961 "Insert a set of generated numbers into a rectangle.
3962The upper left corner is defined by point. The numbers are padded to three
3963digits, starting with 000 and extending to (MAX - 1). If no prefix argument
7ea26faf 3964is supplied, then the user is prompted for the MAX number. Consider the
6341f357
DN
3965following code fragment:
3966
7ea26faf
DN
3967 buf buf buf buf000
3968 buf buf buf buf001
3969 buf buf buf buf002
3970 buf buf buf buf003
3971 buf buf ==> generate-numbers ==> buf buf004
3972 buf buf buf buf005
3973 buf buf buf buf006
3974 buf buf buf buf007
3975 buf buf buf buf008"
3976
60618039 3977 (interactive "NMAX: ")
7ea26faf 3978 (verilog-insert-1 "%3.3d" max))
6341f357
DN
3979
3980(defun verilog-mark-defun ()
37ea4b9b 3981 "Mark the current Verilog function (or procedure).
6341f357
DN
3982This puts the mark at the end, and point at the beginning."
3983 (interactive)
7d55bf04
DN
3984 (if (featurep 'xemacs)
3985 (progn
3986 (push-mark (point))
3987 (verilog-end-of-defun)
3988 (push-mark (point))
3989 (verilog-beg-of-defun)
3990 (if (fboundp 'zmacs-activate-region)
3991 (zmacs-activate-region)))
3992 (mark-defun)))
6341f357
DN
3993
3994(defun verilog-comment-region (start end)
3995 ; checkdoc-params: (start end)
3996 "Put the region into a Verilog comment.
3997The comments that are in this area are \"deformed\":
3998`*)' becomes `!(*' and `}' becomes `!{'.
3999These deformed comments are returned to normal if you use
4000\\[verilog-uncomment-region] to undo the commenting.
4001
4002The commented area starts with `verilog-exclude-str-start', and ends with
4003`verilog-exclude-str-end'. But if you change these variables,
4004\\[verilog-uncomment-region] won't recognize the comments."
4005 (interactive "r")
4006 (save-excursion
4007 ;; Insert start and endcomments
4008 (goto-char end)
4009 (if (and (save-excursion (skip-chars-forward " \t") (eolp))
4010 (not (save-excursion (skip-chars-backward " \t") (bolp))))
4011 (forward-line 1)
4012 (beginning-of-line))
4013 (insert verilog-exclude-str-end)
4014 (setq end (point))
4015 (newline)
4016 (goto-char start)
4017 (beginning-of-line)
4018 (insert verilog-exclude-str-start)
4019 (newline)
4020 ;; Replace end-comments within commented area
4021 (goto-char end)
4022 (save-excursion
4023 (while (re-search-backward "\\*/" start t)
4024 (replace-match "*-/" t t)))
4025 (save-excursion
4026 (let ((s+1 (1+ start)))
4027 (while (re-search-backward "/\\*" s+1 t)
60618039 4028 (replace-match "/-*" t t))))))
6341f357
DN
4029
4030(defun verilog-uncomment-region ()
4031 "Uncomment a commented area; change deformed comments back to normal.
4032This command does nothing if the pointer is not in a commented
4033area. See also `verilog-comment-region'."
4034 (interactive)
4035 (save-excursion
4036 (let ((start (point))
4037 (end (point)))
4038 ;; Find the boundaries of the comment
4039 (save-excursion
4040 (setq start (progn (search-backward verilog-exclude-str-start nil t)
4041 (point)))
4042 (setq end (progn (search-forward verilog-exclude-str-end nil t)
4043 (point))))
4044 ;; Check if we're really inside a comment
4045 (if (or (equal start (point)) (<= end (point)))
4046 (message "Not standing within commented area.")
4047 (progn
4048 ;; Remove endcomment
4049 (goto-char end)
4050 (beginning-of-line)
4051 (let ((pos (point)))
4052 (end-of-line)
4053 (delete-region pos (1+ (point))))
4054 ;; Change comments back to normal
4055 (save-excursion
4056 (while (re-search-backward "\\*-/" start t)
4057 (replace-match "*/" t t)))
4058 (save-excursion
4059 (while (re-search-backward "/-\\*" start t)
4060 (replace-match "/*" t t)))
4061 ;; Remove start comment
4062 (goto-char start)
4063 (beginning-of-line)
4064 (let ((pos (point)))
4065 (end-of-line)
4066 (delete-region pos (1+ (point)))))))))
4067
4068(defun verilog-beg-of-defun ()
4069 "Move backward to the beginning of the current function or procedure."
4070 (interactive)
4071 (verilog-re-search-backward verilog-defun-re nil 'move))
4072
9489a450
MM
4073(defun verilog-beg-of-defun-quick ()
4074 "Move backward to the beginning of the current function or procedure.
4075Uses `verilog-scan' cache."
4076 (interactive)
4077 (verilog-re-search-backward-quick verilog-defun-re nil 'move))
4078
6341f357
DN
4079(defun verilog-end-of-defun ()
4080 "Move forward to the end of the current function or procedure."
4081 (interactive)
4082 (verilog-re-search-forward verilog-end-defun-re nil 'move))
4083
0f137a73 4084(defun verilog-get-end-of-defun ()
6341f357
DN
4085 (save-excursion
4086 (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
4087 (point))
4088 (t
4089 (error "%s: Can't find endmodule" (verilog-point-text))
4090 (point-max)))))
4091
ea89ff08
WS
4092(defun verilog-label-be ()
4093 "Label matching begin ... end, fork ... join and case ... endcase statements."
6341f357
DN
4094 (interactive)
4095 (let ((cnt 0)
4096 (oldpos (point))
4097 (b (progn
4098 (verilog-beg-of-defun)
4099 (point-marker)))
4100 (e (progn
4101 (verilog-end-of-defun)
60618039 4102 (point-marker))))
6341f357
DN
4103 (goto-char (marker-position b))
4104 (if (> (- e b) 200)
4105 (message "Relabeling module..."))
4106 (while (and
4107 (> (marker-position e) (point))
4108 (verilog-re-search-forward
4109 (concat
4110 "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
4111 "\\|\\(`endif\\)\\|\\(`else\\)")
4112 nil 'move))
4113 (goto-char (match-beginning 0))
4114 (let ((indent-str (verilog-indent-line)))
4115 (verilog-set-auto-endcomments indent-str 't)
4116 (end-of-line)
60618039 4117 (delete-horizontal-space))
6341f357
DN
4118 (setq cnt (1+ cnt))
4119 (if (= 9 (% cnt 10))
60618039 4120 (message "%d..." cnt)))
6341f357
DN
4121 (goto-char oldpos)
4122 (if (or
4123 (> (- e b) 200)
4124 (> cnt 20))
60618039 4125 (message "%d lines auto commented" cnt))))
6341f357
DN
4126
4127(defun verilog-beg-of-statement ()
4128 "Move backward to beginning of statement."
4129 (interactive)
4130 ;; Move back token by token until we see the end
4c36be58 4131 ;; of some earlier line.
a03c2342
WS
4132 (let (h)
4133 (while
4134 ;; If the current point does not begin a new
4135 ;; statement, as in the character ahead of us is a ';', or SOF
4136 ;; or the string after us unambiguously starts a statement,
4137 ;; or the token before us unambiguously ends a statement,
4138 ;; then move back a token and test again.
4139 (not (or
4140 ;; stop if beginning of buffer
4141 (bolp)
4142 ;; stop if we find a ;
4143 (= (preceding-char) ?\;)
4144 ;; stop if we see a named coverpoint
4145 (looking-at "\\w+\\W*:\\W*\\(coverpoint\\|cross\\|constraint\\)")
4146 ;; keep going if we are in the middle of a word
4147 (not (or (looking-at "\\<") (forward-word -1)))
53964682 4148 ;; stop if we see an assertion (perhaps labeled)
a03c2342
WS
4149 (and
4150 (looking-at "\\(\\<\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(\\<assert\\>\\)")
4151 (progn
4152 (setq h (point))
4153 (save-excursion
4154 (verilog-backward-token)
4155 (if (looking-at verilog-label-re)
4156 (setq h (point))))
4157 (goto-char h)))
47086495 4158 ;; stop if we see an extended complete reg, perhaps a complete one
a03c2342
WS
4159 (and
4160 (looking-at verilog-complete-reg)
4161 (let* ((p (point)))
4162 (while (and (looking-at verilog-extended-complete-re)
4163 (progn (setq p (point))
4164 (verilog-backward-token)
4165 (/= p (point)))))
4166 (goto-char p)))
4167 ;; stop if we see a complete reg (previous found extended ones)
4168 (looking-at verilog-basic-complete-re)
4169 ;; stop if previous token is an ender
4170 (save-excursion
4171 (verilog-backward-token)
4172 (or
4173 (looking-at verilog-end-block-re)
4174 (looking-at verilog-preprocessor-re))))) ;; end of test
6341f357
DN
4175 (verilog-backward-syntactic-ws)
4176 (verilog-backward-token))
a03c2342
WS
4177 ;; Now point is where the previous line ended.
4178 (verilog-forward-syntactic-ws)))
6341f357
DN
4179
4180(defun verilog-beg-of-statement-1 ()
4181 "Move backward to beginning of statement."
4182 (interactive)
a3a8b002
DN
4183 (if (verilog-in-comment-p)
4184 (verilog-backward-syntactic-ws))
6341f357 4185 (let ((pt (point)))
a3a8b002
DN
4186 (catch 'done
4187 (while (not (looking-at verilog-complete-reg))
4188 (setq pt (point))
4189 (verilog-backward-syntactic-ws)
4190 (if (or (bolp)
a03c2342
WS
4191 (= (preceding-char) ?\;)
4192 (save-excursion
4193 (verilog-backward-token)
4194 (looking-at verilog-ends-re)))
a3a8b002
DN
4195 (progn
4196 (goto-char pt)
4197 (throw 'done t))
4198 (verilog-backward-token))))
4199 (verilog-forward-syntactic-ws)))
4200;
4201; (while (and
4202; (not (looking-at verilog-complete-reg))
4203; (not (bolp))
4204; (not (= (preceding-char) ?\;)))
4205; (verilog-backward-token)
4206; (verilog-backward-syntactic-ws)
4207; (setq pt (point)))
4208; (goto-char pt)
4209; ;(verilog-forward-syntactic-ws)
6341f357
DN
4210
4211(defun verilog-end-of-statement ()
4212 "Move forward to end of current statement."
4213 (interactive)
4214 (let ((nest 0) pos)
a3a8b002
DN
4215 (cond
4216 ((verilog-in-directive-p)
4217 (forward-line 1)
4218 (backward-char 1))
4219
4220 ((looking-at verilog-beg-block-re)
4221 (verilog-forward-sexp))
4222
4223 ((equal (char-after) ?\})
4224 (forward-char))
4225
4226 ;; Skip to end of statement
4227 ((condition-case nil
4228 (setq pos
4229 (catch 'found
4230 (while t
4231 (forward-sexp 1)
4232 (verilog-skip-forward-comment-or-string)
4233 (if (eolp)
4234 (forward-line 1))
4235 (cond ((looking-at "[ \t]*;")
4236 (skip-chars-forward "^;")
4237 (forward-char 1)
4238 (throw 'found (point)))
4239 ((save-excursion
4240 (forward-sexp -1)
4241 (looking-at verilog-beg-block-re))
4242 (goto-char (match-beginning 0))
4243 (throw 'found nil))
4244 ((looking-at "[ \t]*)")
4245 (throw 'found (point)))
4246 ((eobp)
4247 (throw 'found (point)))
4248 )))
4249
4250 )
4251 (error nil))
4252 (if (not pos)
4253 ;; Skip a whole block
4254 (catch 'found
4255 (while t
4256 (verilog-re-search-forward verilog-end-statement-re nil 'move)
4257 (setq nest (if (match-end 1)
4258 (1+ nest)
4259 (1- nest)))
4260 (cond ((eobp)
4261 (throw 'found (point)))
4262 ((= 0 nest)
4263 (throw 'found (verilog-end-of-statement))))))
4264 pos)))))
6341f357
DN
4265
4266(defun verilog-in-case-region-p ()
37ea4b9b
JB
4267 "Return true if in a case region.
4268More specifically, point @ in the line foo : @ begin"
6341f357
DN
4269 (interactive)
4270 (save-excursion
4271 (if (and
4272 (progn (verilog-forward-syntactic-ws)
4273 (looking-at "\\<begin\\>"))
4274 (progn (verilog-backward-syntactic-ws)
4275 (= (preceding-char) ?\:)))
4276 (catch 'found
4277 (let ((nest 1))
4278 (while t
4279 (verilog-re-search-backward
4280 (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
4281 "\\(\\<endcase\\>\\)\\>")
4282 nil 'move)
4283 (cond
4284 ((match-end 3)
4285 (setq nest (1+ nest)))
4286 ((match-end 2)
4287 (if (= nest 1)
4288 (throw 'found 1))
4289 (setq nest (1- nest)))
4290 (t
60618039 4291 (throw 'found (= nest 0)))))))
6341f357 4292 nil)))
9489a450 4293
a03c2342 4294(defun verilog-backward-up-list (arg)
47086495 4295 "Call `backward-up-list' ARG, ignoring comments."
9489a450
MM
4296 (let ((parse-sexp-ignore-comments t))
4297 (backward-up-list arg)))
4298
4299(defun verilog-forward-sexp-cmt (arg)
47086495 4300 "Call `forward-sexp' ARG, inside comments."
9489a450
MM
4301 (let ((parse-sexp-ignore-comments nil))
4302 (forward-sexp arg)))
4303
4304(defun verilog-forward-sexp-ign-cmt (arg)
47086495 4305 "Call `forward-sexp' ARG, ignoring comments."
9489a450
MM
4306 (let ((parse-sexp-ignore-comments t))
4307 (forward-sexp arg)))
a03c2342 4308
6341f357 4309(defun verilog-in-generate-region-p ()
37ea4b9b
JB
4310 "Return true if in a generate region.
4311More specifically, after a generate and before an endgenerate."
6341f357 4312 (interactive)
a3a8b002 4313 (let ((nest 1))
6341f357 4314 (save-excursion
a3a8b002
DN
4315 (catch 'done
4316 (while (and
4317 (/= nest 0)
4318 (verilog-re-search-backward
4319 "\\<\\(module\\)\\|\\(generate\\)\\|\\(endgenerate\\)\\>" nil 'move)
4320 (cond
4321 ((match-end 1) ; module - we have crawled out
4322 (throw 'done 1))
4323 ((match-end 2) ; generate
4324 (setq nest (1- nest)))
4325 ((match-end 3) ; endgenerate
4326 (setq nest (1+ nest))))))))
6341f357
DN
4327 (= nest 0) )) ; return nest
4328
4329(defun verilog-in-fork-region-p ()
4330 "Return true if between a fork and join."
4331 (interactive)
4332 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
60618039 4333 (nest 1))
6341f357
DN
4334 (save-excursion
4335 (while (and
4336 (/= nest 0)
4337 (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
4338 (cond
4339 ((match-end 1) ; fork
4340 (setq nest (1- nest)))
4341 ((match-end 2) ; join
60618039 4342 (setq nest (1+ nest)))))))
6341f357
DN
4343 (= nest 0) )) ; return nest
4344
4345(defun verilog-backward-case-item (lim)
4346 "Skip backward to nearest enclosing case item.
4347Limit search to point LIM."
4348 (interactive)
4349 (let ((str 'nil)
4350 (lim1
4351 (progn
4352 (save-excursion
4353 (verilog-re-search-backward verilog-endcomment-reason-re
4354 lim 'move)
4355 (point)))))
4356 ;; Try to find the real :
4357 (if (save-excursion (search-backward ":" lim1 t))
4358 (let ((colon 0)
4359 b e )
4360 (while
4361 (and
4362 (< colon 1)
4363 (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
4364 lim1 'move))
4365 (cond
4366 ((match-end 1) ;; [
4367 (setq colon (1+ colon))
4368 (if (>= colon 0)
4369 (error "%s: unbalanced [" (verilog-point-text))))
4370 ((match-end 2) ;; ]
4371 (setq colon (1- colon)))
4372
4373 ((match-end 3) ;; :
60618039 4374 (setq colon (1+ colon)))))
6341f357
DN
4375 ;; Skip back to beginning of case item
4376 (skip-chars-backward "\t ")
4377 (verilog-skip-backward-comment-or-string)
4378 (setq e (point))
4379 (setq b
4380 (progn
4381 (if
4382 (verilog-re-search-backward
4383 "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
4384 (progn
4385 (cond
4386 ((match-end 1)
4387 (goto-char (match-end 1))
4388 (verilog-forward-ws&directives)
4389 (if (looking-at "(")
4390 (progn
4391 (forward-sexp)
4392 (verilog-forward-ws&directives)))
4393 (point))
4394 (t
4395 (goto-char (match-end 0))
4396 (verilog-forward-ws&directives)
60618039
DN
4397 (point))))
4398 (error "Malformed case item"))))
6341f357
DN
4399 (setq str (buffer-substring b e))
4400 (if
4401 (setq e
4402 (string-match
4403 "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
4404 (setq str (concat (substring str 0 e) "...")))
4405 str)
4406 'nil)))
4407\f
4408
4409;;
4410;; Other functions
4411;;
4412
6ca0ff73 4413(defun verilog-kill-existing-comment ()
6341f357
DN
4414 "Kill auto comment on this line."
4415 (save-excursion
4416 (let* (
4417 (e (progn
4418 (end-of-line)
4419 (point)))
4420 (b (progn
4421 (beginning-of-line)
4422 (search-forward "//" e t))))
4423 (if b
4424 (delete-region (- b 2) e)))))
4425
4426(defconst verilog-directive-nest-re
4427 (concat "\\(`else\\>\\)\\|"
4428 "\\(`endif\\>\\)\\|"
4429 "\\(`if\\>\\)\\|"
4430 "\\(`ifdef\\>\\)\\|"
a03c2342
WS
4431 "\\(`ifndef\\>\\)\\|"
4432 "\\(`elsif\\>\\)"))
6341f357
DN
4433(defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
4434 "Add ending comment with given INDENT-STR.
4435With KILL-EXISTING-COMMENT, remove what was there before.
4436Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
4437Insert `// case expr ' if this line ends a case block.
4438Insert `// ifdef FOO ' if this line ends code conditional on FOO.
37ea4b9b
JB
4439Insert `// NAME ' if this line ends a function, task, module,
4440primitive or interface named NAME."
6341f357
DN
4441 (save-excursion
4442 (cond
4443 (; Comment close preprocessor directives
4444 (and
4445 (looking-at "\\(`endif\\)\\|\\(`else\\)")
4446 (or kill-existing-comment
4447 (not (save-excursion
4448 (end-of-line)
3ba6b2ee 4449 (search-backward "//" (point-at-bol) t)))))
6341f357
DN
4450 (let ((nest 1) b e
4451 m
60618039 4452 (else (if (match-end 2) "!" " ")))
6341f357
DN
4453 (end-of-line)
4454 (if kill-existing-comment
6ca0ff73 4455 (verilog-kill-existing-comment))
6341f357
DN
4456 (delete-horizontal-space)
4457 (save-excursion
4458 (backward-sexp 1)
4459 (while (and (/= nest 0)
4460 (verilog-re-search-backward verilog-directive-nest-re nil 'move))
4461 (cond
4462 ((match-end 1) ; `else
4463 (if (= nest 1)
4464 (setq else "!")))
4465 ((match-end 2) ; `endif
4466 (setq nest (1+ nest)))
4467 ((match-end 3) ; `if
4468 (setq nest (1- nest)))
4469 ((match-end 4) ; `ifdef
4470 (setq nest (1- nest)))
4471 ((match-end 5) ; `ifndef
a03c2342
WS
4472 (setq nest (1- nest)))
4473 ((match-end 6) ; `elsif
4474 (if (= nest 1)
4475 (progn
4476 (setq else "!")
4477 (setq nest 0))))))
6341f357
DN
4478 (if (match-end 0)
4479 (setq
4480 m (buffer-substring
4481 (match-beginning 0)
4482 (match-end 0))
4483 b (progn
4484 (skip-chars-forward "^ \t")
4485 (verilog-forward-syntactic-ws)
4486 (point))
4487 e (progn
4488 (skip-chars-forward "a-zA-Z0-9_")
60618039 4489 (point)))))
6341f357
DN
4490 (if b
4491 (if (> (count-lines (point) b) verilog-minimum-comment-distance)
4492 (insert (concat " // " else m " " (buffer-substring b e))))
4493 (progn
a03c2342 4494 (insert " // unmatched `else, `elsif or `endif")
60618039 4495 (ding 't)))))
6341f357
DN
4496
4497 (; Comment close case/class/function/task/module and named block
4498 (and (looking-at "\\<end")
4499 (or kill-existing-comment
4500 (not (save-excursion
4501 (end-of-line)
3ba6b2ee 4502 (search-backward "//" (point-at-bol) t)))))
6341f357
DN
4503 (let ((type (car indent-str)))
4504 (unless (eq type 'declaration)
4505 (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
4506 (if (looking-at verilog-end-block-ordered-re)
4507 (cond
4508 (;- This is a case block; search back for the start of this case
4509 (match-end 1) ;; of verilog-end-block-ordered-re
4510
4511 (let ((err 't)
4512 (str "UNMATCHED!!"))
4513 (save-excursion
4514 (verilog-leap-to-head)
4515 (cond
4516 ((looking-at "\\<randcase\\>")
4517 (setq str "randcase")
7ea26faf 4518 (setq err nil))
ea89ff08 4519 ((looking-at "\\(\\(unique0?\\s-+\\|priority\\s-+\\)?case[xz]?\\)")
a3a8b002
DN
4520 (goto-char (match-end 0))
4521 (setq str (concat (match-string 0) " " (verilog-get-expr)))
4522 (setq err nil))
4523 ))
6341f357
DN
4524 (end-of-line)
4525 (if kill-existing-comment
6ca0ff73 4526 (verilog-kill-existing-comment))
6341f357
DN
4527 (delete-horizontal-space)
4528 (insert (concat " // " str ))
7ea26faf 4529 (if err (ding 't))))
6341f357
DN
4530
4531 (;- This is a begin..end block
4532 (match-end 2) ;; of verilog-end-block-ordered-re
4533 (let ((str " // UNMATCHED !!")
4534 (err 't)
4535 (here (point))
4536 there
60618039 4537 cntx)
6341f357
DN
4538 (save-excursion
4539 (verilog-leap-to-head)
4540 (setq there (point))
4541 (if (not (match-end 0))
4542 (progn
4543 (goto-char here)
4544 (end-of-line)
4545 (if kill-existing-comment
6ca0ff73 4546 (verilog-kill-existing-comment))
6341f357
DN
4547 (delete-horizontal-space)
4548 (insert str)
60618039 4549 (ding 't))
6341f357
DN
4550 (let ((lim
4551 (save-excursion (verilog-beg-of-defun) (point)))
60618039 4552 (here (point)))
6341f357
DN
4553 (cond
4554 (;-- handle named block differently
4555 (looking-at verilog-named-block-re)
4556 (search-forward ":")
4557 (setq there (point))
4558 (setq str (verilog-get-expr))
4559 (setq err nil)
4560 (setq str (concat " // block: " str )))
4561
4562 ((verilog-in-case-region-p) ;-- handle case item differently
4563 (goto-char here)
4564 (setq str (verilog-backward-case-item lim))
4565 (setq there (point))
4566 (setq err nil)
4567 (setq str (concat " // case: " str )))
4568
4569 (;- try to find "reason" for this begin
4570 (cond
4571 (;
4572 (eq here (progn
a03c2342
WS
4573 ;; (verilog-backward-token)
4574 (verilog-beg-of-statement)
6341f357
DN
4575 (point)))
4576 (setq err nil)
4577 (setq str ""))
4578 ((looking-at verilog-endcomment-reason-re)
4579 (setq there (match-end 0))
a3a8b002 4580 (setq cntx (concat (match-string 0) " "))
6341f357
DN
4581 (cond
4582 (;- begin
a3a8b002 4583 (match-end 1)
6341f357
DN
4584 (setq err nil)
4585 (save-excursion
4586 (if (and (verilog-continued-line)
4587 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
4588 (progn
4589 (goto-char (match-end 0))
4590 (setq there (point))
4591 (setq str
a3a8b002 4592 (concat " // " (match-string 0) " " (verilog-get-expr))))
6341f357
DN
4593 (setq str ""))))
4594
4595 (;- else
a3a8b002 4596 (match-end 2)
6341f357 4597 (let ((nest 0)
a03c2342 4598 ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
6341f357
DN
4599 (catch 'skip
4600 (while (verilog-re-search-backward reg nil 'move)
4601 (cond
4602 ((match-end 1) ; begin
4603 (setq nest (1- nest)))
4604 ((match-end 2) ; end
4605 (setq nest (1+ nest)))
4606 ((match-end 3)
4607 (if (= 0 nest)
4608 (progn
4609 (goto-char (match-end 0))
4610 (setq there (point))
4611 (setq err nil)
4612 (setq str (verilog-get-expr))
4613 (setq str (concat " // else: !if" str ))
a03c2342
WS
4614 (throw 'skip 1))))
4615 ((match-end 4)
4616 (if (= 0 nest)
4617 (progn
4618 (goto-char (match-end 0))
4619 (setq there (point))
4620 (setq err nil)
4621 (setq str (verilog-get-expr))
4622 (setq str (concat " // else: !assert " str ))
60618039 4623 (throw 'skip 1)))))))))
6341f357 4624 (;- end else
a3a8b002 4625 (match-end 3)
6341f357
DN
4626 (goto-char there)
4627 (let ((nest 0)
a03c2342 4628 (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
6341f357
DN
4629 (catch 'skip
4630 (while (verilog-re-search-backward reg nil 'move)
4631 (cond
4632 ((match-end 1) ; begin
4633 (setq nest (1- nest)))
4634 ((match-end 2) ; end
4635 (setq nest (1+ nest)))
4636 ((match-end 3)
4637 (if (= 0 nest)
4638 (progn
4639 (goto-char (match-end 0))
4640 (setq there (point))
4641 (setq err nil)
4642 (setq str (verilog-get-expr))
4643 (setq str (concat " // else: !if" str ))
a03c2342
WS
4644 (throw 'skip 1))))
4645 ((match-end 4)
4646 (if (= 0 nest)
4647 (progn
4648 (goto-char (match-end 0))
4649 (setq there (point))
4650 (setq err nil)
4651 (setq str (verilog-get-expr))
4652 (setq str (concat " // else: !assert " str ))
60618039 4653 (throw 'skip 1)))))))))
a03c2342 4654
a3a8b002
DN
4655 (; always_comb, always_ff, always_latch
4656 (or (match-end 4) (match-end 5) (match-end 6))
4657 (goto-char (match-end 0))
4658 (setq there (point))
4659 (setq err nil)
4660 (setq str (concat " // " cntx )))
6341f357
DN
4661
4662 (;- task/function/initial et cetera
4663 t
4664 (match-end 0)
4665 (goto-char (match-end 0))
4666 (setq there (point))
4667 (setq err nil)
a3a8b002 4668 (setq str (concat " // " cntx (verilog-get-expr))))
6341f357
DN
4669
4670 (;-- otherwise...
60618039 4671 (setq str " // auto-endcomment confused "))))
6341f357
DN
4672
4673 ((and
4674 (verilog-in-case-region-p) ;-- handle case item differently
4675 (progn
4676 (setq there (point))
4677 (goto-char here)
4678 (setq str (verilog-backward-case-item lim))))
4679 (setq err nil)
4680 (setq str (concat " // case: " str )))
4681
4682 ((verilog-in-fork-region-p)
4683 (setq err nil)
4684 (setq str " // fork branch" ))
4685
4686 ((looking-at "\\<end\\>")
4687 ;; HERE
4688 (forward-word 1)
4689 (verilog-forward-syntactic-ws)
4690 (setq err nil)
4691 (setq str (verilog-get-expr))
4692 (setq str (concat " // " cntx str )))
4693
4694 ))))
4695 (goto-char here)
4696 (end-of-line)
4697 (if kill-existing-comment
6ca0ff73 4698 (verilog-kill-existing-comment))
6341f357
DN
4699 (delete-horizontal-space)
4700 (if (or err
4701 (> (count-lines here there) verilog-minimum-comment-distance))
4702 (insert str))
4703 (if err (ding 't))
4704 ))))
4705 (;- this is endclass, which can be nested
4706 (match-end 11) ;; of verilog-end-block-ordered-re
4707 ;;(goto-char there)
4708 (let ((nest 0)
60618039
DN
4709 (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
4710 string)
6341f357
DN
4711 (save-excursion
4712 (catch 'skip
4713 (while (verilog-re-search-backward reg nil 'move)
4714 (cond
4715 ((match-end 3) ; endclass
4716 (ding 't)
4717 (setq string "unmatched endclass")
4718 (throw 'skip 1))
4719
4720 ((match-end 2) ; endclass
4721 (setq nest (1+ nest)))
4722
4723 ((match-end 1) ; class
4724 (setq nest (1- nest))
4725 (if (< nest 0)
4726 (progn
4727 (goto-char (match-end 0))
4728 (let (b e)
4729 (setq b (progn
4730 (skip-chars-forward "^ \t")
4731 (verilog-forward-ws&directives)
4732 (point))
4733 e (progn
4734 (skip-chars-forward "a-zA-Z0-9_")
4735 (point)))
4736 (setq string (buffer-substring b e)))
4737 (throw 'skip 1))))
4738 ))))
4739 (end-of-line)
60618039 4740 (insert (concat " // " string ))))
6341f357
DN
4741
4742 (;- this is end{function,generate,task,module,primitive,table,generate}
4743 ;- which can not be nested.
4744 t
9c059794 4745 (let (string reg (name-re nil))
6341f357
DN
4746 (end-of-line)
4747 (if kill-existing-comment
4748 (save-match-data
6ca0ff73 4749 (verilog-kill-existing-comment)))
6341f357
DN
4750 (delete-horizontal-space)
4751 (backward-sexp)
4752 (cond
4753 ((match-end 5) ;; of verilog-end-block-ordered-re
4754 (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
47086495 4755 (setq name-re "\\w+\\s-*("))
6341f357 4756 ((match-end 6) ;; of verilog-end-block-ordered-re
47086495
WS
4757 (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
4758 (setq name-re "\\w+\\s-*("))
6341f357
DN
4759 ((match-end 7) ;; of verilog-end-block-ordered-re
4760 (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
4761 ((match-end 8) ;; of verilog-end-block-ordered-re
4762 (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4763 ((match-end 9) ;; of verilog-end-block-ordered-re
4764 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
4765 ((match-end 10) ;; of verilog-end-block-ordered-re
4766 (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4767 ((match-end 11) ;; of verilog-end-block-ordered-re
4768 (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4769 ((match-end 12) ;; of verilog-end-block-ordered-re
4770 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4771 ((match-end 13) ;; of verilog-end-block-ordered-re
4772 (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4773 ((match-end 14) ;; of verilog-end-block-ordered-re
4774 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4775 ((match-end 15) ;; of verilog-end-block-ordered-re
4776 (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
4777
60618039 4778 (t (error "Problem in verilog-set-auto-endcomments")))
6341f357
DN
4779 (let (b e)
4780 (save-excursion
4781 (verilog-re-search-backward reg nil 'move)
4782 (cond
4783 ((match-end 1)
4784 (setq b (progn
4785 (skip-chars-forward "^ \t")
4786 (verilog-forward-ws&directives)
a03c2342
WS
4787 (if (looking-at "static\\|automatic")
4788 (progn
4789 (goto-char (match-end 0))
4790 (verilog-forward-ws&directives)))
9c059794 4791 (if (and name-re (verilog-re-search-forward name-re nil 'move))
6341f357 4792 (progn
9c059794 4793 (goto-char (match-beginning 0))
60618039 4794 (verilog-forward-ws&directives)))
6341f357
DN
4795 (point))
4796 e (progn
4797 (skip-chars-forward "a-zA-Z0-9_")
4798 (point)))
4799 (setq string (buffer-substring b e)))
4800 (t
4801 (ding 't)
4802 (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
4803 (end-of-line)
4804 (insert (concat " // " string )))
4805 ))))))))))
4806
4807(defun verilog-get-expr()
65e7ca35 4808 "Grab expression at point, e.g., case ( a | b & (c ^d))."
6341f357
DN
4809 (let* ((b (progn
4810 (verilog-forward-syntactic-ws)
4811 (skip-chars-forward " \t")
4812 (point)))
4813 (e (let ((par 1))
4814 (cond
4815 ((looking-at "@")
4816 (forward-char 1)
4817 (verilog-forward-syntactic-ws)
4818 (if (looking-at "(")
4819 (progn
4820 (forward-char 1)
4821 (while (and (/= par 0)
4822 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4823 (cond
4824 ((match-end 1)
4825 (setq par (1+ par)))
4826 ((match-end 2)
4827 (setq par (1- par)))))))
4828 (point))
4829 ((looking-at "(")
4830 (forward-char 1)
4831 (while (and (/= par 0)
4832 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4833 (cond
4834 ((match-end 1)
4835 (setq par (1+ par)))
4836 ((match-end 2)
4837 (setq par (1- par)))))
4838 (point))
4839 ((looking-at "\\[")
4840 (forward-char 1)
4841 (while (and (/= par 0)
4842 (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
4843 (cond
4844 ((match-end 1)
4845 (setq par (1+ par)))
4846 ((match-end 2)
4847 (setq par (1- par)))))
4848 (verilog-forward-syntactic-ws)
4849 (skip-chars-forward "^ \t\n\f")
4850 (point))
4851 ((looking-at "/[/\\*]")
4852 b)
4853 ('t
4854 (skip-chars-forward "^: \t\n\f")
60618039 4855 (point)))))
6341f357
DN
4856 (str (buffer-substring b e)))
4857 (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
4858 (setq str (concat (substring str 0 e) "...")))
4859 str))
4860
4861(defun verilog-expand-vector ()
4862 "Take a signal vector on the current line and expand it to multiple lines.
4863Useful for creating tri's and other expanded fields."
4864 (interactive)
4865 (verilog-expand-vector-internal "[" "]"))
4866
4867(defun verilog-expand-vector-internal (bra ket)
4868 "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
4869 (save-excursion
4870 (forward-line 0)
4871 (let ((signal-string (buffer-substring (point)
4872 (progn
4873 (end-of-line) (point)))))
7ea26faf
DN
4874 (if (string-match
4875 (concat "\\(.*\\)"
4876 (regexp-quote bra)
4877 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
60618039
DN
4878 (regexp-quote ket)
4879 "\\(.*\\)$") signal-string)
6341f357 4880 (let* ((sig-head (match-string 1 signal-string))
7ea26faf 4881 (vec-start (string-to-number (match-string 2 signal-string)))
6341f357
DN
4882 (vec-end (if (= (match-beginning 3) (match-end 3))
4883 vec-start
7ea26faf
DN
4884 (string-to-number
4885 (substring signal-string (1+ (match-beginning 3))
4886 (match-end 3)))))
4887 (vec-range
4888 (if (= (match-beginning 4) (match-end 4))
4889 1
4890 (string-to-number
4891 (substring signal-string (+ 2 (match-beginning 4))
4892 (match-end 4)))))
6341f357
DN
4893 (sig-tail (match-string 5 signal-string))
4894 vec)
4895 ;; Decode vectors
4896 (setq vec nil)
4897 (if (< vec-range 0)
4898 (let ((tmp vec-start))
4899 (setq vec-start vec-end
4900 vec-end tmp
4901 vec-range (- vec-range))))
4902 (if (< vec-end vec-start)
4903 (while (<= vec-end vec-start)
4904 (setq vec (append vec (list vec-start)))
4905 (setq vec-start (- vec-start vec-range)))
4906 (while (<= vec-start vec-end)
4907 (setq vec (append vec (list vec-start)))
4908 (setq vec-start (+ vec-start vec-range))))
4909 ;;
4910 ;; Delete current line
4911 (delete-region (point) (progn (forward-line 0) (point)))
4912 ;;
4913 ;; Expand vector
4914 (while vec
7ea26faf
DN
4915 (insert (concat sig-head bra
4916 (int-to-string (car vec)) ket sig-tail "\n"))
6341f357
DN
4917 (setq vec (cdr vec)))
4918 (delete-char -1)
4919 ;;
4920 )))))
4921
4922(defun verilog-strip-comments ()
37ea4b9b 4923 "Strip all comments from the Verilog code."
6341f357
DN
4924 (interactive)
4925 (goto-char (point-min))
4926 (while (re-search-forward "//" nil t)
4927 (if (verilog-within-string)
4928 (re-search-forward "\"" nil t)
4929 (if (verilog-in-star-comment-p)
4930 (re-search-forward "\*/" nil t)
4931 (let ((bpt (- (point) 2)))
4932 (end-of-line)
4933 (delete-region bpt (point))))))
4934 ;;
4935 (goto-char (point-min))
4936 (while (re-search-forward "/\\*" nil t)
4937 (if (verilog-within-string)
4938 (re-search-forward "\"" nil t)
4939 (let ((bpt (- (point) 2)))
4940 (re-search-forward "\\*/")
4941 (delete-region bpt (point))))))
4942
4943(defun verilog-one-line ()
37ea4b9b 4944 "Convert structural Verilog instances to occupy one line."
6341f357
DN
4945 (interactive)
4946 (goto-char (point-min))
4947 (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
4948 (replace-match "\\1 " nil nil)))
4949
4950(defun verilog-linter-name ()
4951 "Return name of linter, either surelint or verilint."
4952 (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4953 compile-command))
4954 (lint-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4955 verilog-linter)))
4956 (cond ((equal compile-word1 "surelint") `surelint)
4957 ((equal compile-word1 "verilint") `verilint)
4958 ((equal lint-word1 "surelint") `surelint)
4959 ((equal lint-word1 "verilint") `verilint)
4960 (t `surelint)))) ;; back compatibility
4961
4962(defun verilog-lint-off ()
4963 "Convert a Verilog linter warning line into a disable statement.
4964For example:
4965 pci_bfm_null.v, line 46: Unused input: pci_rst_
4966becomes a comment for the appropriate tool.
4967
4968The first word of the `compile-command' or `verilog-linter'
37ea4b9b 4969variables is used to determine which product is being used.
6341f357
DN
4970
4971See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
4972 (interactive)
4973 (let ((linter (verilog-linter-name)))
4974 (cond ((equal linter `surelint)
4975 (verilog-surelint-off))
4976 ((equal linter `verilint)
4977 (verilog-verilint-off))
4978 (t (error "Linter name not set")))))
4979
7ea26faf 4980(defvar compilation-last-buffer)
a3a8b002 4981(defvar next-error-last-buffer)
7ea26faf 4982
6341f357
DN
4983(defun verilog-surelint-off ()
4984 "Convert a SureLint warning line into a disable statement.
4985Run from Verilog source window; assumes there is a *compile* buffer
4986with point set appropriately.
4987
4988For example:
4989 WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
4990becomes:
4991 // surefire lint_line_off UDDONX"
4992 (interactive)
7ea26faf
DN
4993 (let ((buff (if (boundp 'next-error-last-buffer)
4994 next-error-last-buffer
4995 compilation-last-buffer)))
4996 (when (buffer-live-p buff)
7ea26faf
DN
4997 (save-excursion
4998 (switch-to-buffer buff)
4999 (beginning-of-line)
5000 (when
5001 (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
5002 (let* ((code (match-string 2))
5003 (file (match-string 3))
5004 (line (match-string 4))
5005 (buffer (get-file-buffer file))
5006 dir filename)
5007 (unless buffer
5008 (progn
5009 (setq buffer
5010 (and (file-exists-p file)
5011 (find-file-noselect file)))
5012 (or buffer
5013 (let* ((pop-up-windows t))
5014 (let ((name (expand-file-name
5015 (read-file-name
5016 (format "Find this error in: (default %s) "
5017 file)
5018 dir file t))))
5019 (if (file-directory-p name)
5020 (setq name (expand-file-name filename name)))
5021 (setq buffer
5022 (and (file-exists-p name)
5023 (find-file-noselect name))))))))
5024 (switch-to-buffer buffer)
5f68c1b7
GM
5025 (goto-char (point-min))
5026 (forward-line (- (string-to-number line)))
7ea26faf
DN
5027 (end-of-line)
5028 (catch 'already
5029 (cond
5030 ((verilog-in-slash-comment-p)
5031 (re-search-backward "//")
5032 (cond
5033 ((looking-at "// surefire lint_off_line ")
5034 (goto-char (match-end 0))
3ba6b2ee 5035 (let ((lim (point-at-eol)))
7ea26faf
DN
5036 (if (re-search-forward code lim 'move)
5037 (throw 'already t)
5038 (insert (concat " " code)))))
5039 (t
5040 )))
5041 ((verilog-in-star-comment-p)
5042 (re-search-backward "/\*")
60618039 5043 (insert (format " // surefire lint_off_line %6s" code )))
7ea26faf
DN
5044 (t
5045 (insert (format " // surefire lint_off_line %6s" code ))
5046 )))))))))
6341f357
DN
5047
5048(defun verilog-verilint-off ()
5049 "Convert a Verilint warning line into a disable statement.
5050
5051For example:
5052 (W240) pci_bfm_null.v, line 46: Unused input: pci_rst_
5053becomes:
5054 //Verilint 240 off // WARNING: Unused input"
5055 (interactive)
5056 (save-excursion
5057 (beginning-of-line)
5058 (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
5059 (replace-match (format
5060 ;; %3s makes numbers 1-999 line up nicely
5061 "\\1//Verilint %3s off // WARNING: \\3"
5062 (match-string 2)))
5063 (beginning-of-line)
5064 (verilog-indent-line))))
5065
5066(defun verilog-auto-save-compile ()
5067 "Update automatics with \\[verilog-auto], save the buffer, and compile."
5068 (interactive)
5069 (verilog-auto) ; Always do it for safety
5070 (save-buffer)
5071 (compile compile-command))
5072
a03c2342 5073(defun verilog-preprocess (&optional command filename)
47086495 5074 "Preprocess the buffer, similar to `compile', but put output in Verilog-Mode.
a03c2342 5075Takes optional COMMAND or defaults to `verilog-preprocessor', and
47086495 5076FILENAME to find directory to run in, or defaults to `buffer-file-name`."
a03c2342
WS
5077 (interactive
5078 (list
5079 (let ((default (verilog-expand-command verilog-preprocessor)))
5080 (set (make-local-variable `verilog-preprocessor)
47086495
WS
5081 (read-from-minibuffer "Run Preprocessor (like this): "
5082 default nil nil
5083 'verilog-preprocess-history default)))))
a03c2342 5084 (unless command (setq command (verilog-expand-command verilog-preprocessor)))
8468f78b 5085 (let* ((fontlocked (and (boundp 'font-lock-mode) font-lock-mode))
47086495
WS
5086 (dir (file-name-directory (or filename buffer-file-name)))
5087 (cmd (concat "cd " dir "; " command)))
a03c2342 5088 (with-output-to-temp-buffer "*Verilog-Preprocessed*"
8468f78b 5089 (with-current-buffer (get-buffer "*Verilog-Preprocessed*")
a03c2342 5090 (insert (concat "// " cmd "\n"))
47086495 5091 (call-process shell-file-name nil t nil shell-command-switch cmd)
a03c2342 5092 (verilog-mode)
8468f78b
WS
5093 ;; Without this force, it takes a few idle seconds
5094 ;; to get the color, which is very jarring
5095 (when fontlocked (font-lock-fontify-buffer))))))
6341f357
DN
5096\f
5097
5098;;
5099;; Batch
5100;;
5101
47086495
WS
5102(defun verilog-warn (string &rest args)
5103 "Print a warning with `format' using STRING and optional ARGS."
5104 (apply 'message (concat "%%Warning: " string) args))
5105
5106(defun verilog-warn-error (string &rest args)
5107 "Call `error' using STRING and optional ARGS.
5108If `verilog-warn-fatal' is non-nil, call `verilog-warn' instead."
5109 (if verilog-warn-fatal
5110 (apply 'error string args)
5111 (apply 'verilog-warn string args)))
5112
6341f357
DN
5113(defmacro verilog-batch-error-wrapper (&rest body)
5114 "Execute BODY and add error prefix to any errors found.
5115This lets programs calling batch mode to easily extract error messages."
47086495
WS
5116 `(let ((verilog-warn-fatal nil))
5117 (condition-case err
5118 (progn ,@body)
5119 (error
5120 (error "%%Error: %s%s" (error-message-string err)
5121 (if (featurep 'xemacs) "\n" "")))))) ;; XEmacs forgets to add a newline
6341f357 5122
9489a450 5123(defun verilog-batch-execute-func (funref &optional no-save)
47086495
WS
5124 "Internal processing of a batch command.
5125Runs FUNREF on all command arguments.
9489a450 5126Save the result unless optional NO-SAVE is t."
6341f357 5127 (verilog-batch-error-wrapper
14862301
SM
5128 ;; Setting global variables like that is *VERY NASTY* !!! --Stef
5129 ;; However, this function is called only when Emacs is being used as
5130 ;; a standalone language instead of as an editor, so we'll live.
5131 ;;
6341f357
DN
5132 ;; General globals needed
5133 (setq make-backup-files nil)
5134 (setq-default make-backup-files nil)
5135 (setq enable-local-variables t)
5136 (setq enable-local-eval t)
ea89ff08 5137 (setq create-lockfiles nil)
6341f357 5138 ;; Make sure any sub-files we read get proper mode
14acf2f5 5139 (setq-default major-mode 'verilog-mode)
6341f357 5140 ;; Ditto files already read in
7ea26faf 5141 (mapc (lambda (buf)
60618039 5142 (when (buffer-file-name buf)
14acf2f5 5143 (with-current-buffer buf
60618039
DN
5144 (verilog-mode))))
5145 (buffer-list))
6341f357 5146 ;; Process the files
4f91a816 5147 (mapcar (lambda (buf)
9489a450
MM
5148 (when (buffer-file-name buf)
5149 (save-excursion
5150 (if (not (file-exists-p (buffer-file-name buf)))
5151 (error
5152 (concat "File not found: " (buffer-file-name buf))))
5153 (message (concat "Processing " (buffer-file-name buf)))
5154 (set-buffer buf)
5155 (funcall funref)
5156 (unless no-save (save-buffer)))))
6341f357
DN
5157 (buffer-list))))
5158
5159(defun verilog-batch-auto ()
5160 "For use with --batch, perform automatic expansions as a stand-alone tool.
37ea4b9b 5161This sets up the appropriate Verilog mode environment, updates automatics
6341f357
DN
5162with \\[verilog-auto] on all command-line files, and saves the buffers.
5163For proper results, multiple filenames need to be passed on the command
5164line in bottom-up order."
5165 (unless noninteractive
5166 (error "Use verilog-batch-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
5167 (verilog-batch-execute-func `verilog-auto))
5168
5169(defun verilog-batch-delete-auto ()
5170 "For use with --batch, perform automatic deletion as a stand-alone tool.
37ea4b9b 5171This sets up the appropriate Verilog mode environment, deletes automatics
6341f357
DN
5172with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
5173 (unless noninteractive
5174 (error "Use verilog-batch-delete-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
5175 (verilog-batch-execute-func `verilog-delete-auto))
5176
179f044b
WS
5177(defun verilog-batch-delete-trailing-whitespace ()
5178 "For use with --batch, perform whitespace deletion as a stand-alone tool.
5179This sets up the appropriate Verilog mode environment, removes
5180whitespace with \\[verilog-delete-trailing-whitespace] on all
5181command-line files, and saves the buffers."
5182 (unless noninteractive
735135f9 5183 (error "Use verilog-batch-delete-trailing-whitespace only with --batch")) ;; Otherwise we'd mess up buffer modes
179f044b
WS
5184 (verilog-batch-execute-func `verilog-delete-trailing-whitespace))
5185
9489a450
MM
5186(defun verilog-batch-diff-auto ()
5187 "For use with --batch, perform automatic differences as a stand-alone tool.
5188This sets up the appropriate Verilog mode environment, expand automatics
5189with \\[verilog-diff-auto] on all command-line files, and reports an error
5190if any differences are observed. This is appropriate for adding to regressions
5191to insure automatics are always properly maintained."
5192 (unless noninteractive
5193 (error "Use verilog-batch-diff-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
5194 (verilog-batch-execute-func `verilog-diff-auto t))
5195
6341f357
DN
5196(defun verilog-batch-inject-auto ()
5197 "For use with --batch, perform automatic injection as a stand-alone tool.
37ea4b9b 5198This sets up the appropriate Verilog mode environment, injects new automatics
6341f357
DN
5199with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
5200For proper results, multiple filenames need to be passed on the command
5201line in bottom-up order."
5202 (unless noninteractive
5203 (error "Use verilog-batch-inject-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
5204 (verilog-batch-execute-func `verilog-inject-auto))
5205
5206(defun verilog-batch-indent ()
47086495 5207 "For use with --batch, reindent an entire file as a stand-alone tool.
37ea4b9b 5208This sets up the appropriate Verilog mode environment, calls
6341f357
DN
5209\\[verilog-indent-buffer] on all command-line files, and saves the buffers."
5210 (unless noninteractive
5211 (error "Use verilog-batch-indent only with --batch")) ;; Otherwise we'd mess up buffer modes
5212 (verilog-batch-execute-func `verilog-indent-buffer))
5213\f
5214
5215;;
5216;; Indentation
5217;;
5218(defconst verilog-indent-alist
5219 '((block . (+ ind verilog-indent-level))
5220 (case . (+ ind verilog-case-indent))
5221 (cparenexp . (+ ind verilog-indent-level))
5222 (cexp . (+ ind verilog-cexp-indent))
5223 (defun . verilog-indent-level-module)
5224 (declaration . verilog-indent-level-declaration)
5225 (directive . (verilog-calculate-indent-directive))
5226 (tf . verilog-indent-level)
5227 (behavioral . (+ verilog-indent-level-behavioral verilog-indent-level-module))
5228 (statement . ind)
5229 (cpp . 0)
5230 (comment . (verilog-comment-indent))
5231 (unknown . 3)
5232 (string . 0)))
5233
5234(defun verilog-continued-line-1 (lim)
5235 "Return true if this is a continued line.
5236Set point to where line starts. Limit search to point LIM."
5237 (let ((continued 't))
5238 (if (eq 0 (forward-line -1))
5239 (progn
5240 (end-of-line)
5241 (verilog-backward-ws&directives lim)
5242 (if (bobp)
5243 (setq continued nil)
5244 (setq continued (verilog-backward-token))))
5245 (setq continued nil))
5246 continued))
5247
5248(defun verilog-calculate-indent ()
5249 "Calculate the indent of the current Verilog line.
5250Examine previous lines. Once a line is found that is definitive as to the
37ea4b9b
JB
5251type of the current line, return that lines' indent level and its type.
5252Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
6341f357
DN
5253 (save-excursion
5254 (let* ((starting_position (point))
5255 (par 0)
5256 (begin (looking-at "[ \t]*begin\\>"))
5257 (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
ea89ff08 5258 (structres nil)
6341f357
DN
5259 (type (catch 'nesting
5260 ;; Keep working backwards until we can figure out
5261 ;; what type of statement this is.
5262 ;; Basically we need to figure out
5263 ;; 1) if this is a continuation of the previous line;
5264 ;; 2) are we in a block scope (begin..end)
5265
5266 ;; if we are in a comment, done.
5267 (if (verilog-in-star-comment-p)
5268 (throw 'nesting 'comment))
5269
5270 ;; if we have a directive, done.
a3a8b002
DN
5271 (if (save-excursion (beginning-of-line)
5272 (and (looking-at verilog-directive-re-1)
9489a450 5273 (not (or (looking-at "[ \t]*`[ou]vm_")
86a4c7ac 5274 (looking-at "[ \t]*`vmm_")))))
6341f357 5275 (throw 'nesting 'directive))
a3a8b002 5276 ;; indent structs as if there were module level
ea89ff08
WS
5277 (setq structres (verilog-in-struct-nested-p))
5278 (cond ((not structres) nil)
5279 ;;((and structres (equal (char-after) ?\})) (throw 'nesting 'struct-close))
5280 ((> structres 0) (throw 'nesting 'nested-struct))
5281 ((= structres 0) (throw 'nesting 'block))
5282 (t nil))
6341f357 5283
9489a450
MM
5284 ;; if we are in a parenthesized list, and the user likes to indent these, return.
5285 ;; unless we are in the newfangled coverpoint or constraint blocks
5286 (if (and
a3a8b002
DN
5287 verilog-indent-lists
5288 (verilog-in-paren)
5289 (not (verilog-in-coverage-p))
5290 )
9489a450 5291 (progn (setq par 1)
a3a8b002 5292 (throw 'nesting 'block)))
6341f357 5293
9489a450
MM
5294 ;; See if we are continuing a previous line
5295 (while t
5296 ;; trap out if we crawl off the top of the buffer
5297 (if (bobp) (throw 'nesting 'cpp))
5298
ea89ff08
WS
5299 (if (and (verilog-continued-line-1 lim)
5300 (or (not (verilog-in-coverage-p))
5301 (looking-at verilog-in-constraint-re) )) ;; may still get hosed if concat in constraint
9489a450
MM
5302 (let ((sp (point)))
5303 (if (and
5304 (not (looking-at verilog-complete-reg))
5305 (verilog-continued-line-1 lim))
5306 (progn (goto-char sp)
5307 (throw 'nesting 'cexp))
5308
5309 (goto-char sp))
ea89ff08
WS
5310 (if (and (verilog-in-coverage-p)
5311 (looking-at verilog-in-constraint-re))
5312 (progn
5313 (beginning-of-line)
5314 (skip-chars-forward " \t")
5315 (throw 'nesting 'constraint)))
9489a450 5316 (if (and begin
ea89ff08
WS
5317 (not verilog-indent-begin-after-if)
5318 (looking-at verilog-no-indent-begin-re))
9489a450
MM
5319 (progn
5320 (beginning-of-line)
5321 (skip-chars-forward " \t")
5322 (throw 'nesting 'statement))
5323 (progn
5324 (throw 'nesting 'cexp))))
5325 ;; not a continued line
5326 (goto-char starting_position))
5327
5328 (if (looking-at "\\<else\\>")
5329 ;; search back for governing if, striding across begin..end pairs
5330 ;; appropriately
5331 (let ((elsec 1))
5332 (while (verilog-re-search-backward verilog-ends-re nil 'move)
5333 (cond
5334 ((match-end 1) ; else, we're in deep
5335 (setq elsec (1+ elsec)))
5336 ((match-end 2) ; if
5337 (setq elsec (1- elsec))
5338 (if (= 0 elsec)
5339 (if verilog-align-ifelse
5340 (throw 'nesting 'statement)
5341 (progn ;; back up to first word on this line
5342 (beginning-of-line)
5343 (verilog-forward-syntactic-ws)
5344 (throw 'nesting 'statement)))))
5345 ((match-end 3) ; assert block
5346 (setq elsec (1- elsec))
5347 (verilog-beg-of-statement) ;; doesn't get to beginning
5348 (if (looking-at verilog-property-re)
5349 (throw 'nesting 'statement) ; We don't need an endproperty for these
47086495 5350 (throw 'nesting 'block) ;We still need an endproperty
9489a450
MM
5351 ))
5352 (t ; endblock
5353 ; try to leap back to matching outward block by striding across
5354 ; indent level changing tokens then immediately
5355 ; previous line governs indentation.
5356 (let (( reg) (nest 1))
5357 ;; verilog-ends => else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
5358 (cond
5359 ((match-end 4) ; end
5360 ;; Search back for matching begin
5361 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
5362 ((match-end 5) ; endcase
5363 ;; Search back for matching case
5364 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
5365 ((match-end 6) ; endfunction
5366 ;; Search back for matching function
5367 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
5368 ((match-end 7) ; endtask
5369 ;; Search back for matching task
5370 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
5371 ((match-end 8) ; endspecify
5372 ;; Search back for matching specify
5373 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
5374 ((match-end 9) ; endtable
5375 ;; Search back for matching table
5376 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
5377 ((match-end 10) ; endgenerate
5378 ;; Search back for matching generate
5379 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
5380 ((match-end 11) ; joins
5381 ;; Search back for matching fork
5382 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
5383 ((match-end 12) ; class
5384 ;; Search back for matching class
5385 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
5386 ((match-end 13) ; covergroup
5387 ;; Search back for matching covergroup
5388 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
5389 (catch 'skip
5390 (while (verilog-re-search-backward reg nil 'move)
6341f357 5391 (cond
9489a450
MM
5392 ((match-end 1) ; begin
5393 (setq nest (1- nest))
5394 (if (= 0 nest)
5395 (throw 'skip 1)))
5396 ((match-end 2) ; end
5397 (setq nest (1+ nest)))))
5398 )))))))
5399 (throw 'nesting (verilog-calc-1)))
5400 );; catch nesting
6341f357
DN
5401 );; type
5402 )
5403 ;; Return type of block and indent level.
5404 (if (not type)
5405 (setq type 'cpp))
5406 (if (> par 0) ; Unclosed Parenthesis
5407 (list 'cparenexp par)
5408 (cond
5409 ((eq type 'case)
5410 (list type (verilog-case-indent-level)))
5411 ((eq type 'statement)
5412 (list type (current-column)))
5413 ((eq type 'defun)
5414 (list type 0))
ea89ff08
WS
5415 ((eq type 'constraint)
5416 (list 'block (current-column)))
5417 ((eq type 'nested-struct)
5418 (list 'block structres))
6341f357 5419 (t
60618039
DN
5420 (list type (verilog-current-indent-level))))))))
5421
6341f357
DN
5422(defun verilog-wai ()
5423 "Show matching nesting block for debugging."
5424 (interactive)
5425 (save-excursion
4c5e69c6
DN
5426 (let* ((type (verilog-calc-1))
5427 depth)
5428 ;; Return type of block and indent level.
5429 (if (not type)
5430 (setq type 'cpp))
5431 (if (and
5432 verilog-indent-lists
a3a8b002
DN
5433 (not(or (verilog-in-coverage-p)
5434 (verilog-in-struct-p)))
4c5e69c6
DN
5435 (verilog-in-paren))
5436 (setq depth 1)
5437 (cond
5438 ((eq type 'case)
5439 (setq depth (verilog-case-indent-level)))
5440 ((eq type 'statement)
5441 (setq depth (current-column)))
5442 ((eq type 'defun)
5443 (setq depth 0))
5444 (t
5445 (setq depth (verilog-current-indent-level)))))
5446 (message "You are at nesting %s depth %d" type depth))))
ea89ff08 5447
6341f357
DN
5448(defun verilog-calc-1 ()
5449 (catch 'nesting
ea89ff08
WS
5450 (let ((re (concat "\\({\\|}\\|" verilog-indent-re "\\)"))
5451 (inconstraint (verilog-in-coverage-p)))
a3a8b002
DN
5452 (while (verilog-re-search-backward re nil 'move)
5453 (catch 'continue
5454 (cond
5455 ((equal (char-after) ?\{)
a67c4ae0 5456 ;; block type returned based on outer constraint { or inner
a3a8b002 5457 (if (verilog-at-constraint-p)
ea89ff08
WS
5458 (cond (inconstraint (throw 'nesting 'constraint))
5459 (t (throw 'nesting 'statement)))))
a3a8b002 5460 ((equal (char-after) ?\})
ea89ff08
WS
5461 (let (par-pos
5462 (there (verilog-at-close-constraint-p)))
86a4c7ac 5463 (if there ;; we are at the } that closes a constraint. Find the { that opens it
a3a8b002 5464 (progn
ea89ff08
WS
5465 (if (> (verilog-in-paren-count) 0)
5466 (forward-char 1))
5467 (setq par-pos (verilog-parenthesis-depth))
5468 (cond (par-pos
5469 (goto-char par-pos)
5470 (forward-char 1))
5471 (t
5472 (backward-char 1)))))))
6341f357 5473
a3a8b002
DN
5474 ((looking-at verilog-beg-block-re-ordered)
5475 (cond
5476 ((match-end 2) ; *sigh* could be "unique case" or "priority casex"
5477 (let ((here (point)))
5478 (verilog-beg-of-statement)
5479 (if (looking-at verilog-extended-case-re)
5480 (throw 'nesting 'case)
5481 (goto-char here)))
5482 (throw 'nesting 'case))
5483
5484 ((match-end 4) ; *sigh* could be "disable fork"
5485 (let ((here (point)))
5486 (verilog-beg-of-statement)
9489a450 5487 (if (looking-at verilog-disable-fork-re)
fd9ea9d3 5488 t ; this is a normal statement
a3a8b002
DN
5489 (progn ; or is fork, starts a new block
5490 (goto-char here)
5491 (throw 'nesting 'block)))))
5492
a03c2342
WS
5493 ((match-end 27) ; *sigh* might be a clocking declaration
5494 (let ((here (point)))
5495 (if (verilog-in-paren)
5496 t ; this is a normal statement
5497 (progn ; or is fork, starts a new block
5498 (goto-char here)
5499 (throw 'nesting 'block)))))
a3a8b002
DN
5500
5501 ;; need to consider typedef struct here...
5502 ((looking-at "\\<class\\|struct\\|function\\|task\\>")
6341f357
DN
5503 ; *sigh* These words have an optional prefix:
5504 ; extern {virtual|protected}? function a();
6341f357
DN
5505 ; typedef class foo;
5506 ; and we don't want to confuse this with
5507 ; function a();
5508 ; property
5509 ; ...
5510 ; endfunction
a3a8b002
DN
5511 (verilog-beg-of-statement)
5512 (if (looking-at verilog-beg-block-re-ordered)
47086495
WS
5513 (throw 'nesting 'block)
5514 (throw 'nesting 'defun)))
7cb1c4d7 5515
47086495 5516 ;;
a3a8b002
DN
5517 ((looking-at "\\<property\\>")
5518 ; *sigh*
7cb1c4d7 5519 ; {assert|assume|cover} property (); are complete
14862301 5520 ; and could also be labeled: - foo: assert property
7cb1c4d7
DN
5521 ; but
5522 ; property ID () ... needs end_property
a3a8b002 5523 (verilog-beg-of-statement)
a03c2342 5524 (if (looking-at verilog-property-re)
14862301 5525 (throw 'continue 'statement) ; We don't need an endproperty for these
47086495 5526 (throw 'nesting 'block) ;We still need an endproperty
a3a8b002 5527 ))
6341f357 5528
a3a8b002 5529 (t (throw 'nesting 'block))))
6341f357 5530
a3a8b002
DN
5531 ((looking-at verilog-end-block-re)
5532 (verilog-leap-to-head)
5533 (if (verilog-in-case-region-p)
5534 (progn
5535 (verilog-leap-to-case-head)
5536 (if (looking-at verilog-extended-case-re)
5537 (throw 'nesting 'case)))))
6341f357 5538
a3a8b002
DN
5539 ((looking-at verilog-defun-level-re)
5540 (if (looking-at verilog-defun-level-generate-only-re)
5541 (if (verilog-in-generate-region-p)
14862301 5542 (throw 'continue 'foo) ; always block in a generate - keep looking
a3a8b002
DN
5543 (throw 'nesting 'defun))
5544 (throw 'nesting 'defun)))
5545
5546 ((looking-at verilog-cpp-level-re)
5547 (throw 'nesting 'cpp))
5548
5549 ((bobp)
5550 (throw 'nesting 'cpp)))))
5551
5552 (throw 'nesting 'cpp))))
6341f357
DN
5553
5554(defun verilog-calculate-indent-directive ()
5555 "Return indentation level for directive.
5556For speed, the searcher looks at the last directive, not the indent
5557of the appropriate enclosing block."
5558 (let ((base -1) ;; Indent of the line that determines our indentation
60618039 5559 (ind 0)) ;; Relative offset caused by other directives (like `endif on same line as `else)
6341f357
DN
5560 ;; Start at current location, scan back for another directive
5561
5562 (save-excursion
5563 (beginning-of-line)
5564 (while (and (< base 0)
5565 (verilog-re-search-backward verilog-directive-re nil t))
5566 (cond ((save-excursion (skip-chars-backward " \t") (bolp))
60618039 5567 (setq base (current-indentation))))
6341f357
DN
5568 (cond ((and (looking-at verilog-directive-end) (< base 0)) ;; Only matters when not at BOL
5569 (setq ind (- ind verilog-indent-level-directive)))
5570 ((and (looking-at verilog-directive-middle) (>= base 0)) ;; Only matters when at BOL
5571 (setq ind (+ ind verilog-indent-level-directive)))
5572 ((looking-at verilog-directive-begin)
5573 (setq ind (+ ind verilog-indent-level-directive)))))
5574 ;; Adjust indent to starting indent of critical line
5575 (setq ind (max 0 (+ ind base))))
5576
5577 (save-excursion
5578 (beginning-of-line)
5579 (skip-chars-forward " \t")
5580 (cond ((or (looking-at verilog-directive-middle)
5581 (looking-at verilog-directive-end))
5582 (setq ind (max 0 (- ind verilog-indent-level-directive))))))
5583 ind))
5584
5585(defun verilog-leap-to-case-head ()
5586 (let ((nest 1))
5587 (while (/= 0 nest)
a3a8b002
DN
5588 (verilog-re-search-backward
5589 (concat
ea89ff08 5590 "\\(\\<randcase\\>\\|\\(\\<unique0?\\s-+\\|priority\\s-+\\)?\\<case[xz]?\\>\\)"
a3a8b002
DN
5591 "\\|\\(\\<endcase\\>\\)" )
5592 nil 'move)
6341f357
DN
5593 (cond
5594 ((match-end 1)
a3a8b002
DN
5595 (let ((here (point)))
5596 (verilog-beg-of-statement)
5597 (unless (looking-at verilog-extended-case-re)
5598 (goto-char here)))
6341f357 5599 (setq nest (1- nest)))
a3a8b002 5600 ((match-end 3)
6341f357
DN
5601 (setq nest (1+ nest)))
5602 ((bobp)
5603 (ding 't)
5604 (setq nest 0))))))
5605
5606(defun verilog-leap-to-head ()
37ea4b9b
JB
5607 "Move point to the head of this block.
5608Jump from end to matching begin, from endcase to matching case, and so on."
6341f357
DN
5609 (let ((reg nil)
5610 snest
4c5e69c6 5611 (nesting 'yes)
6341f357
DN
5612 (nest 1))
5613 (cond
5614 ((looking-at "\\<end\\>")
5615 ;; 1: Search back for matching begin
5616 (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
5617 "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
4c5e69c6 5618 ((looking-at "\\<endtask\\>")
a3a8b002 5619 ;; 2: Search back for matching task
4c5e69c6
DN
5620 (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
5621 (setq nesting 'no))
6341f357 5622 ((looking-at "\\<endcase\\>")
a3a8b002
DN
5623 (catch 'nesting
5624 (verilog-leap-to-case-head) )
5625 (setq reg nil) ; to force skip
5626 )
5627
6341f357 5628 ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
a3a8b002 5629 ;; 4: Search back for matching fork
6341f357
DN
5630 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5631 ((looking-at "\\<endclass\\>")
a3a8b002 5632 ;; 5: Search back for matching class
6341f357
DN
5633 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
5634 ((looking-at "\\<endtable\\>")
a3a8b002 5635 ;; 6: Search back for matching table
6341f357
DN
5636 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
5637 ((looking-at "\\<endspecify\\>")
a3a8b002 5638 ;; 7: Search back for matching specify
6341f357
DN
5639 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
5640 ((looking-at "\\<endfunction\\>")
a3a8b002
DN
5641 ;; 8: Search back for matching function
5642 (setq reg "\\(\\<function\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<function\\>\\)")
5643 (setq nesting 'no))
5644 ;;(setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
6341f357
DN
5645 ((looking-at "\\<endgenerate\\>")
5646 ;; 8: Search back for matching generate
5647 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
6341f357
DN
5648 ((looking-at "\\<endgroup\\>")
5649 ;; 10: Search back for matching covergroup
5650 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
5651 ((looking-at "\\<endproperty\\>")
5652 ;; 11: Search back for matching property
5653 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
9489a450
MM
5654 ((looking-at verilog-uvm-end-re)
5655 ;; 12: Search back for matching sequence
5656 (setq reg (concat "\\(" verilog-uvm-begin-re "\\|" verilog-uvm-end-re "\\)")))
a3a8b002
DN
5657 ((looking-at verilog-ovm-end-re)
5658 ;; 12: Search back for matching sequence
5659 (setq reg (concat "\\(" verilog-ovm-begin-re "\\|" verilog-ovm-end-re "\\)")))
86a4c7ac
DN
5660 ((looking-at verilog-vmm-end-re)
5661 ;; 12: Search back for matching sequence
5662 (setq reg (concat "\\(" verilog-vmm-begin-re "\\|" verilog-vmm-end-re "\\)")))
6341f357
DN
5663 ((looking-at "\\<endinterface\\>")
5664 ;; 12: Search back for matching interface
5665 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
5666 ((looking-at "\\<endsequence\\>")
5667 ;; 12: Search back for matching sequence
5668 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
5669 ((looking-at "\\<endclocking\\>")
5670 ;; 12: Search back for matching clocking
60618039 5671 (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
6341f357
DN
5672 (if reg
5673 (catch 'skip
4c5e69c6
DN
5674 (if (eq nesting 'yes)
5675 (let (sreg)
5676 (while (verilog-re-search-backward reg nil 'move)
5677 (cond
5678 ((match-end 1) ; begin
0e5c8aed
DN
5679 (if (looking-at "fork")
5680 (let ((here (point)))
5681 (verilog-beg-of-statement)
5682 (unless (looking-at verilog-disable-fork-re)
5683 (goto-char here)
5684 (setq nest (1- nest))))
5685 (setq nest (1- nest)))
4c5e69c6
DN
5686 (if (= 0 nest)
5687 ;; Now previous line describes syntax
5688 (throw 'skip 1))
5689 (if (and snest
5690 (= snest nest))
5691 (setq reg sreg)))
5692 ((match-end 2) ; end
5693 (setq nest (1+ nest)))
5694 ((match-end 3)
5695 ;; endcase, jump to case
5696 (setq snest nest)
5697 (setq nest (1+ nest))
5698 (setq sreg reg)
5699 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
5700 ((match-end 4)
5701 ;; join, jump to fork
5702 (setq snest nest)
5703 (setq nest (1+ nest))
5704 (setq sreg reg)
5705 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5706 )))
5707 ;no nesting
5708 (if (and
a3a8b002 5709 (verilog-re-search-backward reg nil 'move)
4c5e69c6
DN
5710 (match-end 1)) ; task -> could be virtual and/or protected
5711 (progn
5712 (verilog-beg-of-statement)
5713 (throw 'skip 1))
5714 (throw 'skip 1)))))))
6341f357
DN
5715
5716(defun verilog-continued-line ()
5717 "Return true if this is a continued line.
37ea4b9b 5718Set point to where line starts."
6341f357
DN
5719 (let ((continued 't))
5720 (if (eq 0 (forward-line -1))
5721 (progn
5722 (end-of-line)
5723 (verilog-backward-ws&directives)
5724 (if (bobp)
5725 (setq continued nil)
5726 (while (and continued
5727 (save-excursion
5728 (skip-chars-backward " \t")
5729 (not (bolp))))
60618039 5730 (setq continued (verilog-backward-token)))))
6341f357
DN
5731 (setq continued nil))
5732 continued))
5733
5734(defun verilog-backward-token ()
0b381c7e 5735 "Step backward token, returning true if this is a continued line."
6341f357
DN
5736 (interactive)
5737 (verilog-backward-syntactic-ws)
5738 (cond
5739 ((bolp)
5740 nil)
5741 (;-- Anything ending in a ; is complete
5742 (= (preceding-char) ?\;)
5743 nil)
5744 (; If a "}" is prefixed by a ";", then this is a complete statement
5745 ; i.e.: constraint foo { a = b; }
5746 (= (preceding-char) ?\})
5747 (progn
5748 (backward-char)
a3a8b002 5749 (not(verilog-at-close-constraint-p))))
6341f357
DN
5750 (;-- constraint foo { a = b }
5751 ; is a complete statement. *sigh*
5752 (= (preceding-char) ?\{)
5753 (progn
5754 (backward-char)
60618039 5755 (not (verilog-at-constraint-p))))
a3a8b002
DN
5756 (;" string "
5757 (= (preceding-char) ?\")
5758 (backward-char)
5759 (verilog-skip-backward-comment-or-string)
5760 nil)
5761
5762 (; [3:4]
5763 (= (preceding-char) ?\])
5764 (backward-char)
5765 (verilog-backward-open-bracket)
5766 t)
5767
6341f357
DN
5768 (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
5769 ; also could be simply '@(foo)'
5770 ; or foo u1 #(a=8)
5771 ; (b, ... which ISN'T complete
5772 ;;;; Do we need this???
5773 (= (preceding-char) ?\))
5774 (progn
5775 (backward-char)
a03c2342 5776 (verilog-backward-up-list 1)
6341f357
DN
5777 (verilog-backward-syntactic-ws)
5778 (let ((back (point)))
5779 (forward-word -1)
5780 (cond
a3a8b002 5781 ;;XX
6341f357
DN
5782 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
5783 (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
9489a450
MM
5784 ((looking-at verilog-uvm-statement-re)
5785 nil)
5786 ((looking-at verilog-uvm-begin-re)
5787 t)
5788 ((looking-at verilog-uvm-end-re)
5789 t)
a3a8b002
DN
5790 ((looking-at verilog-ovm-statement-re)
5791 nil)
5792 ((looking-at verilog-ovm-begin-re)
5793 t)
5794 ((looking-at verilog-ovm-end-re)
5795 t)
86a4c7ac
DN
5796 ;; JBA find VMM macros
5797 ((looking-at verilog-vmm-statement-re)
5798 nil )
5799 ((looking-at verilog-vmm-begin-re)
5800 t)
5801 ((looking-at verilog-vmm-end-re)
5802 nil)
5803 ;; JBA trying to catch macro lines with no ; at end
5804 ((looking-at "\\<`")
5805 nil)
6341f357
DN
5806 (t
5807 (goto-char back)
5808 (cond
5809 ((= (preceding-char) ?\@)
5810 (backward-char)
5811 (save-excursion
5812 (verilog-backward-token)
5813 (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
5814 ((= (preceding-char) ?\#)
60618039
DN
5815 (backward-char))
5816 (t t)))))))
6341f357
DN
5817
5818 (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
5819 t
5820 (forward-word -1)
0e5c8aed
DN
5821 (while (= (preceding-char) ?\_)
5822 (forward-word -1))
6341f357
DN
5823 (cond
5824 ((looking-at "\\<else\\>")
5825 t)
2a9eb3f5
DN
5826 ((looking-at verilog-behavioral-block-beg-re)
5827 t)
6341f357
DN
5828 ((looking-at verilog-indent-re)
5829 nil)
5830 (t
5831 (let
5832 ((back (point)))
5833 (verilog-backward-syntactic-ws)
5834 (cond
5835 ((= (preceding-char) ?\:)
5836 (backward-char)
5837 (verilog-backward-syntactic-ws)
5838 (backward-sexp)
5839 (if (looking-at verilog-nameable-item-re )
5840 nil
60618039 5841 t))
6341f357
DN
5842 ((= (preceding-char) ?\#)
5843 (backward-char)
5844 t)
5845 ((= (preceding-char) ?\`)
5846 (backward-char)
5847 t)
5848
5849 (t
5850 (goto-char back)
60618039 5851 t))))))))
6341f357 5852
fd9ea9d3 5853(defun verilog-backward-syntactic-ws ()
9489a450 5854 "Move backwards putting point after first non-whitespace non-comment."
fd9ea9d3
WS
5855 (verilog-skip-backward-comments)
5856 (forward-comment (- (buffer-size))))
6341f357 5857
9489a450 5858(defun verilog-backward-syntactic-ws-quick ()
47086495 5859 "As with `verilog-backward-syntactic-ws' but use `verilog-scan' cache."
9489a450
MM
5860 (while (cond ((bobp)
5861 nil) ; Done
5862 ((> (skip-syntax-backward " ") 0)
5863 t)
5864 ((eq (preceding-char) ?\n) ;; \n's terminate // so aren't space syntax
5865 (forward-char -1)
5866 t)
5867 ((or (verilog-inside-comment-or-string-p (1- (point)))
5868 (verilog-inside-comment-or-string-p (point)))
5869 (re-search-backward "[/\"]" nil t) ;; Only way a comment or quote can begin
5870 t))))
5871
fd9ea9d3
WS
5872(defun verilog-forward-syntactic-ws ()
5873 (verilog-skip-forward-comment-p)
5874 (forward-comment (buffer-size)))
6341f357
DN
5875
5876(defun verilog-backward-ws&directives (&optional bound)
5877 "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
5878Optional BOUND limits search."
5879 (save-restriction
5880 (let* ((bound (or bound (point-min)))
5881 (here bound)
5882 (p nil) )
5883 (if (< bound (point))
5884 (progn
d63b01e1 5885 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5886 (cond
5887 ((nth 7 state) ;; in // comment
5888 (verilog-re-search-backward "//" nil 'move)
5889 (skip-chars-backward "/"))
5890 ((nth 4 state) ;; in /* */ comment
5891 (verilog-re-search-backward "/\*" nil 'move))))
5892 (narrow-to-region bound (point))
5893 (while (/= here (point))
5894 (setq here (point))
5895 (verilog-skip-backward-comments)
5896 (setq p
5897 (save-excursion
5898 (beginning-of-line)
5899 (cond
a3a8b002
DN
5900 ((and verilog-highlight-translate-off
5901 (verilog-within-translate-off))
6341f357
DN
5902 (verilog-back-to-start-translate-off (point-min)))
5903 ((looking-at verilog-directive-re-1)
5904 (point))
5905 (t
5906 nil))))
60618039 5907 (if p (goto-char p))))))))
6341f357
DN
5908
5909(defun verilog-forward-ws&directives (&optional bound)
5910 "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
5911Optional BOUND limits search."
5912 (save-restriction
5913 (let* ((bound (or bound (point-max)))
5914 (here bound)
60618039 5915 jump)
6341f357
DN
5916 (if (> bound (point))
5917 (progn
d63b01e1 5918 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5919 (cond
5920 ((nth 7 state) ;; in // comment
a03c2342
WS
5921 (end-of-line)
5922 (forward-char 1)
5923 (skip-chars-forward " \t\n\f")
5924 )
6341f357 5925 ((nth 4 state) ;; in /* */ comment
a03c2342 5926 (verilog-re-search-forward "\*\/\\s-*" nil 'move))))
6341f357
DN
5927 (narrow-to-region (point) bound)
5928 (while (/= here (point))
5929 (setq here (point)
5930 jump nil)
5931 (forward-comment (buffer-size))
a03c2342
WS
5932 (and (looking-at "\\s-*(\\*.*\\*)\\s-*") ;; Attribute
5933 (goto-char (match-end 0)))
6341f357
DN
5934 (save-excursion
5935 (beginning-of-line)
5936 (if (looking-at verilog-directive-re-1)
5937 (setq jump t)))
5938 (if jump
60618039 5939 (beginning-of-line 2))))))))
6341f357
DN
5940
5941(defun verilog-in-comment-p ()
5942 "Return true if in a star or // comment."
d63b01e1 5943 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5944 (or (nth 4 state) (nth 7 state))))
5945
5946(defun verilog-in-star-comment-p ()
5947 "Return true if in a star comment."
d63b01e1 5948 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5949 (and
5950 (nth 4 state) ; t if in a comment of style a // or b /**/
5951 (not
5952 (nth 7 state) ; t if in a comment of style b /**/
5953 ))))
5954
5955(defun verilog-in-slash-comment-p ()
5956 "Return true if in a slash comment."
d63b01e1 5957 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5958 (nth 7 state)))
5959
5960(defun verilog-in-comment-or-string-p ()
5961 "Return true if in a string or comment."
d63b01e1 5962 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5963 (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
5964
a03c2342
WS
5965(defun verilog-in-attribute-p ()
5966 "Return true if point is in an attribute (* [] attribute *)."
9489a450
MM
5967 (save-match-data
5968 (save-excursion
5969 (verilog-re-search-backward "\\((\\*\\)\\|\\(\\*)\\)" nil 'move)
5970 (numberp (match-beginning 1)))))
5971
5972(defun verilog-in-parameter-p ()
5973 "Return true if point is in a parameter assignment #( p1=1, p2=5)."
5974 (save-match-data
5975 (save-excursion
5976 (verilog-re-search-backward "\\(#(\\)\\|\\()\\)" nil 'move)
5977 (numberp (match-beginning 1)))))
a03c2342 5978
6341f357
DN
5979(defun verilog-in-escaped-name-p ()
5980 "Return true if in an escaped name."
5981 (save-excursion
5982 (backward-char)
5983 (skip-chars-backward "^ \t\n\f")
5984 (if (equal (char-after (point) ) ?\\ )
5985 t
5986 nil)))
a3a8b002 5987(defun verilog-in-directive-p ()
a03c2342 5988 "Return true if in a directive."
a3a8b002
DN
5989 (save-excursion
5990 (beginning-of-line)
5991 (looking-at verilog-directive-re-1)))
6341f357 5992
9489a450
MM
5993(defun verilog-in-parenthesis-p ()
5994 "Return true if in a ( ) expression (but not { } or [ ])."
5995 (save-match-data
5996 (save-excursion
5997 (verilog-re-search-backward "\\((\\)\\|\\()\\)" nil 'move)
5998 (numberp (match-beginning 1)))))
5999
6341f357 6000(defun verilog-in-paren ()
9489a450
MM
6001 "Return true if in a parenthetical expression.
6002May cache result using `verilog-syntax-ppss'."
d63b01e1 6003 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
6004 (> (nth 0 state) 0 )))
6005
ea89ff08
WS
6006(defun verilog-in-paren-count ()
6007 "Return paren depth, floor to 0.
6008May cache result using `verilog-syntax-ppss'."
6009 (let ((state (save-excursion (verilog-syntax-ppss))))
6010 (if (> (nth 0 state) 0)
6011 (nth 0 state)
6012 0 )))
6013
9489a450
MM
6014(defun verilog-in-paren-quick ()
6015 "Return true if in a parenthetical expression.
47086495 6016Always starts from `point-min', to allow inserts with hooks disabled."
9489a450
MM
6017 ;; The -quick refers to its use alongside the other -quick functions,
6018 ;; not that it's likely to be faster than verilog-in-paren.
6019 (let ((state (save-excursion (parse-partial-sexp (point-min) (point)))))
6020 (> (nth 0 state) 0 )))
6021
a3a8b002
DN
6022(defun verilog-in-struct-p ()
6023 "Return true if in a struct declaration."
6024 (interactive)
6025 (save-excursion
6026 (if (verilog-in-paren)
6027 (progn
a03c2342 6028 (verilog-backward-up-list 1)
a3a8b002
DN
6029 (verilog-at-struct-p)
6030 )
6031 nil)))
6032
ea89ff08
WS
6033(defun verilog-in-struct-nested-p ()
6034 "Return nil for not in struct.
6035Return 0 for in non-nested struct.
6036Return >0 for nested struct."
6037 (interactive)
6038 (let (col)
6039 (save-excursion
6040 (if (verilog-in-paren)
6041 (progn
6042 (verilog-backward-up-list 1)
6043 (setq col (verilog-at-struct-mv-p))
6044 (if col
6045 (if (verilog-in-struct-p) (current-column) 0)))
6046 nil))))
6047
a3a8b002 6048(defun verilog-in-coverage-p ()
6341f357
DN
6049 "Return true if in a constraint or coverpoint expression."
6050 (interactive)
6051 (save-excursion
6052 (if (verilog-in-paren)
6053 (progn
a03c2342 6054 (verilog-backward-up-list 1)
6341f357
DN
6055 (verilog-at-constraint-p)
6056 )
6057 nil)))
6058(defun verilog-at-close-constraint-p ()
6059 "If at the } that closes a constraint or covergroup, return true."
6060 (if (and
6061 (equal (char-after) ?\})
ea89ff08 6062 (verilog-in-coverage-p))
6341f357
DN
6063
6064 (save-excursion
6065 (verilog-backward-ws&directives)
ea89ff08
WS
6066 (if (or (equal (char-before) ?\;)
6067 (equal (char-before) ?\}) ;; can end with inner constraint { } block or ;
6068 (equal (char-before) ?\{)) ;; empty constraint block
6341f357
DN
6069 (point)
6070 nil))))
6071
6072(defun verilog-at-constraint-p ()
6073 "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
6074 (if (save-excursion
6075 (and
6076 (equal (char-after) ?\{)
6077 (forward-list)
6078 (progn (backward-char 1)
6079 (verilog-backward-ws&directives)
ea89ff08
WS
6080 (or (equal (char-before) ?\{) ;; empty case
6081 (equal (char-before) ?\;)
6082 (equal (char-before) ?\})))))
6083 (progn
6084 (let ( (pt (point)) (pass 0))
6085 (verilog-backward-ws&directives)
6086 (verilog-backward-token)
6087 (if (looking-at (concat "\\<constraint\\|coverpoint\\|cross\\|with\\>\\|" verilog-in-constraint-re))
6088 (progn (setq pass 1)
6089 (if (looking-at "\\<with\\>")
6090 (progn (verilog-backward-ws&directives)
6091 (beginning-of-line) ;; 1
6092 (verilog-forward-ws&directives)
6093 1 )
6094 (verilog-beg-of-statement)
6095 ))
6096 ;; if first word token not keyword, it maybe the instance name
6097 ;; check next word token
6098 (if (looking-at "\\<\\w+\\>\\|\\s-*(\\s-*\\w+")
6099 (progn (verilog-beg-of-statement)
6100 (if (looking-at (concat "\\<\\(constraint\\|"
6101 "\\(?:\\w+\\s-*:\\s-*\\)?\\(coverpoint\\|cross\\)"
6102 "\\|with\\)\\>\\|" verilog-in-constraint-re))
6103 (setq pass 1)))))
6104 (if (eq pass 0)
6105 (progn (goto-char pt) nil) 1)))
6341f357 6106 ;; not
60618039 6107 nil))
6341f357 6108
a3a8b002 6109(defun verilog-at-struct-p ()
ea89ff08 6110 "If at the { of a struct, return true, not moving point."
a3a8b002
DN
6111 (save-excursion
6112 (if (and (equal (char-after) ?\{)
6113 (verilog-backward-token))
0e5c8aed 6114 (looking-at "\\<struct\\|union\\|packed\\|\\(un\\)?signed\\>")
a3a8b002
DN
6115 nil)))
6116
ea89ff08
WS
6117(defun verilog-at-struct-mv-p ()
6118 "If at the { of a struct, return true, moving point to struct."
6119 (let ((pt (point)))
6120 (if (and (equal (char-after) ?\{)
6121 (verilog-backward-token))
6122 (if (looking-at "\\<struct\\|union\\|packed\\|\\(un\\)?signed\\>")
6123 (progn (verilog-beg-of-statement) (point))
6124 (progn (goto-char pt) nil))
6125 (progn (goto-char pt) nil))))
6126
6127(defun verilog-at-close-struct-p ()
6128 "If at the } that closes a struct, return true."
6129 (if (and
6130 (equal (char-after) ?\})
6131 (verilog-in-struct-p))
6132 ;; true
6133 (save-excursion
6134 (if (looking-at "}\\(?:\\s-*\\w+\\s-*\\)?;") 1))
6135 ;; false
6136 nil))
6137
6341f357
DN
6138(defun verilog-parenthesis-depth ()
6139 "Return non zero if in parenthetical-expression."
d63b01e1 6140 (save-excursion (nth 1 (verilog-syntax-ppss))))
6341f357
DN
6141
6142
6143(defun verilog-skip-forward-comment-or-string ()
6144 "Return true if in a string or comment."
d63b01e1 6145 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
6146 (cond
6147 ((nth 3 state) ;Inside string
495ab0d5 6148 (search-forward "\"")
6341f357
DN
6149 t)
6150 ((nth 7 state) ;Inside // comment
6151 (forward-line 1)
6152 t)
6153 ((nth 4 state) ;Inside any comment (hence /**/)
6154 (search-forward "*/"))
6155 (t
6156 nil))))
6157
6158(defun verilog-skip-backward-comment-or-string ()
6159 "Return true if in a string or comment."
d63b01e1 6160 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
6161 (cond
6162 ((nth 3 state) ;Inside string
6163 (search-backward "\"")
6164 t)
6165 ((nth 7 state) ;Inside // comment
6166 (search-backward "//")
6167 (skip-chars-backward "/")
6168 t)
6169 ((nth 4 state) ;Inside /* */ comment
6170 (search-backward "/*")
6171 t)
6172 (t
6173 nil))))
6174
6175(defun verilog-skip-backward-comments ()
6176 "Return true if a comment was skipped."
6177 (let ((more t))
6178 (while more
6179 (setq more
d63b01e1 6180 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
6181 (cond
6182 ((nth 7 state) ;Inside // comment
6183 (search-backward "//")
6184 (skip-chars-backward "/")
6185 (skip-chars-backward " \t\n\f")
6186 t)
6187 ((nth 4 state) ;Inside /* */ comment
6188 (search-backward "/*")
6189 (skip-chars-backward " \t\n\f")
6190 t)
6191 ((and (not (bobp))
6192 (= (char-before) ?\/)
60618039 6193 (= (char-before (1- (point))) ?\*))
6341f357 6194 (goto-char (- (point) 2))
a03c2342
WS
6195 t) ;; Let nth 4 state handle the rest
6196 ((and (not (bobp))
6197 (= (char-before) ?\))
6198 (= (char-before (1- (point))) ?\*))
6199 (goto-char (- (point) 2))
6200 (if (search-backward "(*" nil t)
6201 (progn
6202 (skip-chars-backward " \t\n\f")
6203 t)
6204 (progn
6205 (goto-char (+ (point) 2))
6206 nil)))
6341f357 6207 (t
a03c2342 6208 (/= (skip-chars-backward " \t\n\f") 0))))))))
6341f357
DN
6209
6210(defun verilog-skip-forward-comment-p ()
6211 "If in comment, move to end and return true."
a03c2342
WS
6212 (let* (h
6213 (state (save-excursion (verilog-syntax-ppss)))
6214 (skip (cond
6215 ((nth 3 state) ;Inside string
6216 t)
6217 ((nth 7 state) ;Inside // comment
6218 (end-of-line)
6219 (forward-char 1)
6220 t)
6221 ((nth 4 state) ;Inside /* comment
6222 (search-forward "*/")
6223 t)
6224 ((verilog-in-attribute-p) ;Inside (* attribute
6225 (search-forward "*)" nil t)
6226 t)
6227 (t nil))))
6228 (skip-chars-forward " \t\n\f")
6229 (while
6230 (cond
6231 ((looking-at "\\/\\*")
6232 (progn
6233 (setq h (point))
6234 (goto-char (match-end 0))
6235 (if (search-forward "*/" nil t)
6236 (progn
6237 (skip-chars-forward " \t\n\f")
6238 (setq skip 't))
6239 (progn
6240 (goto-char h)
6241 nil))))
6242 ((looking-at "(\\*")
6243 (progn
6244 (setq h (point))
6245 (goto-char (match-end 0))
6246 (if (search-forward "*)" nil t)
6247 (progn
6248 (skip-chars-forward " \t\n\f")
6249 (setq skip 't))
6250 (progn
6251 (goto-char h)
6252 nil))))
6253 (t nil)))
6254 skip))
6341f357
DN
6255
6256(defun verilog-indent-line-relative ()
6257 "Cheap version of indent line.
6258Only look at a few lines to determine indent level."
6259 (interactive)
6260 (let ((indent-str)
6261 (sp (point)))
6262 (if (looking-at "^[ \t]*$")
6263 (cond ;- A blank line; No need to be too smart.
6264 ((bobp)
6265 (setq indent-str (list 'cpp 0)))
6266 ((verilog-continued-line)
6267 (let ((sp1 (point)))
6268 (if (verilog-continued-line)
7ea26faf
DN
6269 (progn
6270 (goto-char sp)
60618039
DN
6271 (setq indent-str
6272 (list 'statement (verilog-current-indent-level))))
6341f357
DN
6273 (goto-char sp1)
6274 (setq indent-str (list 'block (verilog-current-indent-level)))))
6275 (goto-char sp))
6276 ((goto-char sp)
6277 (setq indent-str (verilog-calculate-indent))))
6278 (progn (skip-chars-forward " \t")
6279 (setq indent-str (verilog-calculate-indent))))
6280 (verilog-do-indent indent-str)))
6281
6282(defun verilog-indent-line ()
6283 "Indent for special part of code."
6284 (verilog-do-indent (verilog-calculate-indent)))
6285
6286(defun verilog-do-indent (indent-str)
6287 (let ((type (car indent-str))
6288 (ind (car (cdr indent-str))))
6289 (cond
6290 (; handle continued exp
6291 (eq type 'cexp)
6292 (let ((here (point)))
6293 (verilog-backward-syntactic-ws)
6294 (cond
6295 ((or
6296 (= (preceding-char) ?\,)
6297 (= (preceding-char) ?\])
6298 (save-excursion
6299 (verilog-beg-of-statement-1)
6300 (looking-at verilog-declaration-re)))
6301 (let* ( fst
6302 (val
6303 (save-excursion
6304 (backward-char 1)
6305 (verilog-beg-of-statement-1)
6306 (setq fst (point))
6307 (if (looking-at verilog-declaration-re)
6308 (progn ;; we have multiple words
6309 (goto-char (match-end 0))
6310 (skip-chars-forward " \t")
6311 (cond
6312 ((and verilog-indent-declaration-macros
6313 (= (following-char) ?\`))
6314 (progn
6315 (forward-char 1)
6316 (forward-word 1)
6317 (skip-chars-forward " \t")))
6318 ((= (following-char) ?\[)
6319 (progn
6320 (forward-char 1)
a03c2342 6321 (verilog-backward-up-list -1)
60618039 6322 (skip-chars-forward " \t"))))
6341f357
DN
6323 (current-column))
6324 (progn
6325 (goto-char fst)
60618039 6326 (+ (current-column) verilog-cexp-indent))))))
6341f357 6327 (goto-char here)
9489a450
MM
6328 (indent-line-to val)
6329 (if (and (not verilog-indent-lists)
6330 (verilog-in-paren))
47086495 6331 (verilog-pretty-declarations-auto))
9489a450 6332 ))
6341f357
DN
6333 ((= (preceding-char) ?\) )
6334 (goto-char here)
6335 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
6336 (indent-line-to val)))
6337 (t
6338 (goto-char here)
6339 (let ((val))
6340 (verilog-beg-of-statement-1)
6341 (if (and (< (point) here)
6342 (verilog-re-search-forward "=[ \\t]*" here 'move))
6343 (setq val (current-column))
6344 (setq val (eval (cdr (assoc type verilog-indent-alist)))))
6345 (goto-char here)
60618039 6346 (indent-line-to val))))))
6341f357
DN
6347
6348 (; handle inside parenthetical expressions
6349 (eq type 'cparenexp)
a03c2342
WS
6350 (let* ( here
6351 (val (save-excursion
6352 (verilog-backward-up-list 1)
6353 (forward-char 1)
6354 (if verilog-indent-lists
6355 (skip-chars-forward " \t")
6356 (verilog-forward-syntactic-ws))
6357 (setq here (point))
6358 (current-column)))
6359
6360 (decl (save-excursion
6361 (goto-char here)
6362 (verilog-forward-syntactic-ws)
6363 (setq here (point))
6364 (looking-at verilog-declaration-re))))
6365 (indent-line-to val)
6366 (if decl
47086495 6367 (verilog-pretty-declarations-auto))))
a3a8b002 6368
6341f357
DN
6369 (;-- Handle the ends
6370 (or
ea89ff08
WS
6371 (looking-at verilog-end-block-re)
6372 (verilog-at-close-constraint-p)
6373 (verilog-at-close-struct-p))
6341f357
DN
6374 (let ((val (if (eq type 'statement)
6375 (- ind verilog-indent-level)
6376 ind)))
6377 (indent-line-to val)))
6378
6379 (;-- Case -- maybe line 'em up
6380 (and (eq type 'case) (not (looking-at "^[ \t]*$")))
6381 (progn
6382 (cond
6383 ((looking-at "\\<endcase\\>")
6384 (indent-line-to ind))
6385 (t
6386 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
6387 (indent-line-to val))))))
6388
6389 (;-- defun
6390 (and (eq type 'defun)
6391 (looking-at verilog-zero-indent-re))
6392 (indent-line-to 0))
6393
6394 (;-- declaration
6395 (and (or
6396 (eq type 'defun)
6397 (eq type 'block))
6398 (looking-at verilog-declaration-re))
6399 (verilog-indent-declaration ind))
6400
6401 (;-- Everything else
6402 t
6403 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
60618039
DN
6404 (indent-line-to val))))
6405
6341f357
DN
6406 (if (looking-at "[ \t]+$")
6407 (skip-chars-forward " \t"))
6408 indent-str ; Return indent data
6409 ))
6410
6411(defun verilog-current-indent-level ()
37ea4b9b 6412 "Return the indent-level of the current statement."
6341f357
DN
6413 (save-excursion
6414 (let (par-pos)
6415 (beginning-of-line)
6416 (setq par-pos (verilog-parenthesis-depth))
6417 (while par-pos
6418 (goto-char par-pos)
6419 (beginning-of-line)
6420 (setq par-pos (verilog-parenthesis-depth)))
6421 (skip-chars-forward " \t")
6422 (current-column))))
6423
6424(defun verilog-case-indent-level ()
37ea4b9b 6425 "Return the indent-level of the current statement.
6341f357
DN
6426Do not count named blocks or case-statements."
6427 (save-excursion
6428 (skip-chars-forward " \t")
6429 (cond
6430 ((looking-at verilog-named-block-re)
6431 (current-column))
a3a8b002 6432 ((and (not (looking-at verilog-extended-case-re))
6341f357
DN
6433 (looking-at "^[^:;]+[ \t]*:"))
6434 (verilog-re-search-forward ":" nil t)
6435 (skip-chars-forward " \t")
6436 (current-column))
6437 (t
6438 (current-column)))))
6439
6440(defun verilog-indent-comment ()
6441 "Indent current line as comment."
6442 (let* ((stcol
6443 (cond
6444 ((verilog-in-star-comment-p)
6445 (save-excursion
6446 (re-search-backward "/\\*" nil t)
6447 (1+(current-column))))
6448 (comment-column
6449 comment-column )
6450 (t
6451 (save-excursion
6452 (re-search-backward "//" nil t)
60618039 6453 (current-column))))))
6341f357
DN
6454 (indent-line-to stcol)
6455 stcol))
6456
6457(defun verilog-more-comment ()
6458 "Make more comment lines like the previous."
6459 (let* ((star 0)
6460 (stcol
6461 (cond
6462 ((verilog-in-star-comment-p)
6463 (save-excursion
6464 (setq star 1)
6465 (re-search-backward "/\\*" nil t)
6466 (1+(current-column))))
6467 (comment-column
6468 comment-column )
6469 (t
6470 (save-excursion
6471 (re-search-backward "//" nil t)
60618039 6472 (current-column))))))
6341f357
DN
6473 (progn
6474 (indent-to stcol)
6475 (if (and star
6476 (save-excursion
6477 (forward-line -1)
6478 (skip-chars-forward " \t")
6479 (looking-at "\*")))
6480 (insert "* ")))))
6481
0f137a73 6482(defun verilog-comment-indent (&optional _arg)
6341f357 6483 "Return the column number the line should be indented to.
0f137a73 6484_ARG is ignored, for `comment-indent-function' compatibility."
6341f357
DN
6485 (cond
6486 ((verilog-in-star-comment-p)
6487 (save-excursion
6488 (re-search-backward "/\\*" nil t)
6489 (1+(current-column))))
6490 ( comment-column
6491 comment-column )
6492 (t
6493 (save-excursion
6494 (re-search-backward "//" nil t)
6495 (current-column)))))
6496
6497;;
6498
47086495
WS
6499(defun verilog-pretty-declarations-auto (&optional quiet)
6500 "Call `verilog-pretty-declarations' QUIET based on `verilog-auto-lineup'."
6501 (when (or (eq 'all verilog-auto-lineup)
6502 (eq 'declarations verilog-auto-lineup))
6503 (verilog-pretty-declarations quiet)))
6504
7e2a6000 6505(defun verilog-pretty-declarations (&optional quiet)
a3a8b002
DN
6506 "Line up declarations around point.
6507Be verbose about progress unless optional QUIET set."
6341f357 6508 (interactive)
fd9ea9d3
WS
6509 (let* ((m1 (make-marker))
6510 (e (point))
6511 el
6512 r
6513 (here (point))
6514 ind
6515 start
6516 startpos
6517 end
6518 endpos
6519 base-ind
6520 )
6521 (save-excursion
6522 (if (progn
6523; (verilog-beg-of-statement-1)
6524 (beginning-of-line)
a03c2342 6525 (verilog-forward-syntactic-ws)
fd9ea9d3 6526 (and (not (verilog-in-directive-p)) ;; could have `define input foo
a3a8b002 6527 (looking-at verilog-declaration-re)))
fd9ea9d3 6528 (progn
a03c2342
WS
6529 (if (verilog-parenthesis-depth)
6530 ;; in an argument list or parameter block
6531 (setq el (verilog-backward-up-list -1)
fd9ea9d3
WS
6532 start (progn
6533 (goto-char e)
a03c2342 6534 (verilog-backward-up-list 1)
fd9ea9d3
WS
6535 (forward-line) ;; ignore ( input foo,
6536 (verilog-re-search-forward verilog-declaration-re el 'move)
6537 (goto-char (match-beginning 0))
6538 (skip-chars-backward " \t")
6539 (point))
6540 startpos (set-marker (make-marker) start)
6541 end (progn
6542 (goto-char start)
a03c2342 6543 (verilog-backward-up-list -1)
fd9ea9d3
WS
6544 (forward-char -1)
6545 (verilog-backward-syntactic-ws)
6546 (point))
6547 endpos (set-marker (make-marker) end)
6548 base-ind (progn
6549 (goto-char start)
a03c2342
WS
6550 (forward-char 1)
6551 (skip-chars-forward " \t")
6552 (current-column))
fd9ea9d3
WS
6553 )
6554 ;; in a declaration block (not in argument list)
a03c2342 6555 (setq
fd9ea9d3
WS
6556 start (progn
6557 (verilog-beg-of-statement-1)
6558 (while (and (looking-at verilog-declaration-re)
6559 (not (bobp)))
6560 (skip-chars-backward " \t")
6561 (setq e (point))
6562 (beginning-of-line)
6563 (verilog-backward-syntactic-ws)
6564 (backward-char)
6565 (verilog-beg-of-statement-1))
6566 e)
6567 startpos (set-marker (make-marker) start)
6568 end (progn
6569 (goto-char here)
6570 (verilog-end-of-statement)
6571 (setq e (point)) ;Might be on last line
6572 (verilog-forward-syntactic-ws)
6573 (while (looking-at verilog-declaration-re)
fd9ea9d3
WS
6574 (verilog-end-of-statement)
6575 (setq e (point))
6576 (verilog-forward-syntactic-ws))
6577 e)
6578 endpos (set-marker (make-marker) end)
6579 base-ind (progn
6580 (goto-char start)
6581 (verilog-do-indent (verilog-calculate-indent))
6582 (verilog-forward-ws&directives)
6583 (current-column))))
6584 ;; OK, start and end are set
6585 (goto-char (marker-position startpos))
6586 (if (and (not quiet)
6587 (> (- end start) 100))
6588 (message "Lining up declarations..(please stand by)"))
6589 ;; Get the beginning of line indent first
6590 (while (progn (setq e (marker-position endpos))
6591 (< (point) e))
6592 (cond
a03c2342 6593 ((save-excursion (skip-chars-backward " \t")
fd9ea9d3
WS
6594 (bolp))
6595 (verilog-forward-ws&directives)
6596 (indent-line-to base-ind)
6597 (verilog-forward-ws&directives)
6598 (if (< (point) e)
6599 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
6600 (t
6601 (just-one-space)
6602 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
6603 ;;(forward-line)
6604 )
6605 ;; Now find biggest prefix
6606 (setq ind (verilog-get-lineup-indent (marker-position startpos) endpos))
6607 ;; Now indent each line.
6608 (goto-char (marker-position startpos))
6609 (while (progn (setq e (marker-position endpos))
6610 (setq r (- e (point)))
6611 (> r 0))
6612 (setq e (point))
6613 (unless quiet (message "%d" r))
a03c2342 6614 ;;(verilog-do-indent (verilog-calculate-indent)))
fd9ea9d3
WS
6615 (verilog-forward-ws&directives)
6616 (cond
6617 ((or (and verilog-indent-declaration-macros
6618 (looking-at verilog-declaration-re-2-macro))
6619 (looking-at verilog-declaration-re-2-no-macro))
6620 (let ((p (match-end 0)))
6621 (set-marker m1 p)
6622 (if (verilog-re-search-forward "[[#`]" p 'move)
6623 (progn
6624 (forward-char -1)
6625 (just-one-space)
6626 (goto-char (marker-position m1))
6627 (just-one-space)
6628 (indent-to ind))
6629 (progn
6630 (just-one-space)
6631 (indent-to ind)))))
6632 ((verilog-continued-line-1 (marker-position startpos))
6633 (goto-char e)
6634 (indent-line-to ind))
6635 ((verilog-in-struct-p)
6636 ;; could have a declaration of a user defined item
6637 (goto-char e)
6638 (verilog-end-of-statement))
6639 (t ; Must be comment or white space
6640 (goto-char e)
6641 (verilog-forward-ws&directives)
6642 (forward-line -1)))
6643 (forward-line 1))
6644 (unless quiet (message "")))))))
6341f357 6645
0f137a73
SM
6646(defun verilog-pretty-expr (&optional quiet _myre)
6647 "Line up expressions around point, optionally QUIET with regexp _MYRE ignored."
9489a450
MM
6648 (interactive)
6649 (if (not (verilog-in-comment-or-string-p))
6650 (save-excursion
47086495
WS
6651 (let ( (rexp (concat "^\\s-*" verilog-complete-reg))
6652 (rexp1 (concat "^\\s-*" verilog-basic-complete-re)))
6653 (beginning-of-line)
6654 (if (and (not (looking-at rexp ))
6655 (looking-at verilog-assignment-operation-re)
6656 (save-excursion
6657 (goto-char (match-end 2))
6658 (and (not (verilog-in-attribute-p))
6659 (not (verilog-in-parameter-p))
6660 (not (verilog-in-comment-or-string-p)))))
6661 (let* ((here (point))
6662 (e) (r)
6663 (start
6664 (progn
6665 (beginning-of-line)
6666 (setq e (point))
6667 (verilog-backward-syntactic-ws)
6668 (beginning-of-line)
6669 (while (and (not (looking-at rexp1))
6670 (looking-at verilog-assignment-operation-re)
6671 (not (bobp))
6672 )
6673 (setq e (point))
6674 (verilog-backward-syntactic-ws)
6675 (beginning-of-line)
6676 ) ;Ack, need to grok `define
6677 e))
6678 (end
6679 (progn
6680 (goto-char here)
6681 (end-of-line)
6682 (setq e (point)) ;Might be on last line
6683 (verilog-forward-syntactic-ws)
6684 (beginning-of-line)
6685 (while (and
6686 (not (looking-at rexp1 ))
6687 (looking-at verilog-assignment-operation-re)
6688 (progn
6689 (end-of-line)
6690 (not (eq e (point)))))
6691 (setq e (point))
6692 (verilog-forward-syntactic-ws)
6693 (beginning-of-line)
6694 )
6695 e))
6696 (endpos (set-marker (make-marker) end))
6697 (ind)
6698 )
6699 (goto-char start)
6700 (verilog-do-indent (verilog-calculate-indent))
6701 (if (and (not quiet)
6702 (> (- end start) 100))
6703 (message "Lining up expressions..(please stand by)"))
6704
6705 ;; Set indent to minimum throughout region
6706 (while (< (point) (marker-position endpos))
6707 (beginning-of-line)
6708 (verilog-just-one-space verilog-assignment-operation-re)
6709 (beginning-of-line)
6710 (verilog-do-indent (verilog-calculate-indent))
6711 (end-of-line)
6712 (verilog-forward-syntactic-ws)
6713 )
6714
6715 ;; Now find biggest prefix
6716 (setq ind (verilog-get-lineup-indent-2 verilog-assignment-operation-re start endpos))
6717
6718 ;; Now indent each line.
6719 (goto-char start)
6720 (while (progn (setq e (marker-position endpos))
6721 (setq r (- e (point)))
6722 (> r 0))
6723 (setq e (point))
6724 (if (not quiet) (message "%d" r))
6725 (cond
6726 ((looking-at verilog-assignment-operation-re)
6727 (goto-char (match-beginning 2))
6728 (if (not (or (verilog-in-parenthesis-p) ;; leave attributes and comparisons alone
6729 (verilog-in-coverage-p)))
6730 (if (eq (char-after) ?=)
6731 (indent-to (1+ ind)) ; line up the = of the <= with surrounding =
6732 (indent-to ind)
6733 ))
6734 )
6735 ((verilog-continued-line-1 start)
6736 (goto-char e)
6737 (indent-line-to ind))
6738 (t ; Must be comment or white space
6739 (goto-char e)
6740 (verilog-forward-ws&directives)
6741 (forward-line -1))
6742 )
6743 (forward-line 1))
6744 (unless quiet (message ""))
6745 ))))))
6341f357
DN
6746
6747(defun verilog-just-one-space (myre)
6748 "Remove extra spaces around regular expression MYRE."
6749 (interactive)
6750 (if (and (not(looking-at verilog-complete-reg))
6751 (looking-at myre))
6752 (let ((p1 (match-end 1))
6753 (p2 (match-end 2)))
6754 (progn
6755 (goto-char p2)
9489a450 6756 (just-one-space)
6341f357 6757 (goto-char p1)
9489a450 6758 (just-one-space)))))
6341f357
DN
6759
6760(defun verilog-indent-declaration (baseind)
6761 "Indent current lines as declaration.
6762Line up the variable names based on previous declaration's indentation.
6763BASEIND is the base indent to offset everything."
6764 (interactive)
6765 (let ((pos (point-marker))
6766 (lim (save-excursion
6767 ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
6768 (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
6769 (point)))
6770 (ind)
6771 (val)
60618039 6772 (m1 (make-marker)))
7ea26faf
DN
6773 (setq val
6774 (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6341f357
DN
6775 (indent-line-to val)
6776
6777 ;; Use previous declaration (in this module) as template.
a3a8b002
DN
6778 (if (or (eq 'all verilog-auto-lineup)
6779 (eq 'declarations verilog-auto-lineup))
6edb5716 6780 (if (verilog-re-search-backward
6341f357
DN
6781 (or (and verilog-indent-declaration-macros
6782 verilog-declaration-re-1-macro)
6783 verilog-declaration-re-1-no-macro) lim t)
6784 (progn
6785 (goto-char (match-end 0))
6786 (skip-chars-forward " \t")
6787 (setq ind (current-column))
6788 (goto-char pos)
7ea26faf
DN
6789 (setq val
6790 (+ baseind
6791 (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6341f357
DN
6792 (indent-line-to val)
6793 (if (and verilog-indent-declaration-macros
6794 (looking-at verilog-declaration-re-2-macro))
6795 (let ((p (match-end 0)))
6796 (set-marker m1 p)
6797 (if (verilog-re-search-forward "[[#`]" p 'move)
6798 (progn
6799 (forward-char -1)
6800 (just-one-space)
6801 (goto-char (marker-position m1))
6802 (just-one-space)
60618039 6803 (indent-to ind))
6341f357
DN
6804 (if (/= (current-column) ind)
6805 (progn
6806 (just-one-space)
60618039 6807 (indent-to ind)))))
6341f357
DN
6808 (if (looking-at verilog-declaration-re-2-no-macro)
6809 (let ((p (match-end 0)))
6810 (set-marker m1 p)
6811 (if (verilog-re-search-forward "[[`#]" p 'move)
6812 (progn
6813 (forward-char -1)
6814 (just-one-space)
6815 (goto-char (marker-position m1))
6816 (just-one-space)
6817 (indent-to ind))
6818 (if (/= (current-column) ind)
6819 (progn
6820 (just-one-space)
7ea26faf
DN
6821 (indent-to ind))))))))))
6822 (goto-char pos)))
6341f357
DN
6823
6824(defun verilog-get-lineup-indent (b edpos)
6825 "Return the indent level that will line up several lines within the region.
6826Region is defined by B and EDPOS."
6827 (save-excursion
6828 (let ((ind 0) e)
6829 (goto-char b)
6830 ;; Get rightmost position
6831 (while (progn (setq e (marker-position edpos))
6832 (< (point) e))
6edb5716 6833 (if (verilog-re-search-forward
6341f357
DN
6834 (or (and verilog-indent-declaration-macros
6835 verilog-declaration-re-1-macro)
6836 verilog-declaration-re-1-no-macro) e 'move)
6837 (progn
6838 (goto-char (match-end 0))
6839 (verilog-backward-syntactic-ws)
6840 (if (> (current-column) ind)
6841 (setq ind (current-column)))
6842 (goto-char (match-end 0)))))
6843 (if (> ind 0)
6844 (1+ ind)
6845 ;; No lineup-string found
6846 (goto-char b)
6847 (end-of-line)
fd9ea9d3
WS
6848 (verilog-backward-syntactic-ws)
6849 ;;(skip-chars-backward " \t")
6341f357
DN
6850 (1+ (current-column))))))
6851
6852(defun verilog-get-lineup-indent-2 (myre b edpos)
6853 "Return the indent level that will line up several lines within the region."
6854 (save-excursion
6855 (let ((ind 0) e)
6856 (goto-char b)
6857 ;; Get rightmost position
6858 (while (progn (setq e (marker-position edpos))
6859 (< (point) e))
7e2a6000 6860 (if (and (verilog-re-search-forward myre e 'move)
9489a450 6861 (not (verilog-in-attribute-p))) ;; skip attribute exprs
6341f357 6862 (progn
7e2a6000 6863 (goto-char (match-beginning 2))
6341f357
DN
6864 (verilog-backward-syntactic-ws)
6865 (if (> (current-column) ind)
6866 (setq ind (current-column)))
7e2a6000
DN
6867 (goto-char (match-end 0)))
6868 ))
6341f357
DN
6869 (if (> ind 0)
6870 (1+ ind)
6871 ;; No lineup-string found
6872 (goto-char b)
6873 (end-of-line)
6874 (skip-chars-backward " \t")
6875 (1+ (current-column))))))
6876
6877(defun verilog-comment-depth (type val)
6878 "A useful mode debugging aide. TYPE and VAL are comments for insertion."
6879 (save-excursion
6880 (let
6881 ((b (prog2
6882 (beginning-of-line)
6883 (point-marker)
0f137a73 6884 (end-of-line))))
6341f357
DN
6885 (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
6886 (progn
6887 (replace-match " /* -# ## */")
6888 (end-of-line))
6889 (progn
6890 (end-of-line)
6891 (insert " /* ## ## */"))))
6892 (backward-char 6)
6893 (insert
6894 (format "%s %d" type val))))
6895
6896;; \f
6897;;
6898;; Completion
6899;;
6900(defvar verilog-str nil)
6901(defvar verilog-all nil)
6902(defvar verilog-pred nil)
6903(defvar verilog-buffer-to-use nil)
6904(defvar verilog-flag nil)
6905(defvar verilog-toggle-completions nil
fb7ada5f 6906 "True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
6341f357
DN
6907Repeated use of \\[verilog-complete-word] will show you all of them.
6908Normally, when there is more than one possible completion,
6909it displays a list of all possible completions.")
6910
6911
6912(defvar verilog-type-keywords
6913 '(
6914 "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
6915 "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
fd9ea9d3 6916 "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
6341f357
DN
6917 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
6918 "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
6919 "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
6920 )
fb7ada5f 6921 "Keywords for types used when completing a word in a declaration or parmlist.
0e5c8aed 6922\(integer, real, reg...)")
6341f357
DN
6923
6924(defvar verilog-cpp-keywords
6925 '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
6926 "endif")
fb7ada5f 6927 "Keywords to complete when at first word of a line in declarative scope.
0e5c8aed 6928\(initial, always, begin, assign...)
6341f357 6929The procedures and variables defined within the Verilog program
37ea4b9b 6930will be completed at runtime and should not be added to this list.")
6341f357
DN
6931
6932(defvar verilog-defun-keywords
6933 (append
6934 '(
6935 "always" "always_comb" "always_ff" "always_latch" "assign"
6936 "begin" "end" "generate" "endgenerate" "module" "endmodule"
6937 "specify" "endspecify" "function" "endfunction" "initial" "final"
6938 "task" "endtask" "primitive" "endprimitive"
6939 )
6940 verilog-type-keywords)
fb7ada5f 6941 "Keywords to complete when at first word of a line in declarative scope.
0e5c8aed 6942\(initial, always, begin, assign...)
6341f357 6943The procedures and variables defined within the Verilog program
37ea4b9b 6944will be completed at runtime and should not be added to this list.")
6341f357
DN
6945
6946(defvar verilog-block-keywords
6947 '(
6948 "begin" "break" "case" "continue" "else" "end" "endfunction"
6949 "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
6950 "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
6951 "while")
fb7ada5f 6952 "Keywords to complete when at first word of a line in behavioral scope.
0e5c8aed 6953\(begin, if, then, else, for, fork...)
6341f357 6954The procedures and variables defined within the Verilog program
37ea4b9b 6955will be completed at runtime and should not be added to this list.")
6341f357
DN
6956
6957(defvar verilog-tf-keywords
6958 '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
fb7ada5f 6959 "Keywords to complete when at first word of a line in a task or function.
0e5c8aed 6960\(begin, if, then, else, for, fork.)
6341f357 6961The procedures and variables defined within the Verilog program
37ea4b9b 6962will be completed at runtime and should not be added to this list.")
6341f357
DN
6963
6964(defvar verilog-case-keywords
6965 '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
fb7ada5f 6966 "Keywords to complete when at first word of a line in case scope.
0e5c8aed 6967\(begin, if, then, else, for, fork...)
6341f357 6968The procedures and variables defined within the Verilog program
37ea4b9b 6969will be completed at runtime and should not be added to this list.")
6341f357
DN
6970
6971(defvar verilog-separator-keywords
6972 '("else" "then" "begin")
fb7ada5f 6973 "Keywords to complete when NOT standing at the first word of a statement.
0e5c8aed 6974\(else, then, begin...)
37ea4b9b
JB
6975Variables and function names defined within the Verilog program
6976will be completed at runtime and should not be added to this list.")
6341f357 6977
a03c2342
WS
6978(defvar verilog-gate-ios
6979 ;; All these have an implied {"input"...} at the end
6980 '(("and" "output")
6981 ("buf" "output")
6982 ("bufif0" "output")
6983 ("bufif1" "output")
6984 ("cmos" "output")
6985 ("nand" "output")
6986 ("nmos" "output")
6987 ("nor" "output")
6988 ("not" "output")
6989 ("notif0" "output")
6990 ("notif1" "output")
6991 ("or" "output")
6992 ("pmos" "output")
6993 ("pulldown" "output")
6994 ("pullup" "output")
6995 ("rcmos" "output")
6996 ("rnmos" "output")
6997 ("rpmos" "output")
6998 ("rtran" "inout" "inout")
6999 ("rtranif0" "inout" "inout")
7000 ("rtranif1" "inout" "inout")
7001 ("tran" "inout" "inout")
7002 ("tranif0" "inout" "inout")
7003 ("tranif1" "inout" "inout")
7004 ("xnor" "output")
7005 ("xor" "output"))
fb7ada5f 7006 "Map of direction for each positional argument to each gate primitive.")
a03c2342
WS
7007
7008(defvar verilog-gate-keywords (mapcar `car verilog-gate-ios)
fb7ada5f 7009 "Keywords for gate primitives.")
a03c2342 7010
6341f357
DN
7011(defun verilog-string-diff (str1 str2)
7012 "Return index of first letter where STR1 and STR2 differs."
7013 (catch 'done
7014 (let ((diff 0))
7015 (while t
7016 (if (or (> (1+ diff) (length str1))
7017 (> (1+ diff) (length str2)))
7018 (throw 'done diff))
7019 (or (equal (aref str1 diff) (aref str2 diff))
7020 (throw 'done diff))
7021 (setq diff (1+ diff))))))
7022
7023;; Calculate all possible completions for functions if argument is `function',
7024;; completions for procedures if argument is `procedure' or both functions and
7025;; procedures otherwise.
7026
7027(defun verilog-func-completion (type)
7028 "Build regular expression for module/task/function names.
7029TYPE is 'module, 'tf for task or function, or t if unknown."
7030 (if (string= verilog-str "")
7031 (setq verilog-str "[a-zA-Z_]"))
7032 (let ((verilog-str (concat (cond
7033 ((eq type 'module) "\\<\\(module\\)\\s +")
7034 ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
7035 (t "\\<\\(task\\|function\\|module\\)\\s +"))
7036 "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
7037 match)
7038
7039 (if (not (looking-at verilog-defun-re))
7040 (verilog-re-search-backward verilog-defun-re nil t))
7041 (forward-char 1)
7042
7043 ;; Search through all reachable functions
7044 (goto-char (point-min))
7045 (while (verilog-re-search-forward verilog-str (point-max) t)
7046 (progn (setq match (buffer-substring (match-beginning 2)
7047 (match-end 2)))
7048 (if (or (null verilog-pred)
7049 (funcall verilog-pred match))
7050 (setq verilog-all (cons match verilog-all)))))
7051 (if (match-beginning 0)
7052 (goto-char (match-beginning 0)))))
7053
7054(defun verilog-get-completion-decl (end)
7055 "Macro for searching through current declaration (var, type or const)
7056for matches of `str' and adding the occurrence tp `all' through point END."
7057 (let ((re (or (and verilog-indent-declaration-macros
7058 verilog-declaration-re-2-macro)
7059 verilog-declaration-re-2-no-macro))
7060 decl-end match)
7061 ;; Traverse lines
7062 (while (and (< (point) end)
7063 (verilog-re-search-forward re end t))
7064 ;; Traverse current line
7065 (setq decl-end (save-excursion (verilog-declaration-end)))
7066 (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
7067 (not (match-end 1)))
7068 (setq match (buffer-substring (match-beginning 0) (match-end 0)))
7069 (if (string-match (concat "\\<" verilog-str) match)
7070 (if (or (null verilog-pred)
7071 (funcall verilog-pred match))
7072 (setq verilog-all (cons match verilog-all)))))
60618039
DN
7073 (forward-line 1)))
7074 verilog-all)
6341f357 7075
6341f357
DN
7076(defun verilog-var-completion ()
7077 "Calculate all possible completions for variables (or constants)."
7078 (let ((start (point)))
7079 ;; Search for all reachable var declarations
7080 (verilog-beg-of-defun)
7081 (save-excursion
7082 ;; Check var declarations
7083 (verilog-get-completion-decl start))))
7084
7085(defun verilog-keyword-completion (keyword-list)
7086 "Give list of all possible completions of keywords in KEYWORD-LIST."
4f91a816 7087 (mapcar (lambda (s)
9489a450
MM
7088 (if (string-match (concat "\\<" verilog-str) s)
7089 (if (or (null verilog-pred)
7090 (funcall verilog-pred s))
7091 (setq verilog-all (cons s verilog-all)))))
6341f357
DN
7092 keyword-list))
7093
7094
7095(defun verilog-completion (verilog-str verilog-pred verilog-flag)
7096 "Function passed to `completing-read', `try-completion' or `all-completions'.
7097Called to get completion on VERILOG-STR. If VERILOG-PRED is non-nil, it
7098must be a function to be called for every match to check if this should
37ea4b9b
JB
7099really be a match. If VERILOG-FLAG is t, the function returns a list of
7100all possible completions. If VERILOG-FLAG is nil it returns a string,
7101the longest possible completion, or t if VERILOG-STR is an exact match.
7102If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
7103exact match, nil otherwise."
6341f357
DN
7104 (save-excursion
7105 (let ((verilog-all nil))
7106 ;; Set buffer to use for searching labels. This should be set
7107 ;; within functions which use verilog-completions
7108 (set-buffer verilog-buffer-to-use)
7109
7110 ;; Determine what should be completed
7111 (let ((state (car (verilog-calculate-indent))))
7112 (cond ((eq state 'defun)
7113 (save-excursion (verilog-var-completion))
7114 (verilog-func-completion 'module)
7115 (verilog-keyword-completion verilog-defun-keywords))
7116
7117 ((eq state 'behavioral)
7118 (save-excursion (verilog-var-completion))
7119 (verilog-func-completion 'module)
7120 (verilog-keyword-completion verilog-defun-keywords))
7121
7122 ((eq state 'block)
7123 (save-excursion (verilog-var-completion))
7124 (verilog-func-completion 'tf)
7125 (verilog-keyword-completion verilog-block-keywords))
7126
7127 ((eq state 'case)
7128 (save-excursion (verilog-var-completion))
7129 (verilog-func-completion 'tf)
7130 (verilog-keyword-completion verilog-case-keywords))
7131
7132 ((eq state 'tf)
7133 (save-excursion (verilog-var-completion))
7134 (verilog-func-completion 'tf)
7135 (verilog-keyword-completion verilog-tf-keywords))
7136
7137 ((eq state 'cpp)
7138 (save-excursion (verilog-var-completion))
7139 (verilog-keyword-completion verilog-cpp-keywords))
7140
7141 ((eq state 'cparenexp)
7142 (save-excursion (verilog-var-completion)))
7143
7144 (t;--Anywhere else
7145 (save-excursion (verilog-var-completion))
7146 (verilog-func-completion 'both)
7147 (verilog-keyword-completion verilog-separator-keywords))))
7148
7149 ;; Now we have built a list of all matches. Give response to caller
7150 (verilog-completion-response))))
7151
7152(defun verilog-completion-response ()
7153 (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
7154 ;; This was not called by all-completions
7155 (if (null verilog-all)
7156 ;; Return nil if there was no matching label
7157 nil
7158 ;; Get longest string common in the labels
0f137a73 7159 ;; FIXME: Why not use `try-completion'?
6341f357
DN
7160 (let* ((elm (cdr verilog-all))
7161 (match (car verilog-all))
7162 (min (length match))
7163 tmp)
7164 (if (string= match verilog-str)
7165 ;; Return t if first match was an exact match
7166 (setq match t)
7167 (while (not (null elm))
7168 ;; Find longest common string
7169 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
7170 (progn
7171 (setq min tmp)
7172 (setq match (substring match 0 min))))
7173 ;; Terminate with match=t if this is an exact match
7174 (if (string= (car elm) verilog-str)
7175 (progn
7176 (setq match t)
7177 (setq elm nil))
7178 (setq elm (cdr elm)))))
7179 ;; If this is a test just for exact match, return nil ot t
7180 (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
7181 nil
7182 match))))
7183 ;; If flag is t, this was called by all-completions. Return
7184 ;; list of all possible completions
7185 (verilog-flag
7186 verilog-all)))
7187
7188(defvar verilog-last-word-numb 0)
7189(defvar verilog-last-word-shown nil)
7190(defvar verilog-last-completions nil)
7191
7192(defun verilog-complete-word ()
7193 "Complete word at current point.
7194\(See also `verilog-toggle-completions', `verilog-type-keywords',
7195and `verilog-separator-keywords'.)"
0f137a73 7196 ;; FIXME: Provide completion-at-point-function.
6341f357
DN
7197 (interactive)
7198 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
7199 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
7200 (verilog-str (buffer-substring b e))
7201 ;; The following variable is used in verilog-completion
7202 (verilog-buffer-to-use (current-buffer))
7203 (allcomp (if (and verilog-toggle-completions
7204 (string= verilog-last-word-shown verilog-str))
7205 verilog-last-completions
7206 (all-completions verilog-str 'verilog-completion)))
7207 (match (if verilog-toggle-completions
7208 "" (try-completion
4f91a816 7209 verilog-str (mapcar (lambda (elm)
6341f357
DN
7210 (cons elm 0)) allcomp)))))
7211 ;; Delete old string
7212 (delete-region b e)
7213
7214 ;; Toggle-completions inserts whole labels
7215 (if verilog-toggle-completions
7216 (progn
7217 ;; Update entry number in list
7218 (setq verilog-last-completions allcomp
7219 verilog-last-word-numb
7220 (if (>= verilog-last-word-numb (1- (length allcomp)))
7221 0
7222 (1+ verilog-last-word-numb)))
7223 (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
7224 ;; Display next match or same string if no match was found
7225 (if (not (null allcomp))
7226 (insert "" verilog-last-word-shown)
7227 (insert "" verilog-str)
7228 (message "(No match)")))
7229 ;; The other form of completion does not necessarily do that.
7230
7231 ;; Insert match if found, or the original string if no match
7232 (if (or (null match) (equal match 't))
7233 (progn (insert "" verilog-str)
7234 (message "(No match)"))
7235 (insert "" match))
7236 ;; Give message about current status of completion
7237 (cond ((equal match 't)
7238 (if (not (null (cdr allcomp)))
7239 (message "(Complete but not unique)")
7240 (message "(Sole completion)")))
7241 ;; Display buffer if the current completion didn't help
7242 ;; on completing the label.
7243 ((and (not (null (cdr allcomp))) (= (length verilog-str)
7244 (length match)))
7245 (with-output-to-temp-buffer "*Completions*"
7246 (display-completion-list allcomp))
7247 ;; Wait for a key press. Then delete *Completion* window
7248 (momentary-string-display "" (point))
7249 (delete-window (get-buffer-window (get-buffer "*Completions*")))
7250 )))))
7251
7252(defun verilog-show-completions ()
7253 "Show all possible completions at current point."
7254 (interactive)
7255 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
7256 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
7257 (verilog-str (buffer-substring b e))
7258 ;; The following variable is used in verilog-completion
7259 (verilog-buffer-to-use (current-buffer))
7260 (allcomp (if (and verilog-toggle-completions
7261 (string= verilog-last-word-shown verilog-str))
7262 verilog-last-completions
7263 (all-completions verilog-str 'verilog-completion))))
7264 ;; Show possible completions in a temporary buffer.
7265 (with-output-to-temp-buffer "*Completions*"
7266 (display-completion-list allcomp))
7267 ;; Wait for a key press. Then delete *Completion* window
7268 (momentary-string-display "" (point))
7269 (delete-window (get-buffer-window (get-buffer "*Completions*")))))
7270
7271
7272(defun verilog-get-default-symbol ()
7273 "Return symbol around current point as a string."
7274 (save-excursion
7275 (buffer-substring (progn
7276 (skip-chars-backward " \t")
7277 (skip-chars-backward "a-zA-Z0-9_")
7278 (point))
7279 (progn
7280 (skip-chars-forward "a-zA-Z0-9_")
7281 (point)))))
7282
7283(defun verilog-build-defun-re (str &optional arg)
7284 "Return function/task/module starting with STR as regular expression.
7285With optional second ARG non-nil, STR is the complete name of the instruction."
7286 (if arg
7287 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
7288 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
7289
7290(defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
7291 "Function passed to `completing-read', `try-completion' or `all-completions'.
7292Returns a completion on any function name based on VERILOG-STR prefix. If
7293VERILOG-PRED is non-nil, it must be a function to be called for every match
7294to check if this should really be a match. If VERILOG-FLAG is t, the
7295function returns a list of all possible completions. If it is nil it
7296returns a string, the longest possible completion, or t if VERILOG-STR is
7297an exact match. If VERILOG-FLAG is 'lambda, the function returns t if
7298VERILOG-STR is an exact match, nil otherwise."
7299 (save-excursion
7300 (let ((verilog-all nil)
7301 match)
7302
7303 ;; Set buffer to use for searching labels. This should be set
7304 ;; within functions which use verilog-completions
7305 (set-buffer verilog-buffer-to-use)
7306
7307 (let ((verilog-str verilog-str))
7308 ;; Build regular expression for functions
7309 (if (string= verilog-str "")
7310 (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
7311 (setq verilog-str (verilog-build-defun-re verilog-str)))
7312 (goto-char (point-min))
7313
7314 ;; Build a list of all possible completions
7315 (while (verilog-re-search-forward verilog-str nil t)
7316 (setq match (buffer-substring (match-beginning 2) (match-end 2)))
7317 (if (or (null verilog-pred)
7318 (funcall verilog-pred match))
7319 (setq verilog-all (cons match verilog-all)))))
7320
7321 ;; Now we have built a list of all matches. Give response to caller
7322 (verilog-completion-response))))
7323
7324(defun verilog-goto-defun ()
a03c2342 7325 "Move to specified Verilog module/interface/task/function.
6341f357
DN
7326The default is a name found in the buffer around point.
7327If search fails, other files are checked based on
7328`verilog-library-flags'."
7329 (interactive)
7330 (let* ((default (verilog-get-default-symbol))
7331 ;; The following variable is used in verilog-comp-function
7332 (verilog-buffer-to-use (current-buffer))
7333 (label (if (not (string= default ""))
7334 ;; Do completion with default
a3a8b002
DN
7335 (completing-read (concat "Goto-Label: (default "
7336 default ") ")
6341f357
DN
7337 'verilog-comp-defun nil nil "")
7338 ;; There is no default value. Complete without it
a3a8b002 7339 (completing-read "Goto-Label: "
6341f357
DN
7340 'verilog-comp-defun nil nil "")))
7341 pt)
a3a8b002
DN
7342 ;; Make sure library paths are correct, in case need to resolve module
7343 (verilog-auto-reeval-locals)
7344 (verilog-getopt-flags)
6341f357
DN
7345 ;; If there was no response on prompt, use default value
7346 (if (string= label "")
7347 (setq label default))
7348 ;; Goto right place in buffer if label is not an empty string
7349 (or (string= label "")
7350 (progn
7351 (save-excursion
7352 (goto-char (point-min))
7ea26faf
DN
7353 (setq pt
7354 (re-search-forward (verilog-build-defun-re label t) nil t)))
6341f357
DN
7355 (when pt
7356 (goto-char pt)
7357 (beginning-of-line))
7358 pt)
60618039 7359 (verilog-goto-defun-file label))))
6341f357
DN
7360
7361;; Eliminate compile warning
7d55bf04 7362(defvar occur-pos-list)
6341f357
DN
7363
7364(defun verilog-showscopes ()
7365 "List all scopes in this module."
7366 (interactive)
7367 (let ((buffer (current-buffer))
7368 (linenum 1)
7369 (nlines 0)
7370 (first 1)
7371 (prevpos (point-min))
7372 (final-context-start (make-marker))
60618039 7373 (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
6341f357
DN
7374 (with-output-to-temp-buffer "*Occur*"
7375 (save-excursion
7376 (message (format "Searching for %s ..." regexp))
7377 ;; Find next match, but give up if prev match was at end of buffer.
7378 (while (and (not (= prevpos (point-max)))
7379 (verilog-re-search-forward regexp nil t))
7380 (goto-char (match-beginning 0))
7381 (beginning-of-line)
7382 (save-match-data
7383 (setq linenum (+ linenum (count-lines prevpos (point)))))
7384 (setq prevpos (point))
7385 (goto-char (match-end 0))
7386 (let* ((start (save-excursion
7387 (goto-char (match-beginning 0))
7388 (forward-line (if (< nlines 0) nlines (- nlines)))
7389 (point)))
7390 (end (save-excursion
7391 (goto-char (match-end 0))
7392 (if (> nlines 0)
7393 (forward-line (1+ nlines))
7394 (forward-line 1))
7395 (point)))
7396 (tag (format "%3d" linenum))
7397 (empty (make-string (length tag) ?\ ))
7398 tem)
7399 (save-excursion
7400 (setq tem (make-marker))
7401 (set-marker tem (point))
7402 (set-buffer standard-output)
7403 (setq occur-pos-list (cons tem occur-pos-list))
7404 (or first (zerop nlines)
7405 (insert "--------\n"))
7406 (setq first nil)
7407 (insert-buffer-substring buffer start end)
7408 (backward-char (- end start))
7409 (setq tem (if (< nlines 0) (- nlines) nlines))
7410 (while (> tem 0)
7411 (insert empty ?:)
7412 (forward-line 1)
7413 (setq tem (1- tem)))
7414 (let ((this-linenum linenum))
7415 (set-marker final-context-start
7416 (+ (point) (- (match-end 0) (match-beginning 0))))
7417 (while (< (point) final-context-start)
7418 (if (null tag)
7419 (setq tag (format "%3d" this-linenum)))
7420 (insert tag ?:)))))))
7421 (set-buffer-modified-p nil))))
7422
7423
7424;; Highlight helper functions
7425(defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
7426(defun verilog-within-translate-off ()
7427 "Return point if within translate-off region, else nil."
7428 (and (save-excursion
7429 (re-search-backward
7430 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
7431 nil t))
7432 (equal "off" (match-string 2))
7433 (point)))
7434
7435(defun verilog-start-translate-off (limit)
7436 "Return point before translate-off directive if before LIMIT, else nil."
7437 (when (re-search-forward
7438 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
7439 limit t)
7440 (match-beginning 0)))
7441
7442(defun verilog-back-to-start-translate-off (limit)
7443 "Return point before translate-off directive if before LIMIT, else nil."
7444 (when (re-search-backward
7445 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
7446 limit t)
7447 (match-beginning 0)))
7448
7449(defun verilog-end-translate-off (limit)
7450 "Return point after translate-on directive if before LIMIT, else nil."
7451
7452 (re-search-forward (concat
7453 "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
7454
7455(defun verilog-match-translate-off (limit)
7456 "Match a translate-off block, setting `match-data' and returning t, else nil.
7457Bound search by LIMIT."
7458 (when (< (point) limit)
7459 (let ((start (or (verilog-within-translate-off)
7460 (verilog-start-translate-off limit)))
7461 (case-fold-search t))
7462 (when start
7463 (let ((end (or (verilog-end-translate-off limit) limit)))
7464 (set-match-data (list start end))
7465 (goto-char end))))))
7466
7467(defun verilog-font-lock-match-item (limit)
7468 "Match, and move over, any declaration item after point.
7469Bound search by LIMIT. Adapted from
7470`font-lock-match-c-style-declaration-item-and-skip-to-next'."
7471 (condition-case nil
7472 (save-restriction
7473 (narrow-to-region (point-min) limit)
7474 ;; match item
7475 (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
7476 (save-match-data
7477 (goto-char (match-end 1))
7478 ;; move to next item
7479 (if (looking-at "\\(\\s-*,\\)")
7480 (goto-char (match-end 1))
7481 (end-of-line) t))))
7482 (error nil)))
7483
7484
7485;; Added by Subbu Meiyappan for Header
7486
7487(defun verilog-header ()
a3a8b002
DN
7488 "Insert a standard Verilog file header.
7489See also `verilog-sk-header' for an alternative format."
6341f357
DN
7490 (interactive)
7491 (let ((start (point)))
7492 (insert "\
7493//-----------------------------------------------------------------------------
7494// Title : <title>
7495// Project : <project>
7496//-----------------------------------------------------------------------------
7497// File : <filename>
7498// Author : <author>
7499// Created : <credate>
7500// Last modified : <moddate>
7501//-----------------------------------------------------------------------------
7502// Description :
7503// <description>
7504//-----------------------------------------------------------------------------
7505// Copyright (c) <copydate> by <company> This model is the confidential and
7506// proprietary property of <company> and the possession or use of this
7507// file requires a written license from <company>.
7508//------------------------------------------------------------------------------
7509// Modification history :
7510// <modhist>
7511//-----------------------------------------------------------------------------
7512
7513")
7514 (goto-char start)
7515 (search-forward "<filename>")
7516 (replace-match (buffer-name) t t)
7517 (search-forward "<author>") (replace-match "" t t)
7518 (insert (user-full-name))
7519 (insert " <" (user-login-name) "@" (system-name) ">")
7520 (search-forward "<credate>") (replace-match "" t t)
6ca0ff73 7521 (verilog-insert-date)
6341f357 7522 (search-forward "<moddate>") (replace-match "" t t)
6ca0ff73 7523 (verilog-insert-date)
6341f357 7524 (search-forward "<copydate>") (replace-match "" t t)
6ca0ff73 7525 (verilog-insert-year)
6341f357 7526 (search-forward "<modhist>") (replace-match "" t t)
6ca0ff73 7527 (verilog-insert-date)
6341f357
DN
7528 (insert " : created")
7529 (goto-char start)
7530 (let (string)
7531 (setq string (read-string "title: "))
7532 (search-forward "<title>")
7533 (replace-match string t t)
7534 (setq string (read-string "project: " verilog-project))
6341f357
DN
7535 (setq verilog-project string)
7536 (search-forward "<project>")
7537 (replace-match string t t)
7538 (setq string (read-string "Company: " verilog-company))
6341f357
DN
7539 (setq verilog-company string)
7540 (search-forward "<company>")
7541 (replace-match string t t)
7542 (search-forward "<company>")
7543 (replace-match string t t)
7544 (search-forward "<company>")
7545 (replace-match string t t)
7546 (search-backward "<description>")
60618039 7547 (replace-match "" t t))))
6341f357 7548
6ca0ff73 7549;; verilog-header Uses the verilog-insert-date function
6341f357 7550
6ca0ff73 7551(defun verilog-insert-date ()
6341f357
DN
7552 "Insert date from the system."
7553 (interactive)
a3a8b002
DN
7554 (if verilog-date-scientific-format
7555 (insert (format-time-string "%Y/%m/%d"))
7556 (insert (format-time-string "%d.%m.%Y"))))
6341f357 7557
6ca0ff73 7558(defun verilog-insert-year ()
6341f357
DN
7559 "Insert year from the system."
7560 (interactive)
a3a8b002 7561 (insert (format-time-string "%Y")))
6341f357
DN
7562
7563\f
7564;;
7565;; Signal list parsing
7566;;
7567
7568;; Elements of a signal list
47086495 7569;; Unfortunately we use 'assoc' on this, so can't be a vector
a03c2342
WS
7570(defsubst verilog-sig-new (name bits comment mem enum signed type multidim modport)
7571 (list name bits comment mem enum signed type multidim modport))
6341f357
DN
7572(defsubst verilog-sig-name (sig)
7573 (car sig))
ea89ff08 7574(defsubst verilog-sig-bits (sig) ;; First element of packed array (pre signal-name)
6341f357
DN
7575 (nth 1 sig))
7576(defsubst verilog-sig-comment (sig)
7577 (nth 2 sig))
ea89ff08 7578(defsubst verilog-sig-memory (sig) ;; Unpacked array (post signal-name)
6341f357
DN
7579 (nth 3 sig))
7580(defsubst verilog-sig-enum (sig)
7581 (nth 4 sig))
7582(defsubst verilog-sig-signed (sig)
7583 (nth 5 sig))
7584(defsubst verilog-sig-type (sig)
7585 (nth 6 sig))
47086495
WS
7586(defsubst verilog-sig-type-set (sig type)
7587 (setcar (nthcdr 6 sig) type))
ea89ff08 7588(defsubst verilog-sig-multidim (sig) ;; Second and additional elements of packed array
6341f357
DN
7589 (nth 7 sig))
7590(defsubst verilog-sig-multidim-string (sig)
7591 (if (verilog-sig-multidim sig)
7592 (let ((str "") (args (verilog-sig-multidim sig)))
7593 (while args
7594 (setq str (concat str (car args)))
7595 (setq args (cdr args)))
7596 str)))
a3a8b002
DN
7597(defsubst verilog-sig-modport (sig)
7598 (nth 8 sig))
6341f357
DN
7599(defsubst verilog-sig-width (sig)
7600 (verilog-make-width-expression (verilog-sig-bits sig)))
7601
9489a450 7602(defsubst verilog-alw-new (outputs-del outputs-imm temps inputs)
47086495 7603 (vector outputs-del outputs-imm temps inputs))
9489a450 7604(defsubst verilog-alw-get-outputs-delayed (sigs)
47086495 7605 (aref sigs 0))
9489a450 7606(defsubst verilog-alw-get-outputs-immediate (sigs)
47086495 7607 (aref sigs 1))
9489a450 7608(defsubst verilog-alw-get-temps (sigs)
47086495 7609 (aref sigs 2))
9489a450 7610(defsubst verilog-alw-get-inputs (sigs)
47086495 7611 (aref sigs 3))
9489a450 7612(defsubst verilog-alw-get-uses-delayed (sigs)
47086495 7613 (aref sigs 0))
6341f357 7614
179f044b
WS
7615(defsubst verilog-modport-new (name clockings decls)
7616 (list name clockings decls))
7617(defsubst verilog-modport-name (sig)
7618 (car sig))
7619(defsubst verilog-modport-clockings (sig)
7620 (nth 1 sig)) ;; Returns list of names
7621(defsubst verilog-modport-clockings-add (sig val)
7622 (setcar (nthcdr 1 sig) (cons val (nth 1 sig))))
7623(defsubst verilog-modport-decls (sig)
7624 (nth 2 sig)) ;; Returns verilog-decls-* structure
7625(defsubst verilog-modport-decls-set (sig val)
7626 (setcar (nthcdr 2 sig) val))
7627
a03c2342
WS
7628(defsubst verilog-modi-new (name fob pt type)
7629 (vector name fob pt type))
7630(defsubst verilog-modi-name (modi)
7631 (aref modi 0))
7632(defsubst verilog-modi-file-or-buffer (modi)
7633 (aref modi 1))
7634(defsubst verilog-modi-get-point (modi)
7635 (aref modi 2))
7636(defsubst verilog-modi-get-type (modi) ;; "module" or "interface"
7637 (aref modi 3))
7638(defsubst verilog-modi-get-decls (modi)
7639 (verilog-modi-cache-results modi 'verilog-read-decls))
7640(defsubst verilog-modi-get-sub-decls (modi)
7641 (verilog-modi-cache-results modi 'verilog-read-sub-decls))
7642
7643;; Signal reading for given module
7644;; Note these all take modi's - as returned from verilog-modi-current
179f044b
WS
7645(defsubst verilog-decls-new (out inout in vars modports assigns consts gparams interfaces)
7646 (vector out inout in vars modports assigns consts gparams interfaces))
7647(defsubst verilog-decls-append (a b)
7648 (cond ((not a) b) ((not b) a)
7649 (t (vector (append (aref a 0) (aref b 0)) (append (aref a 1) (aref b 1))
7650 (append (aref a 2) (aref b 2)) (append (aref a 3) (aref b 3))
7651 (append (aref a 4) (aref b 4)) (append (aref a 5) (aref b 5))
7652 (append (aref a 6) (aref b 6)) (append (aref a 7) (aref b 7))
7653 (append (aref a 8) (aref b 8))))))
a03c2342
WS
7654(defsubst verilog-decls-get-outputs (decls)
7655 (aref decls 0))
7656(defsubst verilog-decls-get-inouts (decls)
7657 (aref decls 1))
7658(defsubst verilog-decls-get-inputs (decls)
7659 (aref decls 2))
9489a450 7660(defsubst verilog-decls-get-vars (decls)
a03c2342 7661 (aref decls 3))
179f044b
WS
7662(defsubst verilog-decls-get-modports (decls) ;; Also for clocking blocks; contains another verilog-decls struct
7663 (aref decls 4)) ;; Returns verilog-modport* structure
a03c2342
WS
7664(defsubst verilog-decls-get-assigns (decls)
7665 (aref decls 5))
7666(defsubst verilog-decls-get-consts (decls)
7667 (aref decls 6))
7668(defsubst verilog-decls-get-gparams (decls)
7669 (aref decls 7))
7670(defsubst verilog-decls-get-interfaces (decls)
7671 (aref decls 8))
7672
179f044b 7673
a03c2342
WS
7674(defsubst verilog-subdecls-new (out inout in intf intfd)
7675 (vector out inout in intf intfd))
7676(defsubst verilog-subdecls-get-outputs (subdecls)
7677 (aref subdecls 0))
7678(defsubst verilog-subdecls-get-inouts (subdecls)
7679 (aref subdecls 1))
7680(defsubst verilog-subdecls-get-inputs (subdecls)
7681 (aref subdecls 2))
7682(defsubst verilog-subdecls-get-interfaces (subdecls)
7683 (aref subdecls 3))
7684(defsubst verilog-subdecls-get-interfaced (subdecls)
7685 (aref subdecls 4))
7686
47086495
WS
7687(defun verilog-signals-from-signame (signame-list)
7688 "Return signals in standard form from SIGNAME-LIST, a simple list of names."
7689 (mapcar (lambda (name) (verilog-sig-new name nil nil nil nil nil nil nil nil))
7690 signame-list))
7691
179f044b
WS
7692(defun verilog-signals-in (in-list not-list)
7693 "Return list of signals in IN-LIST that are also in NOT-LIST.
7694Also remove any duplicates in IN-LIST.
7695Signals must be in standard (base vector) form."
7696 ;; This function is hot, so implemented as O(1)
7697 (cond ((eval-when-compile (fboundp 'make-hash-table))
7698 (let ((ht (make-hash-table :test 'equal :rehash-size 4.0))
7699 (ht-not (make-hash-table :test 'equal :rehash-size 4.0))
7700 out-list)
7701 (while not-list
7702 (puthash (car (car not-list)) t ht-not)
7703 (setq not-list (cdr not-list)))
7704 (while in-list
7705 (when (and (gethash (verilog-sig-name (car in-list)) ht-not)
7706 (not (gethash (verilog-sig-name (car in-list)) ht)))
7707 (setq out-list (cons (car in-list) out-list))
7708 (puthash (verilog-sig-name (car in-list)) t ht))
7709 (setq in-list (cdr in-list)))
7710 (nreverse out-list)))
7711 ;; Slower Fallback if no hash tables (pre Emacs 21.1/XEmacs 21.4)
7712 (t
7713 (let (out-list)
7714 (while in-list
7715 (if (and (assoc (verilog-sig-name (car in-list)) not-list)
7716 (not (assoc (verilog-sig-name (car in-list)) out-list)))
7717 (setq out-list (cons (car in-list) out-list)))
7718 (setq in-list (cdr in-list)))
7719 (nreverse out-list)))))
7720;;(verilog-signals-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("C" "")))
7721
6341f357 7722(defun verilog-signals-not-in (in-list not-list)
37ea4b9b
JB
7723 "Return list of signals in IN-LIST that aren't also in NOT-LIST.
7724Also remove any duplicates in IN-LIST.
6341f357 7725Signals must be in standard (base vector) form."
a03c2342
WS
7726 ;; This function is hot, so implemented as O(1)
7727 (cond ((eval-when-compile (fboundp 'make-hash-table))
7728 (let ((ht (make-hash-table :test 'equal :rehash-size 4.0))
7729 out-list)
7730 (while not-list
7731 (puthash (car (car not-list)) t ht)
7732 (setq not-list (cdr not-list)))
7733 (while in-list
47086495 7734 (when (not (gethash (verilog-sig-name (car in-list)) ht))
a03c2342 7735 (setq out-list (cons (car in-list) out-list))
47086495 7736 (puthash (verilog-sig-name (car in-list)) t ht))
a03c2342
WS
7737 (setq in-list (cdr in-list)))
7738 (nreverse out-list)))
7739 ;; Slower Fallback if no hash tables (pre Emacs 21.1/XEmacs 21.4)
7740 (t
7741 (let (out-list)
7742 (while in-list
179f044b
WS
7743 (if (and (not (assoc (verilog-sig-name (car in-list)) not-list))
7744 (not (assoc (verilog-sig-name (car in-list)) out-list)))
a03c2342
WS
7745 (setq out-list (cons (car in-list) out-list)))
7746 (setq in-list (cdr in-list)))
7747 (nreverse out-list)))))
6341f357
DN
7748;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
7749
6341f357 7750(defun verilog-signals-memory (in-list)
53964682 7751 "Return list of signals in IN-LIST that are memorized (multidimensional)."
6341f357
DN
7752 (let (out-list)
7753 (while in-list
7754 (if (nth 3 (car in-list))
7755 (setq out-list (cons (car in-list) out-list)))
7756 (setq in-list (cdr in-list)))
7757 out-list))
7758;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
7759
7760(defun verilog-signals-sort-compare (a b)
7761 "Compare signal A and B for sorting."
47086495 7762 (string< (verilog-sig-name a) (verilog-sig-name b)))
6341f357
DN
7763
7764(defun verilog-signals-not-params (in-list)
7765 "Return list of signals in IN-LIST that aren't parameters or numeric constants."
7766 (let (out-list)
7767 (while in-list
0f137a73 7768 ;; Namespace intentionally short for AUTOs and compatibility
47086495
WS
7769 (unless (boundp (intern (concat "vh-" (verilog-sig-name (car in-list)))))
7770 (setq out-list (cons (car in-list) out-list)))
7771 (setq in-list (cdr in-list)))
7772 (nreverse out-list)))
7773
7774(defun verilog-signals-with (func in-list)
ea89ff08 7775 "Return list of signals where FUNC is true executed on each signal in IN-LIST."
47086495
WS
7776 (let (out-list)
7777 (while in-list
7778 (when (funcall func (car in-list))
6341f357
DN
7779 (setq out-list (cons (car in-list) out-list)))
7780 (setq in-list (cdr in-list)))
7781 (nreverse out-list)))
7782
7783(defun verilog-signals-combine-bus (in-list)
301b181a 7784 "Return a list of signals in IN-LIST, with buses combined.
6341f357
DN
7785Duplicate signals are also removed. For example A[2] and A[1] become A[2:1]."
7786 (let (combo buswarn
7787 out-list
7788 sig highbit lowbit ; Temp information about current signal
7789 sv-name sv-highbit sv-lowbit ; Details about signal we are forming
7790 sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
a3a8b002 7791 sv-modport
6341f357
DN
7792 bus)
7793 ;; Shove signals so duplicated signals will be adjacent
7794 (setq in-list (sort in-list `verilog-signals-sort-compare))
7795 (while in-list
7796 (setq sig (car in-list))
7797 ;; No current signal; form from existing details
7798 (unless sv-name
7799 (setq sv-name (verilog-sig-name sig)
7800 sv-highbit nil
7801 sv-busstring nil
7802 sv-comment (verilog-sig-comment sig)
7803 sv-memory (verilog-sig-memory sig)
7804 sv-enum (verilog-sig-enum sig)
7805 sv-signed (verilog-sig-signed sig)
7806 sv-type (verilog-sig-type sig)
7807 sv-multidim (verilog-sig-multidim sig)
a3a8b002 7808 sv-modport (verilog-sig-modport sig)
6341f357 7809 combo ""
60618039 7810 buswarn ""))
6341f357
DN
7811 ;; Extract bus details
7812 (setq bus (verilog-sig-bits sig))
9489a450 7813 (setq bus (and bus (verilog-simplify-range-expression bus)))
6341f357
DN
7814 (cond ((and bus
7815 (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
7ea26faf
DN
7816 (setq highbit (string-to-number (match-string 1 bus))
7817 lowbit (string-to-number
7818 (match-string 2 bus))))
6341f357 7819 (and (string-match "\\[\\([0-9]+\\)\\]" bus)
7ea26faf 7820 (setq highbit (string-to-number (match-string 1 bus))
6341f357
DN
7821 lowbit highbit))))
7822 ;; Combine bits in bus
7823 (if sv-highbit
7824 (setq sv-highbit (max highbit sv-highbit)
7825 sv-lowbit (min lowbit sv-lowbit))
7826 (setq sv-highbit highbit
7827 sv-lowbit lowbit)))
7828 (bus
7829 ;; String, probably something like `preproc:0
7830 (setq sv-busstring bus)))
7831 ;; Peek ahead to next signal
7832 (setq in-list (cdr in-list))
7833 (setq sig (car in-list))
7834 (cond ((and sig (equal sv-name (verilog-sig-name sig)))
7835 ;; Combine with this signal
7ea26faf
DN
7836 (when (and sv-busstring
7837 (not (equal sv-busstring (verilog-sig-bits sig))))
6341f357
DN
7838 (when nil ;; Debugging
7839 (message (concat "Warning, can't merge into single bus "
7840 sv-name bus
7841 ", the AUTOs may be wrong")))
7842 (setq buswarn ", Couldn't Merge"))
7843 (if (verilog-sig-comment sig) (setq combo ", ..."))
7844 (setq sv-memory (or sv-memory (verilog-sig-memory sig))
7845 sv-enum (or sv-enum (verilog-sig-enum sig))
7846 sv-signed (or sv-signed (verilog-sig-signed sig))
7847 sv-type (or sv-type (verilog-sig-type sig))
a3a8b002
DN
7848 sv-multidim (or sv-multidim (verilog-sig-multidim sig))
7849 sv-modport (or sv-modport (verilog-sig-modport sig))))
6341f357
DN
7850 ;; Doesn't match next signal, add to queue, zero in prep for next
7851 ;; Note sig may also be nil for the last signal in the list
7852 (t
7853 (setq out-list
a03c2342
WS
7854 (cons (verilog-sig-new
7855 sv-name
7ea26faf
DN
7856 (or sv-busstring
7857 (if sv-highbit
7858 (concat "[" (int-to-string sv-highbit) ":"
7859 (int-to-string sv-lowbit) "]")))
60618039 7860 (concat sv-comment combo buswarn)
a3a8b002 7861 sv-memory sv-enum sv-signed sv-type sv-multidim sv-modport)
a03c2342 7862 out-list)
60618039 7863 sv-name nil))))
6341f357
DN
7864 ;;
7865 out-list))
7866
47086495 7867(defun verilog-sig-tieoff (sig)
60618039 7868 "Return tieoff expression for given SIG, with appropriate width.
47086495
WS
7869Tieoff value uses `verilog-active-low-regexp' and
7870`verilog-auto-reset-widths'."
7871 (concat
7872 (if (and verilog-active-low-regexp
ea89ff08 7873 (verilog-string-match-fold verilog-active-low-regexp (verilog-sig-name sig)))
47086495
WS
7874 "~" "")
7875 (cond ((not verilog-auto-reset-widths)
7876 "0")
7877 ((equal verilog-auto-reset-widths 'unbased)
7878 "'0")
7879 ;; Else presume verilog-auto-reset-widths is true
7880 (t
7881 (let* ((width (verilog-sig-width sig)))
bc8bc17d
WS
7882 (cond ((not width)
7883 "`0/*NOWIDTH*/")
7884 ((string-match "^[0-9]+$" width)
7885 (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
7886 (t
7887 (concat "{" width "{1'b0}}"))))))))
47086495
WS
7888
7889;;
7890;; Dumping
7891;;
7892
179f044b 7893(defun verilog-decls-princ (decls &optional header prefix)
47086495 7894 "For debug, dump the `verilog-read-decls' structure DECLS."
179f044b
WS
7895 (when decls
7896 (if header (princ header))
7897 (setq prefix (or prefix ""))
7898 (verilog-signals-princ (verilog-decls-get-outputs decls)
7899 (concat prefix "Outputs:\n") (concat prefix " "))
7900 (verilog-signals-princ (verilog-decls-get-inouts decls)
7901 (concat prefix "Inout:\n") (concat prefix " "))
7902 (verilog-signals-princ (verilog-decls-get-inputs decls)
7903 (concat prefix "Inputs:\n") (concat prefix " "))
7904 (verilog-signals-princ (verilog-decls-get-vars decls)
7905 (concat prefix "Vars:\n") (concat prefix " "))
7906 (verilog-signals-princ (verilog-decls-get-assigns decls)
7907 (concat prefix "Assigns:\n") (concat prefix " "))
7908 (verilog-signals-princ (verilog-decls-get-consts decls)
7909 (concat prefix "Consts:\n") (concat prefix " "))
7910 (verilog-signals-princ (verilog-decls-get-gparams decls)
7911 (concat prefix "Gparams:\n") (concat prefix " "))
7912 (verilog-signals-princ (verilog-decls-get-interfaces decls)
7913 (concat prefix "Interfaces:\n") (concat prefix " "))
7914 (verilog-modport-princ (verilog-decls-get-modports decls)
7915 (concat prefix "Modports:\n") (concat prefix " "))
7916 (princ "\n")))
47086495
WS
7917
7918(defun verilog-signals-princ (signals &optional header prefix)
7919 "For debug, dump internal SIGNALS structures, with HEADER and PREFIX."
7920 (when signals
179f044b 7921 (if header (princ header))
47086495
WS
7922 (while signals
7923 (let ((sig (car signals)))
7924 (setq signals (cdr signals))
7925 (princ prefix)
7926 (princ "\"") (princ (verilog-sig-name sig)) (princ "\"")
7927 (princ " bits=") (princ (verilog-sig-bits sig))
7928 (princ " cmt=") (princ (verilog-sig-comment sig))
7929 (princ " mem=") (princ (verilog-sig-memory sig))
7930 (princ " enum=") (princ (verilog-sig-enum sig))
7931 (princ " sign=") (princ (verilog-sig-signed sig))
7932 (princ " type=") (princ (verilog-sig-type sig))
7933 (princ " dim=") (princ (verilog-sig-multidim sig))
7934 (princ " modp=") (princ (verilog-sig-modport sig))
7935 (princ "\n")))))
6341f357 7936
179f044b
WS
7937(defun verilog-modport-princ (modports &optional header prefix)
7938 "For debug, dump internal MODPORT structures, with HEADER and PREFIX."
7939 (when modports
7940 (if header (princ header))
7941 (while modports
7942 (let ((sig (car modports)))
7943 (setq modports (cdr modports))
7944 (princ prefix)
7945 (princ "\"") (princ (verilog-modport-name sig)) (princ "\"")
7946 (princ " clockings=") (princ (verilog-modport-clockings sig))
7947 (princ "\n")
7948 (verilog-decls-princ (verilog-modport-decls sig)
7949 (concat prefix " syms:\n")
7950 (concat prefix " "))))))
7951
6341f357
DN
7952;;
7953;; Port/Wire/Etc Reading
7954;;
7955
7956(defun verilog-read-inst-backward-name ()
7957 "Internal. Move point back to beginning of inst-name."
7958 (verilog-backward-open-paren)
7959 (let (done)
7960 (while (not done)
7961 (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil) ; ] isn't word boundary
7962 (cond ((looking-at ")")
7963 (verilog-backward-open-paren))
7964 (t (setq done t)))))
7965 (while (looking-at "\\]")
7966 (verilog-backward-open-bracket)
7967 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
7968 (skip-chars-backward "a-zA-Z0-9`_$"))
7969
a03c2342
WS
7970(defun verilog-read-inst-module-matcher ()
7971 "Set match data 0 with module_name when point is inside instantiation."
7972 (verilog-read-inst-backward-name)
7973 ;; Skip over instantiation name
7974 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
7975 ;; Check for parameterized instantiations
7976 (when (looking-at ")")
7977 (verilog-backward-open-paren)
7978 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
7979 (skip-chars-backward "a-zA-Z0-9'_$")
ea89ff08
WS
7980 ;; #1 is legal syntax for gate primitives
7981 (when (save-excursion
7982 (verilog-backward-syntactic-ws-quick)
7983 (eq ?# (char-before)))
7984 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
7985 (skip-chars-backward "a-zA-Z0-9'_$"))
a03c2342
WS
7986 (looking-at "[a-zA-Z0-9`_\$]+")
7987 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7988 (buffer-substring-no-properties (match-beginning 0) (match-end 0))
7989 ;; Caller assumes match-beginning/match-end is still set
7990 )
7991
6341f357
DN
7992(defun verilog-read-inst-module ()
7993 "Return module_name when point is inside instantiation."
7994 (save-excursion
a03c2342 7995 (verilog-read-inst-module-matcher)))
6341f357
DN
7996
7997(defun verilog-read-inst-name ()
7998 "Return instance_name when point is inside instantiation."
7999 (save-excursion
8000 (verilog-read-inst-backward-name)
8001 (looking-at "[a-zA-Z0-9`_\$]+")
d63b01e1 8002 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6341f357
DN
8003 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
8004
8005(defun verilog-read-module-name ()
8006 "Return module name when after its ( or ;."
8007 (save-excursion
8008 (re-search-backward "[(;]")
9489a450
MM
8009 ;; Due to "module x import y (" we must search for declaration begin
8010 (verilog-re-search-backward-quick verilog-defun-re nil nil)
8011 (goto-char (match-end 0))
8012 (verilog-re-search-forward-quick "\\b[a-zA-Z0-9`_\$]+" nil nil)
d63b01e1 8013 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
a3a8b002
DN
8014 (verilog-symbol-detick
8015 (buffer-substring-no-properties (match-beginning 0) (match-end 0)) t)))
6341f357 8016
4c5e69c6
DN
8017(defun verilog-read-inst-param-value ()
8018 "Return list of parameters and values when point is inside instantiation."
8019 (save-excursion
8020 (verilog-read-inst-backward-name)
8021 ;; Skip over instantiation name
8022 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
8023 ;; If there are parameterized instantiations
8024 (when (looking-at ")")
8025 (let ((end-pt (point))
8026 params
8027 param-name paren-beg-pt param-value)
8028 (verilog-backward-open-paren)
8029 (while (verilog-re-search-forward-quick "\\." end-pt t)
8030 (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
8031 (skip-chars-backward "a-zA-Z0-9'_$")
8032 (looking-at "[a-zA-Z0-9`_\$]+")
8033 (setq param-name (buffer-substring-no-properties
8034 (match-beginning 0) (match-end 0)))
8035 (verilog-re-search-forward-quick "(" nil nil)
8036 (setq paren-beg-pt (point))
8037 (verilog-forward-close-paren)
8038 (setq param-value (verilog-string-remove-spaces
8039 (buffer-substring-no-properties
8040 paren-beg-pt (1- (point)))))
8041 (setq params (cons (list param-name param-value) params)))
8042 params))))
8043
6341f357
DN
8044(defun verilog-read-auto-params (num-param &optional max-param)
8045 "Return parameter list inside auto.
8046Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
8047 (let ((olist))
8048 (save-excursion
8049 ;; /*AUTOPUNT("parameter", "parameter")*/
47086495 8050 (backward-sexp 1)
6341f357
DN
8051 (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
8052 (setq olist (cons (match-string 1) olist))
8053 (goto-char (match-end 0))))
8054 (or (eq nil num-param)
8055 (<= num-param (length olist))
8056 (error "%s: Expected %d parameters" (verilog-point-text) num-param))
8057 (if (eq max-param nil) (setq max-param num-param))
8058 (or (eq nil max-param)
8059 (>= max-param (length olist))
8060 (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
8061 (nreverse olist)))
8062
8063(defun verilog-read-decls ()
8064 "Compute signal declaration information for the current module at point.
47086495 8065Return an array of [outputs inouts inputs wire reg assign const]."
0f137a73 8066 (let ((end-mod-point (or (verilog-get-end-of-defun) (point-max)))
a3a8b002 8067 (functask 0) (paren 0) (sig-paren 0) (v2kargs-ok t)
179f044b 8068 in-modport in-clocking ptype ign-prop
9489a450 8069 sigs-in sigs-out sigs-inout sigs-var sigs-assign sigs-const
179f044b 8070 sigs-gparam sigs-intf sigs-modports
a3a8b002 8071 vec expect-signal keywd newsig rvalue enum io signed typedefed multidim
179f044b
WS
8072 modport
8073 varstack tmp)
bc8bc17d 8074 ;;(if dbg (setq dbg (concat dbg (format "\n\nverilog-read-decls START PT %s END %s\n" (point) end-mod-point))))
6341f357 8075 (save-excursion
9489a450 8076 (verilog-beg-of-defun-quick)
6341f357
DN
8077 (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
8078 (while (< (point) end-mod-point)
a03c2342 8079 ;;(if dbg (setq dbg (concat dbg (format "Pt %s Vec %s C%c Kwd'%s'\n" (point) vec (following-char) keywd))))
6341f357
DN
8080 (cond
8081 ((looking-at "//")
47086495
WS
8082 (if (looking-at "[^\n]*\\(auto\\|synopsys\\)\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
8083 (setq enum (match-string 2)))
6341f357
DN
8084 (search-forward "\n"))
8085 ((looking-at "/\\*")
8086 (forward-char 2)
47086495
WS
8087 (if (looking-at "[^\n]*\\(auto\\|synopsys\\)\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
8088 (setq enum (match-string 2)))
6341f357
DN
8089 (or (search-forward "*/")
8090 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8091 ((looking-at "(\\*")
9489a450
MM
8092 ;; To advance past either "(*)" or "(* ... *)" don't forward past first *
8093 (forward-char 1)
8094 (or (search-forward "*)")
6341f357
DN
8095 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
8096 ((eq ?\" (following-char))
8097 (or (re-search-forward "[^\\]\"" nil t) ;; don't forward-char first, since we look for a non backslash first
8098 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
8099 ((eq ?\; (following-char))
179f044b
WS
8100 (when (and in-modport (not (eq in-modport t))) ;; end of a modport declaration
8101 (verilog-modport-decls-set
8102 in-modport
8103 (verilog-decls-new sigs-out sigs-inout sigs-in
8104 nil nil nil nil nil nil))
8105 ;; Pop from varstack to restore state to pre-clocking
8106 (setq tmp (car varstack)
8107 varstack (cdr varstack)
8108 sigs-out (aref tmp 0)
8109 sigs-inout (aref tmp 1)
8110 sigs-in (aref tmp 2)))
a3a8b002 8111 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil
9489a450 8112 v2kargs-ok nil in-modport nil ign-prop nil)
6341f357
DN
8113 (forward-char 1))
8114 ((eq ?= (following-char))
8115 (setq rvalue t newsig nil)
8116 (forward-char 1))
14862301
SM
8117 ((and (eq ?, (following-char))
8118 (eq paren sig-paren))
8119 (setq rvalue nil)
8120 (forward-char 1))
8121 ;; ,'s can occur inside {} & funcs
8122 ((looking-at "[{(]")
8123 (setq paren (1+ paren))
8124 (forward-char 1))
8125 ((looking-at "[})]")
8126 (setq paren (1- paren))
8127 (forward-char 1)
8128 (when (< paren sig-paren)
bc8bc17d 8129 (setq expect-signal nil rvalue nil))) ; ) that ends variables inside v2k arg list
6341f357
DN
8130 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
8131 (goto-char (match-end 0))
8132 (cond (newsig ; Memory, not just width. Patch last signal added's memory (nth 3)
8468f78b
WS
8133 (setcar (cdr (cdr (cdr newsig)))
8134 (if (verilog-sig-memory newsig)
8135 (concat (verilog-sig-memory newsig) (match-string 1))
8136 (match-string 1))))
6341f357
DN
8137 (vec ;; Multidimensional
8138 (setq multidim (cons vec multidim))
8139 (setq vec (verilog-string-replace-matches
8140 "\\s-+" "" nil nil (match-string 1))))
8141 (t ;; Bit width
8142 (setq vec (verilog-string-replace-matches
8143 "\\s-+" "" nil nil (match-string 1))))))
8144 ;; Normal or escaped identifier -- note we remember the \ if escaped
8145 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
8146 (goto-char (match-end 0))
8147 (setq keywd (match-string 1))
86a4c7ac 8148 (when (string-match "^\\\\" (match-string 1))
6341f357 8149 (setq keywd (concat keywd " "))) ;; Escaped ID needs space at end
86a4c7ac
DN
8150 ;; Add any :: package names to same identifier
8151 (while (looking-at "\\s-*::\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
8152 (goto-char (match-end 0))
8153 (setq keywd (concat keywd "::" (match-string 1)))
8154 (when (string-match "^\\\\" (match-string 1))
8155 (setq keywd (concat keywd " ")))) ;; Escaped ID needs space at end
6341f357 8156 (cond ((equal keywd "input")
47086495
WS
8157 (setq vec nil enum nil rvalue nil newsig nil signed nil
8158 typedefed nil multidim nil ptype nil modport nil
8159 expect-signal 'sigs-in io t sig-paren paren))
6341f357 8160 ((equal keywd "output")
47086495
WS
8161 (setq vec nil enum nil rvalue nil newsig nil signed nil
8162 typedefed nil multidim nil ptype nil modport nil
8163 expect-signal 'sigs-out io t sig-paren paren))
6341f357 8164 ((equal keywd "inout")
47086495
WS
8165 (setq vec nil enum nil rvalue nil newsig nil signed nil
8166 typedefed nil multidim nil ptype nil modport nil
8167 expect-signal 'sigs-inout io t sig-paren paren))
a3a8b002 8168 ((equal keywd "parameter")
47086495
WS
8169 (setq vec nil enum nil rvalue nil signed nil
8170 typedefed nil multidim nil ptype nil modport nil
8171 expect-signal 'sigs-gparam io t sig-paren paren))
8172 ((member keywd '("wire" "reg" ; Fast
8173 ;; net_type
8174 "tri" "tri0" "tri1" "triand" "trior" "trireg"
8175 "uwire" "wand" "wor"
8176 ;; integer_atom_type
a3a8b002 8177 "byte" "shortint" "int" "longint" "integer" "time"
47086495
WS
8178 "supply0" "supply1"
8179 ;; integer_vector_type - "reg" above
a03c2342 8180 "bit" "logic"
47086495 8181 ;; non_integer_type
a03c2342 8182 "shortreal" "real" "realtime"
47086495 8183 ;; data_type
a03c2342 8184 "string" "event" "chandle"))
47086495
WS
8185 (cond (io
8186 (setq typedefed
8187 (if typedefed (concat typedefed " " keywd) keywd)))
8188 (t (setq vec nil enum nil rvalue nil signed nil
8189 typedefed nil multidim nil sig-paren paren
8190 expect-signal 'sigs-var modport nil))))
6341f357 8191 ((equal keywd "assign")
47086495
WS
8192 (setq vec nil enum nil rvalue nil signed nil
8193 typedefed nil multidim nil ptype nil modport nil
8194 expect-signal 'sigs-assign sig-paren paren))
8195 ((member keywd '("localparam" "genvar"))
8196 (unless io
8197 (setq vec nil enum nil rvalue nil signed nil
8198 typedefed nil multidim nil ptype nil modport nil
8199 expect-signal 'sigs-const sig-paren paren)))
9489a450
MM
8200 ((member keywd '("signed" "unsigned"))
8201 (setq signed keywd))
8202 ((member keywd '("assert" "assume" "cover" "expect" "restrict"))
8203 (setq ign-prop t))
179f044b 8204 ((member keywd '("class" "covergroup" "function"
a3a8b002 8205 "property" "randsequence" "sequence" "task"))
9489a450
MM
8206 (unless ign-prop
8207 (setq functask (1+ functask))))
179f044b 8208 ((member keywd '("endclass" "endgroup" "endfunction"
a3a8b002 8209 "endproperty" "endsequence" "endtask"))
6341f357 8210 (setq functask (1- functask)))
a03c2342
WS
8211 ((equal keywd "modport")
8212 (setq in-modport t))
179f044b
WS
8213 ((equal keywd "clocking")
8214 (setq in-clocking t))
47086495
WS
8215 ((equal keywd "type")
8216 (setq ptype t))
a3a8b002 8217 ;; Ifdef? Ignore name of define
a03c2342 8218 ((member keywd '("`ifdef" "`ifndef" "`elsif"))
6341f357 8219 (setq rvalue t))
a3a8b002 8220 ;; Type?
47086495
WS
8221 ((unless ptype
8222 (verilog-typedef-name-p keywd))
ea89ff08
WS
8223 (cond (io
8224 (setq typedefed
8225 (if typedefed (concat typedefed " " keywd) keywd)))
8226 (t (setq vec nil enum nil rvalue nil signed nil
8227 typedefed nil multidim nil sig-paren paren
8228 expect-signal 'sigs-var modport nil))))
a3a8b002
DN
8229 ;; Interface with optional modport in v2k arglist?
8230 ;; Skip over parsing modport, and take the interface name as the type
8231 ((and v2kargs-ok
8232 (eq paren 1)
a03c2342
WS
8233 (not rvalue)
8234 (looking-at "\\s-*\\(\\.\\(\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*\\)\\|\\)\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*"))
a3a8b002 8235 (when (match-end 2) (goto-char (match-end 2)))
47086495
WS
8236 (setq vec nil enum nil rvalue nil signed nil
8237 typedefed keywd multidim nil ptype nil modport (match-string 2)
8238 newsig nil sig-paren paren
8239 expect-signal 'sigs-intf io t ))
a03c2342
WS
8240 ;; Ignore dotted LHS assignments: "assign foo.bar = z;"
8241 ((looking-at "\\s-*\\.")
8242 (goto-char (match-end 0))
8243 (when (not rvalue)
8244 (setq expect-signal nil)))
179f044b
WS
8245 ;; "modport <keywd>"
8246 ((and (eq in-modport t)
8247 (not (member keywd verilog-keywords)))
8248 (setq in-modport (verilog-modport-new keywd nil nil))
8249 (setq sigs-modports (cons in-modport sigs-modports))
8250 ;; Push old sig values to stack and point to new signal list
8251 (setq varstack (cons (vector sigs-out sigs-inout sigs-in)
8252 varstack))
8253 (setq sigs-in nil sigs-inout nil sigs-out nil))
8254 ;; "modport x (clocking <keywd>)"
8255 ((and in-modport in-clocking)
8256 (verilog-modport-clockings-add in-modport keywd)
8257 (setq in-clocking nil))
8258 ;; endclocking
8259 ((and in-clocking
8260 (equal keywd "endclocking"))
8261 (unless (eq in-clocking t)
8262 (verilog-modport-decls-set
8263 in-clocking
8264 (verilog-decls-new sigs-out sigs-inout sigs-in
8265 nil nil nil nil nil nil))
8266 ;; Pop from varstack to restore state to pre-clocking
8267 (setq tmp (car varstack)
8268 varstack (cdr varstack)
8269 sigs-out (aref tmp 0)
8270 sigs-inout (aref tmp 1)
8271 sigs-in (aref tmp 2)))
8272 (setq in-clocking nil))
8273 ;; "clocking <keywd>"
8274 ((and (eq in-clocking t)
8275 (not (member keywd verilog-keywords)))
8276 (setq in-clocking (verilog-modport-new keywd nil nil))
8277 (setq sigs-modports (cons in-clocking sigs-modports))
8278 ;; Push old sig values to stack and point to new signal list
8279 (setq varstack (cons (vector sigs-out sigs-inout sigs-in)
8280 varstack))
8281 (setq sigs-in nil sigs-inout nil sigs-out nil))
a3a8b002 8282 ;; New signal, maybe?
6341f357 8283 ((and expect-signal
6341f357 8284 (not rvalue)
a03c2342 8285 (eq functask 0)
6341f357
DN
8286 (not (member keywd verilog-keywords)))
8287 ;; Add new signal to expect-signal's variable
a03c2342 8288 (setq newsig (verilog-sig-new keywd vec nil nil enum signed typedefed multidim modport))
6341f357
DN
8289 (set expect-signal (cons newsig
8290 (symbol-value expect-signal))))))
8291 (t
8292 (forward-char 1)))
8293 (skip-syntax-forward " "))
8294 ;; Return arguments
179f044b
WS
8295 (setq tmp (verilog-decls-new (nreverse sigs-out)
8296 (nreverse sigs-inout)
8297 (nreverse sigs-in)
8298 (nreverse sigs-var)
8299 (nreverse sigs-modports)
8300 (nreverse sigs-assign)
8301 (nreverse sigs-const)
8302 (nreverse sigs-gparam)
8303 (nreverse sigs-intf)))
8304 ;;(if dbg (verilog-decls-princ tmp))
8305 tmp)))
a03c2342
WS
8306
8307(defvar verilog-read-sub-decls-in-interfaced nil
8308 "For `verilog-read-sub-decls', process next signal as under interfaced block.")
8309
8310(defvar verilog-read-sub-decls-gate-ios nil
8311 "For `verilog-read-sub-decls', gate IO pins remaining, nil if non-primitive.")
6341f357 8312
60618039
DN
8313(eval-when-compile
8314 ;; Prevent compile warnings; these are let's, not globals
8315 ;; Do not remove the eval-when-compile
47086495 8316 ;; - we want an error when we are debugging this code if they are refed.
60618039
DN
8317 (defvar sigs-in)
8318 (defvar sigs-inout)
a03c2342 8319 (defvar sigs-intf)
ea89ff08
WS
8320 (defvar sigs-intfd)
8321 (defvar sigs-out)
8322 (defvar sigs-out-d)
8323 (defvar sigs-out-i)
8324 (defvar sigs-out-unk)
8325 (defvar sigs-temp)
8326 ;; These are known to be from other packages and may not be defined
8327 (defvar diff-command nil)
8328 (defvar vector-skip-list)
8329 ;; There are known to be from newer versions of Emacs
8330 (defvar create-lockfiles))
5509c6ad
DN
8331
8332(defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
37ea4b9b 8333 "For `verilog-read-sub-decls-line', add a signal."
a03c2342
WS
8334 ;; sig eq t to indicate .name syntax
8335 ;;(message "vrsds: %s(%S)" port sig)
8336 (let ((dotname (eq sig t))
8337 portdata)
6341f357
DN
8338 (when sig
8339 (setq port (verilog-symbol-detick-denumber port))
a03c2342 8340 (setq sig (if dotname port (verilog-symbol-detick-denumber sig)))
6341f357
DN
8341 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
8342 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
8343 (unless (or (not sig)
8344 (equal sig "")) ;; Ignore .foo(1'b1) assignments
a03c2342
WS
8345 (cond ((or (setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
8346 (equal "inout" verilog-read-sub-decls-gate-ios))
8347 (setq sigs-inout
8348 (cons (verilog-sig-new
8349 sig
8350 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
8351 (concat "To/From " comment)
8352 (verilog-sig-memory portdata)
8353 nil
a03c2342 8354 (verilog-sig-signed portdata)
47086495
WS
8355 (unless (member (verilog-sig-type portdata) '("wire" "reg"))
8356 (verilog-sig-type portdata))
a03c2342
WS
8357 multidim nil)
8358 sigs-inout)))
8359 ((or (setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
8360 (equal "output" verilog-read-sub-decls-gate-ios))
8361 (setq sigs-out
8362 (cons (verilog-sig-new
8363 sig
8364 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
8365 (concat "From " comment)
8366 (verilog-sig-memory portdata)
8367 nil
a03c2342 8368 (verilog-sig-signed portdata)
47086495
WS
8369 ;; Though ok in SV, in V2K code, propagating the
8370 ;; "reg" in "output reg" upwards isn't legal.
8371 ;; Also for backwards compatibility we don't propagate
8372 ;; "input wire" upwards.
8373 ;; See also `verilog-signals-edit-wire-reg'.
8374 (unless (member (verilog-sig-type portdata) '("wire" "reg"))
8375 (verilog-sig-type portdata))
a03c2342
WS
8376 multidim nil)
8377 sigs-out)))
8378 ((or (setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
8379 (equal "input" verilog-read-sub-decls-gate-ios))
8380 (setq sigs-in
8381 (cons (verilog-sig-new
8382 sig
8383 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
8384 (concat "To " comment)
8385 (verilog-sig-memory portdata)
8386 nil
a03c2342 8387 (verilog-sig-signed portdata)
47086495
WS
8388 (unless (member (verilog-sig-type portdata) '("wire" "reg"))
8389 (verilog-sig-type portdata))
a03c2342
WS
8390 multidim nil)
8391 sigs-in)))
a3a8b002 8392 ((setq portdata (assoc port (verilog-decls-get-interfaces submoddecls)))
a03c2342
WS
8393 (setq sigs-intf
8394 (cons (verilog-sig-new
8395 sig
8396 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
8397 (concat "To/From " comment)
8398 (verilog-sig-memory portdata)
8399 nil
a03c2342
WS
8400 (verilog-sig-signed portdata)
8401 (verilog-sig-type portdata)
8402 multidim nil)
8403 sigs-intf)))
8404 ((setq portdata (and verilog-read-sub-decls-in-interfaced
9489a450 8405 (assoc port (verilog-decls-get-vars submoddecls))))
a03c2342
WS
8406 (setq sigs-intfd
8407 (cons (verilog-sig-new
8408 sig
8409 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
8410 (concat "To/From " comment)
8411 (verilog-sig-memory portdata)
8412 nil
a03c2342
WS
8413 (verilog-sig-signed portdata)
8414 (verilog-sig-type portdata)
8415 multidim nil)
8416 sigs-intf)))
6341f357
DN
8417 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
8418 )))))
8419
a3a8b002
DN
8420(defun verilog-read-sub-decls-expr (submoddecls comment port expr)
8421 "For `verilog-read-sub-decls-line', parse a subexpression and add signals."
8422 ;;(message "vrsde: '%s'" expr)
8423 ;; Replace special /*[....]*/ comments inserted by verilog-auto-inst-port
8424 (setq expr (verilog-string-replace-matches "/\\*\\(\\[[^*]+\\]\\)\\*/" "\\1" nil nil expr))
8425 ;; Remove front operators
8426 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
8427 ;;
8428 (cond
8429 ;; {..., a, b} requires us to recurse on a,b
a03c2342
WS
8430 ;; To support {#{},{#{a,b}} we'll just split everything on [{},]
8431 ((string-match "^\\s-*{\\(.*\\)}\\s-*$" expr)
14862301 8432 (unless verilog-auto-ignore-concat
a03c2342 8433 (let ((mlst (split-string (match-string 1 expr) "[{},]"))
14862301
SM
8434 mstr)
8435 (while (setq mstr (pop mlst))
8436 (verilog-read-sub-decls-expr submoddecls comment port mstr)))))
a3a8b002
DN
8437 (t
8438 (let (sig vec multidim)
a03c2342
WS
8439 ;; Remove leading reduction operators, etc
8440 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
8441 ;;(message "vrsde-ptop: '%s'" expr)
a3a8b002
DN
8442 (cond ;; Find \signal. Final space is part of escaped signal name
8443 ((string-match "^\\s-*\\(\\\\[^ \t\n\f]+\\s-\\)" expr)
8444 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
8445 (setq sig (match-string 1 expr)
8446 expr (substring expr (match-end 0))))
8447 ;; Find signal
a03c2342 8448 ((string-match "^\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" expr)
a3a8b002
DN
8449 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
8450 (setq sig (verilog-string-remove-spaces (match-string 1 expr))
8451 expr (substring expr (match-end 0)))))
8452 ;; Find [vector] or [multi][multi][multi][vector]
8453 (while (string-match "^\\s-*\\(\\[[^]]+\\]\\)" expr)
8454 ;;(message "vrsde-v: '%s'" (match-string 1 expr))
8455 (when vec (setq multidim (cons vec multidim)))
8456 (setq vec (match-string 1 expr)
8457 expr (substring expr (match-end 0))))
8458 ;; If found signal, and nothing unrecognized, add the signal
8459 ;;(message "vrsde-rem: '%s'" expr)
8460 (when (and sig (string-match "^\\s-*$" expr))
8461 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))))
8462
5509c6ad 8463(defun verilog-read-sub-decls-line (submoddecls comment)
a03c2342
WS
8464 "For `verilog-read-sub-decls', read lines of port defs until none match.
8465Inserts the list of signals found, using submodi to look up each port."
a3a8b002 8466 (let (done port)
6341f357
DN
8467 (save-excursion
8468 (forward-line 1)
8469 (while (not done)
8470 ;; Get port name
8471 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
8472 (setq port (match-string 1))
8473 (goto-char (match-end 0)))
a03c2342 8474 ;; .\escaped (
6341f357
DN
8475 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
8476 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
8477 (goto-char (match-end 0)))
a03c2342
WS
8478 ;; .name
8479 ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*[,)/]")
8480 (verilog-read-sub-decls-sig
8481 submoddecls comment (match-string 1) t ; sig==t for .name
8482 nil nil) ; vec multidim
8483 (setq port nil))
8484 ;; .\escaped_name
8485 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*[,)/]")
8486 (verilog-read-sub-decls-sig
8487 submoddecls comment (concat (match-string 1) " ") t ; sig==t for .name
8488 nil nil) ; vec multidim
8489 (setq port nil))
8490 ;; random
6341f357
DN
8491 ((looking-at "\\s-*\\.[^(]*(")
8492 (setq port nil) ;; skip this line
8493 (goto-char (match-end 0)))
8494 (t
8495 (setq port nil done t))) ;; Unknown, ignore rest of line
a3a8b002
DN
8496 ;; Get signal name. Point is at the first-non-space after (
8497 ;; We intentionally ignore (non-escaped) signals with .s in them
8498 ;; this prevents AUTOWIRE etc from noticing hierarchical sigs.
6341f357 8499 (when port
a03c2342 8500 (cond ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*)")
a3a8b002
DN
8501 (verilog-read-sub-decls-sig
8502 submoddecls comment port
8503 (verilog-string-remove-spaces (match-string 1)) ; sig
8504 nil nil)) ; vec multidim
8505 ;;
a03c2342 8506 ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
a3a8b002
DN
8507 (verilog-read-sub-decls-sig
8508 submoddecls comment port
8509 (verilog-string-remove-spaces (match-string 1)) ; sig
8510 (match-string 2) nil)) ; vec multidim
8511 ;; Fastpath was above looking-at's.
8512 ;; For something more complicated invoke a parser
8513 ((looking-at "[^)]+")
8514 (verilog-read-sub-decls-expr
8515 submoddecls comment port
8516 (buffer-substring
fd9ea9d3 8517 (point) (1- (progn (search-backward "(") ; start at (
9489a450
MM
8518 (verilog-forward-sexp-ign-cmt 1)
8519 (point)))))))) ; expr
6341f357
DN
8520 ;;
8521 (forward-line 1)))))
8522
a03c2342
WS
8523(defun verilog-read-sub-decls-gate (submoddecls comment submod end-inst-point)
8524 "For `verilog-read-sub-decls', read lines of UDP gate decl until none match.
8525Inserts the list of signals found."
8526 (save-excursion
8527 (let ((iolist (cdr (assoc submod verilog-gate-ios))))
8528 (while (< (point) end-inst-point)
8529 ;; Get primitive's signal name, as will never have port, and no trailing )
8530 (cond ((looking-at "//")
8531 (search-forward "\n"))
8532 ((looking-at "/\\*")
8533 (or (search-forward "*/")
8534 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8535 ((looking-at "(\\*")
9489a450
MM
8536 ;; To advance past either "(*)" or "(* ... *)" don't forward past first *
8537 (forward-char 1)
8538 (or (search-forward "*)")
a03c2342
WS
8539 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
8540 ;; On pins, parse and advance to next pin
8541 ;; Looking at pin, but *not* an // Output comment, or ) to end the inst
8542 ((looking-at "\\s-*[a-zA-Z0-9`_$({}\\\\][^,]*")
8543 (goto-char (match-end 0))
8544 (setq verilog-read-sub-decls-gate-ios (or (car iolist) "input")
8545 iolist (cdr iolist))
8546 (verilog-read-sub-decls-expr
8547 submoddecls comment "primitive_port"
8548 (match-string 0)))
8549 (t
8550 (forward-char 1)
8551 (skip-syntax-forward " ")))))))
8552
6341f357
DN
8553(defun verilog-read-sub-decls ()
8554 "Internally parse signals going to modules under this module.
47086495 8555Return an array of [ outputs inouts inputs ] signals for modules that are
6341f357 8556instantiated in this module. For example if declare A A (.B(SIG)) and SIG
47086495 8557is an output, then SIG will be included in the list.
6341f357
DN
8558
8559This only works on instantiations created with /*AUTOINST*/ converted by
8560\\[verilog-auto-inst]. Otherwise, it would have to read in the whole
8561component library to determine connectivity of the design.
8562
8563One work around for this problem is to manually create // Inputs and //
8564Outputs comments above subcell signals, for example:
8565
1dd4b004 8566 module ModuleName (
6341f357
DN
8567 // Outputs
8568 .out (out),
8569 // Inputs
8570 .in (in));"
8571 (save-excursion
0f137a73 8572 (let ((end-mod-point (verilog-get-end-of-defun))
6341f357
DN
8573 st-point end-inst-point
8574 ;; below 3 modified by verilog-read-sub-decls-line
a03c2342 8575 sigs-out sigs-inout sigs-in sigs-intf sigs-intfd)
9489a450
MM
8576 (verilog-beg-of-defun-quick)
8577 (while (verilog-re-search-forward-quick "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
6341f357
DN
8578 (save-excursion
8579 (goto-char (match-beginning 0))
9489a450 8580 (unless (verilog-inside-comment-or-string-p)
6341f357
DN
8581 ;; Attempt to snarf a comment
8582 (let* ((submod (verilog-read-inst-module))
8583 (inst (verilog-read-inst-name))
a03c2342 8584 (subprim (member submod verilog-gate-keywords))
5509c6ad
DN
8585 (comment (concat inst " of " submod ".v"))
8586 submodi submoddecls)
ea89ff08 8587 (cond
a03c2342
WS
8588 (subprim
8589 (setq submodi `primitive
8590 submoddecls (verilog-decls-new nil nil nil nil nil nil nil nil nil)
8591 comment (concat inst " of " submod))
6341f357 8592 (verilog-backward-open-paren)
9489a450
MM
8593 (setq end-inst-point (save-excursion (verilog-forward-sexp-ign-cmt 1)
8594 (point))
6341f357 8595 st-point (point))
a03c2342
WS
8596 (forward-char 1)
8597 (verilog-read-sub-decls-gate submoddecls comment submod end-inst-point))
8598 ;; Non-primitive
8599 (t
8600 (when (setq submodi (verilog-modi-lookup submod t))
8601 (setq submoddecls (verilog-modi-get-decls submodi)
8602 verilog-read-sub-decls-gate-ios nil)
8603 (verilog-backward-open-paren)
9489a450
MM
8604 (setq end-inst-point (save-excursion (verilog-forward-sexp-ign-cmt 1)
8605 (point))
a03c2342
WS
8606 st-point (point))
8607 ;; This could have used a list created by verilog-auto-inst
8608 ;; However I want it to be runnable even on user's manually added signals
8609 (let ((verilog-read-sub-decls-in-interfaced t))
8610 (while (re-search-forward "\\s *(?\\s *// Interfaced" end-inst-point t)
8611 (verilog-read-sub-decls-line submoddecls comment))) ;; Modifies sigs-ifd
8612 (goto-char st-point)
8613 (while (re-search-forward "\\s *(?\\s *// Interfaces" end-inst-point t)
8614 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
8615 (goto-char st-point)
8616 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
8617 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
8618 (goto-char st-point)
8619 (while (re-search-forward "\\s *(?\\s *// Inouts" end-inst-point t)
8620 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
8621 (goto-char st-point)
8622 (while (re-search-forward "\\s *(?\\s *// Inputs" end-inst-point t)
8623 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
8624 )))))))
6341f357
DN
8625 ;; Combine duplicate bits
8626 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
a03c2342
WS
8627 (verilog-subdecls-new
8628 (verilog-signals-combine-bus (nreverse sigs-out))
8629 (verilog-signals-combine-bus (nreverse sigs-inout))
8630 (verilog-signals-combine-bus (nreverse sigs-in))
8631 (verilog-signals-combine-bus (nreverse sigs-intf))
8632 (verilog-signals-combine-bus (nreverse sigs-intfd))))))
6341f357
DN
8633
8634(defun verilog-read-inst-pins ()
37ea4b9b 8635 "Return an array of [ pins ] for the current instantiation at point.
6341f357
DN
8636For example if declare A A (.B(SIG)) then B will be included in the list."
8637 (save-excursion
8638 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
8639 pins pin)
8640 (verilog-backward-open-paren)
8641 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
8642 (setq pin (match-string 1))
9489a450 8643 (unless (verilog-inside-comment-or-string-p)
6341f357
DN
8644 (setq pins (cons (list pin) pins))
8645 (when (looking-at "(")
9489a450 8646 (verilog-forward-sexp-ign-cmt 1))))
6341f357
DN
8647 (vector pins))))
8648
8649(defun verilog-read-arg-pins ()
37ea4b9b 8650 "Return an array of [ pins ] for the current argument declaration at point."
6341f357
DN
8651 (save-excursion
8652 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
8653 pins pin)
8654 (verilog-backward-open-paren)
8655 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
8656 (setq pin (match-string 1))
9489a450 8657 (unless (verilog-inside-comment-or-string-p)
6341f357
DN
8658 (setq pins (cons (list pin) pins))))
8659 (vector pins))))
8660
8661(defun verilog-read-auto-constants (beg end-mod-point)
8662 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
8663 ;; Insert new
8664 (save-excursion
8665 (let (sig-list tpl-end-pt)
8666 (goto-char beg)
8667 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
8668 (if (not (looking-at "\\s *("))
8669 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
8670 (search-forward "(" end-mod-point)
8671 (setq tpl-end-pt (save-excursion
8672 (backward-char 1)
9489a450 8673 (verilog-forward-sexp-cmt 1) ;; Moves to paren that closes argdecl's
6341f357
DN
8674 (backward-char 1)
8675 (point)))
8676 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
8677 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
8678 sig-list)))
8679
a03c2342
WS
8680(defvar verilog-cache-has-lisp nil "True if any AUTO_LISP in buffer.")
8681(make-variable-buffer-local 'verilog-cache-has-lisp)
8682
8683(defun verilog-read-auto-lisp-present ()
8684 "Set `verilog-cache-has-lisp' if any AUTO_LISP in this buffer."
6341f357 8685 (save-excursion
9489a450 8686 (goto-char (point-min))
a03c2342
WS
8687 (setq verilog-cache-has-lisp (re-search-forward "\\<AUTO_LISP(" nil t))))
8688
8689(defun verilog-read-auto-lisp (start end)
47086495 8690 "Look for and evaluate an AUTO_LISP between START and END.
a03c2342
WS
8691Must call `verilog-read-auto-lisp-present' before this function."
8692 ;; This function is expensive for large buffers, so we cache if any AUTO_LISP exists
8693 (when verilog-cache-has-lisp
8694 (save-excursion
8695 (goto-char start)
8696 (while (re-search-forward "\\<AUTO_LISP(" end t)
8697 (backward-char)
8698 (let* ((beg-pt (prog1 (point)
9489a450 8699 (verilog-forward-sexp-cmt 1))) ;; Closing paren
47086495
WS
8700 (end-pt (point))
8701 (verilog-in-hooks t))
a03c2342 8702 (eval-region beg-pt end-pt nil))))))
6341f357 8703
6341f357 8704(defun verilog-read-always-signals-recurse
a03c2342 8705 (exit-keywd rvalue temp-next)
6341f357
DN
8706 "Recursive routine for parentheses/bracket matching.
8707EXIT-KEYWD is expression to stop at, nil if top level.
8708RVALUE is true if at right hand side of equal.
8709IGNORE-NEXT is true to ignore next token, fake from inside case statement."
8710 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
a03c2342
WS
8711 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-list end-else-check
8712 ignore-next)
8713 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue temp-next))))
6341f357
DN
8714 (while (not (or (eobp) gotend))
8715 (cond
8716 ((looking-at "//")
8717 (search-forward "\n"))
8718 ((looking-at "/\\*")
8719 (or (search-forward "*/")
8720 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8721 ((looking-at "(\\*")
9489a450
MM
8722 ;; To advance past either "(*)" or "(* ... *)" don't forward past first *
8723 (forward-char 1)
8724 (or (search-forward "*)")
6341f357
DN
8725 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
8726 (t (setq keywd (buffer-substring-no-properties
8727 (point)
8728 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
8729 (forward-char 1))
8730 (point)))
8731 sig-last-tolk sig-tolk
8732 sig-tolk nil)
14862301 8733 ;;(if dbg (setq dbg (concat dbg (format "\tPt=%S %S\trv=%S in=%S ee=%S gs=%S\n" (point) keywd rvalue ignore-next end-else-check got-sig))))
6341f357
DN
8734 (cond
8735 ((equal keywd "\"")
8736 (or (re-search-forward "[^\\]\"" nil t)
8737 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
8738 ;; else at top level loop, keep parsing
8739 ((and end-else-check (equal keywd "else"))
8740 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
8741 ;; no forward movement, want to see else in lower loop
8742 (setq end-else-check nil))
8743 ;; End at top level loop
8744 ((and end-else-check (looking-at "[^ \t\n\f]"))
8745 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
8746 (setq gotend t))
8747 ;; Final statement?
8748 ((and exit-keywd (equal keywd exit-keywd))
8749 (setq gotend t)
8750 (forward-char (length keywd)))
8751 ;; Standard tokens...
8752 ((equal keywd ";")
8753 (setq ignore-next nil rvalue semi-rvalue)
8754 ;; Final statement at top level loop?
8755 (when (not exit-keywd)
8756 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
8757 (setq end-else-check t))
8758 (forward-char 1))
8759 ((equal keywd "'")
14862301 8760 (if (looking-at "'[sS]?[hdxboHDXBO]?[ \t]*[0-9a-fA-F_xzXZ?]+")
6341f357
DN
8761 (goto-char (match-end 0))
8762 (forward-char 1)))
8763 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
8764 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
8765 (setq ignore-next nil rvalue nil))
8766 ((equal "?" exit-keywd) ;; x?y:z rvalue
8767 ) ;; NOP
a3a8b002
DN
8768 ((equal "]" exit-keywd) ;; [x:y] rvalue
8769 ) ;; NOP
6341f357
DN
8770 (got-sig ;; label: statement
8771 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
8772 ((not rvalue) ;; begin label
8773 (setq ignore-next t rvalue nil)))
8774 (forward-char 1))
8775 ((equal keywd "=")
9489a450
MM
8776 (when got-sig
8777 ;;(if dbg (setq dbg (concat dbg (format "\t\tequal got-sig=%S got-list=%s\n" got-sig got-list))))
8778 (set got-list (cons got-sig (symbol-value got-list)))
8779 (setq got-sig nil))
8780 (when (not rvalue)
8781 (if (eq (char-before) ?< )
8782 (setq sigs-out-d (append sigs-out-d sigs-out-unk)
8783 sigs-out-unk nil)
8784 (setq sigs-out-i (append sigs-out-i sigs-out-unk)
8785 sigs-out-unk nil)))
6341f357
DN
8786 (setq ignore-next nil rvalue t)
8787 (forward-char 1))
8788 ((equal keywd "?")
8789 (forward-char 1)
8790 (verilog-read-always-signals-recurse ":" rvalue nil))
8791 ((equal keywd "[")
8792 (forward-char 1)
8793 (verilog-read-always-signals-recurse "]" t nil))
8794 ((equal keywd "(")
8795 (forward-char 1)
8796 (cond (sig-last-tolk ;; Function call; zap last signal
8797 (setq got-sig nil)))
8798 (cond ((equal last-keywd "for")
a03c2342
WS
8799 ;; temp-next: Variables on LHS are lvalues, but generally we want
8800 ;; to ignore them, assuming they are loop increments
8801 (verilog-read-always-signals-recurse ";" nil t)
6341f357
DN
8802 (verilog-read-always-signals-recurse ";" t nil)
8803 (verilog-read-always-signals-recurse ")" nil nil))
8804 (t (verilog-read-always-signals-recurse ")" t nil))))
8805 ((equal keywd "begin")
8806 (skip-syntax-forward "w_")
8807 (verilog-read-always-signals-recurse "end" nil nil)
8808 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
8809 (setq ignore-next nil rvalue semi-rvalue)
8810 (if (not exit-keywd) (setq end-else-check t)))
a03c2342 8811 ((member keywd '("case" "casex" "casez"))
6341f357
DN
8812 (skip-syntax-forward "w_")
8813 (verilog-read-always-signals-recurse "endcase" t nil)
8814 (setq ignore-next nil rvalue semi-rvalue)
8815 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
8816 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
a03c2342 8817 (cond ((member keywd '("`ifdef" "`ifndef" "`elsif"))
6341f357
DN
8818 (setq ignore-next t))
8819 ((or ignore-next
8820 (member keywd verilog-keywords)
8821 (string-match "^\\$" keywd)) ;; PLI task
8822 (setq ignore-next nil))
8823 (t
8824 (setq keywd (verilog-symbol-detick-denumber keywd))
8825 (when got-sig
a03c2342
WS
8826 (set got-list (cons got-sig (symbol-value got-list)))
8827 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S got-list=%S\n" got-sig got-list))))
6341f357 8828 )
a03c2342
WS
8829 (setq got-list (cond (temp-next 'sigs-temp)
8830 (rvalue 'sigs-in)
9489a450 8831 (t 'sigs-out-unk))
6341f357 8832 got-sig (if (or (not keywd)
a03c2342 8833 (assoc keywd (symbol-value got-list)))
6341f357 8834 nil (list keywd nil nil))
a03c2342 8835 temp-next nil
6341f357
DN
8836 sig-tolk t)))
8837 (skip-chars-forward "a-zA-Z0-9$_.%`"))
8838 (t
8839 (forward-char 1)))
8840 ;; End of non-comment token
60618039 8841 (setq last-keywd keywd)))
6341f357
DN
8842 (skip-syntax-forward " "))
8843 ;; Append the final pending signal
8844 (when got-sig
a03c2342
WS
8845 ;;(if dbg (setq dbg (concat dbg (format "\t\tfinal got-sig=%S got-list=%s\n" got-sig got-list))))
8846 (set got-list (cons got-sig (symbol-value got-list)))
6341f357
DN
8847 (setq got-sig nil))
8848 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
8849 ))
8850
8851(defun verilog-read-always-signals ()
8852 "Parse always block at point and return list of (outputs inout inputs)."
6341f357
DN
8853 (save-excursion
8854 (let* (;;(dbg "")
9489a450 8855 sigs-out-d sigs-out-i sigs-out-unk sigs-temp sigs-in)
6341f357
DN
8856 (search-forward ")")
8857 (verilog-read-always-signals-recurse nil nil nil)
9489a450
MM
8858 (setq sigs-out-i (append sigs-out-i sigs-out-unk)
8859 sigs-out-unk nil)
14862301 8860 ;;(if dbg (with-current-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg ""))
6341f357 8861 ;; Return what was found
9489a450 8862 (verilog-alw-new sigs-out-d sigs-out-i sigs-temp sigs-in))))
6341f357
DN
8863
8864(defun verilog-read-instants ()
8865 "Parse module at point and return list of ( ( file instance ) ... )."
9489a450 8866 (verilog-beg-of-defun-quick)
0f137a73 8867 (let* ((end-mod-point (verilog-get-end-of-defun))
6341f357
DN
8868 (state nil)
8869 (instants-list nil))
8870 (save-excursion
8871 (while (< (point) end-mod-point)
8872 ;; Stay at level 0, no comments
8873 (while (progn
8874 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
8875 (or (> (car state) 0) ; in parens
8876 (nth 5 state) ; comment
8877 ))
8878 (forward-line 1))
8879 (beginning-of-line)
8880 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
8881 ;;(if (looking-at "^\\(.+\\)$")
8882 (let ((module (match-string 1))
8883 (instant (match-string 2)))
8884 (if (not (member module verilog-keywords))
8885 (setq instants-list (cons (list module instant) instants-list)))))
60618039 8886 (forward-line 1)))
6341f357
DN
8887 instants-list))
8888
8889
47086495
WS
8890(defun verilog-read-auto-template-middle ()
8891 "With point in middle of an AUTO_TEMPLATE, parse it.
8892Returns REGEXP and list of ( (signal_name connection_name)... )."
6341f357
DN
8893 (save-excursion
8894 ;; Find beginning
8895 (let ((tpl-regexp "\\([0-9]+\\)")
9489a450 8896 (lineno -1) ; -1 to offset for the AUTO_TEMPLATE's newline
6341f357
DN
8897 (templateno 0)
8898 tpl-sig-list tpl-wild-list tpl-end-pt rep)
47086495
WS
8899 ;; Parse "REGEXP"
8900 ;; We reserve @"..." for future lisp expressions that evaluate
8901 ;; once-per-AUTOINST
8902 (when (looking-at "\\s-*\"\\([^\"]*\\)\"")
8903 (setq tpl-regexp (match-string 1))
8904 (goto-char (match-end 0)))
8905 (search-forward "(")
8906 ;; Parse lines in the template
8907 (when (or verilog-auto-inst-template-numbers
8908 verilog-auto-template-warn-unused)
8909 (save-excursion
8910 (let ((pre-pt (point)))
8911 (goto-char (point-min))
8912 (while (search-forward "AUTO_TEMPLATE" pre-pt t)
8913 (setq templateno (1+ templateno)))
8914 (while (< (point) pre-pt)
8915 (forward-line 1)
8916 (setq lineno (1+ lineno))))))
8917 (setq tpl-end-pt (save-excursion
8918 (backward-char 1)
8919 (verilog-forward-sexp-cmt 1) ;; Moves to paren that closes argdecl's
8920 (backward-char 1)
8921 (point)))
8922 ;;
8923 (while (< (point) tpl-end-pt)
8924 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
8925 (setq tpl-sig-list
8926 (cons (list
8927 (match-string-no-properties 1)
8928 (match-string-no-properties 2)
8929 templateno lineno)
8930 tpl-sig-list))
8931 (goto-char (match-end 0)))
8932 ;; Regexp form??
8933 ((looking-at
8934 ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
8935 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
8936 (setq rep (match-string-no-properties 3))
8937 (goto-char (match-end 0))
8938 (setq tpl-wild-list
8939 (cons (list
8940 (concat "^"
8941 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
8942 (match-string 1))
8943 "$")
8944 rep
8945 templateno lineno)
8946 tpl-wild-list)))
8947 ((looking-at "[ \t\f]+")
8948 (goto-char (match-end 0)))
8949 ((looking-at "\n")
8950 (setq lineno (1+ lineno))
8951 (goto-char (match-end 0)))
8952 ((looking-at "//")
8953 (search-forward "\n")
8954 (setq lineno (1+ lineno)))
8955 ((looking-at "/\\*")
8956 (forward-char 2)
8957 (or (search-forward "*/")
8958 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8959 (t
8960 (error "%s: AUTO_TEMPLATE parsing error: %s"
8961 (verilog-point-text)
8962 (progn (looking-at ".*$") (match-string 0))))))
8963 ;; Return
8964 (vector tpl-regexp
8965 (list tpl-sig-list tpl-wild-list)))))
8966
8967(defun verilog-read-auto-template (module)
8968 "Look for an auto_template for the instantiation of the given MODULE.
8969If found returns `verilog-read-auto-template-inside' structure."
8970 (save-excursion
8971 ;; Find beginning
8972 (let ((pt (point)))
a03c2342
WS
8973 ;; Note this search is expensive, as we hunt from mod-begin to point
8974 ;; for every instantiation. Likewise in verilog-read-auto-lisp.
8975 ;; So, we look first for an exact string rather than a slow regexp.
8976 ;; Someday we may keep a cache of every template, but this would also
8977 ;; need to record the relative position of each AUTOINST, as multiple
8978 ;; templates exist for each module, and we're inserting lines.
6341f357 8979 (cond ((or
47086495 8980 ;; See also regexp in `verilog-auto-template-lint'
a03c2342
WS
8981 (verilog-re-search-backward-substr
8982 "AUTO_TEMPLATE"
8983 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
8984 ;; Also try forward of this AUTOINST
8985 ;; This is for historical support; this isn't speced as working
8986 (progn
8987 (goto-char pt)
8988 (verilog-re-search-forward-substr
8989 "AUTO_TEMPLATE"
8990 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
6341f357 8991 (goto-char (match-end 0))
47086495 8992 (verilog-read-auto-template-middle))
6341f357 8993 ;; If no template found
47086495 8994 (t (vector "" nil))))))
6341f357
DN
8995;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
8996
47086495
WS
8997(defvar verilog-auto-template-hits nil "Successful lookups with `verilog-read-auto-template-hit'.")
8998(make-variable-buffer-local 'verilog-auto-template-hits)
8999
9000(defun verilog-read-auto-template-hit (tpl-ass)
9001 "Record that TPL-ASS template from `verilog-read-auto-template' was used."
9002 (when (eval-when-compile (fboundp 'make-hash-table)) ;; else feature not allowed
9003 (when verilog-auto-template-warn-unused
9004 (unless verilog-auto-template-hits
9005 (setq verilog-auto-template-hits
9006 (make-hash-table :test 'equal :rehash-size 4.0)))
9007 (puthash (vector (nth 2 tpl-ass) (nth 3 tpl-ass)) t
9008 verilog-auto-template-hits))))
9009
6341f357
DN
9010(defun verilog-set-define (defname defvalue &optional buffer enumname)
9011 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
9012Optionally associate it with the specified enumeration ENUMNAME."
9a529312 9013 (with-current-buffer (or buffer (current-buffer))
0f137a73 9014 ;; Namespace intentionally short for AUTOs and compatibility
6341f357
DN
9015 (let ((mac (intern (concat "vh-" defname))))
9016 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
9017 ;; Need to define to a constant if no value given
14862301 9018 (set (make-local-variable mac)
6341f357
DN
9019 (if (equal defvalue "") "1" defvalue)))
9020 (if enumname
0f137a73 9021 ;; Namespace intentionally short for AUTOs and compatibility
6341f357
DN
9022 (let ((enumvar (intern (concat "venum-" enumname))))
9023 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
a3a8b002 9024 (unless (boundp enumvar) (set enumvar nil))
175069ef 9025 (add-to-list (make-local-variable enumvar) defname)))))
6341f357
DN
9026
9027(defun verilog-read-defines (&optional filename recurse subcall)
9028 "Read `defines and parameters for the current file, or optional FILENAME.
9029If the filename is provided, `verilog-library-flags' will be used to
9030resolve it. If optional RECURSE is non-nil, recurse through `includes.
9031
9032Parameters must be simple assignments to constants, or have their own
9033\"parameter\" label rather than a list of parameters. Thus:
9034
9035 parameter X = 5, Y = 10; // Ok
9036 parameter X = {1'b1, 2'h2}; // Ok
9037 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
9038
9039Defines must be simple text substitutions, one on a line, starting
9040at the beginning of the line. Any ifdefs or multiline comments around the
9041define are ignored.
9042
9043Defines are stored inside Emacs variables using the name vh-{definename}.
9044
9045This function is useful for setting vh-* variables. The file variables
9046feature can be used to set defines that `verilog-mode' can see; put at the
9047*END* of your file something like:
9048
9049 // Local Variables:
9050 // vh-macro:\"macro_definition\"
9051 // End:
9052
9053If macros are defined earlier in the same file and you want their values,
9054you can read them automatically (provided `enable-local-eval' is on):
9055
9056 // Local Variables:
9057 // eval:(verilog-read-defines)
9058 // eval:(verilog-read-defines \"group_standard_includes.v\")
9059 // End:
9060
9061Note these are only read when the file is first visited, you must use
9062\\[find-alternate-file] RET to have these take effect after editing them!
9063
9064If you want to disable the \"Process `eval' or hook local variables\"
865fe16f 9065warning message, you need to add to your init file:
6341f357
DN
9066
9067 (setq enable-local-eval t)"
9068 (let ((origbuf (current-buffer)))
9069 (save-excursion
9070 (unless subcall (verilog-getopt-flags))
9071 (when filename
9072 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
9073 (if fns
9074 (set-buffer (find-file-noselect (car fns)))
9075 (error (concat (verilog-point-text)
9076 ": Can't find verilog-read-defines file: " filename)))))
9077 (when recurse
9078 (goto-char (point-min))
9079 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
a03c2342
WS
9080 (let ((inc (verilog-string-replace-matches
9081 "\"" "" nil nil (match-string-no-properties 1))))
9489a450 9082 (unless (verilog-inside-comment-or-string-p)
6341f357
DN
9083 (verilog-read-defines inc recurse t)))))
9084 ;; Read `defines
9085 ;; note we don't use verilog-re... it's faster this way, and that
9086 ;; function has problems when comments are at the end of the define
9087 (goto-char (point-min))
9088 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
9089 (let ((defname (match-string-no-properties 1))
9090 (defvalue (match-string-no-properties 2)))
ea89ff08
WS
9091 (unless (verilog-inside-comment-or-string-p (match-beginning 0))
9092 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
9093 (verilog-set-define defname defvalue origbuf))))
6341f357
DN
9094 ;; Hack: Read parameters
9095 (goto-char (point-min))
9096 (while (re-search-forward
9489a450 9097 "^\\s-*\\(parameter\\|localparam\\)\\(\\s-*\\[[^]]*\\]\\)?\\s-*" nil t)
a3a8b002 9098 (let (enumname)
6341f357
DN
9099 ;; The primary way of getting defines is verilog-read-decls
9100 ;; However, that isn't called yet for included files, so we'll add another scheme
47086495
WS
9101 (if (looking-at "[^\n]*\\(auto\\|synopsys\\)\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
9102 (setq enumname (match-string-no-properties 2)))
9103 (forward-comment 99999)
9489a450
MM
9104 (while (looking-at (concat "\\s-*,?\\s-*\\(?:/[/*].*?$\\)?\\s-*\\([a-zA-Z0-9_$]+\\)"
9105 "\\s-*=\\s-*\\([^;,]*\\),?\\s-*\\(/[/*].*?$\\)?\\s-*"))
ea89ff08
WS
9106 (unless (verilog-inside-comment-or-string-p (match-beginning 0))
9107 (verilog-set-define (match-string-no-properties 1)
9108 (match-string-no-properties 2) origbuf enumname))
6341f357 9109 (goto-char (match-end 0))
47086495 9110 (forward-comment 99999)))))))
6341f357
DN
9111
9112(defun verilog-read-includes ()
9113 "Read `includes for the current file.
9114This will find all of the `includes which are at the beginning of lines,
9115ignoring any ifdefs or multiline comments around them.
9116`verilog-read-defines' is then performed on the current and each included
9117file.
9118
9119It is often useful put at the *END* of your file something like:
9120
9121 // Local Variables:
9122 // eval:(verilog-read-defines)
9123 // eval:(verilog-read-includes)
9124 // End:
9125
9126Note includes are only read when the file is first visited, you must use
9127\\[find-alternate-file] RET to have these take effect after editing them!
9128
9129It is good to get in the habit of including all needed files in each .v
9130file that needs it, rather than waiting for compile time. This will aid
9131this process, Verilint, and readability. To prevent defining the same
9132variable over and over when many modules are compiled together, put a test
9133around the inside each include file:
9134
47086495 9135foo.v (an include file):
6341f357
DN
9136 `ifdef _FOO_V // include if not already included
9137 `else
9138 `define _FOO_V
9139 ... contents of file
9140 `endif // _FOO_V"
9141;;slow: (verilog-read-defines nil t))
9142 (save-excursion
9143 (verilog-getopt-flags)
9144 (goto-char (point-min))
9145 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
9146 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
9147 (verilog-read-defines inc nil t)))))
9148
9149(defun verilog-read-signals (&optional start end)
9150 "Return a simple list of all possible signals in the file.
9151Bounded by optional region from START to END. Overly aggressive but fast.
37ea4b9b 9152Some macros and such are also found and included. For dinotrace.el."
6341f357
DN
9153 (let (sigs-all keywd)
9154 (progn;save-excursion
9155 (goto-char (or start (point-min)))
9156 (setq end (or end (point-max)))
9157 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
9158 (forward-char -1)
9159 (cond
9160 ((looking-at "//")
9161 (search-forward "\n"))
9162 ((looking-at "/\\*")
9163 (search-forward "*/"))
9164 ((looking-at "(\\*")
9165 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
9166 (search-forward "*)")))
9167 ((eq ?\" (following-char))
9168 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
9169 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
9170 (goto-char (match-end 0))
9171 (setq keywd (match-string-no-properties 1))
9172 (or (member keywd verilog-keywords)
9173 (member keywd sigs-all)
9174 (setq sigs-all (cons keywd sigs-all))))
60618039 9175 (t (forward-char 1))))
6341f357
DN
9176 ;; Return list
9177 sigs-all)))
9178
9179;;
9180;; Argument file parsing
9181;;
9182
9183(defun verilog-getopt (arglist)
9184 "Parse -f, -v etc arguments in ARGLIST list or string."
9185 (unless (listp arglist) (setq arglist (list arglist)))
9186 (let ((space-args '())
9187 arg next-param)
9188 ;; Split on spaces, so users can pass whole command lines
9189 (while arglist
9190 (setq arg (car arglist)
9191 arglist (cdr arglist))
9192 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
9193 (setq space-args (append space-args
9194 (list (match-string-no-properties 1 arg))))
9195 (setq arg (match-string 2 arg))))
9196 ;; Parse arguments
9197 (while space-args
9198 (setq arg (car space-args)
9199 space-args (cdr space-args))
9200 (cond
9201 ;; Need another arg
9202 ((equal arg "-f")
9203 (setq next-param arg))
9204 ((equal arg "-v")
9205 (setq next-param arg))
9206 ((equal arg "-y")
9207 (setq next-param arg))
9208 ;; +libext+(ext1)+(ext2)...
9209 ((string-match "^\\+libext\\+\\(.*\\)" arg)
9210 (setq arg (match-string 1 arg))
9211 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
9212 (verilog-add-list-unique `verilog-library-extensions
9213 (match-string 1 arg))
9214 (setq arg (match-string 2 arg))))
9215 ;;
9216 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
9217 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
9218 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
9219 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
9220 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
9221 ;;
9222 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
9223 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
9224 (verilog-add-list-unique `verilog-library-directories
a3a8b002 9225 (match-string 1 (substitute-in-file-name arg))))
6341f357
DN
9226 ;; Ignore
9227 ((equal "+librescan" arg))
9228 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
9229 ;; Second parameters
9230 ((equal next-param "-f")
9231 (setq next-param nil)
a3a8b002 9232 (verilog-getopt-file (substitute-in-file-name arg)))
6341f357
DN
9233 ((equal next-param "-v")
9234 (setq next-param nil)
a3a8b002
DN
9235 (verilog-add-list-unique `verilog-library-files
9236 (substitute-in-file-name arg)))
6341f357
DN
9237 ((equal next-param "-y")
9238 (setq next-param nil)
a3a8b002
DN
9239 (verilog-add-list-unique `verilog-library-directories
9240 (substitute-in-file-name arg)))
6341f357
DN
9241 ;; Filename
9242 ((string-match "^[^-+]" arg)
a3a8b002
DN
9243 (verilog-add-list-unique `verilog-library-files
9244 (substitute-in-file-name arg)))
6341f357 9245 ;; Default - ignore; no warning
60618039 9246 ))))
6341f357
DN
9247;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
9248
9249(defun verilog-getopt-file (filename)
37ea4b9b 9250 "Read Verilog options from the specified FILENAME."
6341f357
DN
9251 (save-excursion
9252 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
9253 (orig-buffer (current-buffer))
9254 line)
9255 (if fns
9256 (set-buffer (find-file-noselect (car fns)))
9257 (error (concat (verilog-point-text)
5509c6ad 9258 ": Can't find verilog-getopt-file -f file: " filename)))
6341f357
DN
9259 (goto-char (point-min))
9260 (while (not (eobp))
3ba6b2ee 9261 (setq line (buffer-substring (point) (point-at-eol)))
6341f357
DN
9262 (forward-line 1)
9263 (when (string-match "//" line)
9264 (setq line (substring line 0 (match-beginning 0))))
14862301 9265 (with-current-buffer orig-buffer ; Variables are buffer-local, so need right context.
6341f357
DN
9266 (verilog-getopt line))))))
9267
9268(defun verilog-getopt-flags ()
9269 "Convert `verilog-library-flags' into standard library variables."
9270 ;; If the flags are local, then all the outputs should be local also
9271 (when (local-variable-p `verilog-library-flags (current-buffer))
7ea26faf
DN
9272 (mapc 'make-local-variable '(verilog-library-extensions
9273 verilog-library-directories
9274 verilog-library-files
9275 verilog-library-flags)))
6341f357 9276 ;; Allow user to customize
9489a450 9277 (verilog-run-hooks 'verilog-before-getopt-flags-hook)
6341f357
DN
9278 ;; Process arguments
9279 (verilog-getopt verilog-library-flags)
9280 ;; Allow user to customize
9489a450 9281 (verilog-run-hooks 'verilog-getopt-flags-hook))
6341f357
DN
9282
9283(defun verilog-add-list-unique (varref object)
9284 "Append to VARREF list the given OBJECT,
37ea4b9b 9285unless it is already a member of the variable's list."
6341f357
DN
9286 (unless (member object (symbol-value varref))
9287 (set varref (append (symbol-value varref) (list object))))
9288 varref)
9289;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
9290
a03c2342
WS
9291(defun verilog-current-flags ()
9292 "Convert `verilog-library-flags' and similar variables to command line.
9293Used for __FLAGS__ in `verilog-expand-command'."
9294 (let ((cmd (mapconcat `concat verilog-library-flags " ")))
9295 (when (equal cmd "")
9296 (setq cmd (concat
9297 "+libext+" (mapconcat `concat verilog-library-extensions "+")
9298 (mapconcat (lambda (i) (concat " -y " i " +incdir+" i))
9299 verilog-library-directories "")
9300 (mapconcat (lambda (i) (concat " -v " i))
9301 verilog-library-files ""))))
9302 cmd))
9303;;(verilog-current-flags)
9304
6341f357 9305\f
5509c6ad
DN
9306;;
9307;; Cached directory support
9308;;
9309
9310(defvar verilog-dir-cache-preserving nil
ea89ff08 9311 "If true, the directory cache is enabled, and file system changes are ignored.
5509c6ad
DN
9312See `verilog-dir-exists-p' and `verilog-dir-files'.")
9313
9314;; If adding new cached variable, add also to verilog-preserve-dir-cache
9315(defvar verilog-dir-cache-list nil
9316 "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
9317(defvar verilog-dir-cache-lib-filenames nil
9318 "Cached data for `verilog-library-filenames'.")
9319
9320(defmacro verilog-preserve-dir-cache (&rest body)
9321 "Execute the BODY forms, allowing directory cache preservation within BODY.
9322This means that changes inside BODY made to the file system will not be
9323seen by the `verilog-dir-files' and related functions."
a03c2342 9324 `(let ((verilog-dir-cache-preserving (current-buffer))
5509c6ad
DN
9325 verilog-dir-cache-list
9326 verilog-dir-cache-lib-filenames)
9327 (progn ,@body)))
9328
9329(defun verilog-dir-files (dirname)
9330 "Return all filenames in the DIRNAME directory.
9331Relative paths depend on the `default-directory'.
9332Results are cached if inside `verilog-preserve-dir-cache'."
9333 (unless verilog-dir-cache-preserving
9334 (setq verilog-dir-cache-list nil)) ;; Cache disabled
9335 ;; We don't use expand-file-name on the dirname to make key, as it's slow
9336 (let* ((cache-key (list dirname default-directory))
9337 (fass (assoc cache-key verilog-dir-cache-list))
9338 exp-dirname data)
9339 (cond (fass ;; Return data from cache hit
9340 (nth 1 fass))
9341 (t
9342 (setq exp-dirname (expand-file-name dirname)
9343 data (and (file-directory-p exp-dirname)
9344 (directory-files exp-dirname nil nil nil)))
9345 ;; Note we also encache nil for non-existing dirs.
9346 (setq verilog-dir-cache-list (cons (list cache-key data)
9347 verilog-dir-cache-list))
9348 data))))
9349;; Miss-and-hit test:
9350;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
9351;; (prin1 (verilog-dir-files ".")) nil)
9352
9353(defun verilog-dir-file-exists-p (filename)
9354 "Return true if FILENAME exists.
9355Like `file-exists-p' but results are cached if inside
9356`verilog-preserve-dir-cache'."
9357 (let* ((dirname (file-name-directory filename))
9358 ;; Correct for file-name-nondirectory returning same if no slash.
9359 (dirnamed (if (or (not dirname) (equal dirname filename))
9360 default-directory dirname))
9361 (flist (verilog-dir-files dirnamed)))
9362 (and flist
9363 (member (file-name-nondirectory filename) flist)
9364 t)))
9365;;(verilog-dir-file-exists-p "verilog-mode.el")
9366;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
9367
9368\f
6341f357
DN
9369;;
9370;; Module name lookup
9371;;
9372
9373(defun verilog-module-inside-filename-p (module filename)
a03c2342 9374 "Return modi if MODULE is specified inside FILENAME, else nil.
6341f357
DN
9375Allows version control to check out the file if need be."
9376 (and (or (file-exists-p filename)
7ea26faf
DN
9377 (and (fboundp 'vc-backend)
9378 (vc-backend filename)))
a03c2342 9379 (let (modi type)
9a529312 9380 (with-current-buffer (find-file-noselect filename)
14862301
SM
9381 (save-excursion
9382 (goto-char (point-min))
9383 (while (and
9384 ;; It may be tempting to look for verilog-defun-re,
9385 ;; don't, it slows things down a lot!
9489a450 9386 (verilog-re-search-forward-quick "\\<\\(module\\|interface\\|program\\)\\>" nil t)
a03c2342 9387 (setq type (match-string-no-properties 0))
14862301
SM
9388 (verilog-re-search-forward-quick "[(;]" nil t))
9389 (if (equal module (verilog-read-module-name))
a03c2342
WS
9390 (setq modi (verilog-modi-new module filename (point) type))))
9391 modi)))))
6341f357
DN
9392
9393(defun verilog-is-number (symbol)
9394 "Return true if SYMBOL is number-like."
9395 (or (string-match "^[0-9 \t:]+$" symbol)
9396 (string-match "^[---]*[0-9]+$" symbol)
60618039 9397 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
6341f357
DN
9398
9399(defun verilog-symbol-detick (symbol wing-it)
37ea4b9b 9400 "Return an expanded SYMBOL name without any defines.
6341f357
DN
9401If the variable vh-{symbol} is defined, return that value.
9402If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
9403 (while (and symbol (string-match "^`" symbol))
9404 (setq symbol (substring symbol 1))
9405 (setq symbol
0f137a73 9406 ;; Namespace intentionally short for AUTOs and compatibility
6341f357
DN
9407 (if (boundp (intern (concat "vh-" symbol)))
9408 ;; Emacs has a bug where boundp on a buffer-local
9409 ;; variable in only one buffer returns t in another.
9410 ;; This can confuse, so check for nil.
0f137a73 9411 ;; Namespace intentionally short for AUTOs and compatibility
6341f357
DN
9412 (let ((val (eval (intern (concat "vh-" symbol)))))
9413 (if (eq val nil)
9414 (if wing-it symbol nil)
9415 val))
9416 (if wing-it symbol nil))))
9417 symbol)
9418;;(verilog-symbol-detick "`mod" nil)
9419
9420(defun verilog-symbol-detick-denumber (symbol)
9421 "Return SYMBOL with defines converted and any numbers dropped to nil."
9422 (when (string-match "^`" symbol)
9423 ;; This only will work if the define is a simple signal, not
9424 ;; something like a[b]. Sorry, it should be substituted into the parser
9425 (setq symbol
9426 (verilog-string-replace-matches
9427 "\[[^0-9: \t]+\]" "" nil nil
9428 (or (verilog-symbol-detick symbol nil)
9429 (if verilog-auto-sense-defines-constant
9430 "0"
9431 symbol)))))
9432 (if (verilog-is-number symbol)
9433 nil
9434 symbol))
9435
9436(defun verilog-symbol-detick-text (text)
37ea4b9b 9437 "Return TEXT without any known defines.
6341f357
DN
9438If the variable vh-{symbol} is defined, substitute that value."
9439 (let ((ok t) symbol val)
9440 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
9441 (setq symbol (match-string 1 text))
a3a8b002 9442 ;;(message symbol)
6341f357 9443 (cond ((and
0f137a73 9444 ;; Namespace intentionally short for AUTOs and compatibility
6341f357
DN
9445 (boundp (intern (concat "vh-" symbol)))
9446 ;; Emacs has a bug where boundp on a buffer-local
9447 ;; variable in only one buffer returns t in another.
9448 ;; This can confuse, so check for nil.
0f137a73 9449 ;; Namespace intentionally short for AUTOs and compatibility
6341f357
DN
9450 (setq val (eval (intern (concat "vh-" symbol)))))
9451 (setq text (replace-match val nil nil text)))
9452 (t (setq ok nil)))))
9453 text)
9454;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
9455
9456(defun verilog-expand-dirnames (&optional dirnames)
9457 "Return a list of existing directories given a list of wildcarded DIRNAMES.
9458Or, just the existing dirnames themselves if there are no wildcards."
5509c6ad
DN
9459 ;; Note this function is performance critical.
9460 ;; Do not call anything that requires disk access that cannot be cached.
6341f357
DN
9461 (interactive)
9462 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
9463 (setq dirnames (reverse dirnames)) ; not nreverse
9464 (let ((dirlist nil)
5509c6ad 9465 pattern dirfile dirfiles dirname root filename rest basefile)
6341f357
DN
9466 (while dirnames
9467 (setq dirname (substitute-in-file-name (car dirnames))
9468 dirnames (cdr dirnames))
9469 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
9470 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
9471 "\\(.*\\)") ;; rest
9472 dirname)
9473 (setq root (match-string 1 dirname)
9474 filename (match-string 2 dirname)
9475 rest (match-string 3 dirname)
9476 pattern filename)
9477 ;; now replace those * and ? with .+ and .
9478 ;; use ^ and /> to get only whole file names
6341f357
DN
9479 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
9480 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
5509c6ad
DN
9481 pattern (concat "^" pattern "$")
9482 dirfiles (verilog-dir-files root))
6341f357 9483 (while dirfiles
5509c6ad
DN
9484 (setq basefile (car dirfiles)
9485 dirfile (expand-file-name (concat root basefile rest))
6341f357 9486 dirfiles (cdr dirfiles))
5509c6ad
DN
9487 (if (and (string-match pattern basefile)
9488 ;; Don't allow abc/*/rtl to match abc/rtl via ..
9489 (not (equal basefile "."))
9490 (not (equal basefile ".."))
9491 (file-directory-p dirfile))
60618039 9492 (setq dirlist (cons dirfile dirlist)))))
6341f357
DN
9493 ;; Defaults
9494 (t
9495 (if (file-directory-p dirname)
60618039 9496 (setq dirlist (cons dirname dirlist))))))
6341f357
DN
9497 dirlist))
9498;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
9499
0e5c8aed 9500(defun verilog-library-filenames (filename &optional current check-ext)
5509c6ad 9501 "Return a search path to find the given FILENAME or module name.
47086495 9502Uses the optional CURRENT filename or variable `buffer-file-name', plus
0e5c8aed
DN
9503`verilog-library-directories' and `verilog-library-extensions'
9504variables to build the path. With optional CHECK-EXT also check
9505`verilog-library-extensions'."
9506 (unless current (setq current (buffer-file-name)))
5509c6ad
DN
9507 (unless verilog-dir-cache-preserving
9508 (setq verilog-dir-cache-lib-filenames nil))
9509 (let* ((cache-key (list filename current check-ext))
9510 (fass (assoc cache-key verilog-dir-cache-lib-filenames))
9511 chkdirs chkdir chkexts fn outlist)
9512 (cond (fass ;; Return data from cache hit
9513 (nth 1 fass))
9514 (t
9515 ;; Note this expand can't be easily cached, as we need to
9516 ;; pick up buffer-local variables for newly read sub-module files
9517 (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
9518 (while chkdirs
9519 (setq chkdir (expand-file-name (car chkdirs)
9520 (file-name-directory current))
9521 chkexts (if check-ext verilog-library-extensions `("")))
9522 (while chkexts
9523 (setq fn (expand-file-name (concat filename (car chkexts))
9524 chkdir))
9525 ;;(message "Check for %s" fn)
9526 (if (verilog-dir-file-exists-p fn)
9527 (setq outlist (cons (expand-file-name
9528 fn (file-name-directory current))
9529 outlist)))
9530 (setq chkexts (cdr chkexts)))
9531 (setq chkdirs (cdr chkdirs)))
9532 (setq outlist (nreverse outlist))
9533 (setq verilog-dir-cache-lib-filenames
9534 (cons (list cache-key outlist)
9535 verilog-dir-cache-lib-filenames))
9536 outlist))))
6341f357
DN
9537
9538(defun verilog-module-filenames (module current)
9539 "Return a search path to find the given MODULE name.
9540Uses the CURRENT filename, `verilog-library-extensions',
9541`verilog-library-directories' and `verilog-library-files'
9542variables to build the path."
9543 ;; Return search locations for it
9544 (append (list current) ; first, current buffer
9545 (verilog-library-filenames module current t)
9546 verilog-library-files)) ; finally, any libraries
9547
9548;;
9549;; Module Information
9550;;
9551;; Many of these functions work on "modi" a module information structure
9552;; A modi is: [module-name-string file-name begin-point]
9553
9554(defvar verilog-cache-enabled t
47086495 9555 "Non-nil enables caching of signals, etc. Set to nil for debugging to make things SLOW!")
6341f357
DN
9556
9557(defvar verilog-modi-cache-list nil
9558 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
9559For speeding up verilog-modi-get-* commands.
9560Buffer-local.")
7ea26faf
DN
9561(make-variable-buffer-local 'verilog-modi-cache-list)
9562
6341f357
DN
9563(defvar verilog-modi-cache-preserve-tick nil
9564 "Modification tick after which the cache is still considered valid.
5509c6ad 9565Use `verilog-preserve-modi-cache' to set it.")
6341f357
DN
9566(defvar verilog-modi-cache-preserve-buffer nil
9567 "Modification tick after which the cache is still considered valid.
5509c6ad 9568Use `verilog-preserve-modi-cache' to set it.")
a03c2342 9569(defvar verilog-modi-cache-current-enable nil
47086495 9570 "Non-nil means allow caching `verilog-modi-current', set by let().")
a03c2342
WS
9571(defvar verilog-modi-cache-current nil
9572 "Currently active `verilog-modi-current', if any, set by let().")
9573(defvar verilog-modi-cache-current-max nil
9574 "Current endmodule point for `verilog-modi-cache-current', if any.")
6341f357
DN
9575
9576(defun verilog-modi-current ()
a03c2342
WS
9577 "Return the modi structure for the module currently at point, possibly cached."
9578 (cond ((and verilog-modi-cache-current
9579 (>= (point) (verilog-modi-get-point verilog-modi-cache-current))
9580 (<= (point) verilog-modi-cache-current-max))
9581 ;; Slow assertion, for debugging the cache:
9582 ;;(or (equal verilog-modi-cache-current (verilog-modi-current-get)) (debug))
9583 verilog-modi-cache-current)
9584 (verilog-modi-cache-current-enable
9585 (setq verilog-modi-cache-current (verilog-modi-current-get)
9586 verilog-modi-cache-current-max
9587 ;; The cache expires when we pass "endmodule" as then the
9588 ;; current modi may change to the next module
9589 ;; This relies on the AUTOs generally inserting, not deleting text
9590 (save-excursion
9591 (verilog-re-search-forward-quick verilog-end-defun-re nil nil)))
9592 verilog-modi-cache-current)
9593 (t
9594 (verilog-modi-current-get))))
9595
9596(defun verilog-modi-current-get ()
6341f357 9597 "Return the modi structure for the module currently at point."
a03c2342 9598 (let* (name type pt)
6341f357
DN
9599 ;; read current module's name
9600 (save-excursion
9601 (verilog-re-search-backward-quick verilog-defun-re nil nil)
a03c2342 9602 (setq type (match-string-no-properties 0))
6341f357
DN
9603 (verilog-re-search-forward-quick "(" nil nil)
9604 (setq name (verilog-read-module-name))
9605 (setq pt (point)))
a03c2342
WS
9606 ;; return modi - note this vector built two places
9607 (verilog-modi-new name (or (buffer-file-name) (current-buffer)) pt type)))
6341f357 9608
a03c2342
WS
9609(defvar verilog-modi-lookup-cache nil "Hash of (modulename modi).")
9610(make-variable-buffer-local 'verilog-modi-lookup-cache)
9611(defvar verilog-modi-lookup-last-current nil "Cache of `current-buffer' at last lookup.")
9612(defvar verilog-modi-lookup-last-tick nil "Cache of `buffer-chars-modified-tick' at last lookup.")
6341f357
DN
9613
9614(defun verilog-modi-lookup (module allow-cache &optional ignore-error)
9615 "Find the file and point at which MODULE is defined.
9616If ALLOW-CACHE is set, check and remember cache of previous lookups.
9617Return modi if successful, else print message unless IGNORE-ERROR is true."
a03c2342
WS
9618 (let* ((current (or (buffer-file-name) (current-buffer)))
9619 modi)
9620 ;; Check cache
9621 ;;(message "verilog-modi-lookup: %s" module)
9622 (cond ((and verilog-modi-lookup-cache
6341f357
DN
9623 verilog-cache-enabled
9624 allow-cache
a03c2342 9625 (setq modi (gethash module verilog-modi-lookup-cache))
6341f357 9626 (equal verilog-modi-lookup-last-current current)
a03c2342
WS
9627 ;; Iff hit is in current buffer, then tick must match
9628 (or (equal verilog-modi-lookup-last-tick (buffer-chars-modified-tick))
9629 (not (equal current (verilog-modi-file-or-buffer modi)))))
9630 ;;(message "verilog-modi-lookup: HIT %S" modi)
9631 modi)
9632 ;; Miss
179f044b
WS
9633 (t (let* ((realname (verilog-symbol-detick module t))
9634 (orig-filenames (verilog-module-filenames realname current))
6341f357 9635 (filenames orig-filenames)
a03c2342
WS
9636 mif)
9637 (while (and filenames (not mif))
179f044b 9638 (if (not (setq mif (verilog-module-inside-filename-p realname (car filenames))))
6341f357 9639 (setq filenames (cdr filenames))))
a03c2342
WS
9640 ;; mif has correct form to become later elements of modi
9641 (cond (mif (setq modi mif))
9642 (t (setq modi nil)
6341f357
DN
9643 (or ignore-error
9644 (error (concat (verilog-point-text)
9645 ": Can't locate " module " module definition"
179f044b
WS
9646 (if (not (equal module realname))
9647 (concat " (Expanded macro to " realname ")")
6341f357
DN
9648 "")
9649 "\n Check the verilog-library-directories variable."
9650 "\n I looked in (if not listed, doesn't exist):\n\t"
60618039 9651 (mapconcat 'concat orig-filenames "\n\t"))))))
a03c2342
WS
9652 (when (eval-when-compile (fboundp 'make-hash-table))
9653 (unless verilog-modi-lookup-cache
9654 (setq verilog-modi-lookup-cache
9655 (make-hash-table :test 'equal :rehash-size 4.0)))
9656 (puthash module modi verilog-modi-lookup-cache))
9657 (setq verilog-modi-lookup-last-current current
9658 verilog-modi-lookup-last-tick (buffer-chars-modified-tick)))))
9659 modi))
6341f357
DN
9660
9661(defun verilog-modi-filename (modi)
37ea4b9b 9662 "Filename of MODI, or name of buffer if it's never been saved."
6341f357
DN
9663 (if (bufferp (verilog-modi-file-or-buffer modi))
9664 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
9665 (buffer-name (verilog-modi-file-or-buffer modi)))
9666 (verilog-modi-file-or-buffer modi)))
9667
9668(defun verilog-modi-goto (modi)
9669 "Move point/buffer to specified MODI."
9670 (or modi (error "Passed unfound modi to goto, check earlier"))
9671 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
9672 (verilog-modi-file-or-buffer modi)
9673 (find-file-noselect (verilog-modi-file-or-buffer modi))))
37ea4b9b 9674 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
6341f357 9675 (verilog-mode))
a03c2342 9676 (goto-char (verilog-modi-get-point modi)))
6341f357
DN
9677
9678(defun verilog-goto-defun-file (module)
9679 "Move point to the file at which a given MODULE is defined."
9680 (interactive "sGoto File for Module: ")
9681 (let* ((modi (verilog-modi-lookup module nil)))
9682 (when modi
9683 (verilog-modi-goto modi)
9684 (switch-to-buffer (current-buffer)))))
9685
9686(defun verilog-modi-cache-results (modi function)
9687 "Run on MODI the given FUNCTION. Locate the module in a file.
9688Cache the output of function so next call may have faster access."
5509c6ad
DN
9689 (let (fass)
9690 (save-excursion ;; Cache is buffer-local so can't avoid this.
6341f357 9691 (verilog-modi-goto modi)
5509c6ad 9692 (if (and (setq fass (assoc (list modi function)
6341f357
DN
9693 verilog-modi-cache-list))
9694 ;; Destroy caching when incorrect; Modified or file changed
9695 (not (and verilog-cache-enabled
a03c2342 9696 (or (equal (buffer-chars-modified-tick) (nth 1 fass))
6341f357
DN
9697 (and verilog-modi-cache-preserve-tick
9698 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
9699 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
9700 (equal (visited-file-modtime) (nth 2 fass)))))
9701 (setq verilog-modi-cache-list nil
9702 fass nil))
9703 (cond (fass
5509c6ad
DN
9704 ;; Return data from cache hit
9705 (nth 3 fass))
6341f357
DN
9706 (t
9707 ;; Read from file
86a4c7ac 9708 ;; Clear then restore any highlighting to make emacs19 happy
47086495
WS
9709 (let (func-returns)
9710 (verilog-save-font-mods
9711 (setq func-returns (funcall function)))
9c059794
DN
9712 ;; Cache for next time
9713 (setq verilog-modi-cache-list
5509c6ad 9714 (cons (list (list modi function)
a03c2342 9715 (buffer-chars-modified-tick)
9c059794
DN
9716 (visited-file-modtime)
9717 func-returns)
5509c6ad
DN
9718 verilog-modi-cache-list))
9719 func-returns))))))
6341f357
DN
9720
9721(defun verilog-modi-cache-add (modi function element sig-list)
9722 "Add function return results to the module cache.
9723Update MODI's cache for given FUNCTION so that the return ELEMENT of that
9724function now contains the additional SIG-LIST parameters."
9725 (let (fass)
9726 (save-excursion
9727 (verilog-modi-goto modi)
5509c6ad 9728 (if (setq fass (assoc (list modi function)
6341f357
DN
9729 verilog-modi-cache-list))
9730 (let ((func-returns (nth 3 fass)))
9731 (aset func-returns element
9732 (append sig-list (aref func-returns element))))))))
9733
5509c6ad 9734(defmacro verilog-preserve-modi-cache (&rest body)
6341f357
DN
9735 "Execute the BODY forms, allowing cache preservation within BODY.
9736This means that changes to the buffer will not result in the cache being
9737flushed. If the changes affect the modsig state, they must call the
9738modsig-cache-add-* function, else the results of later calls may be
9739incorrect. Without this, changes are assumed to be adding/removing signals
9740and invalidating the cache."
a03c2342 9741 `(let ((verilog-modi-cache-preserve-tick (buffer-chars-modified-tick))
6341f357
DN
9742 (verilog-modi-cache-preserve-buffer (current-buffer)))
9743 (progn ,@body)))
9744
6341f357 9745
179f044b
WS
9746(defun verilog-modi-modport-lookup-one (modi name &optional ignore-error)
9747 "Given a MODI, return the declarations related to the given modport NAME."
9748 ;; Recursive routine - see below
9749 (let* ((realname (verilog-symbol-detick name t))
9750 (modport (assoc name (verilog-decls-get-modports (verilog-modi-get-decls modi)))))
9751 (or modport ignore-error
9752 (error (concat (verilog-point-text)
9753 ": Can't locate " name " modport definition"
9754 (if (not (equal name realname))
9755 (concat " (Expanded macro to " realname ")")
9756 ""))))
9757 (let* ((decls (verilog-modport-decls modport))
9758 (clks (verilog-modport-clockings modport)))
9759 ;; Now expand any clocking's
9760 (while clks
9761 (setq decls (verilog-decls-append
9762 decls
9763 (verilog-modi-modport-lookup-one modi (car clks) ignore-error)))
9764 (setq clks (cdr clks)))
9765 decls)))
9766
9767(defun verilog-modi-modport-lookup (modi name-re &optional ignore-error)
9768 "Given a MODI, return the declarations related to the given modport NAME-RE.
9769If the modport points to any clocking blocks, expand the signals to include
9770those clocking block's signals."
9771 ;; Recursive routine - see below
9772 (let* ((mod-decls (verilog-modi-get-decls modi))
9773 (clks (verilog-decls-get-modports mod-decls))
9774 (name-re (concat "^" name-re "$"))
9775 (decls (verilog-decls-new nil nil nil nil nil nil nil nil nil)))
9776 ;; Pull in all modports
9777 (while clks
9778 (when (string-match name-re (verilog-modport-name (car clks)))
9779 (setq decls (verilog-decls-append
9780 decls
9781 (verilog-modi-modport-lookup-one modi (verilog-modport-name (car clks)) ignore-error))))
9782 (setq clks (cdr clks)))
9783 decls))
9784
6341f357
DN
9785(defun verilog-signals-matching-enum (in-list enum)
9786 "Return all signals in IN-LIST matching the given ENUM."
9787 (let (out-list)
9788 (while in-list
9789 (if (equal (verilog-sig-enum (car in-list)) enum)
9790 (setq out-list (cons (car in-list) out-list)))
9791 (setq in-list (cdr in-list)))
9792 ;; New scheme
0f137a73 9793 ;; Namespace intentionally short for AUTOs and compatibility
6341f357
DN
9794 (let* ((enumvar (intern (concat "venum-" enum)))
9795 (enumlist (and (boundp enumvar) (eval enumvar))))
9796 (while enumlist
9797 (add-to-list 'out-list (list (car enumlist)))
9798 (setq enumlist (cdr enumlist))))
9799 (nreverse out-list)))
9800
e2076c2c
DN
9801(defun verilog-signals-matching-regexp (in-list regexp)
9802 "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
a3a8b002 9803 (if (or (not regexp) (equal regexp ""))
e2076c2c 9804 in-list
ea89ff08
WS
9805 (let ((case-fold-search verilog-case-fold)
9806 out-list)
e2076c2c
DN
9807 (while in-list
9808 (if (string-match regexp (verilog-sig-name (car in-list)))
9809 (setq out-list (cons (car in-list) out-list)))
9810 (setq in-list (cdr in-list)))
9811 (nreverse out-list))))
9812
6341f357
DN
9813(defun verilog-signals-not-matching-regexp (in-list regexp)
9814 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
a3a8b002 9815 (if (or (not regexp) (equal regexp ""))
6341f357 9816 in-list
ea89ff08
WS
9817 (let ((case-fold-search verilog-case-fold)
9818 out-list)
6341f357
DN
9819 (while in-list
9820 (if (not (string-match regexp (verilog-sig-name (car in-list))))
9821 (setq out-list (cons (car in-list) out-list)))
9822 (setq in-list (cdr in-list)))
9823 (nreverse out-list))))
9824
a3a8b002 9825(defun verilog-signals-matching-dir-re (in-list decl-type regexp)
0e5c8aed 9826 "Return all signals in IN-LIST matching the given DECL-TYPE and REGEXP,
a3a8b002
DN
9827if non-nil."
9828 (if (or (not regexp) (equal regexp ""))
9829 in-list
9830 (let (out-list to-match)
9831 (while in-list
9832 ;; Note verilog-insert-one-definition matches on this order
9833 (setq to-match (concat
9834 decl-type
9835 " " (verilog-sig-signed (car in-list))
9836 " " (verilog-sig-multidim (car in-list))
9837 (verilog-sig-bits (car in-list))))
9838 (if (string-match regexp to-match)
9839 (setq out-list (cons (car in-list) out-list)))
9840 (setq in-list (cdr in-list)))
9841 (nreverse out-list))))
9842
47086495
WS
9843(defun verilog-signals-edit-wire-reg (in-list)
9844 "Return all signals in IN-LIST with wire/reg data types made blank."
9845 (mapcar (lambda (sig)
9846 (when (member (verilog-sig-type sig) '("wire" "reg"))
9847 (verilog-sig-type-set sig nil))
9848 sig) in-list))
9849
6341f357 9850;; Combined
5509c6ad 9851(defun verilog-decls-get-signals (decls)
47086495 9852 "Return all declared signals in DECLS, excluding 'assign' statements."
6341f357 9853 (append
5509c6ad
DN
9854 (verilog-decls-get-outputs decls)
9855 (verilog-decls-get-inouts decls)
9856 (verilog-decls-get-inputs decls)
9489a450 9857 (verilog-decls-get-vars decls)
5509c6ad
DN
9858 (verilog-decls-get-consts decls)
9859 (verilog-decls-get-gparams decls)))
9860
9861(defun verilog-decls-get-ports (decls)
6341f357 9862 (append
5509c6ad
DN
9863 (verilog-decls-get-outputs decls)
9864 (verilog-decls-get-inouts decls)
9865 (verilog-decls-get-inputs decls)))
6341f357 9866
179f044b
WS
9867(defun verilog-decls-get-iovars (decls)
9868 (append
9869 (verilog-decls-get-vars decls)
9870 (verilog-decls-get-outputs decls)
9871 (verilog-decls-get-inouts decls)
9872 (verilog-decls-get-inputs decls)))
9873
6341f357
DN
9874(defsubst verilog-modi-cache-add-outputs (modi sig-list)
9875 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
9876(defsubst verilog-modi-cache-add-inouts (modi sig-list)
9877 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
9878(defsubst verilog-modi-cache-add-inputs (modi sig-list)
9879 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
9489a450 9880(defsubst verilog-modi-cache-add-vars (modi sig-list)
6341f357 9881 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
179f044b
WS
9882(defsubst verilog-modi-cache-add-gparams (modi sig-list)
9883 (verilog-modi-cache-add modi 'verilog-read-decls 7 sig-list))
6341f357 9884
6341f357
DN
9885\f
9886;;
9887;; Auto creation utilities
9888;;
9889
495ab0d5
DN
9890(defun verilog-auto-re-search-do (search-for func)
9891 "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
6341f357 9892 (goto-char (point-min))
9489a450 9893 (while (verilog-re-search-forward-quick search-for nil t)
495ab0d5 9894 (funcall func)))
6341f357 9895
6341f357 9896(defun verilog-insert-one-definition (sig type indent-pt)
60618039 9897 "Print out a definition for SIG of the given TYPE,
6341f357
DN
9898with appropriate INDENT-PT indentation."
9899 (indent-to indent-pt)
a3a8b002 9900 ;; Note verilog-signals-matching-dir-re matches on this order
6341f357 9901 (insert type)
a3a8b002
DN
9902 (when (verilog-sig-modport sig)
9903 (insert "." (verilog-sig-modport sig)))
6341f357
DN
9904 (when (verilog-sig-signed sig)
9905 (insert " " (verilog-sig-signed sig)))
9906 (when (verilog-sig-multidim sig)
9907 (insert " " (verilog-sig-multidim-string sig)))
9908 (when (verilog-sig-bits sig)
9909 (insert " " (verilog-sig-bits sig)))
9910 (indent-to (max 24 (+ indent-pt 16)))
9911 (unless (= (char-syntax (preceding-char)) ?\ )
9912 (insert " ")) ; Need space between "]name" if indent-to did nothing
8468f78b
WS
9913 (insert (verilog-sig-name sig))
9914 (when (verilog-sig-memory sig)
9915 (insert " " (verilog-sig-memory sig))))
6341f357 9916
9489a450
MM
9917(defun verilog-insert-definition (modi sigs direction indent-pt v2k &optional dont-sort)
9918 "Print out a definition for MODI's list of SIGS of the given DIRECTION,
6341f357 9919with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
9489a450
MM
9920format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output.
9921When MODI is non-null, also add to modi-cache, for tracking."
9922 (when modi
9923 (cond ((equal direction "wire")
9924 (verilog-modi-cache-add-vars modi sigs))
9925 ((equal direction "reg")
9926 (verilog-modi-cache-add-vars modi sigs))
9927 ((equal direction "output")
9928 (verilog-modi-cache-add-outputs modi sigs)
9929 (when verilog-auto-declare-nettype
9930 (verilog-modi-cache-add-vars modi sigs)))
9931 ((equal direction "input")
9932 (verilog-modi-cache-add-inputs modi sigs)
9933 (when verilog-auto-declare-nettype
9934 (verilog-modi-cache-add-vars modi sigs)))
9935 ((equal direction "inout")
9936 (verilog-modi-cache-add-inouts modi sigs)
9937 (when verilog-auto-declare-nettype
9938 (verilog-modi-cache-add-vars modi sigs)))
9939 ((equal direction "interface"))
179f044b
WS
9940 ((equal direction "parameter")
9941 (verilog-modi-cache-add-gparams modi sigs))
9489a450
MM
9942 (t
9943 (error "Unsupported verilog-insert-definition direction: %s" direction))))
6341f357
DN
9944 (or dont-sort
9945 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
9946 (while sigs
9947 (let ((sig (car sigs)))
9948 (verilog-insert-one-definition
9949 sig
9950 ;; Want "type x" or "output type x", not "wire type x"
9489a450
MM
9951 (cond ((or (verilog-sig-type sig)
9952 verilog-auto-wire-type)
6341f357 9953 (concat
9489a450
MM
9954 (when (member direction '("input" "output" "inout"))
9955 (concat direction " "))
9956 (or (verilog-sig-type sig)
9957 verilog-auto-wire-type)))
9958 ((and verilog-auto-declare-nettype
9959 (member direction '("input" "output" "inout")))
9960 (concat direction " " verilog-auto-declare-nettype))
9961 (t
9962 direction))
6341f357
DN
9963 indent-pt)
9964 (insert (if v2k "," ";"))
9965 (if (or (not (verilog-sig-comment sig))
9966 (equal "" (verilog-sig-comment sig)))
9967 (insert "\n")
9968 (indent-to (max 48 (+ indent-pt 40)))
a03c2342 9969 (verilog-insert "// " (verilog-sig-comment sig) "\n"))
6341f357
DN
9970 (setq sigs (cdr sigs)))))
9971
9972(eval-when-compile
9973 (if (not (boundp 'indent-pt))
9974 (defvar indent-pt nil "Local used by insert-indent")))
9975
9976(defun verilog-insert-indent (&rest stuff)
9977 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
9978Presumes that any newlines end a list element."
9979 (let ((need-indent t))
9980 (while stuff
9981 (if need-indent (indent-to indent-pt))
9982 (setq need-indent nil)
a03c2342 9983 (verilog-insert (car stuff))
6341f357
DN
9984 (setq need-indent (string-match "\n$" (car stuff))
9985 stuff (cdr stuff)))))
9986;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
9987
179f044b
WS
9988(defun verilog-forward-or-insert-line ()
9989 "Move forward a line, unless at EOB, then insert a newline."
9990 (if (eobp) (insert "\n")
9991 (forward-line)))
9992
6341f357 9993(defun verilog-repair-open-comma ()
47086495 9994 "Insert comma if previous argument is other than an open parenthesis or endif."
a3a8b002
DN
9995 ;; We can't just search backward for ) as it might be inside another expression.
9996 ;; Also want "`ifdef X input foo `endif" to just leave things to the human to deal with
6341f357 9997 (save-excursion
9489a450 9998 (verilog-backward-syntactic-ws-quick)
a3a8b002
DN
9999 (when (and (not (save-excursion ;; Not beginning (, or existing ,
10000 (backward-char 1)
10001 (looking-at "[(,]")))
10002 (not (save-excursion ;; Not `endif, or user define
10003 (backward-char 1)
10004 (skip-chars-backward "[a-zA-Z0-9_`]")
10005 (looking-at "`"))))
10006 (insert ","))))
6341f357
DN
10007
10008(defun verilog-repair-close-comma ()
10009 "If point is at a comma followed by a close parenthesis, fix it.
47086495 10010This repairs those mis-inserted by an AUTOARG."
6341f357
DN
10011 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
10012 (save-excursion
10013 (verilog-forward-close-paren)
10014 (backward-char 1)
9489a450 10015 (verilog-backward-syntactic-ws-quick)
6341f357
DN
10016 (backward-char 1)
10017 (when (looking-at ",")
10018 (delete-char 1))))
10019
6341f357
DN
10020(defun verilog-make-width-expression (range-exp)
10021 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
10022 ;; strip off the []
10023 (cond ((not range-exp)
10024 "1")
10025 (t
10026 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
10027 (setq range-exp (match-string 1 range-exp)))
10028 (cond ((not range-exp)
10029 "1")
a3a8b002 10030 ;; [#:#] We can compute a numeric result
7ea26faf
DN
10031 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
10032 range-exp)
10033 (int-to-string
10034 (1+ (abs (- (string-to-number (match-string 1 range-exp))
10035 (string-to-number (match-string 2 range-exp)))))))
a3a8b002
DN
10036 ;; [PARAM-1:0] can just return PARAM
10037 ((string-match "^\\s *\\([a-zA-Z_][a-zA-Z0-9_]*\\)\\s *-\\s *1\\s *:\\s *0\\s *$" range-exp)
10038 (match-string 1 range-exp))
10039 ;; [arbitrary] need math
6341f357 10040 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
7ea26faf 10041 (concat "(1+(" (match-string 1 range-exp) ")"
60618039
DN
10042 (if (equal "0" (match-string 2 range-exp))
10043 "" ;; Don't bother with -(0)
6341f357
DN
10044 (concat "-(" (match-string 2 range-exp) ")"))
10045 ")"))
10046 (t nil)))))
10047;;(verilog-make-width-expression "`A:`B")
10048
9489a450
MM
10049(defun verilog-simplify-range-expression (expr)
10050 "Return a simplified range expression with constants eliminated from EXPR."
10051 ;; Note this is always called with brackets; ie [z] or [z:z]
10052 (if (not (string-match "[---+*()]" expr))
10053 expr ;; short-circuit
10054 (let ((out expr)
10055 (last-pass ""))
10056 (while (not (equal last-pass out))
10057 (setq last-pass out)
10058 ;; Prefix regexp needs beginning of match, or some symbol of
10059 ;; lesser or equal precedence. We assume the [:]'s exist in expr.
10060 ;; Ditto the end.
10061 (while (string-match
10062 (concat "\\([[({:*+-]\\)" ; - must be last
10063 "(\\<\\([0-9A-Za-z_]+\\))"
10064 "\\([])}:*+-]\\)")
10065 out)
10066 (setq out (replace-match "\\1\\2\\3" nil nil out)))
179f044b
WS
10067 (while (string-match
10068 (concat "\\([[({:*+-]\\)" ; - must be last
10069 "\\$clog2\\s *(\\<\\([0-9]+\\))"
10070 "\\([])}:*+-]\\)")
10071 out)
10072 (setq out (replace-match
10073 (concat
10074 (match-string 1 out)
10075 (int-to-string (verilog-clog2 (string-to-number (match-string 2 out))))
10076 (match-string 3 out))
10077 nil nil out)))
9489a450
MM
10078 ;; For precedence do * before +/-
10079 (while (string-match
10080 (concat "\\([[({:*+-]\\)"
10081 "\\([0-9]+\\)\\s *\\([*]\\)\\s *\\([0-9]+\\)"
10082 "\\([])}:*+-]\\)")
10083 out)
10084 (setq out (replace-match
10085 (concat (match-string 1 out)
10086 (int-to-string (* (string-to-number (match-string 2 out))
10087 (string-to-number (match-string 4 out))))
10088 (match-string 5 out))
10089 nil nil out)))
10090 (while (string-match
10091 (concat "\\([[({:+-]\\)" ; No * here as higher prec
10092 "\\([0-9]+\\)\\s *\\([---+]\\)\\s *\\([0-9]+\\)"
10093 "\\([])}:+-]\\)")
10094 out)
10095 (let ((pre (match-string 1 out))
10096 (lhs (string-to-number (match-string 2 out)))
10097 (rhs (string-to-number (match-string 4 out)))
10098 (post (match-string 5 out))
10099 val)
10100 (when (equal pre "-")
10101 (setq lhs (- lhs)))
10102 (setq val (if (equal (match-string 3 out) "-")
10103 (- lhs rhs)
10104 (+ lhs rhs))
10105 out (replace-match
10106 (concat (if (and (equal pre "-")
10107 (< val 0))
10108 "" ;; Not "--20" but just "-20"
10109 pre)
10110 (int-to-string val)
10111 post)
10112 nil nil out)) )))
10113 out)))
179f044b 10114
9489a450
MM
10115;;(verilog-simplify-range-expression "[1:3]") ;; 1
10116;;(verilog-simplify-range-expression "[(1):3]") ;; 1
10117;;(verilog-simplify-range-expression "[(((16)+1)+1+(1+1))]") ;;20
10118;;(verilog-simplify-range-expression "[(2*3+6*7)]") ;; 48
10119;;(verilog-simplify-range-expression "[(FOO*4-1*2)]") ;; FOO*4-2
10120;;(verilog-simplify-range-expression "[(FOO*4+1-1)]") ;; FOO*4+0
10121;;(verilog-simplify-range-expression "[(func(BAR))]") ;; func(BAR)
10122;;(verilog-simplify-range-expression "[FOO-1+1-1+1]") ;; FOO-0
179f044b
WS
10123;;(verilog-simplify-range-expression "[$clog2(2)]") ;; 1
10124;;(verilog-simplify-range-expression "[$clog2(7)]") ;; 3
10125
10126(defun verilog-clog2 (value)
10127 "Compute $clog2 - ceiling log2 of VALUE."
10128 (if (< value 1)
10129 0
10130 (ceiling (/ (log value) (log 2)))))
4c5e69c6 10131
6341f357
DN
10132(defun verilog-typedef-name-p (variable-name)
10133 "Return true if the VARIABLE-NAME is a type definition."
10134 (when verilog-typedef-regexp
ea89ff08 10135 (verilog-string-match-fold verilog-typedef-regexp variable-name)))
6341f357
DN
10136\f
10137;;
10138;; Auto deletion
10139;;
10140
10141(defun verilog-delete-autos-lined ()
10142 "Delete autos that occupy multiple lines, between begin and end comments."
9489a450
MM
10143 ;; The newline must not have a comment property, so we must
10144 ;; delete the end auto's newline, not the first newline
10145 (forward-line 1)
6341f357 10146 (let ((pt (point)))
6341f357
DN
10147 (when (and
10148 (looking-at "\\s-*// Beginning")
10149 (search-forward "// End of automatic" nil t))
10150 ;; End exists
10151 (end-of-line)
9489a450
MM
10152 (forward-line 1)
10153 (delete-region pt (point)))))
6341f357 10154
0e5c8aed
DN
10155(defun verilog-delete-empty-auto-pair ()
10156 "Delete begin/end auto pair at point, if empty."
10157 (forward-line 0)
10158 (when (looking-at (concat "\\s-*// Beginning of automatic.*\n"
10159 "\\s-*// End of automatics\n"))
10160 (delete-region (point) (save-excursion (forward-line 2) (point)))))
10161
6341f357 10162(defun verilog-forward-close-paren ()
37ea4b9b
JB
10163 "Find the close parenthesis that match the current point.
10164Ignore other close parenthesis with matching open parens."
6341f357
DN
10165 (let ((parens 1))
10166 (while (> parens 0)
10167 (unless (verilog-re-search-forward-quick "[()]" nil t)
10168 (error "%s: Mismatching ()" (verilog-point-text)))
10169 (cond ((= (preceding-char) ?\( )
10170 (setq parens (1+ parens)))
10171 ((= (preceding-char) ?\) )
10172 (setq parens (1- parens)))))))
10173
10174(defun verilog-backward-open-paren ()
37ea4b9b
JB
10175 "Find the open parenthesis that match the current point.
10176Ignore other open parenthesis with matching close parens."
6341f357
DN
10177 (let ((parens 1))
10178 (while (> parens 0)
10179 (unless (verilog-re-search-backward-quick "[()]" nil t)
10180 (error "%s: Mismatching ()" (verilog-point-text)))
10181 (cond ((= (following-char) ?\) )
10182 (setq parens (1+ parens)))
10183 ((= (following-char) ?\( )
10184 (setq parens (1- parens)))))))
10185
10186(defun verilog-backward-open-bracket ()
37ea4b9b
JB
10187 "Find the open bracket that match the current point.
10188Ignore other open bracket with matching close bracket."
6341f357
DN
10189 (let ((parens 1))
10190 (while (> parens 0)
10191 (unless (verilog-re-search-backward-quick "[][]" nil t)
10192 (error "%s: Mismatching []" (verilog-point-text)))
10193 (cond ((= (following-char) ?\] )
10194 (setq parens (1+ parens)))
10195 ((= (following-char) ?\[ )
10196 (setq parens (1- parens)))))))
10197
10198(defun verilog-delete-to-paren ()
10199 "Delete the automatic inst/sense/arg created by autos.
9489a450 10200Deletion stops at the matching end parenthesis, outside comments."
6341f357
DN
10201 (delete-region (point)
10202 (save-excursion
10203 (verilog-backward-open-paren)
9489a450 10204 (verilog-forward-sexp-ign-cmt 1) ;; Moves to paren that closes argdecl's
6341f357
DN
10205 (backward-char 1)
10206 (point))))
10207
10208(defun verilog-auto-star-safe ()
10209 "Return if a .* AUTOINST is safe to delete or expand.
10210It was created by the AUTOS themselves, or by the user."
10211 (and verilog-auto-star-expand
9489a450
MM
10212 (looking-at
10213 (concat "[ \t\n\f,]*\\([)]\\|// " verilog-inst-comment-re "\\)"))))
6341f357
DN
10214
10215(defun verilog-delete-auto-star-all ()
10216 "Delete a .* AUTOINST, if it is safe."
10217 (when (verilog-auto-star-safe)
10218 (verilog-delete-to-paren)))
10219
10220(defun verilog-delete-auto-star-implicit ()
10221 "Delete all .* implicit connections created by `verilog-auto-star'.
10222This function will be called automatically at save unless
10223`verilog-auto-star-save' is set, any non-templated expanded pins will be
10224removed."
10225 (interactive)
10226 (let (paren-pt indent have-close-paren)
10227 (save-excursion
10228 (goto-char (point-min))
10229 ;; We need to match these even outside of comments.
10230 ;; For reasonable performance, we don't check if inside comments, sorry.
10231 (while (re-search-forward "// Implicit \\.\\*" nil t)
10232 (setq paren-pt (point))
10233 (beginning-of-line)
10234 (setq have-close-paren
10235 (save-excursion
10236 (when (search-forward ");" paren-pt t)
10237 (setq indent (current-indentation))
10238 t)))
10239 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
10240 (when have-close-paren
10241 ;; Delete extra commentary
10242 (save-excursion
10243 (while (progn
10244 (forward-line -1)
9489a450 10245 (looking-at (concat "\\s *//\\s *" verilog-inst-comment-re "\n")))
6341f357
DN
10246 (delete-region (match-beginning 0) (match-end 0))))
10247 ;; If it is simple, we can put the ); on the same line as the last text
10248 (let ((rtn-pt (point)))
10249 (save-excursion
10250 (while (progn (backward-char 1)
10251 (looking-at "[ \t\n\f]")))
10252 (when (looking-at ",")
10253 (delete-region (+ 1 (point)) rtn-pt))))
10254 (when (bolp)
10255 (indent-to indent))
10256 (insert ");\n")
10257 ;; Still need to kill final comma - always is one as we put one after the .*
10258 (re-search-backward ",")
10259 (delete-char 1))))))
10260
10261(defun verilog-delete-auto ()
10262 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
10263Use \\[verilog-auto] to re-insert the updated AUTOs.
10264
10265The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
10266called before and after this function, respectively."
10267 (interactive)
10268 (save-excursion
10269 (if (buffer-file-name)
10270 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
a03c2342
WS
10271 (verilog-save-no-change-functions
10272 (verilog-save-scan-cache
10273 ;; Allow user to customize
9489a450 10274 (verilog-run-hooks 'verilog-before-delete-auto-hook)
a03c2342
WS
10275
10276 ;; Remove those that have multi-line insertions, possibly with parameters
9489a450
MM
10277 ;; We allow anything beginning with AUTO, so that users can add their own
10278 ;; patterns
a03c2342 10279 (verilog-auto-re-search-do
9489a450 10280 (concat "/\\*AUTO[A-Za-z0-9_]+"
a03c2342
WS
10281 ;; Optional parens or quoted parameter or .* for (((...)))
10282 "\\(\\|([^)]*)\\|(\"[^\"]*\")\\).*?"
10283 "\\*/")
10284 'verilog-delete-autos-lined)
10285 ;; Remove those that are in parenthesis
10286 (verilog-auto-re-search-do
10287 (concat "/\\*"
10288 (eval-when-compile
10289 (verilog-regexp-words
10290 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
10291 "AUTOSENSE")))
10292 "\\*/")
10293 'verilog-delete-to-paren)
10294 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
10295 (verilog-auto-re-search-do "\\.\\*"
10296 'verilog-delete-auto-star-all)
10297 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
10298 (goto-char (point-min))
9489a450 10299 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)\\([ \tLT0-9]*\\| LHS: .*\\)?$" nil t)
a03c2342 10300 (replace-match ""))
6341f357 10301
a03c2342 10302 ;; Final customize
9489a450 10303 (verilog-run-hooks 'verilog-delete-auto-hook)))))
6341f357
DN
10304\f
10305;;
10306;; Auto inject
10307;;
10308
10309(defun verilog-inject-auto ()
10310 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
10311
10312Any always @ blocks with sensitivity lists that match computed lists will
10313be replaced with /*AS*/ comments.
10314
37ea4b9b
JB
10315Any cells will get /*AUTOINST*/ added to the end of the pin list.
10316Pins with have identical names will be deleted.
6341f357
DN
10317
10318Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
10319support adding new ports. You may wish to delete older ports yourself.
10320
10321For example:
10322
1dd4b004 10323 module ExampInject (i, o);
6341f357
DN
10324 input i;
10325 input j;
10326 output o;
10327 always @ (i or j)
10328 o = i | j;
1dd4b004
DN
10329 InstModule instName
10330 (.foobar(baz),
10331 j(j));
6341f357
DN
10332 endmodule
10333
10334Typing \\[verilog-inject-auto] will make this into:
10335
1dd4b004 10336 module ExampInject (i, o/*AUTOARG*/
6341f357
DN
10337 // Inputs
10338 j);
10339 input i;
10340 output o;
10341 always @ (/*AS*/i or j)
10342 o = i | j;
1dd4b004
DN
10343 InstModule instName
10344 (.foobar(baz),
10345 /*AUTOINST*/
10346 // Outputs
10347 j(j));
6341f357
DN
10348 endmodule"
10349 (interactive)
10350 (verilog-auto t))
10351
10352(defun verilog-inject-arg ()
10353 "Inject AUTOARG into new code. See `verilog-inject-auto'."
10354 ;; Presume one module per file.
10355 (save-excursion
10356 (goto-char (point-min))
10357 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
10358 (let ((endmodp (save-excursion
10359 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
10360 (point))))
10361 ;; See if there's already a comment .. inside a comment so not verilog-re-search
10362 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
10363 (verilog-re-search-forward-quick ";" nil t)
10364 (backward-char 1)
9489a450 10365 (verilog-backward-syntactic-ws-quick)
6341f357
DN
10366 (backward-char 1) ; Moves to paren that closes argdecl's
10367 (when (looking-at ")")
a03c2342 10368 (verilog-insert "/*AUTOARG*/")))))))
6341f357
DN
10369
10370(defun verilog-inject-sense ()
10371 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
10372 (save-excursion
10373 (goto-char (point-min))
10374 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
5509c6ad 10375 (let* ((start-pt (point))
9c059794 10376 (modi (verilog-modi-current))
5509c6ad 10377 (moddecls (verilog-modi-get-decls modi))
9c059794
DN
10378 pre-sigs
10379 got-sigs)
6341f357 10380 (backward-char 1)
9489a450 10381 (verilog-forward-sexp-ign-cmt 1)
6341f357 10382 (backward-char 1) ;; End )
9489a450 10383 (when (not (verilog-re-search-backward-quick "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
6341f357
DN
10384 (setq pre-sigs (verilog-signals-from-signame
10385 (verilog-read-signals start-pt (point)))
5509c6ad 10386 got-sigs (verilog-auto-sense-sigs moddecls nil))
6341f357
DN
10387 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
10388 (verilog-signals-not-in got-sigs pre-sigs)))
10389 (delete-region start-pt (point))
a03c2342 10390 (verilog-insert "/*AS*/")))))))
6341f357
DN
10391
10392(defun verilog-inject-inst ()
10393 "Inject AUTOINST into new code. See `verilog-inject-auto'."
10394 (save-excursion
10395 (goto-char (point-min))
10396 ;; It's hard to distinguish modules; we'll instead search for pins.
10397 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
10398 (verilog-backward-open-paren) ;; Inst start
10399 (cond
10400 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
10401 (forward-char 1)
10402 (verilog-forward-close-paren)) ;; Parameters done
10403 (t
10404 (forward-char 1)
10405 (let ((indent-pt (+ (current-column)))
10406 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
9489a450 10407 (cond ((verilog-re-search-forward-quick "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
6341f357
DN
10408 (goto-char end-pt)) ;; Already there, continue search with next instance
10409 (t
10410 ;; Delete identical interconnect
10411 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
9489a450 10412 (while (verilog-re-search-forward-quick "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
6341f357
DN
10413 (delete-region (match-beginning 0) (match-end 0))
10414 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
10415 (while (or (looking-at "[ \t\n\f,]+")
10416 (looking-at "//[^\n]*"))
10417 (delete-region (match-beginning 0) (match-end 0))
10418 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
10419 (verilog-forward-close-paren)
10420 (backward-char 1)
10421 ;; Not verilog-re-search, as we don't want to strip comments
10422 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
10423 (delete-region (match-beginning 0) (match-end 0)))
a03c2342
WS
10424 (verilog-insert "\n")
10425 (verilog-insert-indent "/*AUTOINST*/")))))))))
6341f357 10426\f
9489a450
MM
10427;;
10428;; Auto diff
10429;;
10430
10431(defun verilog-diff-buffers-p (b1 b2 &optional whitespace)
10432 "Return nil if buffers B1 and B2 have same contents.
10433Else, return point in B1 that first mismatches.
10434If optional WHITESPACE true, ignore whitespace."
10435 (save-excursion
10436 (let* ((case-fold-search nil) ;; compare-buffer-substrings cares
10437 (p1 (with-current-buffer b1 (goto-char (point-min))))
10438 (p2 (with-current-buffer b2 (goto-char (point-min))))
10439 (maxp1 (with-current-buffer b1 (point-max)))
10440 (maxp2 (with-current-buffer b2 (point-max)))
301b181a 10441 (op1 -1) (op2 -1)
9489a450
MM
10442 progress size)
10443 (while (not (and (eq p1 op1) (eq p2 op2)))
10444 ;; If both windows have whitespace optionally skip over it.
10445 (when whitespace
10446 ;; skip-syntax-* doesn't count \n
10447 (with-current-buffer b1
10448 (goto-char p1)
10449 (skip-chars-forward " \t\n\r\f\v")
10450 (setq p1 (point)))
10451 (with-current-buffer b2
10452 (goto-char p2)
10453 (skip-chars-forward " \t\n\r\f\v")
10454 (setq p2 (point))))
10455 (setq size (min (- maxp1 p1) (- maxp2 p2)))
10456 (setq progress (compare-buffer-substrings b2 p2 (+ size p2)
10457 b1 p1 (+ size p1)))
10458 (setq progress (if (zerop progress) size (1- (abs progress))))
10459 (setq op1 p1 op2 p2
10460 p1 (+ p1 progress)
10461 p2 (+ p2 progress)))
10462 ;; Return value
10463 (if (and (eq p1 maxp1) (eq p2 maxp2))
10464 nil p1))))
10465
10466(defun verilog-diff-file-with-buffer (f1 b2 &optional whitespace show)
10467 "View the differences between file F1 and buffer B2.
10468This requires the external program `diff-command' to be in your `exec-path',
10469and uses `diff-switches' in which you may want to have \"-u\" flag.
10470Ignores WHITESPACE if t, and writes output to stdout if SHOW."
10471 ;; Similar to `diff-buffer-with-file' but works on XEmacs, and doesn't
10472 ;; call `diff' as `diff' has different calling semantics on different
10473 ;; versions of Emacs.
10474 (if (not (file-exists-p f1))
10475 (message "Buffer %s has no associated file on disc" (buffer-name b2))
10476 (with-temp-buffer "*Verilog-Diff*"
10477 (let ((outbuf (current-buffer))
10478 (f2 (make-temp-file "vm-diff-auto-")))
10479 (unwind-protect
10480 (progn
10481 (with-current-buffer b2
10482 (save-restriction
10483 (widen)
10484 (write-region (point-min) (point-max) f2 nil 'nomessage)))
10485 (call-process diff-command nil outbuf t
10486 diff-switches ;; User may want -u in diff-switches
10487 (if whitespace "-b" "")
10488 f1 f2)
10489 ;; Print out results. Alternatively we could have call-processed
10490 ;; ourself, but this way we can reuse diff switches
10491 (when show
10492 (with-current-buffer outbuf (message "%s" (buffer-string))))))
10493 (sit-for 0)
10494 (when (file-exists-p f2)
10495 (delete-file f2))))))
10496
10497(defun verilog-diff-report (b1 b2 diffpt)
10498 "Report differences detected with `verilog-diff-auto'.
10499Differences are between buffers B1 and B2, starting at point
10500DIFFPT. This function is called via `verilog-diff-function'."
10501 (let ((name1 (with-current-buffer b1 (buffer-file-name))))
47086495
WS
10502 (verilog-warn "%s:%d: Difference in AUTO expansion found"
10503 name1 (with-current-buffer b1
ea89ff08 10504 (count-lines (point-min) diffpt)))
9489a450
MM
10505 (cond (noninteractive
10506 (verilog-diff-file-with-buffer name1 b2 t t))
10507 (t
10508 (ediff-buffers b1 b2)))))
10509
10510(defun verilog-diff-auto ()
47086495 10511 "Expand AUTOs in a temporary buffer and indicate any change.
06827ec8
PE
10512Whitespace is ignored when detecting differences, but once a
10513difference is detected, whitespace differences may be shown.
9489a450
MM
10514
10515To call this from the command line, see \\[verilog-batch-diff-auto].
10516
10517The action on differences is selected with
10518`verilog-diff-function'. The default is `verilog-diff-report'
10519which will report an error and run `ediff' in interactive mode,
10520or `diff' in batch mode."
10521 (interactive)
10522 (let ((b1 (current-buffer)) b2 diffpt
10523 (name1 (buffer-file-name))
10524 (newname "*Verilog-Diff*"))
10525 (save-excursion
10526 (when (get-buffer newname)
10527 (kill-buffer newname))
10528 (setq b2 (let (buffer-file-name) ;; Else clone is upset
10529 (clone-buffer newname)))
10530 (with-current-buffer b2
10531 ;; auto requires the filename, but can't have same filename in two
10532 ;; buffers; so override both b1 and b2's names
10533 (let ((buffer-file-name name1))
10534 (unwind-protect
10535 (progn
10536 (with-current-buffer b1 (setq buffer-file-name nil))
10537 (verilog-auto)
10538 (when (not verilog-auto-star-save)
10539 (verilog-delete-auto-star-implicit)))
10540 ;; Restore name if unwind
10541 (with-current-buffer b1 (setq buffer-file-name name1)))))
10542 ;;
10543 (setq diffpt (verilog-diff-buffers-p b1 b2 t))
10544 (cond ((not diffpt)
10545 (unless noninteractive (message "AUTO expansion identical"))
10546 (kill-buffer newname)) ;; Nice to cleanup after oneself
10547 (t
10548 (funcall verilog-diff-function b1 b2 diffpt)))
10549 ;; Return result of compare
10550 diffpt)))
10551
10552\f
6341f357
DN
10553;;
10554;; Auto save
10555;;
10556
10557(defun verilog-auto-save-check ()
10558 "On saving see if we need auto update."
10559 (cond ((not verilog-auto-save-policy)) ; disabled
10560 ((not (save-excursion
10561 (save-match-data
10562 (let ((case-fold-search nil))
10563 (goto-char (point-min))
10564 (re-search-forward "AUTO" nil t))))))
10565 ((eq verilog-auto-save-policy 'force)
10566 (verilog-auto))
10567 ((not (buffer-modified-p)))
a03c2342 10568 ((eq verilog-auto-update-tick (buffer-chars-modified-tick))) ; up-to-date
6341f357
DN
10569 ((eq verilog-auto-save-policy 'detect)
10570 (verilog-auto))
10571 (t
10572 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
10573 (verilog-auto))
10574 ;; Don't ask again if didn't update
a03c2342 10575 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))))
6341f357
DN
10576 (when (not verilog-auto-star-save)
10577 (verilog-delete-auto-star-implicit))
10578 nil) ;; Always return nil -- we don't write the file ourselves
10579
10580(defun verilog-auto-read-locals ()
10581 "Return file local variable segment at bottom of file."
10582 (save-excursion
10583 (goto-char (point-max))
10584 (if (re-search-backward "Local Variables:" nil t)
10585 (buffer-substring-no-properties (point) (point-max))
10586 "")))
10587
10588(defun verilog-auto-reeval-locals (&optional force)
10589 "Read file local variable segment at bottom of file if it has changed.
10590If FORCE, always reread it."
6341f357
DN
10591 (let ((curlocal (verilog-auto-read-locals)))
10592 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
175069ef 10593 (set (make-local-variable 'verilog-auto-last-file-locals) curlocal)
a3a8b002
DN
10594 ;; Note this may cause this function to be recursively invoked,
10595 ;; because hack-local-variables may call (verilog-mode)
6341f357
DN
10596 ;; The above when statement will prevent it from recursing forever.
10597 (hack-local-variables)
10598 t)))
10599\f
10600;;
10601;; Auto creation
10602;;
10603
10604(defun verilog-auto-arg-ports (sigs message indent-pt)
47086495 10605 "Print a list of ports for an AUTOINST.
6341f357
DN
10606Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
10607 (when sigs
a3a8b002
DN
10608 (when verilog-auto-arg-sort
10609 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
6341f357
DN
10610 (insert "\n")
10611 (indent-to indent-pt)
10612 (insert message)
10613 (insert "\n")
10614 (let ((space ""))
10615 (indent-to indent-pt)
10616 (while sigs
10617 (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
10618 (insert "\n")
10619 (indent-to indent-pt))
10620 (t (insert space)))
10621 (insert (verilog-sig-name (car sigs)) ",")
10622 (setq sigs (cdr sigs)
10623 space " ")))))
10624
10625(defun verilog-auto-arg ()
10626 "Expand AUTOARG statements.
10627Replace the argument declarations at the beginning of the
10628module with ones automatically derived from input and output
10629statements. This can be dangerous if the module is instantiated
10630using position-based connections, so use only name-based when
10631instantiating the resulting module. Long lines are split based
10632on the `fill-column', see \\[set-fill-column].
10633
10634Limitations:
301b181a 10635 Concatenation and outputting partial buses is not supported.
6341f357
DN
10636
10637 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10638
10639For example:
10640
1dd4b004 10641 module ExampArg (/*AUTOARG*/);
6341f357
DN
10642 input i;
10643 output o;
10644 endmodule
10645
10646Typing \\[verilog-auto] will make this into:
10647
1dd4b004 10648 module ExampArg (/*AUTOARG*/
6341f357
DN
10649 // Outputs
10650 o,
10651 // Inputs
10652 i
10653 );
10654 input i;
10655 output o;
10656 endmodule
10657
a3a8b002
DN
10658The argument declarations may be printed in declaration order to best suit
10659order based instantiations, or alphabetically, based on the
10660`verilog-auto-arg-sort' variable.
10661
6341f357
DN
10662Any ports declared between the ( and /*AUTOARG*/ are presumed to be
10663predeclared and are not redeclared by AUTOARG. AUTOARG will make a
37ea4b9b
JB
10664conservative guess on adding a comma for the first signal, if you have
10665any ifdefs or complicated expressions before the AUTOARG you will need
10666to choose the comma yourself.
6341f357
DN
10667
10668Avoid declaring ports manually, as it makes code harder to maintain."
10669 (save-excursion
5509c6ad
DN
10670 (let* ((modi (verilog-modi-current))
10671 (moddecls (verilog-modi-get-decls modi))
9c059794 10672 (skip-pins (aref (verilog-read-arg-pins) 0)))
6341f357
DN
10673 (verilog-repair-open-comma)
10674 (verilog-auto-arg-ports (verilog-signals-not-in
5509c6ad 10675 (verilog-decls-get-outputs moddecls)
6341f357
DN
10676 skip-pins)
10677 "// Outputs"
10678 verilog-indent-level-declaration)
10679 (verilog-auto-arg-ports (verilog-signals-not-in
5509c6ad 10680 (verilog-decls-get-inouts moddecls)
6341f357
DN
10681 skip-pins)
10682 "// Inouts"
10683 verilog-indent-level-declaration)
10684 (verilog-auto-arg-ports (verilog-signals-not-in
5509c6ad 10685 (verilog-decls-get-inputs moddecls)
6341f357
DN
10686 skip-pins)
10687 "// Inputs"
10688 verilog-indent-level-declaration)
10689 (verilog-repair-close-comma)
10690 (unless (eq (char-before) ?/ )
10691 (insert "\n"))
60618039 10692 (indent-to verilog-indent-level-declaration))))
6341f357 10693
179f044b
WS
10694(defun verilog-auto-assign-modport ()
10695 "Expand AUTOASSIGNMODPORT statements, as part of \\[verilog-auto].
10696Take input/output/inout statements from the specified interface
10697and modport and use to build assignments into the modport, for
10698making verification modules that connect to UVM interfaces.
10699
10700 The first parameter is the name of an interface.
10701
10702 The second parameter is a regexp of modports to read from in
10703 that interface.
10704
10705 The third parameter is the instance name to use to dot reference into.
10706
10707 The optional fourth parameter is a regular expression, and only
10708 signals matching the regular expression will be included.
10709
10710Limitations:
10711
10712 Interface names must be resolvable to filenames. See `verilog-auto-inst'.
10713
10714 Inouts are not supported, as assignments must be unidirectional.
10715
10716 If a signal is part of the interface header and in both a
10717 modport and the interface itself, it will not be listed. (As
10718 this would result in a syntax error when the connections are
10719 made.)
10720
10721See the example in `verilog-auto-inout-modport'."
10722 (save-excursion
10723 (let* ((params (verilog-read-auto-params 3 4))
10724 (submod (nth 0 params))
10725 (modport-re (nth 1 params))
10726 (inst-name (nth 2 params))
10727 (regexp (nth 3 params))
10728 direction-re submodi) ;; direction argument not supported until requested
10729 ;; Lookup position, etc of co-module
10730 ;; Note this may raise an error
10731 (when (setq submodi (verilog-modi-lookup submod t))
10732 (let* ((indent-pt (current-indentation))
179f044b
WS
10733 (submoddecls (verilog-modi-get-decls submodi))
10734 (submodportdecls (verilog-modi-modport-lookup submodi modport-re))
10735 (sig-list-i (verilog-signals-in ;; Decls doesn't have data types, must resolve
10736 (verilog-decls-get-vars submoddecls)
10737 (verilog-signals-not-in
10738 (verilog-decls-get-inputs submodportdecls)
10739 (verilog-decls-get-ports submoddecls))))
10740 (sig-list-o (verilog-signals-in ;; Decls doesn't have data types, must resolve
10741 (verilog-decls-get-vars submoddecls)
10742 (verilog-signals-not-in
10743 (verilog-decls-get-outputs submodportdecls)
10744 (verilog-decls-get-ports submoddecls)))))
10745 (forward-line 1)
10746 (setq sig-list-i (verilog-signals-edit-wire-reg
10747 (verilog-signals-matching-dir-re
10748 (verilog-signals-matching-regexp sig-list-i regexp)
10749 "input" direction-re))
10750 sig-list-o (verilog-signals-edit-wire-reg
10751 (verilog-signals-matching-dir-re
10752 (verilog-signals-matching-regexp sig-list-o regexp)
10753 "output" direction-re)))
10754 (setq sig-list-i (sort (copy-alist sig-list-i) `verilog-signals-sort-compare))
10755 (setq sig-list-o (sort (copy-alist sig-list-o) `verilog-signals-sort-compare))
10756 (when (or sig-list-i sig-list-o)
10757 (verilog-insert-indent "// Beginning of automatic assignments from modport\n")
10758 ;; Don't sort them so an upper AUTOINST will match the main module
10759 (let ((sigs sig-list-o))
10760 (while sigs
10761 (verilog-insert-indent "assign " (verilog-sig-name (car sigs))
10762 " = " inst-name
10763 "." (verilog-sig-name (car sigs)) ";\n")
10764 (setq sigs (cdr sigs))))
10765 (let ((sigs sig-list-i))
10766 (while sigs
10767 (verilog-insert-indent "assign " inst-name
10768 "." (verilog-sig-name (car sigs))
10769 " = " (verilog-sig-name (car sigs)) ";\n")
10770 (setq sigs (cdr sigs))))
10771 (verilog-insert-indent "// End of automatics\n")))))))
10772
0f137a73 10773(defun verilog-auto-inst-port-map (_port-st)
6341f357
DN
10774 nil)
10775
6341f357
DN
10776(defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
10777(defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
a3a8b002 10778(defvar vl-modport nil "See `verilog-auto-inst'.") ; Prevent compile warning
6341f357
DN
10779(defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
10780(defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
10781(defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
fd9ea9d3
WS
10782(defvar vl-bits nil "See `verilog-auto-inst'.") ; Prevent compile warning
10783(defvar vl-mbits nil "See `verilog-auto-inst'.") ; Prevent compile warning
6341f357 10784
4c5e69c6 10785(defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
47086495 10786 "Print out an instantiation connection for this PORT-ST.
6341f357
DN
10787Insert to INDENT-PT, use template TPL-LIST.
10788@ are instantiation numbers, replaced with TPL-NUM.
60618039 10789@\"(expression @)\" are evaluated, with @ as a variable.
4c5e69c6
DN
10790If FOR-STAR add comment it is a .* expansion.
10791If PAR-VALUES replace final strings with these parameter values."
6341f357
DN
10792 (let* ((port (verilog-sig-name port-st))
10793 (tpl-ass (or (assoc port (car tpl-list))
10794 (verilog-auto-inst-port-map port-st)))
10795 ;; vl-* are documented for user use
10796 (vl-name (verilog-sig-name port-st))
10797 (vl-width (verilog-sig-width port-st))
a3a8b002 10798 (vl-modport (verilog-sig-modport port-st))
a03c2342 10799 (vl-mbits (if (verilog-sig-multidim port-st)
fd9ea9d3 10800 (verilog-sig-multidim-string port-st) ""))
6341f357
DN
10801 (vl-bits (if (or verilog-auto-inst-vector
10802 (not (assoc port vector-skip-list))
10803 (not (equal (verilog-sig-bits port-st)
10804 (verilog-sig-bits (assoc port vector-skip-list)))))
10805 (or (verilog-sig-bits port-st) "")
10806 ""))
4c5e69c6 10807 (case-fold-search nil)
7cb1c4d7 10808 (check-values par-values)
ea89ff08 10809 tpl-net dflt-bits)
4c5e69c6
DN
10810 ;; Replace parameters in bit-width
10811 (when (and check-values
10812 (not (equal vl-bits "")))
10813 (while check-values
10814 (setq vl-bits (verilog-string-replace-matches
10815 (concat "\\<" (nth 0 (car check-values)) "\\>")
10816 (concat "(" (nth 1 (car check-values)) ")")
10817 t t vl-bits)
9489a450
MM
10818 vl-mbits (verilog-string-replace-matches
10819 (concat "\\<" (nth 0 (car check-values)) "\\>")
10820 (concat "(" (nth 1 (car check-values)) ")")
10821 t t vl-mbits)
4c5e69c6 10822 check-values (cdr check-values)))
9489a450
MM
10823 (setq vl-bits (verilog-simplify-range-expression vl-bits)
10824 vl-mbits (verilog-simplify-range-expression vl-mbits)
10825 vl-width (verilog-make-width-expression vl-bits))) ; Not in the loop for speed
7cb1c4d7 10826 ;; Default net value if not found
ea89ff08
WS
10827 (setq dflt-bits (if (and (verilog-sig-bits port-st)
10828 (or (verilog-sig-multidim port-st)
10829 (verilog-sig-memory port-st)))
10830 (concat "/*" vl-mbits vl-bits "*/")
10831 (concat vl-bits))
10832 tpl-net (concat port
a3a8b002 10833 (if vl-modport (concat "." vl-modport) "")
ea89ff08 10834 dflt-bits))
6341f357
DN
10835 ;; Find template
10836 (cond (tpl-ass ; Template of exact port name
10837 (setq tpl-net (nth 1 tpl-ass)))
10838 ((nth 1 tpl-list) ; Wildcards in template, search them
10839 (let ((wildcards (nth 1 tpl-list)))
10840 (while wildcards
10841 (when (string-match (nth 0 (car wildcards)) port)
10842 (setq tpl-ass (car wildcards) ; so allow @ parsing
10843 tpl-net (replace-match (nth 1 (car wildcards))
10844 t nil port)))
10845 (setq wildcards (cdr wildcards))))))
10846 ;; Parse Templated variable
10847 (when tpl-ass
10848 ;; Evaluate @"(lispcode)"
10849 (when (string-match "@\".*[^\\]\"" tpl-net)
10850 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
10851 (setq tpl-net
10852 (concat
10853 (substring tpl-net 0 (match-beginning 0))
10854 (save-match-data
10855 (let* ((expr (match-string 1 tpl-net))
10856 (value
10857 (progn
10858 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
10859 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
10860 (prin1 (eval (car (read-from-string expr)))
0f137a73 10861 (lambda (_ch) ())))))
6341f357 10862 (if (numberp value) (setq value (number-to-string value)))
60618039 10863 value))
6341f357
DN
10864 (substring tpl-net (match-end 0))))))
10865 ;; Replace @ and [] magic variables in final output
10866 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
ea89ff08 10867 (setq tpl-net (verilog-string-replace-matches "\\[\\]\\[\\]" dflt-bits nil nil tpl-net))
60618039 10868 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
4c5e69c6 10869 ;; Insert it
6341f357
DN
10870 (indent-to indent-pt)
10871 (insert "." port)
a03c2342
WS
10872 (unless (and verilog-auto-inst-dot-name
10873 (equal port tpl-net))
10874 (indent-to verilog-auto-inst-column)
10875 (insert "(" tpl-net ")"))
10876 (insert ",")
6341f357 10877 (cond (tpl-ass
47086495 10878 (verilog-read-auto-template-hit tpl-ass)
6341f357
DN
10879 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
10880 verilog-auto-inst-column))
9489a450
MM
10881 ;; verilog-insert requires the complete comment in one call - including the newline
10882 (cond ((equal verilog-auto-inst-template-numbers `lhs)
10883 (verilog-insert " // Templated"
10884 " LHS: " (nth 0 tpl-ass)
10885 "\n"))
10886 (verilog-auto-inst-template-numbers
10887 (verilog-insert " // Templated"
10888 " T" (int-to-string (nth 2 tpl-ass))
10889 " L" (int-to-string (nth 3 tpl-ass))
10890 "\n"))
10891 (t
10892 (verilog-insert " // Templated\n"))))
6341f357
DN
10893 (for-star
10894 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
10895 verilog-auto-inst-column))
9489a450
MM
10896 (verilog-insert " // Implicit .\*\n")) ;For some reason the . or * must be escaped...
10897 (t
10898 (insert "\n")))))
6341f357
DN
10899;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
10900;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
10901;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
10902
9489a450
MM
10903(defun verilog-auto-inst-port-list (sig-list indent-pt tpl-list tpl-num for-star par-values)
10904 "For `verilog-auto-inst' print a list of ports using `verilog-auto-inst-port'."
10905 (when verilog-auto-inst-sort
10906 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare)))
10907 (mapc (lambda (port)
10908 (verilog-auto-inst-port port indent-pt
10909 tpl-list tpl-num for-star par-values))
10910 sig-list))
10911
6341f357
DN
10912(defun verilog-auto-inst-first ()
10913 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
10914 ;; Do we need a trailing comma?
47086495 10915 ;; There maybe an ifdef or something similar before us. What a mess. Thus
86a4c7ac 10916 ;; to avoid trouble we only insert on preceding ) or *.
6341f357
DN
10917 ;; Insert first port on new line
10918 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
10919 (save-excursion
9489a450 10920 (verilog-re-search-backward-quick "[^ \t\n\f]" nil nil)
6341f357
DN
10921 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
10922 (forward-char 1)
10923 (insert ","))))
10924
10925(defun verilog-auto-star ()
10926 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
10927
10928If `verilog-auto-star-expand' is set, .* pins are treated if they were
37ea4b9b 10929AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
6341f357
DN
10930will also ignore any .* that are not last in your pin list (this prevents
10931it from deleting pins following the .* when it expands the AUTOINST.)
10932
10933On writing your file, unless `verilog-auto-star-save' is set, any
10934non-templated expanded pins will be removed. You may do this at any time
10935with \\[verilog-delete-auto-star-implicit].
10936
10937If you are converting a module to use .* for the first time, you may wish
10938to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
10939
10940See `verilog-auto-inst' for examples, templates, and more information."
10941 (when (verilog-auto-star-safe)
10942 (verilog-auto-inst)))
10943
10944(defun verilog-auto-inst ()
10945 "Expand AUTOINST statements, as part of \\[verilog-auto].
a03c2342
WS
10946Replace the pin connections to an instantiation or interface
10947declaration with ones automatically derived from the module or
10948interface header of the instantiated item.
6341f357
DN
10949
10950If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
10951and delete them before saving unless `verilog-auto-star-save' is set.
10952See `verilog-auto-star' for more information.
10953
9489a450
MM
10954The pins are printed in declaration order or alphabetically,
10955based on the `verilog-auto-inst-sort' variable.
10956
6341f357
DN
10957Limitations:
10958 Module names must be resolvable to filenames by adding a
10959 `verilog-library-extensions', and being found in the same directory, or
10960 by changing the variable `verilog-library-flags' or
10961 `verilog-library-directories'. Macros `modname are translated through the
10962 vh-{name} Emacs variable, if that is not found, it just ignores the `.
10963
10964 In templates you must have one signal per line, ending in a ), or ));,
10965 and have proper () nesting, including a final ); to end the template.
10966
10967 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10968
37ea4b9b 10969 SystemVerilog multidimensional input/output has only experimental support.
6341f357 10970
a03c2342
WS
10971 SystemVerilog .name syntax is used if `verilog-auto-inst-dot-name' is set.
10972
4c5e69c6
DN
10973 Parameters referenced by the instantiation will remain symbolic, unless
10974 `verilog-auto-inst-param-value' is set.
10975
a03c2342
WS
10976 Gate primitives (and/or) may have AUTOINST for the purpose of
10977 AUTOWIRE declarations, etc. Gates are the only case when
10978 position based connections are passed.
10979
ea89ff08
WS
10980 The array part of arrayed instances are ignored; this may
10981 result in undesirable default AUTOINST connections; use a
10982 template instead.
10983
1dd4b004 10984For example, first take the submodule InstModule.v:
6341f357 10985
a03c2342 10986 module InstModule (o,i);
6341f357
DN
10987 output [31:0] o;
10988 input i;
10989 wire [31:0] o = {32{i}};
10990 endmodule
10991
47086495 10992This is then used in an upper level module:
6341f357 10993
a03c2342 10994 module ExampInst (o,i);
6341f357
DN
10995 output o;
10996 input i;
1dd4b004
DN
10997 InstModule instName
10998 (/*AUTOINST*/);
6341f357
DN
10999 endmodule
11000
11001Typing \\[verilog-auto] will make this into:
11002
a03c2342 11003 module ExampInst (o,i);
6341f357
DN
11004 output o;
11005 input i;
1dd4b004
DN
11006 InstModule instName
11007 (/*AUTOINST*/
11008 // Outputs
11009 .ov (ov[31:0]),
11010 // Inputs
11011 .i (i));
6341f357
DN
11012 endmodule
11013
11014Where the list of inputs and outputs came from the inst module.
11015\f
11016Exceptions:
11017
11018 Unless you are instantiating a module multiple times, or the module is
37ea4b9b 11019 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
6341f357 11020 It just makes for unmaintainable code. To sanitize signal names, try
855b42a2 11021 vrename from URL `http://www.veripool.org'.
6341f357
DN
11022
11023 When you need to violate this suggestion there are two ways to list
11024 exceptions, placing them before the AUTOINST, or using templates.
11025
11026 Any ports defined before the /*AUTOINST*/ are not included in the list of
11027 automatics. This is similar to making a template as described below, but
11028 is restricted to simple connections just like you normally make. Also note
11029 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
11030 you have the appropriate // Input or // Output comment, and exactly the
11031 same line formatting as AUTOINST itself uses.
11032
1dd4b004
DN
11033 InstModule instName
11034 (// Inputs
11035 .i (my_i_dont_mess_with_it),
11036 /*AUTOINST*/
11037 // Outputs
11038 .ov (ov[31:0]));
6341f357
DN
11039
11040\f
11041Templates:
11042
11043 For multiple instantiations based upon a single template, create a
11044 commented out template:
11045
1dd4b004 11046 /* InstModule AUTO_TEMPLATE (
6341f357
DN
11047 .sig3 (sigz[]),
11048 );
11049 */
11050
37ea4b9b 11051 Templates go ABOVE the instantiation(s). When an instantiation is
6341f357
DN
11052 expanded `verilog-mode' simply searches up for the closest template.
11053 Thus you can have multiple templates for the same module, just alternate
37ea4b9b 11054 between the template for an instantiation and the instantiation itself.
47086495
WS
11055 (For backward compatibility if no template is found above, it
11056 will also look below, but do not use this behavior in new designs.)
6341f357
DN
11057
11058 The module name must be the same as the name of the module in the
11059 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
11060 words and capitalized. Only signals that must be different for each
11061 instantiation need to be listed.
11062
ea89ff08
WS
11063 Inside a template, a [] in a connection name (with nothing else
11064 inside the brackets) will be replaced by the same bus subscript
11065 as it is being connected to, or the [] will be removed if it is
11066 a single bit signal.
11067
11068 Inside a template, a [][] in a connection name will behave
11069 similarly to a [] for scalar or single-dimensional connection;
11070 for a multidimensional connection it will print a comment
11071 similar to that printed when a template is not used. Generally
11072 it is a good idea to do this for all connections in a template,
11073 as then they will work for any width signal, and with AUTOWIRE.
11074 See PTL_BUS becoming PTL_BUSNEW below.
a67c4ae0 11075
6341f357
DN
11076 Inside a template, a [] in a connection name (with nothing else inside
11077 the brackets) will be replaced by the same bus subscript as it is being
11078 connected to, or the [] will be removed if it is a single bit signal.
11079 Generally it is a good idea to do this for all connections in a template,
11080 as then they will work for any width signal, and with AUTOWIRE. See
11081 PTL_BUS becoming PTL_BUSNEW below.
11082
11083 If you have a complicated template, set `verilog-auto-inst-template-numbers'
11084 to see which regexps are matching. Don't leave that mode set after
11085 debugging is completed though, it will result in lots of extra differences
11086 and merge conflicts.
11087
47086495
WS
11088 Setting `verilog-auto-template-warn-unused' will report errors
11089 if any template lines are unused.
11090
6341f357
DN
11091 For example:
11092
1dd4b004 11093 /* InstModule AUTO_TEMPLATE (
6341f357
DN
11094 .ptl_bus (ptl_busnew[]),
11095 );
11096 */
1dd4b004 11097 InstModule ms2m (/*AUTOINST*/);
6341f357
DN
11098
11099 Typing \\[verilog-auto] will make this into:
11100
1dd4b004 11101 InstModule ms2m (/*AUTOINST*/
6341f357
DN
11102 // Outputs
11103 .NotInTemplate (NotInTemplate),
11104 .ptl_bus (ptl_busnew[3:0]), // Templated
11105 ....
9489a450
MM
11106
11107\f
11108Multiple Module Templates:
11109
11110 The same template lines can be applied to multiple modules with
11111 the syntax as follows:
11112
11113 /* InstModuleA AUTO_TEMPLATE
11114 InstModuleB AUTO_TEMPLATE
11115 InstModuleC AUTO_TEMPLATE
11116 InstModuleD AUTO_TEMPLATE (
11117 .ptl_bus (ptl_busnew[]),
11118 );
11119 */
11120
11121 Note there is only one AUTO_TEMPLATE opening parenthesis.
6341f357
DN
11122\f
11123@ Templates:
11124
11125 It is common to instantiate a cell multiple times, so templates make it
11126 trivial to substitute part of the cell name into the connection name.
11127
1dd4b004 11128 /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
6341f357
DN
11129 .sig1 (sigx[@]),
11130 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
11131 );
11132 */
11133
11134 If no regular expression is provided immediately after the AUTO_TEMPLATE
11135 keyword, then the @ character in any connection names will be replaced
11136 with the instantiation number; the first digits found in the cell's
11137 instantiation name.
11138
11139 If a regular expression is provided, the @ character will be replaced
11140 with the first \(\) grouping that matches against the cell name. Using a
11141 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
11142 regexp is provided. If you use multiple layers of parenthesis,
11143 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
11144 characters after test and before _, whereas
11145 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
11146 match.
11147
11148 For example:
11149
1dd4b004 11150 /* InstModule AUTO_TEMPLATE (
6341f357
DN
11151 .ptl_mapvalidx (ptl_mapvalid[@]),
11152 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
11153 );
11154 */
1dd4b004 11155 InstModule ms2m (/*AUTOINST*/);
6341f357
DN
11156
11157 Typing \\[verilog-auto] will make this into:
11158
1dd4b004 11159 InstModule ms2m (/*AUTOINST*/
6341f357
DN
11160 // Outputs
11161 .ptl_mapvalidx (ptl_mapvalid[2]),
11162 .ptl_mapvalidp1x (ptl_mapvalid[3]));
11163
11164 Note the @ character was replaced with the 2 from \"ms2m\".
11165
11166 Alternatively, using a regular expression for @:
11167
1dd4b004 11168 /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
6341f357
DN
11169 .ptl_mapvalidx (@_ptl_mapvalid),
11170 .ptl_mapvalidp1x (ptl_mapvalid_@),
11171 );
11172 */
1dd4b004
DN
11173 InstModule ms2_FOO (/*AUTOINST*/);
11174 InstModule ms2_BAR (/*AUTOINST*/);
6341f357
DN
11175
11176 Typing \\[verilog-auto] will make this into:
11177
1dd4b004 11178 InstModule ms2_FOO (/*AUTOINST*/
6341f357
DN
11179 // Outputs
11180 .ptl_mapvalidx (FOO_ptl_mapvalid),
11181 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
1dd4b004 11182 InstModule ms2_BAR (/*AUTOINST*/
6341f357
DN
11183 // Outputs
11184 .ptl_mapvalidx (BAR_ptl_mapvalid),
11185 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
11186
11187\f
11188Regexp Templates:
11189
11190 A template entry of the form
11191
11192 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
11193
37ea4b9b 11194 will apply an Emacs style regular expression search for any port beginning
6341f357
DN
11195 in pci_req followed by numbers and ending in _l and connecting that to
11196 the pci_req_jtag_[] net, with the bus subscript coming from what matches
11197 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
11198
11199 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
0e5c8aed 11200 does the same thing. (Note a @ in the connection/replacement text is
6341f357
DN
11201 completely different -- still use \\1 there!) Thus this is the same as
11202 the above template:
11203
11204 .pci_req@_l (pci_req_jtag_[\\1]),
11205
11206 Here's another example to remove the _l, useful when naming conventions
11207 specify _ alone to mean active low. Note the use of [] to keep the bus
11208 subscript:
11209
11210 .\\(.*\\)_l (\\1_[]),
11211\f
11212Lisp Templates:
11213
11214 First any regular expression template is expanded.
11215
11216 If the syntax @\"( ... )\" is found in a connection, the expression in
11217 quotes will be evaluated as a Lisp expression, with @ replaced by the
11218 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
11219 4 into the brackets. Quote all double-quotes inside the expression with
0e5c8aed
DN
11220 a leading backslash (\\\"...\\\"); or if the Lisp template is also a
11221 regexp template backslash the backslash quote (\\\\\"...\\\\\").
11222
11223 There are special variables defined that are useful in these
11224 Lisp functions:
6341f357 11225
37ea4b9b
JB
11226 vl-name Name portion of the input/output port.
11227 vl-bits Bus bits portion of the input/output port ('[2:0]').
fd9ea9d3 11228 vl-mbits Multidimensional array bits for port ('[2:0][3:0]').
37ea4b9b 11229 vl-width Width of the input/output port ('3' for [2:0]).
6341f357 11230 May be a (...) expression if bits isn't a constant.
a3a8b002
DN
11231 vl-dir Direction of the pin input/output/inout/interface.
11232 vl-modport The modport, if an interface with a modport.
1dd4b004
DN
11233 vl-cell-type Module name/type of the cell ('InstModule').
11234 vl-cell-name Instance name of the cell ('instName').
6341f357
DN
11235
11236 Normal Lisp variables may be used in expressions. See
11237 `verilog-read-defines' which can set vh-{definename} variables for use
11238 here. Also, any comments of the form:
11239
11240 /*AUTO_LISP(setq foo 1)*/
11241
11242 will evaluate any Lisp expression inside the parenthesis between the
11243 beginning of the buffer and the point of the AUTOINST. This allows
11244 functions to be defined or variables to be changed between instantiations.
a3a8b002
DN
11245 (See also `verilog-auto-insert-lisp' if you want the output from your
11246 lisp function to be inserted.)
6341f357
DN
11247
11248 Note that when using lisp expressions errors may occur when @ is not a
37ea4b9b 11249 number; you may need to use the standard Emacs Lisp functions
6341f357
DN
11250 `number-to-string' and `string-to-number'.
11251
11252 After the evaluation is completed, @ substitution and [] substitution
0e5c8aed
DN
11253 occur.
11254
11255For more information see the \\[verilog-faq] and forums at URL
11256`http://www.veripool.org'."
6341f357
DN
11257 (save-excursion
11258 ;; Find beginning
11259 (let* ((pt (point))
11260 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
11261 (indent-pt (save-excursion (verilog-backward-open-paren)
11262 (1+ (current-column))))
11263 (verilog-auto-inst-column (max verilog-auto-inst-column
11264 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
11265 (modi (verilog-modi-current))
5509c6ad 11266 (moddecls (verilog-modi-get-decls modi))
6341f357 11267 (vector-skip-list (unless verilog-auto-inst-vector
5509c6ad
DN
11268 (verilog-decls-get-signals moddecls)))
11269 submod submodi submoddecls
4c5e69c6
DN
11270 inst skip-pins tpl-list tpl-num did-first par-values)
11271
6341f357
DN
11272 ;; Find module name that is instantiated
11273 (setq submod (verilog-read-inst-module)
11274 inst (verilog-read-inst-name)
11275 vl-cell-type submod
11276 vl-cell-name inst
11277 skip-pins (aref (verilog-read-inst-pins) 0))
11278
11279 ;; Parse any AUTO_LISP() before here
11280 (verilog-read-auto-lisp (point-min) pt)
11281
4c5e69c6
DN
11282 ;; Read parameters (after AUTO_LISP)
11283 (setq par-values (and verilog-auto-inst-param-value
11284 (verilog-read-inst-param-value)))
11285
6341f357
DN
11286 ;; Lookup position, etc of submodule
11287 ;; Note this may raise an error
a03c2342
WS
11288 (when (and (not (member submod verilog-gate-keywords))
11289 (setq submodi (verilog-modi-lookup submod t)))
5509c6ad 11290 (setq submoddecls (verilog-modi-get-decls submodi))
47086495 11291 ;; If there's a number in the instantiation, it may be an argument to the
6341f357
DN
11292 ;; automatic variable instantiation program.
11293 (let* ((tpl-info (verilog-read-auto-template submod))
11294 (tpl-regexp (aref tpl-info 0)))
ea89ff08 11295 (setq tpl-num (if (verilog-string-match-fold tpl-regexp inst)
6341f357
DN
11296 (match-string 1 inst)
11297 "")
11298 tpl-list (aref tpl-info 1)))
11299 ;; Find submodule's signals and dump
a03c2342
WS
11300 (let ((sig-list (and (equal (verilog-modi-get-type submodi) "interface")
11301 (verilog-signals-not-in
9489a450 11302 (verilog-decls-get-vars submoddecls)
a03c2342
WS
11303 skip-pins)))
11304 (vl-dir "interfaced"))
47086495
WS
11305 (when (and sig-list
11306 verilog-auto-inst-interfaced-ports)
a03c2342
WS
11307 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11308 ;; Note these are searched for in verilog-read-sub-decls.
11309 (verilog-insert-indent "// Interfaced\n")
9489a450
MM
11310 (verilog-auto-inst-port-list sig-list indent-pt
11311 tpl-list tpl-num for-star par-values)))
a3a8b002
DN
11312 (let ((sig-list (verilog-signals-not-in
11313 (verilog-decls-get-interfaces submoddecls)
11314 skip-pins))
11315 (vl-dir "interface"))
11316 (when sig-list
11317 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
a3a8b002 11318 ;; Note these are searched for in verilog-read-sub-decls.
a03c2342 11319 (verilog-insert-indent "// Interfaces\n")
9489a450
MM
11320 (verilog-auto-inst-port-list sig-list indent-pt
11321 tpl-list tpl-num for-star par-values)))
6341f357 11322 (let ((sig-list (verilog-signals-not-in
5509c6ad 11323 (verilog-decls-get-outputs submoddecls)
6341f357
DN
11324 skip-pins))
11325 (vl-dir "output"))
11326 (when sig-list
11327 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
a03c2342 11328 (verilog-insert-indent "// Outputs\n")
9489a450
MM
11329 (verilog-auto-inst-port-list sig-list indent-pt
11330 tpl-list tpl-num for-star par-values)))
6341f357 11331 (let ((sig-list (verilog-signals-not-in
5509c6ad 11332 (verilog-decls-get-inouts submoddecls)
6341f357
DN
11333 skip-pins))
11334 (vl-dir "inout"))
11335 (when sig-list
11336 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
a03c2342 11337 (verilog-insert-indent "// Inouts\n")
9489a450
MM
11338 (verilog-auto-inst-port-list sig-list indent-pt
11339 tpl-list tpl-num for-star par-values)))
6341f357 11340 (let ((sig-list (verilog-signals-not-in
5509c6ad 11341 (verilog-decls-get-inputs submoddecls)
6341f357
DN
11342 skip-pins))
11343 (vl-dir "input"))
11344 (when sig-list
11345 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
a03c2342 11346 (verilog-insert-indent "// Inputs\n")
9489a450
MM
11347 (verilog-auto-inst-port-list sig-list indent-pt
11348 tpl-list tpl-num for-star par-values)))
6341f357
DN
11349 ;; Kill extra semi
11350 (save-excursion
11351 (cond (did-first
11352 (re-search-backward "," pt t)
11353 (delete-char 1)
11354 (insert ");")
11355 (search-forward "\n") ;; Added by inst-port
d355a0b7 11356 (delete-char -1)
6341f357 11357 (if (search-forward ")" nil t) ;; From user, moved up a line
d355a0b7 11358 (delete-char -1))
6341f357 11359 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
d355a0b7 11360 (delete-char -1)))))))))
6341f357
DN
11361
11362(defun verilog-auto-inst-param ()
11363 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
11364Replace the parameter connections to an instantiation with ones
11365automatically derived from the module header of the instantiated netlist.
11366
11367See \\[verilog-auto-inst] for limitations, and templates to customize the
11368output.
11369
1dd4b004 11370For example, first take the submodule InstModule.v:
6341f357 11371
a03c2342 11372 module InstModule (o,i);
6341f357
DN
11373 parameter PAR;
11374 endmodule
11375
47086495 11376This is then used in an upper level module:
6341f357 11377
a03c2342 11378 module ExampInst (o,i);
6341f357 11379 parameter PAR;
1dd4b004
DN
11380 InstModule #(/*AUTOINSTPARAM*/)
11381 instName (/*AUTOINST*/);
6341f357
DN
11382 endmodule
11383
11384Typing \\[verilog-auto] will make this into:
11385
a03c2342 11386 module ExampInst (o,i);
6341f357
DN
11387 output o;
11388 input i;
1dd4b004
DN
11389 InstModule #(/*AUTOINSTPARAM*/
11390 // Parameters
11391 .PAR (PAR));
11392 instName (/*AUTOINST*/);
6341f357
DN
11393 endmodule
11394
11395Where the list of parameter connections come from the inst module.
11396\f
11397Templates:
11398
11399 You can customize the parameter connections using AUTO_TEMPLATEs,
11400 just as you would with \\[verilog-auto-inst]."
11401 (save-excursion
11402 ;; Find beginning
11403 (let* ((pt (point))
11404 (indent-pt (save-excursion (verilog-backward-open-paren)
11405 (1+ (current-column))))
11406 (verilog-auto-inst-column (max verilog-auto-inst-column
11407 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
11408 (modi (verilog-modi-current))
5509c6ad 11409 (moddecls (verilog-modi-get-decls modi))
6341f357 11410 (vector-skip-list (unless verilog-auto-inst-vector
5509c6ad
DN
11411 (verilog-decls-get-signals moddecls)))
11412 submod submodi submoddecls
11413 inst skip-pins tpl-list tpl-num did-first)
6341f357
DN
11414 ;; Find module name that is instantiated
11415 (setq submod (save-excursion
11416 ;; Get to the point where AUTOINST normally is to read the module
11417 (verilog-re-search-forward-quick "[(;]" nil nil)
11418 (verilog-read-inst-module))
11419 inst (save-excursion
11420 ;; Get to the point where AUTOINST normally is to read the module
11421 (verilog-re-search-forward-quick "[(;]" nil nil)
11422 (verilog-read-inst-name))
11423 vl-cell-type submod
11424 vl-cell-name inst
11425 skip-pins (aref (verilog-read-inst-pins) 0))
11426
11427 ;; Parse any AUTO_LISP() before here
11428 (verilog-read-auto-lisp (point-min) pt)
11429
11430 ;; Lookup position, etc of submodule
11431 ;; Note this may raise an error
11432 (when (setq submodi (verilog-modi-lookup submod t))
5509c6ad 11433 (setq submoddecls (verilog-modi-get-decls submodi))
47086495 11434 ;; If there's a number in the instantiation, it may be an argument to the
6341f357
DN
11435 ;; automatic variable instantiation program.
11436 (let* ((tpl-info (verilog-read-auto-template submod))
11437 (tpl-regexp (aref tpl-info 0)))
ea89ff08 11438 (setq tpl-num (if (verilog-string-match-fold tpl-regexp inst)
6341f357
DN
11439 (match-string 1 inst)
11440 "")
11441 tpl-list (aref tpl-info 1)))
11442 ;; Find submodule's signals and dump
11443 (let ((sig-list (verilog-signals-not-in
5509c6ad 11444 (verilog-decls-get-gparams submoddecls)
6341f357
DN
11445 skip-pins))
11446 (vl-dir "parameter"))
11447 (when sig-list
11448 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
7ea26faf 11449 ;; Note these are searched for in verilog-read-sub-decls.
a03c2342 11450 (verilog-insert-indent "// Parameters\n")
9489a450
MM
11451 (verilog-auto-inst-port-list sig-list indent-pt
11452 tpl-list tpl-num nil nil)))
6341f357
DN
11453 ;; Kill extra semi
11454 (save-excursion
11455 (cond (did-first
11456 (re-search-backward "," pt t)
11457 (delete-char 1)
11458 (insert ")")
11459 (search-forward "\n") ;; Added by inst-port
d355a0b7 11460 (delete-char -1)
6341f357 11461 (if (search-forward ")" nil t) ;; From user, moved up a line
d355a0b7 11462 (delete-char -1)))))))))
6341f357
DN
11463
11464(defun verilog-auto-reg ()
11465 "Expand AUTOREG statements, as part of \\[verilog-auto].
11466Make reg statements for any output that isn't already declared,
9489a450
MM
11467and isn't a wire output from a block. `verilog-auto-wire-type'
11468may be used to change the datatype of the declarations.
6341f357
DN
11469
11470Limitations:
11471 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11472
11473 This does NOT work on memories, declare those yourself.
11474
11475An example:
11476
a03c2342 11477 module ExampReg (o,i);
6341f357
DN
11478 output o;
11479 input i;
11480 /*AUTOREG*/
11481 always o = i;
11482 endmodule
11483
11484Typing \\[verilog-auto] will make this into:
11485
a03c2342 11486 module ExampReg (o,i);
6341f357
DN
11487 output o;
11488 input i;
11489 /*AUTOREG*/
11490 // Beginning of automatic regs (for this module's undeclared outputs)
1dd4b004 11491 reg o;
6341f357
DN
11492 // End of automatics
11493 always o = i;
11494 endmodule"
11495 (save-excursion
11496 ;; Point must be at insertion point.
11497 (let* ((indent-pt (current-indentation))
11498 (modi (verilog-modi-current))
5509c6ad
DN
11499 (moddecls (verilog-modi-get-decls modi))
11500 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 11501 (sig-list (verilog-signals-not-in
5509c6ad 11502 (verilog-decls-get-outputs moddecls)
47086495
WS
11503 (append (verilog-signals-with ;; ignore typed signals
11504 'verilog-sig-type
11505 (verilog-decls-get-outputs moddecls))
11506 (verilog-decls-get-vars moddecls)
5509c6ad
DN
11507 (verilog-decls-get-assigns moddecls)
11508 (verilog-decls-get-consts moddecls)
11509 (verilog-decls-get-gparams moddecls)
a03c2342 11510 (verilog-subdecls-get-interfaced modsubdecls)
5509c6ad
DN
11511 (verilog-subdecls-get-outputs modsubdecls)
11512 (verilog-subdecls-get-inouts modsubdecls)))))
6341f357 11513 (when sig-list
179f044b 11514 (verilog-forward-or-insert-line)
6341f357 11515 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
9489a450 11516 (verilog-insert-definition modi sig-list "reg" indent-pt nil)
60618039 11517 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
11518
11519(defun verilog-auto-reg-input ()
11520 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
11521Make reg statements instantiation inputs that aren't already declared.
11522This is useful for making a top level shell for testing the module that is
11523to be instantiated.
11524
11525Limitations:
11526 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
11527
11528 This does NOT work on memories, declare those yourself.
11529
11530An example (see `verilog-auto-inst' for what else is going on here):
11531
a03c2342 11532 module ExampRegInput (o,i);
6341f357
DN
11533 output o;
11534 input i;
11535 /*AUTOREGINPUT*/
1dd4b004
DN
11536 InstModule instName
11537 (/*AUTOINST*/);
6341f357
DN
11538 endmodule
11539
11540Typing \\[verilog-auto] will make this into:
11541
a03c2342 11542 module ExampRegInput (o,i);
6341f357
DN
11543 output o;
11544 input i;
11545 /*AUTOREGINPUT*/
11546 // Beginning of automatic reg inputs (for undeclared ...
1dd4b004 11547 reg [31:0] iv; // From inst of inst.v
6341f357 11548 // End of automatics
1dd4b004
DN
11549 InstModule instName
11550 (/*AUTOINST*/
11551 // Outputs
11552 .o (o[31:0]),
11553 // Inputs
11554 .iv (iv));
6341f357
DN
11555 endmodule"
11556 (save-excursion
11557 ;; Point must be at insertion point.
11558 (let* ((indent-pt (current-indentation))
11559 (modi (verilog-modi-current))
5509c6ad
DN
11560 (moddecls (verilog-modi-get-decls modi))
11561 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357
DN
11562 (sig-list (verilog-signals-combine-bus
11563 (verilog-signals-not-in
5509c6ad
DN
11564 (append (verilog-subdecls-get-inputs modsubdecls)
11565 (verilog-subdecls-get-inouts modsubdecls))
9489a450
MM
11566 (append (verilog-decls-get-signals moddecls)
11567 (verilog-decls-get-assigns moddecls))))))
6341f357 11568 (when sig-list
179f044b 11569 (verilog-forward-or-insert-line)
6341f357 11570 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
9489a450 11571 (verilog-insert-definition modi sig-list "reg" indent-pt nil)
60618039 11572 (verilog-insert-indent "// End of automatics\n")))))
6341f357 11573
47086495
WS
11574(defun verilog-auto-logic-setup ()
11575 "Prepare variables due to AUTOLOGIC."
11576 (unless verilog-auto-wire-type
11577 (set (make-local-variable 'verilog-auto-wire-type)
11578 "logic")))
11579
9489a450
MM
11580(defun verilog-auto-logic ()
11581 "Expand AUTOLOGIC statements, as part of \\[verilog-auto].
11582Make wire statements using the SystemVerilog logic keyword.
99d99081 11583This is currently equivalent to:
9489a450
MM
11584
11585 /*AUTOWIRE*/
11586
11587with the below at the bottom of the file
11588
11589 // Local Variables:
11590 // verilog-auto-logic-type:\"logic\"
11591 // End:
11592
11593In the future AUTOLOGIC may declare additional identifiers,
11594while AUTOWIRE will not."
11595 (save-excursion
47086495 11596 (verilog-auto-logic-setup)
9489a450
MM
11597 (verilog-auto-wire)))
11598
6341f357
DN
11599(defun verilog-auto-wire ()
11600 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
11601Make wire statements for instantiations outputs that aren't
47086495 11602already declared. `verilog-auto-wire-type' may be used to change
9489a450 11603the datatype of the declarations.
6341f357
DN
11604
11605Limitations:
11606 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
301b181a 11607 and all buses must have widths, such as those from AUTOINST, or using []
6341f357
DN
11608 in AUTO_TEMPLATEs.
11609
11610 This does NOT work on memories or SystemVerilog .name connections,
11611 declare those yourself.
11612
37ea4b9b
JB
11613 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
11614 determine how to bus together. This occurs when you have ports with
11615 non-numeric or non-sequential bus subscripts. If Verilog mode
6341f357
DN
11616 mis-guessed, you'll have to declare them yourself.
11617
11618An example (see `verilog-auto-inst' for what else is going on here):
11619
a03c2342 11620 module ExampWire (o,i);
6341f357
DN
11621 output o;
11622 input i;
11623 /*AUTOWIRE*/
1dd4b004
DN
11624 InstModule instName
11625 (/*AUTOINST*/);
6341f357
DN
11626 endmodule
11627
11628Typing \\[verilog-auto] will make this into:
11629
a03c2342 11630 module ExampWire (o,i);
6341f357
DN
11631 output o;
11632 input i;
11633 /*AUTOWIRE*/
11634 // Beginning of automatic wires
11635 wire [31:0] ov; // From inst of inst.v
11636 // End of automatics
1dd4b004
DN
11637 InstModule instName
11638 (/*AUTOINST*/
11639 // Outputs
11640 .ov (ov[31:0]),
11641 // Inputs
11642 .i (i));
6341f357
DN
11643 wire o = | ov;
11644 endmodule"
11645 (save-excursion
11646 ;; Point must be at insertion point.
11647 (let* ((indent-pt (current-indentation))
11648 (modi (verilog-modi-current))
5509c6ad
DN
11649 (moddecls (verilog-modi-get-decls modi))
11650 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357
DN
11651 (sig-list (verilog-signals-combine-bus
11652 (verilog-signals-not-in
5509c6ad
DN
11653 (append (verilog-subdecls-get-outputs modsubdecls)
11654 (verilog-subdecls-get-inouts modsubdecls))
11655 (verilog-decls-get-signals moddecls)))))
6341f357 11656 (when sig-list
179f044b 11657 (verilog-forward-or-insert-line)
6341f357 11658 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
9489a450 11659 (verilog-insert-definition modi sig-list "wire" indent-pt nil)
6341f357 11660 (verilog-insert-indent "// End of automatics\n")
9489a450
MM
11661 ;; We used to optionally call verilog-pretty-declarations and
11662 ;; verilog-pretty-expr here, but it's too slow on huge modules,
11663 ;; plus makes everyone's module change. Finally those call
11664 ;; syntax-ppss which is broken when change hooks are disabled.
11665 ))))
6341f357 11666
179f044b 11667(defun verilog-auto-output ()
6341f357
DN
11668 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
11669Make output statements for any output signal from an /*AUTOINST*/ that
47086495 11670isn't an input to another AUTOINST. This is useful for modules which
6341f357
DN
11671only instantiate other modules.
11672
11673Limitations:
11674 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11675
11676 If placed inside the parenthesis of a module declaration, it creates
11677 Verilog 2001 style, else uses Verilog 1995 style.
11678
11679 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
47086495 11680 instantiation, all bets are off. (For example due to an AUTO_TEMPLATE).
6341f357
DN
11681
11682 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
11683
11684 Signals matching `verilog-auto-output-ignore-regexp' are not included.
11685
11686An example (see `verilog-auto-inst' for what else is going on here):
11687
a03c2342 11688 module ExampOutput (ov,i);
6341f357
DN
11689 input i;
11690 /*AUTOOUTPUT*/
1dd4b004
DN
11691 InstModule instName
11692 (/*AUTOINST*/);
6341f357
DN
11693 endmodule
11694
11695Typing \\[verilog-auto] will make this into:
11696
a03c2342 11697 module ExampOutput (ov,i);
6341f357
DN
11698 input i;
11699 /*AUTOOUTPUT*/
11700 // Beginning of automatic outputs (from unused autoinst outputs)
1dd4b004 11701 output [31:0] ov; // From inst of inst.v
6341f357 11702 // End of automatics
1dd4b004
DN
11703 InstModule instName
11704 (/*AUTOINST*/
11705 // Outputs
11706 .ov (ov[31:0]),
11707 // Inputs
11708 .i (i));
e2076c2c
DN
11709 endmodule
11710
11711You may also provide an optional regular expression, in which case only
11712signals matching the regular expression will be included. For example the
11713same expansion will result from only extracting outputs starting with ov:
11714
11715 /*AUTOOUTPUT(\"^ov\")*/"
6341f357
DN
11716 (save-excursion
11717 ;; Point must be at insertion point.
11718 (let* ((indent-pt (current-indentation))
179f044b
WS
11719 (params (verilog-read-auto-params 0 1))
11720 (regexp (nth 0 params))
9489a450 11721 (v2k (verilog-in-paren-quick))
6341f357 11722 (modi (verilog-modi-current))
5509c6ad
DN
11723 (moddecls (verilog-modi-get-decls modi))
11724 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 11725 (sig-list (verilog-signals-not-in
5509c6ad
DN
11726 (verilog-subdecls-get-outputs modsubdecls)
11727 (append (verilog-decls-get-outputs moddecls)
11728 (verilog-decls-get-inouts moddecls)
ea89ff08 11729 (verilog-decls-get-inputs moddecls)
5509c6ad
DN
11730 (verilog-subdecls-get-inputs modsubdecls)
11731 (verilog-subdecls-get-inouts modsubdecls)))))
e2076c2c
DN
11732 (when regexp
11733 (setq sig-list (verilog-signals-matching-regexp
11734 sig-list regexp)))
6341f357
DN
11735 (setq sig-list (verilog-signals-not-matching-regexp
11736 sig-list verilog-auto-output-ignore-regexp))
179f044b 11737 (verilog-forward-or-insert-line)
6341f357
DN
11738 (when v2k (verilog-repair-open-comma))
11739 (when sig-list
11740 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
9489a450 11741 (verilog-insert-definition modi sig-list "output" indent-pt v2k)
6341f357 11742 (verilog-insert-indent "// End of automatics\n"))
60618039 11743 (when v2k (verilog-repair-close-comma)))))
6341f357
DN
11744
11745(defun verilog-auto-output-every ()
11746 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
11747Make output statements for any signals that aren't primary inputs or
47086495 11748outputs already. This makes every signal in the design an output. This is
6341f357
DN
11749useful to get Synopsys to preserve every signal in the design, since it
11750won't optimize away the outputs.
11751
11752An example:
11753
a03c2342 11754 module ExampOutputEvery (o,i,tempa,tempb);
6341f357
DN
11755 output o;
11756 input i;
11757 /*AUTOOUTPUTEVERY*/
11758 wire tempa = i;
11759 wire tempb = tempa;
11760 wire o = tempb;
11761 endmodule
11762
11763Typing \\[verilog-auto] will make this into:
11764
a03c2342 11765 module ExampOutputEvery (o,i,tempa,tempb);
6341f357
DN
11766 output o;
11767 input i;
11768 /*AUTOOUTPUTEVERY*/
11769 // Beginning of automatic outputs (every signal)
1dd4b004
DN
11770 output tempb;
11771 output tempa;
6341f357
DN
11772 // End of automatics
11773 wire tempa = i;
11774 wire tempb = tempa;
11775 wire o = tempb;
11776 endmodule"
11777 (save-excursion
11778 ;;Point must be at insertion point
11779 (let* ((indent-pt (current-indentation))
9489a450 11780 (v2k (verilog-in-paren-quick))
6341f357 11781 (modi (verilog-modi-current))
5509c6ad 11782 (moddecls (verilog-modi-get-decls modi))
6341f357
DN
11783 (sig-list (verilog-signals-combine-bus
11784 (verilog-signals-not-in
5509c6ad
DN
11785 (verilog-decls-get-signals moddecls)
11786 (verilog-decls-get-ports moddecls)))))
179f044b 11787 (verilog-forward-or-insert-line)
6341f357
DN
11788 (when v2k (verilog-repair-open-comma))
11789 (when sig-list
11790 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
9489a450 11791 (verilog-insert-definition modi sig-list "output" indent-pt v2k)
6341f357 11792 (verilog-insert-indent "// End of automatics\n"))
60618039 11793 (when v2k (verilog-repair-close-comma)))))
6341f357 11794
179f044b 11795(defun verilog-auto-input ()
6341f357
DN
11796 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
11797Make input statements for any input signal into an /*AUTOINST*/ that
11798isn't declared elsewhere inside the module. This is useful for modules which
11799only instantiate other modules.
11800
11801Limitations:
11802 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11803
11804 If placed inside the parenthesis of a module declaration, it creates
11805 Verilog 2001 style, else uses Verilog 1995 style.
11806
11807 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
47086495 11808 instantiation, all bets are off. (For example due to an AUTO_TEMPLATE).
6341f357
DN
11809
11810 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
11811
11812 Signals matching `verilog-auto-input-ignore-regexp' are not included.
11813
11814An example (see `verilog-auto-inst' for what else is going on here):
11815
a03c2342 11816 module ExampInput (ov,i);
6341f357
DN
11817 output [31:0] ov;
11818 /*AUTOINPUT*/
1dd4b004
DN
11819 InstModule instName
11820 (/*AUTOINST*/);
6341f357
DN
11821 endmodule
11822
11823Typing \\[verilog-auto] will make this into:
11824
a03c2342 11825 module ExampInput (ov,i);
6341f357
DN
11826 output [31:0] ov;
11827 /*AUTOINPUT*/
11828 // Beginning of automatic inputs (from unused autoinst inputs)
1dd4b004 11829 input i; // From inst of inst.v
6341f357 11830 // End of automatics
1dd4b004
DN
11831 InstModule instName
11832 (/*AUTOINST*/
11833 // Outputs
11834 .ov (ov[31:0]),
11835 // Inputs
11836 .i (i));
e2076c2c
DN
11837 endmodule
11838
11839You may also provide an optional regular expression, in which case only
11840signals matching the regular expression will be included. For example the
11841same expansion will result from only extracting inputs starting with i:
11842
11843 /*AUTOINPUT(\"^i\")*/"
6341f357
DN
11844 (save-excursion
11845 (let* ((indent-pt (current-indentation))
179f044b
WS
11846 (params (verilog-read-auto-params 0 1))
11847 (regexp (nth 0 params))
9489a450 11848 (v2k (verilog-in-paren-quick))
6341f357 11849 (modi (verilog-modi-current))
5509c6ad
DN
11850 (moddecls (verilog-modi-get-decls modi))
11851 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 11852 (sig-list (verilog-signals-not-in
5509c6ad
DN
11853 (verilog-subdecls-get-inputs modsubdecls)
11854 (append (verilog-decls-get-inputs moddecls)
11855 (verilog-decls-get-inouts moddecls)
ea89ff08 11856 (verilog-decls-get-outputs moddecls)
9489a450 11857 (verilog-decls-get-vars moddecls)
5509c6ad
DN
11858 (verilog-decls-get-consts moddecls)
11859 (verilog-decls-get-gparams moddecls)
a03c2342 11860 (verilog-subdecls-get-interfaced modsubdecls)
5509c6ad
DN
11861 (verilog-subdecls-get-outputs modsubdecls)
11862 (verilog-subdecls-get-inouts modsubdecls)))))
e2076c2c
DN
11863 (when regexp
11864 (setq sig-list (verilog-signals-matching-regexp
11865 sig-list regexp)))
6341f357
DN
11866 (setq sig-list (verilog-signals-not-matching-regexp
11867 sig-list verilog-auto-input-ignore-regexp))
179f044b 11868 (verilog-forward-or-insert-line)
6341f357
DN
11869 (when v2k (verilog-repair-open-comma))
11870 (when sig-list
11871 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
9489a450 11872 (verilog-insert-definition modi sig-list "input" indent-pt v2k)
6341f357 11873 (verilog-insert-indent "// End of automatics\n"))
60618039 11874 (when v2k (verilog-repair-close-comma)))))
6341f357 11875
179f044b 11876(defun verilog-auto-inout ()
6341f357
DN
11877 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
11878Make inout statements for any inout signal in an /*AUTOINST*/ that
11879isn't declared elsewhere inside the module.
11880
11881Limitations:
11882 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11883
11884 If placed inside the parenthesis of a module declaration, it creates
11885 Verilog 2001 style, else uses Verilog 1995 style.
11886
11887 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
47086495 11888 instantiation, all bets are off. (For example due to an AUTO_TEMPLATE).
6341f357
DN
11889
11890 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
11891
11892 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
11893
11894An example (see `verilog-auto-inst' for what else is going on here):
11895
a03c2342 11896 module ExampInout (ov,i);
6341f357
DN
11897 input i;
11898 /*AUTOINOUT*/
1dd4b004
DN
11899 InstModule instName
11900 (/*AUTOINST*/);
6341f357
DN
11901 endmodule
11902
11903Typing \\[verilog-auto] will make this into:
11904
a03c2342 11905 module ExampInout (ov,i);
6341f357
DN
11906 input i;
11907 /*AUTOINOUT*/
11908 // Beginning of automatic inouts (from unused autoinst inouts)
1dd4b004 11909 inout [31:0] ov; // From inst of inst.v
6341f357 11910 // End of automatics
1dd4b004
DN
11911 InstModule instName
11912 (/*AUTOINST*/
11913 // Inouts
11914 .ov (ov[31:0]),
11915 // Inputs
11916 .i (i));
e2076c2c
DN
11917 endmodule
11918
11919You may also provide an optional regular expression, in which case only
11920signals matching the regular expression will be included. For example the
11921same expansion will result from only extracting inouts starting with i:
11922
11923 /*AUTOINOUT(\"^i\")*/"
6341f357
DN
11924 (save-excursion
11925 ;; Point must be at insertion point.
11926 (let* ((indent-pt (current-indentation))
179f044b
WS
11927 (params (verilog-read-auto-params 0 1))
11928 (regexp (nth 0 params))
9489a450 11929 (v2k (verilog-in-paren-quick))
6341f357 11930 (modi (verilog-modi-current))
5509c6ad
DN
11931 (moddecls (verilog-modi-get-decls modi))
11932 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 11933 (sig-list (verilog-signals-not-in
5509c6ad
DN
11934 (verilog-subdecls-get-inouts modsubdecls)
11935 (append (verilog-decls-get-outputs moddecls)
11936 (verilog-decls-get-inouts moddecls)
11937 (verilog-decls-get-inputs moddecls)
11938 (verilog-subdecls-get-inputs modsubdecls)
11939 (verilog-subdecls-get-outputs modsubdecls)))))
e2076c2c
DN
11940 (when regexp
11941 (setq sig-list (verilog-signals-matching-regexp
11942 sig-list regexp)))
6341f357
DN
11943 (setq sig-list (verilog-signals-not-matching-regexp
11944 sig-list verilog-auto-inout-ignore-regexp))
179f044b 11945 (verilog-forward-or-insert-line)
6341f357
DN
11946 (when v2k (verilog-repair-open-comma))
11947 (when sig-list
11948 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
9489a450 11949 (verilog-insert-definition modi sig-list "inout" indent-pt v2k)
6341f357 11950 (verilog-insert-indent "// End of automatics\n"))
60618039 11951 (when v2k (verilog-repair-close-comma)))))
6341f357 11952
9489a450 11953(defun verilog-auto-inout-module (&optional complement all-in)
6341f357
DN
11954 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
11955Take input/output/inout statements from the specified module and insert
11956into the current module. This is useful for making null templates and
37ea4b9b
JB
11957shell modules which need to have identical I/O with another module.
11958Any I/O which are already defined in this module will not be redefined.
9489a450
MM
11959For the complement of this function, see `verilog-auto-inout-comp',
11960and to make monitors with all inputs, see `verilog-auto-inout-in'.
6341f357
DN
11961
11962Limitations:
11963 If placed inside the parenthesis of a module declaration, it creates
11964 Verilog 2001 style, else uses Verilog 1995 style.
11965
301b181a 11966 Concatenation and outputting partial buses is not supported.
6341f357
DN
11967
11968 Module names must be resolvable to filenames. See `verilog-auto-inst'.
11969
11970 Signals are not inserted in the same order as in the original module,
47086495 11971 though they will appear to be in the same order to an AUTOINST
6341f357
DN
11972 instantiating either module.
11973
47086495
WS
11974 Signals declared as \"output reg\" or \"output wire\" etc will
11975 lose the wire/reg declaration so that shell modules may
11976 generate those outputs differently. However, \"output logic\"
11977 is propagated.
11978
6341f357
DN
11979An example:
11980
a03c2342 11981 module ExampShell (/*AUTOARG*/);
1dd4b004 11982 /*AUTOINOUTMODULE(\"ExampMain\")*/
6341f357
DN
11983 endmodule
11984
a03c2342 11985 module ExampMain (i,o,io);
6341f357
DN
11986 input i;
11987 output o;
11988 inout io;
11989 endmodule
11990
11991Typing \\[verilog-auto] will make this into:
11992
a03c2342 11993 module ExampShell (/*AUTOARG*/i,o,io);
1dd4b004 11994 /*AUTOINOUTMODULE(\"ExampMain\")*/
6341f357 11995 // Beginning of automatic in/out/inouts (from specific module)
6341f357
DN
11996 output o;
11997 inout io;
7cb1c4d7 11998 input i;
6341f357 11999 // End of automatics
1dd4b004
DN
12000 endmodule
12001
12002You may also provide an optional regular expression, in which case only
12003signals matching the regular expression will be included. For example the
12004same expansion will result from only extracting signals starting with i:
12005
a3a8b002
DN
12006 /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/
12007
14862301 12008You may also provide an optional second regular expression, in
a3a8b002
DN
12009which case only signals which have that pin direction and data
12010type will be included. This matches against everything before
12011the signal name in the declaration, for example against
12012\"input\" (single bit), \"output logic\" (direction and type) or
12013\"output [1:0]\" (direction and implicit type). You also
12014probably want to skip spaces in your regexp.
12015
12016For example, the below will result in matching the output \"o\"
12017against the previous example's module:
12018
12019 /*AUTOINOUTMODULE(\"ExampMain\",\"\",\"^output.*\")*/"
6341f357 12020 (save-excursion
a3a8b002 12021 (let* ((params (verilog-read-auto-params 1 3))
1dd4b004
DN
12022 (submod (nth 0 params))
12023 (regexp (nth 1 params))
a3a8b002 12024 (direction-re (nth 2 params))
1dd4b004 12025 submodi)
6341f357
DN
12026 ;; Lookup position, etc of co-module
12027 ;; Note this may raise an error
12028 (when (setq submodi (verilog-modi-lookup submod t))
12029 (let* ((indent-pt (current-indentation))
9489a450 12030 (v2k (verilog-in-paren-quick))
6341f357 12031 (modi (verilog-modi-current))
5509c6ad
DN
12032 (moddecls (verilog-modi-get-decls modi))
12033 (submoddecls (verilog-modi-get-decls submodi))
6341f357 12034 (sig-list-i (verilog-signals-not-in
9489a450
MM
12035 (cond (all-in
12036 (append
12037 (verilog-decls-get-inputs submoddecls)
12038 (verilog-decls-get-inouts submoddecls)
12039 (verilog-decls-get-outputs submoddecls)))
12040 (complement
12041 (verilog-decls-get-outputs submoddecls))
12042 (t (verilog-decls-get-inputs submoddecls)))
5509c6ad 12043 (append (verilog-decls-get-inputs moddecls))))
6341f357 12044 (sig-list-o (verilog-signals-not-in
9489a450
MM
12045 (cond (all-in nil)
12046 (complement
12047 (verilog-decls-get-inputs submoddecls))
12048 (t (verilog-decls-get-outputs submoddecls)))
5509c6ad 12049 (append (verilog-decls-get-outputs moddecls))))
6341f357 12050 (sig-list-io (verilog-signals-not-in
9489a450
MM
12051 (cond (all-in nil)
12052 (t (verilog-decls-get-inouts submoddecls)))
a3a8b002
DN
12053 (append (verilog-decls-get-inouts moddecls))))
12054 (sig-list-if (verilog-signals-not-in
12055 (verilog-decls-get-interfaces submoddecls)
12056 (append (verilog-decls-get-interfaces moddecls)))))
6341f357 12057 (forward-line 1)
47086495
WS
12058 (setq sig-list-i (verilog-signals-edit-wire-reg
12059 (verilog-signals-matching-dir-re
12060 (verilog-signals-matching-regexp sig-list-i regexp)
12061 "input" direction-re))
12062 sig-list-o (verilog-signals-edit-wire-reg
12063 (verilog-signals-matching-dir-re
12064 (verilog-signals-matching-regexp sig-list-o regexp)
12065 "output" direction-re))
12066 sig-list-io (verilog-signals-edit-wire-reg
12067 (verilog-signals-matching-dir-re
12068 (verilog-signals-matching-regexp sig-list-io regexp)
12069 "inout" direction-re))
a3a8b002
DN
12070 sig-list-if (verilog-signals-matching-dir-re
12071 (verilog-signals-matching-regexp sig-list-if regexp)
12072 "interface" direction-re))
6341f357
DN
12073 (when v2k (verilog-repair-open-comma))
12074 (when (or sig-list-i sig-list-o sig-list-io)
12075 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
47086495 12076 ;; Don't sort them so an upper AUTOINST will match the main module
9489a450
MM
12077 (verilog-insert-definition modi sig-list-o "output" indent-pt v2k t)
12078 (verilog-insert-definition modi sig-list-io "inout" indent-pt v2k t)
12079 (verilog-insert-definition modi sig-list-i "input" indent-pt v2k t)
12080 (verilog-insert-definition modi sig-list-if "interface" indent-pt v2k t)
6341f357 12081 (verilog-insert-indent "// End of automatics\n"))
60618039 12082 (when v2k (verilog-repair-close-comma)))))))
6341f357 12083
7cb1c4d7
DN
12084(defun verilog-auto-inout-comp ()
12085 "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
12086Take input/output/inout statements from the specified module and
12087insert the inverse into the current module (inputs become outputs
12088and vice-versa.) This is useful for making test and stimulus
12089modules which need to have complementing I/O with another module.
12090Any I/O which are already defined in this module will not be
a03c2342
WS
12091redefined. For the complement of this function, see
12092`verilog-auto-inout-module'.
7cb1c4d7
DN
12093
12094Limitations:
12095 If placed inside the parenthesis of a module declaration, it creates
12096 Verilog 2001 style, else uses Verilog 1995 style.
12097
301b181a 12098 Concatenation and outputting partial buses is not supported.
7cb1c4d7
DN
12099
12100 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12101
12102 Signals are not inserted in the same order as in the original module,
47086495 12103 though they will appear to be in the same order to an AUTOINST
7cb1c4d7
DN
12104 instantiating either module.
12105
12106An example:
12107
a03c2342 12108 module ExampShell (/*AUTOARG*/);
7cb1c4d7
DN
12109 /*AUTOINOUTCOMP(\"ExampMain\")*/
12110 endmodule
12111
a03c2342 12112 module ExampMain (i,o,io);
7cb1c4d7
DN
12113 input i;
12114 output o;
12115 inout io;
12116 endmodule
12117
12118Typing \\[verilog-auto] will make this into:
12119
a03c2342 12120 module ExampShell (/*AUTOARG*/i,o,io);
7cb1c4d7
DN
12121 /*AUTOINOUTCOMP(\"ExampMain\")*/
12122 // Beginning of automatic in/out/inouts (from specific module)
12123 output i;
12124 inout io;
12125 input o;
12126 // End of automatics
12127 endmodule
12128
12129You may also provide an optional regular expression, in which case only
12130signals matching the regular expression will be included. For example the
12131same expansion will result from only extracting signals starting with i:
12132
12133 /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/"
9489a450
MM
12134 (verilog-auto-inout-module t nil))
12135
12136(defun verilog-auto-inout-in ()
12137 "Expand AUTOINOUTIN statements, as part of \\[verilog-auto].
12138Take input/output/inout statements from the specified module and
12139insert them as all inputs into the current module. This is
12140useful for making monitor modules which need to see all signals
12141as inputs based on another module. Any I/O which are already
12142defined in this module will not be redefined. See also
12143`verilog-auto-inout-module'.
12144
12145Limitations:
12146 If placed inside the parenthesis of a module declaration, it creates
12147 Verilog 2001 style, else uses Verilog 1995 style.
12148
301b181a 12149 Concatenation and outputting partial buses is not supported.
9489a450
MM
12150
12151 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12152
12153 Signals are not inserted in the same order as in the original module,
47086495 12154 though they will appear to be in the same order to an AUTOINST
9489a450
MM
12155 instantiating either module.
12156
12157An example:
12158
12159 module ExampShell (/*AUTOARG*/);
12160 /*AUTOINOUTIN(\"ExampMain\")*/
12161 endmodule
12162
12163 module ExampMain (i,o,io);
12164 input i;
12165 output o;
12166 inout io;
12167 endmodule
12168
12169Typing \\[verilog-auto] will make this into:
12170
12171 module ExampShell (/*AUTOARG*/i,o,io);
12172 /*AUTOINOUTIN(\"ExampMain\")*/
12173 // Beginning of automatic in/out/inouts (from specific module)
12174 input i;
12175 input io;
12176 input o;
12177 // End of automatics
12178 endmodule
12179
12180You may also provide an optional regular expression, in which case only
12181signals matching the regular expression will be included. For example the
12182same expansion will result from only extracting signals starting with i:
12183
12184 /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/"
12185 (verilog-auto-inout-module nil t))
7cb1c4d7 12186
179f044b
WS
12187(defun verilog-auto-inout-param ()
12188 "Expand AUTOINOUTPARAM statements, as part of \\[verilog-auto].
12189Take input/output/inout statements from the specified module and insert
12190into the current module. This is useful for making null templates and
12191shell modules which need to have identical I/O with another module.
12192Any I/O which are already defined in this module will not be redefined.
12193For the complement of this function, see `verilog-auto-inout-comp',
12194and to make monitors with all inputs, see `verilog-auto-inout-in'.
12195
12196Limitations:
12197 If placed inside the parenthesis of a module declaration, it creates
12198 Verilog 2001 style, else uses Verilog 1995 style.
12199
179f044b
WS
12200 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12201
ea89ff08 12202 Parameters are inserted in the same order as in the original module.
179f044b 12203
ea89ff08 12204 Parameters do not have values, which is SystemVerilog 2009 syntax.
179f044b
WS
12205
12206An example:
12207
ea89ff08
WS
12208 module ExampShell ();
12209 /*AUTOINOUTPARAM(\"ExampMain\")*/
179f044b
WS
12210 endmodule
12211
ea89ff08
WS
12212 module ExampMain ();
12213 parameter PARAM = 22;
179f044b
WS
12214 endmodule
12215
12216Typing \\[verilog-auto] will make this into:
12217
12218 module ExampShell (/*AUTOARG*/i,o,io);
ea89ff08
WS
12219 /*AUTOINOUTPARAM(\"ExampMain\")*/
12220 // Beginning of automatic parameters (from specific module)
12221 parameter PARAM;
179f044b
WS
12222 // End of automatics
12223 endmodule
12224
12225You may also provide an optional regular expression, in which case only
ea89ff08
WS
12226parameters matching the regular expression will be included. For example the
12227same expansion will result from only extracting parameters starting with i:
179f044b 12228
ea89ff08 12229 /*AUTOINOUTPARAM(\"ExampMain\",\"^i\")*/"
179f044b
WS
12230 (save-excursion
12231 (let* ((params (verilog-read-auto-params 1 2))
12232 (submod (nth 0 params))
12233 (regexp (nth 1 params))
12234 submodi)
12235 ;; Lookup position, etc of co-module
12236 ;; Note this may raise an error
12237 (when (setq submodi (verilog-modi-lookup submod t))
12238 (let* ((indent-pt (current-indentation))
12239 (v2k (verilog-in-paren-quick))
12240 (modi (verilog-modi-current))
12241 (moddecls (verilog-modi-get-decls modi))
12242 (submoddecls (verilog-modi-get-decls submodi))
12243 (sig-list-p (verilog-signals-not-in
12244 (verilog-decls-get-gparams submoddecls)
12245 (append (verilog-decls-get-gparams moddecls)))))
12246 (forward-line 1)
12247 (setq sig-list-p (verilog-signals-matching-regexp sig-list-p regexp))
12248 (when v2k (verilog-repair-open-comma))
12249 (when sig-list-p
12250 (verilog-insert-indent "// Beginning of automatic parameters (from specific module)\n")
12251 ;; Don't sort them so an upper AUTOINST will match the main module
12252 (verilog-insert-definition modi sig-list-p "parameter" indent-pt v2k t)
12253 (verilog-insert-indent "// End of automatics\n"))
12254 (when v2k (verilog-repair-close-comma)))))))
12255
12256(defun verilog-auto-inout-modport ()
12257 "Expand AUTOINOUTMODPORT statements, as part of \\[verilog-auto].
12258Take input/output/inout statements from the specified interface
12259and modport and insert into the current module. This is useful
12260for making verification modules that connect to UVM interfaces.
12261
12262 The first parameter is the name of an interface.
12263
12264 The second parameter is a regexp of modports to read from in
12265 that interface.
12266
12267 The optional third parameter is a regular expression, and only
12268 signals matching the regular expression will be included.
12269
12270Limitations:
12271 If placed inside the parenthesis of a module declaration, it creates
12272 Verilog 2001 style, else uses Verilog 1995 style.
12273
12274 Interface names must be resolvable to filenames. See `verilog-auto-inst'.
12275
12276As with other autos, any inputs/outputs declared in the module
0f137a73 12277will suppress the AUTO from redeclaring an inputs/outputs by
179f044b
WS
12278the same name.
12279
12280An example:
12281
12282 interface ExampIf
12283 ( input logic clk );
12284 logic req_val;
12285 logic [7:0] req_dat;
12286 clocking mon_clkblk @(posedge clk);
12287 input req_val;
12288 input req_dat;
12289 endclocking
12290 modport mp(clocking mon_clkblk);
12291 endinterface
12292
12293 module ExampMain
12294 ( input clk,
12295 /*AUTOINOUTMODPORT(\"ExampIf\" \"mp\")*/
12296 // Beginning of automatic in/out/inouts (from modport)
12297 input [7:0] req_dat,
12298 input req_val
12299 // End of automatics
12300 );
12301 /*AUTOASSIGNMODPORT(\"ExampIf\" \"mp\")*/
12302 endmodule
12303
12304Typing \\[verilog-auto] will make this into:
12305
12306 ...
12307 module ExampMain
12308 ( input clk,
12309 /*AUTOINOUTMODPORT(\"ExampIf\" \"mp\")*/
12310 // Beginning of automatic in/out/inouts (from modport)
12311 input req_dat,
12312 input req_val
12313 // End of automatics
12314 );
12315
12316If the modport is part of a UVM monitor/driver class, this
12317creates a wrapper module that may be used to instantiate the
12318driver/monitor using AUTOINST in the testbench."
12319 (save-excursion
12320 (let* ((params (verilog-read-auto-params 2 3))
12321 (submod (nth 0 params))
12322 (modport-re (nth 1 params))
12323 (regexp (nth 2 params))
12324 direction-re submodi) ;; direction argument not supported until requested
12325 ;; Lookup position, etc of co-module
12326 ;; Note this may raise an error
12327 (when (setq submodi (verilog-modi-lookup submod t))
12328 (let* ((indent-pt (current-indentation))
12329 (v2k (verilog-in-paren-quick))
12330 (modi (verilog-modi-current))
12331 (moddecls (verilog-modi-get-decls modi))
12332 (submoddecls (verilog-modi-get-decls submodi))
12333 (submodportdecls (verilog-modi-modport-lookup submodi modport-re))
12334 (sig-list-i (verilog-signals-in ;; Decls doesn't have data types, must resolve
12335 (verilog-decls-get-vars submoddecls)
12336 (verilog-signals-not-in
12337 (verilog-decls-get-inputs submodportdecls)
12338 (append (verilog-decls-get-ports submoddecls)
12339 (verilog-decls-get-ports moddecls)))))
12340 (sig-list-o (verilog-signals-in ;; Decls doesn't have data types, must resolve
12341 (verilog-decls-get-vars submoddecls)
12342 (verilog-signals-not-in
12343 (verilog-decls-get-outputs submodportdecls)
12344 (append (verilog-decls-get-ports submoddecls)
12345 (verilog-decls-get-ports moddecls)))))
12346 (sig-list-io (verilog-signals-in ;; Decls doesn't have data types, must resolve
12347 (verilog-decls-get-vars submoddecls)
12348 (verilog-signals-not-in
12349 (verilog-decls-get-inouts submodportdecls)
12350 (append (verilog-decls-get-ports submoddecls)
12351 (verilog-decls-get-ports moddecls))))))
12352 (forward-line 1)
12353 (setq sig-list-i (verilog-signals-edit-wire-reg
12354 (verilog-signals-matching-dir-re
12355 (verilog-signals-matching-regexp sig-list-i regexp)
12356 "input" direction-re))
12357 sig-list-o (verilog-signals-edit-wire-reg
12358 (verilog-signals-matching-dir-re
12359 (verilog-signals-matching-regexp sig-list-o regexp)
12360 "output" direction-re))
12361 sig-list-io (verilog-signals-edit-wire-reg
12362 (verilog-signals-matching-dir-re
12363 (verilog-signals-matching-regexp sig-list-io regexp)
12364 "inout" direction-re)))
12365 (when v2k (verilog-repair-open-comma))
12366 (when (or sig-list-i sig-list-o sig-list-io)
12367 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from modport)\n")
12368 ;; Don't sort them so an upper AUTOINST will match the main module
12369 (verilog-insert-definition modi sig-list-o "output" indent-pt v2k t)
12370 (verilog-insert-definition modi sig-list-io "inout" indent-pt v2k t)
12371 (verilog-insert-definition modi sig-list-i "input" indent-pt v2k t)
12372 (verilog-insert-indent "// End of automatics\n"))
12373 (when v2k (verilog-repair-close-comma)))))))
12374
a3a8b002
DN
12375(defun verilog-auto-insert-lisp ()
12376 "Expand AUTOINSERTLISP statements, as part of \\[verilog-auto].
12377The Lisp code provided is called, and the Lisp code calls
12378`insert` to insert text into the current file beginning on the
12379line after the AUTOINSERTLISP.
12380
12381See also AUTO_LISP, which takes a Lisp expression and evaluates
12382it during `verilog-auto-inst' but does not insert any text.
12383
12384An example:
12385
12386 module ExampInsertLisp;
12387 /*AUTOINSERTLISP(my-verilog-insert-hello \"world\")*/
12388 endmodule
12389
12390 // For this example we declare the function in the
12391 // module's file itself. Often you'd define it instead
865fe16f 12392 // in a site-start.el or init file.
a3a8b002
DN
12393 /*
12394 Local Variables:
12395 eval:
12396 (defun my-verilog-insert-hello (who)
12397 (insert (concat \"initial $write(\\\"hello \" who \"\\\");\\n\")))
12398 End:
12399 */
12400
12401Typing \\[verilog-auto] will call my-verilog-insert-hello and
12402expand the above into:
12403
12404 // Beginning of automatic insert lisp
12405 initial $write(\"hello world\");
12406 // End of automatics
12407
12408You can also call an external program and insert the returned
12409text:
12410
12411 /*AUTOINSERTLISP(insert (shell-command-to-string \"echo //hello\"))*/
12412 // Beginning of automatic insert lisp
12413 //hello
12414 // End of automatics"
12415 (save-excursion
12416 ;; Point is at end of /*AUTO...*/
12417 (let* ((indent-pt (current-indentation))
12418 (cmd-end-pt (save-excursion (search-backward ")")
12419 (forward-char)
12420 (point))) ;; Closing paren
12421 (cmd-beg-pt (save-excursion (goto-char cmd-end-pt)
9489a450 12422 (backward-sexp 1) ;; Inside comment
a3a8b002
DN
12423 (point))) ;; Beginning paren
12424 (cmd (buffer-substring-no-properties cmd-beg-pt cmd-end-pt)))
179f044b 12425 (verilog-forward-or-insert-line)
0e5c8aed
DN
12426 ;; Some commands don't move point (like insert-file) so we always
12427 ;; add the begin/end comments, then delete it if not needed
12428 (verilog-insert-indent "// Beginning of automatic insert lisp\n")
12429 (verilog-insert-indent "// End of automatics\n")
12430 (forward-line -1)
12431 (eval (read cmd))
12432 (forward-line -1)
a03c2342 12433 (setq verilog-scan-cache-tick nil) ;; Clear cache; inserted unknown text
0e5c8aed 12434 (verilog-delete-empty-auto-pair))))
a3a8b002 12435
5509c6ad 12436(defun verilog-auto-sense-sigs (moddecls presense-sigs)
6341f357
DN
12437 "Return list of signals for current AUTOSENSE block."
12438 (let* ((sigss (verilog-read-always-signals))
12439 (sig-list (verilog-signals-not-params
12440 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
12441 (append (and (not verilog-auto-sense-include-inputs)
9489a450
MM
12442 (verilog-alw-get-outputs-delayed sigss))
12443 (and (not verilog-auto-sense-include-inputs)
12444 (verilog-alw-get-outputs-immediate sigss))
a03c2342 12445 (verilog-alw-get-temps sigss)
5509c6ad
DN
12446 (verilog-decls-get-consts moddecls)
12447 (verilog-decls-get-gparams moddecls)
6341f357
DN
12448 presense-sigs)))))
12449 sig-list))
12450
12451(defun verilog-auto-sense ()
12452 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
12453Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
12454with one automatically derived from all inputs declared in the always
12455statement. Signals that are generated within the same always block are NOT
12456placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
12457Long lines are split based on the `fill-column', see \\[set-fill-column].
12458
12459Limitations:
12460 Verilog does not allow memories (multidimensional arrays) in sensitivity
12461 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
12462
12463Constant signals:
12464 AUTOSENSE cannot always determine if a `define is a constant or a signal
47086495 12465 (it could be in an include file for example). If a `define or other signal
6341f357
DN
12466 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
12467 declaration anywhere in the module (parenthesis are required):
12468
12469 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
12470
12471 Better yet, use a parameter, which will be understood to be constant
12472 automatically.
12473
12474OOps!
12475 If AUTOSENSE makes a mistake, please report it. (First try putting
12476 a begin/end after your always!) As a workaround, if a signal that
12477 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
12478 If a signal should be in the sensitivity list wasn't, placing it before
12479 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
12480 autos are updated (or added if it occurs there already).
12481
12482An example:
12483
1dd4b004 12484 always @ (/*AS*/) begin
6341f357
DN
12485 /* AUTO_CONSTANT (`constant) */
12486 outin = ina | inb | `constant;
12487 out = outin;
12488 end
12489
12490Typing \\[verilog-auto] will make this into:
12491
1dd4b004 12492 always @ (/*AS*/ina or inb) begin
6341f357
DN
12493 /* AUTO_CONSTANT (`constant) */
12494 outin = ina | inb | `constant;
12495 out = outin;
1dd4b004
DN
12496 end
12497
12498Note in Verilog 2001, you can often get the same result from the new @*
12499operator. (This was added to the language in part due to AUTOSENSE!)
12500
12501 always @* begin
12502 outin = ina | inb | `constant;
12503 out = outin;
6341f357
DN
12504 end"
12505 (save-excursion
12506 ;; Find beginning
12507 (let* ((start-pt (save-excursion
9489a450 12508 (verilog-re-search-backward-quick "(" nil t)
6341f357
DN
12509 (point)))
12510 (indent-pt (save-excursion
12511 (or (and (goto-char start-pt) (1+ (current-column)))
12512 (current-indentation))))
12513 (modi (verilog-modi-current))
5509c6ad 12514 (moddecls (verilog-modi-get-decls modi))
6341f357 12515 (sig-memories (verilog-signals-memory
9489a450 12516 (verilog-decls-get-vars moddecls)))
6341f357
DN
12517 sig-list not-first presense-sigs)
12518 ;; Read signals in always, eliminate outputs from sense list
12519 (setq presense-sigs (verilog-signals-from-signame
12520 (save-excursion
12521 (verilog-read-signals start-pt (point)))))
5509c6ad 12522 (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
6341f357
DN
12523 (when sig-memories
12524 (let ((tlen (length sig-list)))
12525 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
a03c2342 12526 (if (not (eq tlen (length sig-list))) (verilog-insert " /*memory or*/ "))))
6341f357
DN
12527 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
12528 (save-excursion (goto-char (point))
9489a450
MM
12529 (verilog-re-search-backward-quick "[a-zA-Z0-9$_.%`]+" start-pt t)
12530 (verilog-re-search-backward-quick "\\s-" start-pt t)
6341f357 12531 (while (looking-at "\\s-`endif")
9489a450
MM
12532 (verilog-re-search-backward-quick "[a-zA-Z0-9$_.%`]+" start-pt t)
12533 (verilog-re-search-backward-quick "\\s-" start-pt t))
6341f357
DN
12534 (not (looking-at "\\s-or\\b"))))
12535 (setq not-first t))
12536 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
12537 (while sig-list
12538 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
12539 (insert "\n")
12540 (indent-to indent-pt)
12541 (if not-first (insert "or ")))
12542 (not-first (insert " or ")))
12543 (insert (verilog-sig-name (car sig-list)))
12544 (setq sig-list (cdr sig-list)
60618039 12545 not-first t)))))
6341f357
DN
12546
12547(defun verilog-auto-reset ()
12548 "Expand AUTORESET statements, as part of \\[verilog-auto].
12549Replace the /*AUTORESET*/ comment with code to initialize all
12550registers set elsewhere in the always block.
12551
12552Limitations:
12553 AUTORESET will not clear memories.
12554
9489a450 12555 AUTORESET uses <= if the signal has a <= assignment in the block,
a3a8b002 12556 else it uses =.
6341f357 12557
9489a450
MM
12558 If <= is used, all = assigned variables are ignored if
12559 `verilog-auto-reset-blocking-in-non' is nil; they are presumed
12560 to be temporaries.
12561
6341f357
DN
12562/*AUTORESET*/ presumes that any signals mentioned between the previous
12563begin/case/if statement and the AUTORESET comment are being reset manually
12564and should not be automatically reset. This includes omitting any signals
12565used on the right hand side of assignments.
12566
47086495
WS
12567By default, AUTORESET will include the width of the signal in the
12568autos, SystemVerilog designs may want to change this. To control
bc8bc17d
WS
12569this behavior, see `verilog-auto-reset-widths'. In some cases
12570AUTORESET must use a '0 assignment and it will print NOWIDTH; use
12571`verilog-auto-reset-widths' unbased to prevent this.
6341f357
DN
12572
12573AUTORESET ties signals to deasserted, which is presumed to be zero.
22bcf204 12574Signals that match `verilog-active-low-regexp' will be deasserted by tying
6341f357
DN
12575them to a one.
12576
bc8bc17d
WS
12577AUTORESET may try to reset arrays or structures that cannot be
12578reset by a simple assignment, resulting in compile errors. This
12579is a feature to be taken as a hint that you need to reset these
12580signals manually (or put them into a \"`ifdef NEVER signal<=`0;
12581`endif\" so Verilog-Mode ignores them.)
12582
6341f357
DN
12583An example:
12584
12585 always @(posedge clk or negedge reset_l) begin
12586 if (!reset_l) begin
12587 c <= 1;
12588 /*AUTORESET*/
12589 end
12590 else begin
12591 a <= in_a;
12592 b <= in_b;
12593 c <= in_c;
12594 end
12595 end
12596
12597Typing \\[verilog-auto] will make this into:
12598
12599 always @(posedge core_clk or negedge reset_l) begin
12600 if (!reset_l) begin
12601 c <= 1;
12602 /*AUTORESET*/
12603 // Beginning of autoreset for uninitialized flops
12604 a <= 0;
9489a450 12605 b = 0; // if `verilog-auto-reset-blocking-in-non' true
6341f357
DN
12606 // End of automatics
12607 end
12608 else begin
12609 a <= in_a;
9489a450 12610 b = in_b;
6341f357
DN
12611 c <= in_c;
12612 end
12613 end"
12614
12615 (interactive)
12616 (save-excursion
12617 ;; Find beginning
12618 (let* ((indent-pt (current-indentation))
12619 (modi (verilog-modi-current))
5509c6ad
DN
12620 (moddecls (verilog-modi-get-decls modi))
12621 (all-list (verilog-decls-get-signals moddecls))
9489a450 12622 sigss sig-list dly-list prereset-sigs)
6341f357
DN
12623 ;; Read signals in always, eliminate outputs from reset list
12624 (setq prereset-sigs (verilog-signals-from-signame
12625 (save-excursion
12626 (verilog-read-signals
12627 (save-excursion
9489a450 12628 (verilog-re-search-backward-quick "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
6341f357
DN
12629 (point))
12630 (point)))))
12631 (save-excursion
9489a450 12632 (verilog-re-search-backward-quick "@" nil t)
6341f357 12633 (setq sigss (verilog-read-always-signals)))
9489a450
MM
12634 (setq dly-list (verilog-alw-get-outputs-delayed sigss))
12635 (setq sig-list (verilog-signals-not-in (append
12636 (verilog-alw-get-outputs-delayed sigss)
12637 (when (or (not (verilog-alw-get-uses-delayed sigss))
12638 verilog-auto-reset-blocking-in-non)
12639 (verilog-alw-get-outputs-immediate sigss)))
a03c2342
WS
12640 (append
12641 (verilog-alw-get-temps sigss)
12642 prereset-sigs)))
6341f357
DN
12643 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
12644 (when sig-list
12645 (insert "\n");
a03c2342 12646 (verilog-insert-indent "// Beginning of autoreset for uninitialized flops\n");
6341f357
DN
12647 (while sig-list
12648 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
12649 (car sig-list))))
9489a450 12650 (indent-to indent-pt)
6341f357 12651 (insert (verilog-sig-name sig)
9489a450
MM
12652 (if (assoc (verilog-sig-name sig) dly-list)
12653 (concat " <= " verilog-assignment-delay)
12654 " = ")
47086495 12655 (verilog-sig-tieoff sig)
6341f357 12656 ";\n")
6341f357 12657 (setq sig-list (cdr sig-list))))
9489a450 12658 (verilog-insert-indent "// End of automatics")))))
6341f357
DN
12659
12660(defun verilog-auto-tieoff ()
12661 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
12662Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
12663signals to deasserted.
12664
12665/*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
12666input/output list as another module, but no internals. Specifically, it
12667finds all outputs in the module, and if that input is not otherwise declared
12668as a register or wire, creates a tieoff.
12669
12670AUTORESET ties signals to deasserted, which is presumed to be zero.
22bcf204 12671Signals that match `verilog-active-low-regexp' will be deasserted by tying
6341f357
DN
12672them to a one.
12673
a03c2342
WS
12674You can add signals you do not want included in AUTOTIEOFF with
12675`verilog-auto-tieoff-ignore-regexp'.
12676
9489a450
MM
12677`verilog-auto-wire-type' may be used to change the datatype of
12678the declarations.
12679
47086495
WS
12680`verilog-auto-reset-widths' may be used to change how the tieoff
12681value's width is generated.
12682
6341f357
DN
12683An example of making a stub for another module:
12684
1dd4b004 12685 module ExampStub (/*AUTOINST*/);
179f044b 12686 /*AUTOINOUTPARAM(\"Foo\")*/
6341f357
DN
12687 /*AUTOINOUTMODULE(\"Foo\")*/
12688 /*AUTOTIEOFF*/
12689 // verilator lint_off UNUSED
12690 wire _unused_ok = &{1'b0,
12691 /*AUTOUNUSED*/
12692 1'b0};
12693 // verilator lint_on UNUSED
12694 endmodule
12695
12696Typing \\[verilog-auto] will make this into:
12697
1dd4b004 12698 module ExampStub (/*AUTOINST*/...);
179f044b 12699 /*AUTOINOUTPARAM(\"Foo\")*/
6341f357
DN
12700 /*AUTOINOUTMODULE(\"Foo\")*/
12701 // Beginning of autotieoff
12702 output [2:0] foo;
12703 // End of automatics
12704
12705 /*AUTOTIEOFF*/
12706 // Beginning of autotieoff
12707 wire [2:0] foo = 3'b0;
12708 // End of automatics
12709 ...
12710 endmodule"
12711 (interactive)
12712 (save-excursion
12713 ;; Find beginning
12714 (let* ((indent-pt (current-indentation))
12715 (modi (verilog-modi-current))
5509c6ad
DN
12716 (moddecls (verilog-modi-get-decls modi))
12717 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 12718 (sig-list (verilog-signals-not-in
5509c6ad 12719 (verilog-decls-get-outputs moddecls)
9489a450 12720 (append (verilog-decls-get-vars moddecls)
5509c6ad
DN
12721 (verilog-decls-get-assigns moddecls)
12722 (verilog-decls-get-consts moddecls)
12723 (verilog-decls-get-gparams moddecls)
a03c2342 12724 (verilog-subdecls-get-interfaced modsubdecls)
5509c6ad
DN
12725 (verilog-subdecls-get-outputs modsubdecls)
12726 (verilog-subdecls-get-inouts modsubdecls)))))
a03c2342
WS
12727 (setq sig-list (verilog-signals-not-matching-regexp
12728 sig-list verilog-auto-tieoff-ignore-regexp))
6341f357 12729 (when sig-list
179f044b 12730 (verilog-forward-or-insert-line)
6341f357
DN
12731 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
12732 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
9489a450 12733 (verilog-modi-cache-add-vars modi sig-list) ; Before we trash list
6341f357
DN
12734 (while sig-list
12735 (let ((sig (car sig-list)))
9489a450
MM
12736 (cond ((equal verilog-auto-tieoff-declaration "assign")
12737 (indent-to indent-pt)
12738 (insert "assign " (verilog-sig-name sig)))
12739 (t
12740 (verilog-insert-one-definition sig verilog-auto-tieoff-declaration indent-pt)))
6341f357
DN
12741 (indent-to (max 48 (+ indent-pt 40)))
12742 (insert "= " (verilog-sig-tieoff sig)
12743 ";\n")
12744 (setq sig-list (cdr sig-list))))
60618039 12745 (verilog-insert-indent "// End of automatics\n")))))
6341f357 12746
47086495
WS
12747(defun verilog-auto-undef ()
12748 "Expand AUTOUNDEF statements, as part of \\[verilog-auto].
12749Take any `defines since the last AUTOUNDEF in the current file
12750and create `undefs for them. This is used to insure that
c846da43 12751file-local defines do not pollute the global `define name space.
47086495
WS
12752
12753Limitations:
12754 AUTOUNDEF presumes any identifier following `define is the
12755 name of a define. Any `ifdefs are ignored.
12756
12757 AUTOUNDEF suppresses creating an `undef for any define that was
12758 `undefed before the AUTOUNDEF. This may be used to work around
12759 the ignoring of `ifdefs as shown below.
12760
12761An example:
12762
12763 `define XX_FOO
12764 `define M_BAR(x)
12765 `define M_BAZ
12766 ...
12767 `ifdef NEVER
12768 `undef M_BAZ // Emacs will see this and not `undef M_BAZ
12769 `endif
12770 ...
12771 /*AUTOUNDEF*/
12772
12773Typing \\[verilog-auto] will make this into:
12774
12775 ...
12776 /*AUTOUNDEF*/
12777 // Beginning of automatic undefs
12778 `undef XX_FOO
12779 `undef M_BAR
12780 // End of automatics
12781
12782You may also provide an optional regular expression, in which case only
12783defines the regular expression will be undefed."
12784 (save-excursion
12785 (let* ((params (verilog-read-auto-params 0 1))
12786 (regexp (nth 0 params))
12787 (indent-pt (current-indentation))
12788 (end-pt (point))
12789 defs def)
12790 (save-excursion
c846da43 12791 ;; Scan from start of file, or last AUTOUNDEF
47086495
WS
12792 (or (verilog-re-search-backward-quick "/\\*AUTOUNDEF\\>" end-pt t)
12793 (goto-char (point-min)))
12794 (while (verilog-re-search-forward-quick
12795 "`\\(define\\|undef\\)\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" end-pt t)
12796 (cond ((equal (match-string-no-properties 1) "define")
12797 (setq def (match-string-no-properties 2))
12798 (when (and (or (not regexp)
12799 (string-match regexp def))
12800 (not (member def defs))) ;; delete-dups not in 21.1
12801 (setq defs (cons def defs))))
12802 (t
12803 (setq defs (delete (match-string-no-properties 2) defs))))))
12804 ;; Insert
12805 (setq defs (sort defs 'string<))
12806 (when defs
179f044b 12807 (verilog-forward-or-insert-line)
47086495
WS
12808 (verilog-insert-indent "// Beginning of automatic undefs\n")
12809 (while defs
12810 (verilog-insert-indent "`undef " (car defs) "\n")
12811 (setq defs (cdr defs)))
12812 (verilog-insert-indent "// End of automatics\n")))))
12813
6341f357
DN
12814(defun verilog-auto-unused ()
12815 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
12816Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
12817input and inout signals.
12818
12819/*AUTOUNUSED*/ is used to make stub modules; modules that have the same
12820input/output list as another module, but no internals. Specifically, it
12821finds all inputs and inouts in the module, and if that input is not otherwise
12822used, adds it to a comma separated list.
12823
12824The comma separated list is intended to be used to create a _unused_ok
12825signal. Using the exact name \"_unused_ok\" for name of the temporary
12826signal is recommended as it will insure maximum forward compatibility, it
12827also makes lint warnings easy to understand; ignore any unused warnings
12828with \"unused\" in the signal name.
12829
12830To reduce simulation time, the _unused_ok signal should be forced to a
12831constant to prevent wiggling. The easiest thing to do is use a
12832reduction-and with 1'b0 as shown.
12833
12834This way all unused signals are in one place, making it convenient to add
12835your tool's specific pragmas around the assignment to disable any unused
12836warnings.
12837
12838You can add signals you do not want included in AUTOUNUSED with
12839`verilog-auto-unused-ignore-regexp'.
12840
12841An example of making a stub for another module:
12842
1dd4b004 12843 module ExampStub (/*AUTOINST*/);
179f044b 12844 /*AUTOINOUTPARAM(\"Examp\")*/
1dd4b004 12845 /*AUTOINOUTMODULE(\"Examp\")*/
6341f357
DN
12846 /*AUTOTIEOFF*/
12847 // verilator lint_off UNUSED
12848 wire _unused_ok = &{1'b0,
12849 /*AUTOUNUSED*/
12850 1'b0};
12851 // verilator lint_on UNUSED
12852 endmodule
12853
12854Typing \\[verilog-auto] will make this into:
12855
12856 ...
12857 // verilator lint_off UNUSED
12858 wire _unused_ok = &{1'b0,
12859 /*AUTOUNUSED*/
12860 // Beginning of automatics
12861 unused_input_a,
12862 unused_input_b,
12863 unused_input_c,
12864 // End of automatics
12865 1'b0};
12866 // verilator lint_on UNUSED
12867 endmodule"
12868 (interactive)
12869 (save-excursion
12870 ;; Find beginning
12871 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
12872 (modi (verilog-modi-current))
5509c6ad
DN
12873 (moddecls (verilog-modi-get-decls modi))
12874 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 12875 (sig-list (verilog-signals-not-in
5509c6ad
DN
12876 (append (verilog-decls-get-inputs moddecls)
12877 (verilog-decls-get-inouts moddecls))
12878 (append (verilog-subdecls-get-inputs modsubdecls)
12879 (verilog-subdecls-get-inouts modsubdecls)))))
6341f357
DN
12880 (setq sig-list (verilog-signals-not-matching-regexp
12881 sig-list verilog-auto-unused-ignore-regexp))
12882 (when sig-list
179f044b 12883 (verilog-forward-or-insert-line)
6341f357
DN
12884 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
12885 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
12886 (while sig-list
12887 (let ((sig (car sig-list)))
12888 (indent-to indent-pt)
12889 (insert (verilog-sig-name sig) ",\n")
12890 (setq sig-list (cdr sig-list))))
60618039 12891 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
12892
12893(defun verilog-enum-ascii (signm elim-regexp)
37ea4b9b 12894 "Convert an enum name SIGNM to an ascii string for insertion.
6341f357
DN
12895Remove user provided prefix ELIM-REGEXP."
12896 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
12897 (let ((case-fold-search t))
12898 ;; All upper becomes all lower for readability
12899 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
12900
12901(defun verilog-auto-ascii-enum ()
12902 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
47086495 12903Create a register to contain the ASCII decode of an enumerated signal type.
6341f357
DN
12904This will allow trace viewers to show the ASCII name of states.
12905
47086495 12906First, parameters are built into an enumeration using the synopsys enum
6341f357 12907comment. The comment must be between the keyword and the symbol.
6edb5716 12908\(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
6341f357
DN
12909
12910Next, registers which that enum applies to are also tagged with the same
9489a450 12911enum.
6341f357 12912
47086495 12913Finally, an AUTOASCIIENUM command is used.
6341f357
DN
12914
12915 The first parameter is the name of the signal to be decoded.
12916
12917 The second parameter is the name to store the ASCII code into. For the
12918 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
12919 a signal that is just for simulation, and the magic characters _ascii
12920 tell viewers like Dinotrace to display in ASCII format.
12921
9489a450 12922 The third optional parameter is a string which will be removed
47086495 12923 from the state names. It defaults to \"\" which removes nothing.
9489a450
MM
12924
12925 The fourth optional parameter is \"onehot\" to force one-hot
47086495 12926 decoding. If unspecified, if and only if the first parameter
9489a450 12927 width is 2^(number of states in enum) and does NOT match the
47086495 12928 width of the enum, the signal is assumed to be a one-hot
9489a450
MM
12929 decode. Otherwise, it's a normal encoded state vector.
12930
12931 `verilog-auto-wire-type' may be used to change the datatype of
12932 the declarations.
6341f357 12933
47086495
WS
12934 \"auto enum\" may be used in place of \"synopsys enum\".
12935
6341f357
DN
12936An example:
12937
12938 //== State enumeration
12939 parameter [2:0] // synopsys enum state_info
12940 SM_IDLE = 3'b000,
12941 SM_SEND = 3'b001,
12942 SM_WAIT1 = 3'b010;
12943 //== State variables
a3a8b002
DN
12944 reg [2:0] /* synopsys enum state_info */
12945 state_r; /* synopsys state_vector state_r */
12946 reg [2:0] /* synopsys enum state_info */
12947 state_e1;
6341f357
DN
12948
12949 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
12950
12951Typing \\[verilog-auto] will make this into:
12952
12953 ... same front matter ...
12954
12955 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
12956 // Beginning of automatic ASCII enum decoding
12957 reg [39:0] state_ascii_r; // Decode of state_r
12958 always @(state_r) begin
12959 case ({state_r})
12960 SM_IDLE: state_ascii_r = \"idle \";
12961 SM_SEND: state_ascii_r = \"send \";
12962 SM_WAIT1: state_ascii_r = \"wait1\";
12963 default: state_ascii_r = \"%Erro\";
12964 endcase
12965 end
12966 // End of automatics"
12967 (save-excursion
9489a450 12968 (let* ((params (verilog-read-auto-params 2 4))
6341f357
DN
12969 (undecode-name (nth 0 params))
12970 (ascii-name (nth 1 params))
9489a450
MM
12971 (elim-regexp (and (nth 2 params)
12972 (not (equal (nth 2 params) ""))
12973 (nth 2 params)))
12974 (one-hot-flag (nth 3 params))
6341f357
DN
12975 ;;
12976 (indent-pt (current-indentation))
12977 (modi (verilog-modi-current))
5509c6ad 12978 (moddecls (verilog-modi-get-decls modi))
6341f357 12979 ;;
5509c6ad
DN
12980 (sig-list-consts (append (verilog-decls-get-consts moddecls)
12981 (verilog-decls-get-gparams moddecls)))
179f044b 12982 (sig-list-all (verilog-decls-get-iovars moddecls))
6341f357
DN
12983 ;;
12984 (undecode-sig (or (assoc undecode-name sig-list-all)
12985 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
12986 (undecode-enum (or (verilog-sig-enum undecode-sig)
47086495 12987 (error "%s: Signal %s does not have an enum tag" (verilog-point-text) undecode-name)))
6341f357 12988 ;;
a3a8b002
DN
12989 (enum-sigs (verilog-signals-not-in
12990 (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
12991 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum))
12992 nil))
6341f357 12993 ;;
9489a450
MM
12994 (one-hot (or
12995 (string-match "onehot" (or one-hot-flag ""))
12996 (and ;; width(enum) != width(sig)
12997 (or (not (verilog-sig-bits (car enum-sigs)))
12998 (not (equal (verilog-sig-width (car enum-sigs))
12999 (verilog-sig-width undecode-sig))))
13000 ;; count(enums) == width(sig)
13001 (equal (number-to-string (length enum-sigs))
13002 (verilog-sig-width undecode-sig)))))
ea89ff08 13003 (enum-chars 0)
6341f357
DN
13004 (ascii-chars 0))
13005 ;;
13006 ;; Find number of ascii chars needed
13007 (let ((tmp-sigs enum-sigs))
13008 (while tmp-sigs
13009 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
13010 ascii-chars (max ascii-chars (length (verilog-enum-ascii
13011 (verilog-sig-name (car tmp-sigs))
13012 elim-regexp)))
13013 tmp-sigs (cdr tmp-sigs))))
13014 ;;
179f044b 13015 (verilog-forward-or-insert-line)
6341f357
DN
13016 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
13017 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
13018 (concat "Decode of " undecode-name) nil nil))))
9489a450 13019 (verilog-insert-definition modi decode-sig-list "reg" indent-pt nil))
6341f357
DN
13020 ;;
13021 (verilog-insert-indent "always @(" undecode-name ") begin\n")
13022 (setq indent-pt (+ indent-pt verilog-indent-level))
9489a450 13023 (verilog-insert-indent "case ({" undecode-name "})\n")
6341f357
DN
13024 (setq indent-pt (+ indent-pt verilog-case-indent))
13025 ;;
13026 (let ((tmp-sigs enum-sigs)
a3a8b002
DN
13027 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n"
13028 (+ (if one-hot 9 1) (max 8 enum-chars))
6341f357
DN
13029 ascii-name ascii-chars))
13030 (errname (substring "%Error" 0 (min 6 ascii-chars))))
13031 (while tmp-sigs
13032 (verilog-insert-indent
a3a8b002
DN
13033 (concat
13034 (format chrfmt
13035 (concat (if one-hot "(")
9489a450
MM
13036 ;; Use enum-sigs length as that's numeric
13037 ;; verilog-sig-width undecode-sig might not be.
13038 (if one-hot (number-to-string (length enum-sigs)))
a3a8b002
DN
13039 ;; We use a shift instead of var[index]
13040 ;; so that a non-one hot value will show as error.
13041 (if one-hot "'b1<<")
13042 (verilog-sig-name (car tmp-sigs))
13043 (if one-hot ")") ":")
13044 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
13045 elim-regexp))))
6341f357
DN
13046 (setq tmp-sigs (cdr tmp-sigs)))
13047 (verilog-insert-indent (format chrfmt "default:" errname)))
13048 ;;
13049 (setq indent-pt (- indent-pt verilog-case-indent))
13050 (verilog-insert-indent "endcase\n")
13051 (setq indent-pt (- indent-pt verilog-indent-level))
13052 (verilog-insert-indent "end\n"
60618039 13053 "// End of automatics\n"))))
6341f357
DN
13054
13055(defun verilog-auto-templated-rel ()
13056 "Replace Templated relative line numbers with absolute line numbers.
13057Internal use only. This hacks around the line numbers in AUTOINST Templates
13058being different from the final output's line numbering."
a03c2342 13059 (let ((templateno 0) (template-line (list 0)) (buf-line 1))
6341f357 13060 ;; Find line number each template is on
a03c2342 13061 ;; Count lines as we go, as otherwise it's O(n^2) to use count-lines
6341f357 13062 (goto-char (point-min))
a03c2342
WS
13063 (while (not (eobp))
13064 (when (looking-at ".*AUTO_TEMPLATE")
13065 (setq templateno (1+ templateno))
13066 (setq template-line (cons buf-line template-line)))
13067 (setq buf-line (1+ buf-line))
13068 (forward-line 1))
6341f357
DN
13069 (setq template-line (nreverse template-line))
13070 ;; Replace T# L# with absolute line number
13071 (goto-char (point-min))
13072 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
7ea26faf
DN
13073 (replace-match
13074 (concat " Templated "
13075 (int-to-string (+ (nth (string-to-number (match-string 1))
13076 template-line)
13077 (string-to-number (match-string 2)))))
13078 t t))))
6341f357 13079
47086495
WS
13080(defun verilog-auto-template-lint ()
13081 "Check AUTO_TEMPLATEs for unused lines.
13082Enable with `verilog-auto-template-warn-unused'."
13083 (let ((name1 (or (buffer-file-name) (buffer-name))))
13084 (save-excursion
13085 (goto-char (point-min))
13086 (while (re-search-forward
13087 "^\\s-*/?\\*?\\s-*[a-zA-Z0-9`_$]+\\s-+AUTO_TEMPLATE" nil t)
13088 (let* ((tpl-info (verilog-read-auto-template-middle))
13089 (tpl-list (aref tpl-info 1))
13090 (tlines (append (nth 0 tpl-list) (nth 1 tpl-list)))
13091 tpl-ass)
13092 (while tlines
13093 (setq tpl-ass (car tlines)
13094 tlines (cdr tlines))
13095 ;;;
13096 (unless (or (not (eval-when-compile (fboundp 'make-hash-table))) ;; Not supported, no warning
13097 (not verilog-auto-template-hits)
13098 (gethash (vector (nth 2 tpl-ass) (nth 3 tpl-ass))
13099 verilog-auto-template-hits))
13100 (verilog-warn-error "%s:%d: AUTO_TEMPLATE line unused: \".%s (%s)\""
13101 name1
13102 (+ (elt tpl-ass 3) ;; Template line number
13103 (count-lines (point-min) (point)))
13104 (elt tpl-ass 0) (elt tpl-ass 1))
13105 )))))))
13106
6341f357
DN
13107\f
13108;;
13109;; Auto top level
13110;;
13111
47086495 13112(defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing an arg
6341f357
DN
13113 "Expand AUTO statements.
13114Look for any /*AUTO...*/ commands in the code, as used in
13115instantiations or argument headers. Update the list of signals
13116following the /*AUTO...*/ command.
13117
13118Use \\[verilog-delete-auto] to remove the AUTOs.
13119
9489a450
MM
13120Use \\[verilog-diff-auto] to see differences in AUTO expansion.
13121
6341f357
DN
13122Use \\[verilog-inject-auto] to insert AUTOs for the first time.
13123
13124Use \\[verilog-faq] for a pointer to frequently asked questions.
13125
ea89ff08
WS
13126For new users, we recommend setting `verilog-case-fold' to nil
13127and `verilog-auto-arg-sort' to t.
13128
6341f357
DN
13129The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
13130called before and after this function, respectively.
13131
13132For example:
a03c2342 13133 module ModuleName (/*AUTOARG*/);
6341f357
DN
13134 /*AUTOINPUT*/
13135 /*AUTOOUTPUT*/
13136 /*AUTOWIRE*/
13137 /*AUTOREG*/
1dd4b004 13138 InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
6341f357
DN
13139
13140You can also update the AUTOs from the shell using:
13141 emacs --batch <filenames.v> -f verilog-batch-auto
13142Or fix indentation with:
13143 emacs --batch <filenames.v> -f verilog-batch-indent
13144Likewise, you can delete or inject AUTOs with:
13145 emacs --batch <filenames.v> -f verilog-batch-delete-auto
13146 emacs --batch <filenames.v> -f verilog-batch-inject-auto
9489a450
MM
13147Or check if AUTOs have the same expansion
13148 emacs --batch <filenames.v> -f verilog-batch-diff-auto
6341f357
DN
13149
13150Using \\[describe-function], see also:
13151 `verilog-auto-arg' for AUTOARG module instantiations
13152 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
179f044b 13153 `verilog-auto-assign-modport' for AUTOASSIGNMODPORT assignment to/from modport
ea89ff08 13154 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
9489a450
MM
13155 `verilog-auto-inout-comp' for AUTOINOUTCOMP copy complemented i/o
13156 `verilog-auto-inout-in' for AUTOINOUTIN inputs for all i/o
179f044b 13157 `verilog-auto-inout-modport' for AUTOINOUTMODPORT i/o from an interface modport
6341f357 13158 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
179f044b 13159 `verilog-auto-inout-param' for AUTOINOUTPARAM copying params from elsewhere
6341f357 13160 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
a3a8b002 13161 `verilog-auto-insert-lisp' for AUTOINSERTLISP insert code from lisp function
6341f357
DN
13162 `verilog-auto-inst' for AUTOINST instantiation pins
13163 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
13164 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
9489a450 13165 `verilog-auto-logic' for AUTOLOGIC declaring logic signals
6341f357
DN
13166 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
13167 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
13168 `verilog-auto-reg' for AUTOREG registers
13169 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
13170 `verilog-auto-reset' for AUTORESET flop resets
ea89ff08 13171 `verilog-auto-sense' for AUTOSENSE or AS always sensitivity lists
6341f357 13172 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
47086495 13173 `verilog-auto-undef' for AUTOUNDEF `undef of local `defines
6341f357
DN
13174 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
13175 `verilog-auto-wire' for AUTOWIRE instantiation wires
13176
13177 `verilog-read-defines' for reading `define values
13178 `verilog-read-includes' for reading `includes
13179
a3a8b002 13180If you have bugs with these autos, please file an issue at
855b42a2 13181URL `http://www.veripool.org/verilog-mode' or contact the AUTOAUTHOR
a3a8b002 13182Wilson Snyder (wsnyder@wsnyder.org)."
6341f357
DN
13183 (interactive)
13184 (unless noninteractive (message "Updating AUTOs..."))
7ea26faf 13185 (if (fboundp 'dinotrace-unannotate-all)
6341f357 13186 (dinotrace-unannotate-all))
47086495
WS
13187 (verilog-save-font-mods
13188 (let ((oldbuf (if (not (buffer-modified-p))
13189 (buffer-string)))
ea89ff08 13190 (case-fold-search verilog-case-fold)
47086495
WS
13191 ;; Cache directories; we don't write new files, so can't change
13192 (verilog-dir-cache-preserving t)
13193 ;; Cache current module
13194 (verilog-modi-cache-current-enable t)
13195 (verilog-modi-cache-current-max (point-min)) ; IE it's invalid
13196 verilog-modi-cache-current)
a03c2342
WS
13197 (unwind-protect
13198 ;; Disable change hooks for speed
13199 ;; This let can't be part of above let; must restore
13200 ;; after-change-functions before font-lock resumes
13201 (verilog-save-no-change-functions
13202 (verilog-save-scan-cache
13203 (save-excursion
9489a450
MM
13204 ;; Wipe cache; otherwise if we AUTOed a block above this one,
13205 ;; we'll misremember we have generated IOs, confusing AUTOOUTPUT
13206 (setq verilog-modi-cache-list nil)
47086495
WS
13207 ;; Local state
13208 (setq verilog-auto-template-hits nil)
a03c2342
WS
13209 ;; If we're not in verilog-mode, change syntax table so parsing works right
13210 (unless (eq major-mode `verilog-mode) (verilog-mode))
13211 ;; Allow user to customize
9489a450 13212 (verilog-run-hooks 'verilog-before-auto-hook)
a03c2342
WS
13213 ;; Try to save the user from needing to revert-file to reread file local-variables
13214 (verilog-auto-reeval-locals)
13215 (verilog-read-auto-lisp-present)
13216 (verilog-read-auto-lisp (point-min) (point-max))
13217 (verilog-getopt-flags)
13218 ;; From here on out, we can cache anything we read from disk
13219 (verilog-preserve-dir-cache
13220 ;; These two may seem obvious to do always, but on large includes it can be way too slow
13221 (when verilog-auto-read-includes
13222 (verilog-read-includes)
13223 (verilog-read-defines nil nil t))
47086495
WS
13224 ;; Setup variables due to SystemVerilog expansion
13225 (verilog-auto-re-search-do "/\\*AUTOLOGIC\\*/" 'verilog-auto-logic-setup)
a03c2342
WS
13226 ;; This particular ordering is important
13227 ;; INST: Lower modules correct, no internal dependencies, FIRST
13228 (verilog-preserve-modi-cache
13229 ;; Clear existing autos else we'll be screwed by existing ones
13230 (verilog-delete-auto)
13231 ;; Injection if appropriate
13232 (when inject
13233 (verilog-inject-inst)
13234 (verilog-inject-sense)
13235 (verilog-inject-arg))
13236 ;;
13237 ;; Do user inserts first, so their code can insert AUTOs
47086495 13238 ;; We may provide an AUTOINSERTLISPLAST if another cleanup pass is needed
a03c2342
WS
13239 (verilog-auto-re-search-do "/\\*AUTOINSERTLISP(.*?)\\*/"
13240 'verilog-auto-insert-lisp)
13241 ;; Expand instances before need the signals the instances input/output
13242 (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
13243 (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
13244 (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
13245 ;; Doesn't matter when done, but combine it with a common changer
13246 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
13247 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
13248 ;; Must be done before autoin/out as creates a reg
179f044b 13249 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM(.*?)\\*/" 'verilog-auto-ascii-enum)
a03c2342
WS
13250 ;;
13251 ;; first in/outs from other files
179f044b
WS
13252 (verilog-auto-re-search-do "/\\*AUTOINOUTMODPORT(.*?)\\*/" 'verilog-auto-inout-modport)
13253 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE(.*?)\\*/" 'verilog-auto-inout-module)
13254 (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP(.*?)\\*/" 'verilog-auto-inout-comp)
13255 (verilog-auto-re-search-do "/\\*AUTOINOUTIN(.*?)\\*/" 'verilog-auto-inout-in)
13256 (verilog-auto-re-search-do "/\\*AUTOINOUTPARAM(.*?)\\*/" 'verilog-auto-inout-param)
a03c2342 13257 ;; next in/outs which need previous sucked inputs first
179f044b
WS
13258 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((.*?)\\)?\\*/" 'verilog-auto-output)
13259 (verilog-auto-re-search-do "/\\*AUTOINPUT\\((.*?)\\)?\\*/" 'verilog-auto-input)
13260 (verilog-auto-re-search-do "/\\*AUTOINOUT\\((.*?)\\)?\\*/" 'verilog-auto-inout)
a03c2342
WS
13261 ;; Then tie off those in/outs
13262 (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
47086495 13263 ;; These can be anywhere after AUTOINSERTLISP
179f044b 13264 (verilog-auto-re-search-do "/\\*AUTOUNDEF\\((.*?)\\)?\\*/" 'verilog-auto-undef)
a03c2342 13265 ;; Wires/regs must be after inputs/outputs
179f044b 13266 (verilog-auto-re-search-do "/\\*AUTOASSIGNMODPORT(.*?)\\*/" 'verilog-auto-assign-modport)
9489a450 13267 (verilog-auto-re-search-do "/\\*AUTOLOGIC\\*/" 'verilog-auto-logic)
a03c2342
WS
13268 (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
13269 (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
13270 (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
13271 ;; outputevery needs AUTOOUTPUTs done first
13272 (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\*/" 'verilog-auto-output-every)
13273 ;; After we've created all new variables
13274 (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
13275 ;; Must be after all inputs outputs are generated
13276 (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
13277 ;; Fix line numbers (comments only)
13278 (when verilog-auto-inst-template-numbers
47086495
WS
13279 (verilog-auto-templated-rel))
13280 (when verilog-auto-template-warn-unused
13281 (verilog-auto-template-lint))))
a03c2342 13282 ;;
9489a450
MM
13283 (verilog-run-hooks 'verilog-auto-hook)
13284 ;;
13285 (when verilog-auto-delete-trailing-whitespace
13286 (verilog-delete-trailing-whitespace))
a03c2342
WS
13287 ;;
13288 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))
13289 ;;
13290 ;; If end result is same as when started, clear modified flag
13291 (cond ((and oldbuf (equal oldbuf (buffer-string)))
13292 (set-buffer-modified-p nil)
13293 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
13294 (t (unless noninteractive (message "Updating AUTOs...done"))))
13295 ;; End of after-change protection
13296 )))
13297 ;; Unwind forms
47086495
WS
13298 ;; Currently handled in verilog-save-font-mods
13299 ))))
6341f357
DN
13300\f
13301
13302;;
13303;; Skeleton based code insertion
13304;;
60618039 13305(defvar verilog-template-map
6edb5716
DN
13306 (let ((map (make-sparse-keymap)))
13307 (define-key map "a" 'verilog-sk-always)
13308 (define-key map "b" 'verilog-sk-begin)
13309 (define-key map "c" 'verilog-sk-case)
13310 (define-key map "f" 'verilog-sk-for)
13311 (define-key map "g" 'verilog-sk-generate)
13312 (define-key map "h" 'verilog-sk-header)
13313 (define-key map "i" 'verilog-sk-initial)
13314 (define-key map "j" 'verilog-sk-fork)
13315 (define-key map "m" 'verilog-sk-module)
9489a450 13316 (define-key map "o" 'verilog-sk-ovm-class)
6edb5716
DN
13317 (define-key map "p" 'verilog-sk-primitive)
13318 (define-key map "r" 'verilog-sk-repeat)
13319 (define-key map "s" 'verilog-sk-specify)
13320 (define-key map "t" 'verilog-sk-task)
ea89ff08 13321 (define-key map "u" 'verilog-sk-uvm-object)
6edb5716
DN
13322 (define-key map "w" 'verilog-sk-while)
13323 (define-key map "x" 'verilog-sk-casex)
13324 (define-key map "z" 'verilog-sk-casez)
13325 (define-key map "?" 'verilog-sk-if)
13326 (define-key map ":" 'verilog-sk-else-if)
13327 (define-key map "/" 'verilog-sk-comment)
13328 (define-key map "A" 'verilog-sk-assign)
13329 (define-key map "F" 'verilog-sk-function)
13330 (define-key map "I" 'verilog-sk-input)
13331 (define-key map "O" 'verilog-sk-output)
13332 (define-key map "S" 'verilog-sk-state-machine)
13333 (define-key map "=" 'verilog-sk-inout)
ea89ff08 13334 (define-key map "U" 'verilog-sk-uvm-component)
6edb5716
DN
13335 (define-key map "W" 'verilog-sk-wire)
13336 (define-key map "R" 'verilog-sk-reg)
30d48f20
DN
13337 (define-key map "D" 'verilog-sk-define-signal)
13338 map)
6341f357
DN
13339 "Keymap used in Verilog mode for smart template operations.")
13340
6341f357
DN
13341
13342;;
13343;; Place the templates into Verilog Mode. They may be inserted under any key.
13344;; C-c C-t will be the default. If you use templates a lot, you
179f044b 13345;; may want to consider moving the binding to another key in your init
6341f357
DN
13346;; file.
13347;;
9489a450 13348;; Note \C-c and letter are reserved for users
6341f357
DN
13349(define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
13350
13351;;; ---- statement skeletons ------------------------------------------
13352
13353(define-skeleton verilog-sk-prompt-condition
13354 "Prompt for the loop condition."
13355 "[condition]: " str )
13356
13357(define-skeleton verilog-sk-prompt-init
13358 "Prompt for the loop init statement."
13359 "[initial statement]: " str )
13360
13361(define-skeleton verilog-sk-prompt-inc
13362 "Prompt for the loop increment statement."
13363 "[increment statement]: " str )
13364
13365(define-skeleton verilog-sk-prompt-name
13366 "Prompt for the name of something."
13367 "[name]: " str)
13368
13369(define-skeleton verilog-sk-prompt-clock
13370 "Prompt for the name of something."
13371 "name and edge of clock(s): " str)
13372
13373(defvar verilog-sk-reset nil)
13374(defun verilog-sk-prompt-reset ()
13375 "Prompt for the name of a state machine reset."
7ea26faf 13376 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
6341f357
DN
13377
13378
13379(define-skeleton verilog-sk-prompt-state-selector
13380 "Prompt for the name of a state machine selector."
13381 "name of selector (eg {a,b,c,d}): " str )
13382
13383(define-skeleton verilog-sk-prompt-output
13384 "Prompt for the name of something."
13385 "output: " str)
13386
13387(define-skeleton verilog-sk-prompt-msb
9489a450 13388 "Prompt for most significant bit specification."
f07fe184 13389 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
6341f357
DN
13390
13391(define-skeleton verilog-sk-prompt-lsb
13392 "Prompt for least significant bit specification."
13393 "lsb:" str )
13394
13395(defvar verilog-sk-p nil)
13396(define-skeleton verilog-sk-prompt-width
13397 "Prompt for a width specification."
13398 ()
13399 (progn
13400 (setq verilog-sk-p (point))
13401 (verilog-sk-prompt-msb)
13402 (if (> (point) verilog-sk-p) "] " " ")))
13403
13404(defun verilog-sk-header ()
a3a8b002
DN
13405 "Insert a descriptive header at the top of the file.
13406See also `verilog-header' for an alternative format."
6341f357
DN
13407 (interactive "*")
13408 (save-excursion
13409 (goto-char (point-min))
13410 (verilog-sk-header-tmpl)))
13411
13412(define-skeleton verilog-sk-header-tmpl
13413 "Insert a comment block containing the module title, author, etc."
13414 "[Description]: "
13415 "// -*- Mode: Verilog -*-"
13416 "\n// Filename : " (buffer-name)
13417 "\n// Description : " str
13418 "\n// Author : " (user-full-name)
13419 "\n// Created On : " (current-time-string)
a3a8b002
DN
13420 "\n// Last Modified By: " (user-full-name)
13421 "\n// Last Modified On: " (current-time-string)
6341f357
DN
13422 "\n// Update Count : 0"
13423 "\n// Status : Unknown, Use with caution!"
13424 "\n")
13425
13426(define-skeleton verilog-sk-module
13427 "Insert a module definition."
13428 ()
f07fe184 13429 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
6341f357
DN
13430 > _ \n
13431 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
13432
9489a450
MM
13433;;; ------------------------------------------------------------------------
13434;;; Define a default OVM class, with macros and new()
13435;;; ------------------------------------------------------------------------
13436
13437(define-skeleton verilog-sk-ovm-class
13438 "Insert a class definition"
13439 ()
13440 > "class " (setq name (skeleton-read "Name: ")) " extends " (skeleton-read "Extends: ") ";" \n
13441 > _ \n
13442 > "`ovm_object_utils_begin(" name ")" \n
13443 > (- verilog-indent-level) " `ovm_object_utils_end" \n
13444 > _ \n
13445 > "function new(name=\"" name "\");" \n
13446 > "super.new(name);" \n
13447 > (- verilog-indent-level) "endfunction" \n
13448 > _ \n
13449 > "endclass" (progn (electric-verilog-terminate-line) nil))
13450
ea89ff08 13451(define-skeleton verilog-sk-uvm-object
9489a450
MM
13452 "Insert a class definition"
13453 ()
13454 > "class " (setq name (skeleton-read "Name: ")) " extends " (skeleton-read "Extends: ") ";" \n
13455 > _ \n
13456 > "`uvm_object_utils_begin(" name ")" \n
ea89ff08 13457 > (- verilog-indent-level) "`uvm_object_utils_end" \n
9489a450
MM
13458 > _ \n
13459 > "function new(name=\"" name "\");" \n
13460 > "super.new(name);" \n
13461 > (- verilog-indent-level) "endfunction" \n
13462 > _ \n
13463 > "endclass" (progn (electric-verilog-terminate-line) nil))
13464
ea89ff08
WS
13465(define-skeleton verilog-sk-uvm-component
13466 "Insert a class definition"
13467 ()
13468 > "class " (setq name (skeleton-read "Name: ")) " extends " (skeleton-read "Extends: ") ";" \n
13469 > _ \n
13470 > "`uvm_component_utils_begin(" name ")" \n
13471 > (- verilog-indent-level) "`uvm_component_utils_end" \n
13472 > _ \n
13473 > "function new(name=\"\", uvm_component parent);" \n
13474 > "super.new(name, parent);" \n
13475 > (- verilog-indent-level) "endfunction" \n
13476 > _ \n
13477 > "endclass" (progn (electric-verilog-terminate-line) nil))
13478
6341f357
DN
13479(define-skeleton verilog-sk-primitive
13480 "Insert a task definition."
13481 ()
f07fe184 13482 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
6341f357
DN
13483 > _ \n
13484 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
13485
13486(define-skeleton verilog-sk-task
13487 "Insert a task definition."
13488 ()
f07fe184 13489 > "task " '(verilog-sk-prompt-name) & ?; \n
6341f357
DN
13490 > _ \n
13491 > "begin" \n
13492 > \n
13493 > (- verilog-indent-level-behavioral) "end" \n
13494 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
13495
13496(define-skeleton verilog-sk-function
13497 "Insert a function definition."
13498 ()
f07fe184 13499 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
6341f357
DN
13500 > _ \n
13501 > "begin" \n
13502 > \n
13503 > (- verilog-indent-level-behavioral) "end" \n
13504 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
13505
13506(define-skeleton verilog-sk-always
13507 "Insert always block. Uses the minibuffer to prompt
13508for sensitivity list."
13509 ()
13510 > "always @ ( /*AUTOSENSE*/ ) begin\n"
13511 > _ \n
13512 > (- verilog-indent-level-behavioral) "end" \n >
13513 )
13514
13515(define-skeleton verilog-sk-initial
13516 "Insert an initial block."
13517 ()
13518 > "initial begin\n"
13519 > _ \n
13520 > (- verilog-indent-level-behavioral) "end" \n > )
13521
13522(define-skeleton verilog-sk-specify
13523 "Insert specify block. "
13524 ()
13525 > "specify\n"
13526 > _ \n
13527 > (- verilog-indent-level-behavioral) "endspecify" \n > )
13528
13529(define-skeleton verilog-sk-generate
13530 "Insert generate block. "
13531 ()
13532 > "generate\n"
13533 > _ \n
13534 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
13535
13536(define-skeleton verilog-sk-begin
37ea4b9b 13537 "Insert begin end block. Uses the minibuffer to prompt for name."
6341f357 13538 ()
f07fe184 13539 > "begin" '(verilog-sk-prompt-name) \n
6341f357
DN
13540 > _ \n
13541 > (- verilog-indent-level-behavioral) "end"
13542)
13543
13544(define-skeleton verilog-sk-fork
37ea4b9b 13545 "Insert a fork join block."
6341f357
DN
13546 ()
13547 > "fork\n"
13548 > "begin" \n
13549 > _ \n
13550 > (- verilog-indent-level-behavioral) "end" \n
13551 > "begin" \n
13552 > \n
13553 > (- verilog-indent-level-behavioral) "end" \n
13554 > (- verilog-indent-level-behavioral) "join" \n
13555 > )
13556
13557
13558(define-skeleton verilog-sk-case
13559 "Build skeleton case statement, prompting for the selector expression,
13560and the case items."
13561 "[selector expression]: "
13562 > "case (" str ") " \n
a3a8b002 13563 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
6341f357
DN
13564 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
13565
13566(define-skeleton verilog-sk-casex
13567 "Build skeleton casex statement, prompting for the selector expression,
13568and the case items."
13569 "[selector expression]: "
13570 > "casex (" str ") " \n
a3a8b002 13571 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
6341f357
DN
13572 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
13573
13574(define-skeleton verilog-sk-casez
13575 "Build skeleton casez statement, prompting for the selector expression,
13576and the case items."
13577 "[selector expression]: "
13578 > "casez (" str ") " \n
a3a8b002 13579 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
6341f357
DN
13580 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
13581
13582(define-skeleton verilog-sk-if
13583 "Insert a skeleton if statement."
f07fe184 13584 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
6341f357
DN
13585 > _ \n
13586 > (- verilog-indent-level-behavioral) "end " \n )
13587
13588(define-skeleton verilog-sk-else-if
13589 "Insert a skeleton else if statement."
13590 > (verilog-indent-line) "else if ("
f07fe184 13591 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
6341f357
DN
13592 > _ \n
13593 > "end" (progn (electric-verilog-terminate-line) nil))
13594
13595(define-skeleton verilog-sk-datadef
37ea4b9b 13596 "Common routine to get data definition."
6341f357 13597 ()
f07fe184 13598 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
6341f357
DN
13599
13600(define-skeleton verilog-sk-input
13601 "Insert an input definition."
13602 ()
f07fe184 13603 > "input [" '(verilog-sk-datadef))
6341f357
DN
13604
13605(define-skeleton verilog-sk-output
13606 "Insert an output definition."
13607 ()
f07fe184 13608 > "output [" '(verilog-sk-datadef))
6341f357
DN
13609
13610(define-skeleton verilog-sk-inout
13611 "Insert an inout definition."
13612 ()
f07fe184 13613 > "inout [" '(verilog-sk-datadef))
6341f357
DN
13614
13615(defvar verilog-sk-signal nil)
13616(define-skeleton verilog-sk-def-reg
13617 "Insert a reg definition."
13618 ()
47086495 13619 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations-auto) )
6341f357
DN
13620
13621(defun verilog-sk-define-signal ()
13622 "Insert a definition of signal under point at top of module."
13623 (interactive "*")
60618039 13624 (let* ((sig-re "[a-zA-Z0-9_]*")
6341f357
DN
13625 (v1 (buffer-substring
13626 (save-excursion
13627 (skip-chars-backward sig-re)
13628 (point))
13629 (save-excursion
13630 (skip-chars-forward sig-re)
60618039 13631 (point)))))
6341f357
DN
13632 (if (not (member v1 verilog-keywords))
13633 (save-excursion
13634 (setq verilog-sk-signal v1)
13635 (verilog-beg-of-defun)
13636 (verilog-end-of-statement)
13637 (verilog-forward-syntactic-ws)
13638 (verilog-sk-def-reg)
13639 (message "signal at point is %s" v1))
60618039 13640 (message "object at point (%s) is a keyword" v1))))
6341f357
DN
13641
13642(define-skeleton verilog-sk-wire
13643 "Insert a wire definition."
13644 ()
f07fe184 13645 > "wire [" '(verilog-sk-datadef))
6341f357
DN
13646
13647(define-skeleton verilog-sk-reg
13648 "Insert a reg definition."
13649 ()
f07fe184 13650 > "reg [" '(verilog-sk-datadef))
6341f357
DN
13651
13652(define-skeleton verilog-sk-assign
13653 "Insert a skeleton assign statement."
13654 ()
f07fe184 13655 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
6341f357
DN
13656
13657(define-skeleton verilog-sk-while
13658 "Insert a skeleton while loop statement."
13659 ()
f07fe184 13660 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
6341f357
DN
13661 > _ \n
13662 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
13663
13664(define-skeleton verilog-sk-repeat
13665 "Insert a skeleton repeat loop statement."
13666 ()
f07fe184 13667 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
6341f357
DN
13668 > _ \n
13669 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
13670
13671(define-skeleton verilog-sk-for
13672 "Insert a skeleton while loop statement."
13673 ()
13674 > "for ("
f07fe184
DN
13675 '(verilog-sk-prompt-init) "; "
13676 '(verilog-sk-prompt-condition) "; "
13677 '(verilog-sk-prompt-inc)
6341f357
DN
13678 ") begin" \n
13679 > _ \n
13680 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
13681
13682(define-skeleton verilog-sk-comment
13683 "Inserts three comment lines, making a display comment."
13684 ()
13685 > "/*\n"
13686 > "* " _ \n
13687 > "*/")
13688
13689(define-skeleton verilog-sk-state-machine
13690 "Insert a state machine definition."
13691 "Name of state variable: "
13692 '(setq input "state")
13693 > "// State registers for " str | -23 \n
13694 '(setq verilog-sk-state str)
f07fe184 13695 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
6341f357
DN
13696 '(setq input nil)
13697 > \n
13698 > "// State FF for " verilog-sk-state \n
13699 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
13700 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
13701 > verilog-sk-state " = next_" verilog-sk-state ?; \n
13702 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
13703 > \n
13704 > "// Next State Logic for " verilog-sk-state \n
13705 > "always @ ( /*AUTOSENSE*/ ) begin\n"
f07fe184 13706 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
6341f357
DN
13707 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
13708 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
13709 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
6341f357
DN
13710\f
13711
13712;;
13713;; Include file loading with mouse/return event
13714;;
13715;; idea & first impl.: M. Rouat (eldo-mode.el)
13716;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
13717
13718(if (featurep 'xemacs)
af62aa88 13719 (require 'overlay))
6341f357
DN
13720
13721(defconst verilog-include-file-regexp
13722 "^`include\\s-+\"\\([^\n\"]*\\)\""
13723 "Regexp that matches the include file.")
13724
60618039 13725(defvar verilog-mode-mouse-map
6341f357
DN
13726 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
13727 (set-keymap-parent map verilog-mode-map)
13728 ;; mouse button bindings
13729 (define-key map "\r" 'verilog-load-file-at-point)
13730 (if (featurep 'xemacs)
13731 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
13732 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
13733 (if (featurep 'xemacs)
13734 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
30d48f20
DN
13735 (define-key map [S-mouse-2] 'mouse-yank-at-click))
13736 map)
6edb5716
DN
13737 "Map containing mouse bindings for `verilog-mode'.")
13738
6341f357 13739
0f137a73 13740(defun verilog-highlight-region (beg end _old-len)
a03c2342 13741 "Colorize included files and modules in the (changed?) region.
6341f357 13742Clicking on the middle-mouse button loads them in a buffer (as in dired)."
a03c2342
WS
13743 (when (or verilog-highlight-includes
13744 verilog-highlight-modules)
13745 (save-excursion
13746 (save-match-data ;; A query-replace may call this function - do not disturb
13747 (verilog-save-buffer-state
13748 (verilog-save-scan-cache
13749 (let (end-point)
13750 (goto-char end)
3ba6b2ee 13751 (setq end-point (point-at-eol))
a03c2342
WS
13752 (goto-char beg)
13753 (beginning-of-line) ; scan entire line
13754 ;; delete overlays existing on this line
13755 (let ((overlays (overlays-in (point) end-point)))
13756 (while overlays
13757 (if (and
13758 (overlay-get (car overlays) 'detachable)
13759 (or (overlay-get (car overlays) 'verilog-include-file)
13760 (overlay-get (car overlays) 'verilog-inst-module)))
13761 (delete-overlay (car overlays)))
13762 (setq overlays (cdr overlays))))
13763 ;;
13764 ;; make new include overlays
13765 (when verilog-highlight-includes
13766 (while (search-forward-regexp verilog-include-file-regexp end-point t)
13767 (goto-char (match-beginning 1))
13768 (let ((ov (make-overlay (match-beginning 1) (match-end 1))))
13769 (overlay-put ov 'start-closed 't)
13770 (overlay-put ov 'end-closed 't)
13771 (overlay-put ov 'evaporate 't)
13772 (overlay-put ov 'verilog-include-file 't)
13773 (overlay-put ov 'mouse-face 'highlight)
13774 (overlay-put ov 'local-map verilog-mode-mouse-map))))
13775 ;;
13776 ;; make new module overlays
13777 (goto-char beg)
13778 ;; This scanner is syntax-fragile, so don't get bent
13779 (when verilog-highlight-modules
13780 (condition-case nil
9489a450 13781 (while (verilog-re-search-forward-quick "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-point t)
a03c2342
WS
13782 (save-excursion
13783 (goto-char (match-beginning 0))
9489a450 13784 (unless (verilog-inside-comment-or-string-p)
a03c2342
WS
13785 (verilog-read-inst-module-matcher) ;; sets match 0
13786 (let* ((ov (make-overlay (match-beginning 0) (match-end 0))))
13787 (overlay-put ov 'start-closed 't)
13788 (overlay-put ov 'end-closed 't)
13789 (overlay-put ov 'evaporate 't)
13790 (overlay-put ov 'verilog-inst-module 't)
13791 (overlay-put ov 'mouse-face 'highlight)
13792 (overlay-put ov 'local-map verilog-mode-mouse-map)))))
13793 (error nil)))
13794 ;;
13795 ;; Future highlights:
13796 ;; variables - make an Occur buffer of where referenced
13797 ;; pins - make an Occur buffer of the sig in the declaration module
13798 )))))))
13799
13800(defun verilog-highlight-buffer ()
13801 "Colorize included files and modules across the whole buffer."
13802 ;; Invoked via verilog-mode calling font-lock then `font-lock-mode-hook'
6341f357 13803 (interactive)
a03c2342
WS
13804 ;; delete and remake overlays
13805 (verilog-highlight-region (point-min) (point-max) nil))
13806
13807;; Deprecated, but was interactive, so we'll keep it around
13808(defalias 'verilog-colorize-include-files-buffer 'verilog-highlight-buffer)
6341f357 13809
37ea4b9b 13810;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
6341f357
DN
13811;; so define this function to do more or less the same as ffap-at-mouse
13812;; but first resolve filename...
13813(defun verilog-load-file-at-mouse (event)
13814 "Load file under button 2 click's EVENT.
a03c2342 13815Files are checked based on `verilog-library-flags'."
6341f357 13816 (interactive "@e")
37ea4b9b 13817 (save-excursion ;; implement a Verilog specific ffap-at-mouse
6341f357 13818 (mouse-set-point event)
a03c2342 13819 (verilog-load-file-at-point t)))
6341f357 13820
8350f087 13821;; ffap isn't usable for Verilog mode. It uses library paths.
6341f357
DN
13822;; so define this function to do more or less the same as ffap
13823;; but first resolve filename...
a03c2342 13824(defun verilog-load-file-at-point (&optional warn)
6341f357 13825 "Load file under point.
a03c2342
WS
13826If WARN, throw warning if not found.
13827Files are checked based on `verilog-library-flags'."
6341f357 13828 (interactive)
37ea4b9b 13829 (save-excursion ;; implement a Verilog specific ffap
a03c2342
WS
13830 (let ((overlays (overlays-in (point) (point)))
13831 hit)
13832 (while (and overlays (not hit))
13833 (when (overlay-get (car overlays) 'verilog-inst-module)
13834 (verilog-goto-defun-file (buffer-substring
13835 (overlay-start (car overlays))
13836 (overlay-end (car overlays))))
13837 (setq hit t))
13838 (setq overlays (cdr overlays)))
13839 ;; Include?
13840 (beginning-of-line)
13841 (when (and (not hit)
13842 (looking-at verilog-include-file-regexp))
13843 (if (and (car (verilog-library-filenames
13844 (match-string 1) (buffer-file-name)))
13845 (file-readable-p (car (verilog-library-filenames
13846 (match-string 1) (buffer-file-name)))))
6341f357 13847 (find-file (car (verilog-library-filenames
a03c2342
WS
13848 (match-string 1) (buffer-file-name))))
13849 (when warn
13850 (message
13851 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
13852 (match-string 1))))))))
6341f357
DN
13853
13854;;
13855;; Bug reporting
13856;;
13857
13858(defun verilog-faq ()
13859 "Tell the user their current version, and where to get the FAQ etc."
13860 (interactive)
13861 (with-output-to-temp-buffer "*verilog-mode help*"
13862 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
13863 (princ "\n")
13864 (princ "For new releases, see http://www.verilog.com\n")
13865 (princ "\n")
7cb1c4d7 13866 (princ "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
6341f357
DN
13867 (princ "\n")
13868 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
13869 (princ "\n")))
13870
7ea26faf 13871(autoload 'reporter-submit-bug-report "reporter")
60618039 13872(defvar reporter-prompt-for-summary-p)
7ea26faf 13873
6341f357
DN
13874(defun verilog-submit-bug-report ()
13875 "Submit via mail a bug report on verilog-mode.el."
13876 (interactive)
13877 (let ((reporter-prompt-for-summary-p t))
13878 (reporter-submit-bug-report
86a4c7ac 13879 "mac@verilog.com, wsnyder@wsnyder.org"
6341f357
DN
13880 (concat "verilog-mode v" verilog-mode-version)
13881 '(
a03c2342 13882 verilog-active-low-regexp
47086495 13883 verilog-after-save-font-hook
6341f357 13884 verilog-align-ifelse
a03c2342
WS
13885 verilog-assignment-delay
13886 verilog-auto-arg-sort
47086495
WS
13887 verilog-auto-declare-nettype
13888 verilog-auto-delete-trailing-whitespace
6341f357
DN
13889 verilog-auto-endcomments
13890 verilog-auto-hook
a03c2342 13891 verilog-auto-ignore-concat
6341f357 13892 verilog-auto-indent-on-newline
a03c2342
WS
13893 verilog-auto-inout-ignore-regexp
13894 verilog-auto-input-ignore-regexp
13895 verilog-auto-inst-column
13896 verilog-auto-inst-dot-name
47086495 13897 verilog-auto-inst-interfaced-ports
a03c2342 13898 verilog-auto-inst-param-value
47086495 13899 verilog-auto-inst-sort
6341f357 13900 verilog-auto-inst-template-numbers
a03c2342 13901 verilog-auto-inst-vector
6341f357
DN
13902 verilog-auto-lineup
13903 verilog-auto-newline
a03c2342
WS
13904 verilog-auto-output-ignore-regexp
13905 verilog-auto-read-includes
47086495 13906 verilog-auto-reset-blocking-in-non
a03c2342 13907 verilog-auto-reset-widths
6341f357
DN
13908 verilog-auto-save-policy
13909 verilog-auto-sense-defines-constant
13910 verilog-auto-sense-include-inputs
a03c2342
WS
13911 verilog-auto-star-expand
13912 verilog-auto-star-save
47086495
WS
13913 verilog-auto-template-warn-unused
13914 verilog-auto-tieoff-declaration
13915 verilog-auto-tieoff-ignore-regexp
a03c2342 13916 verilog-auto-unused-ignore-regexp
47086495 13917 verilog-auto-wire-type
6341f357 13918 verilog-before-auto-hook
a03c2342
WS
13919 verilog-before-delete-auto-hook
13920 verilog-before-getopt-flags-hook
47086495
WS
13921 verilog-before-save-font-hook
13922 verilog-cache-enabled
ea89ff08 13923 verilog-case-fold
6341f357
DN
13924 verilog-case-indent
13925 verilog-cexp-indent
13926 verilog-compiler
13927 verilog-coverage
a03c2342
WS
13928 verilog-delete-auto-hook
13929 verilog-getopt-flags-hook
13930 verilog-highlight-grouping-keywords
47086495
WS
13931 verilog-highlight-includes
13932 verilog-highlight-modules
a03c2342 13933 verilog-highlight-p1800-keywords
6341f357
DN
13934 verilog-highlight-translate-off
13935 verilog-indent-begin-after-if
13936 verilog-indent-declaration-macros
13937 verilog-indent-level
13938 verilog-indent-level-behavioral
13939 verilog-indent-level-declaration
13940 verilog-indent-level-directive
13941 verilog-indent-level-module
13942 verilog-indent-lists
6341f357
DN
13943 verilog-library-directories
13944 verilog-library-extensions
13945 verilog-library-files
a03c2342 13946 verilog-library-flags
6341f357
DN
13947 verilog-linter
13948 verilog-minimum-comment-distance
13949 verilog-mode-hook
47086495
WS
13950 verilog-mode-release-emacs
13951 verilog-mode-version
a03c2342 13952 verilog-preprocessor
6341f357
DN
13953 verilog-simulator
13954 verilog-tab-always-indent
13955 verilog-tab-to-comment
a03c2342 13956 verilog-typedef-regexp
47086495 13957 verilog-warn-fatal
6341f357
DN
13958 )
13959 nil nil
13960 (concat "Hi Mac,
13961
86a4c7ac 13962I want to report a bug.
6341f357
DN
13963
13964Before I go further, I want to say that Verilog mode has changed my life.
13965I save so much time, my files are colored nicely, my co workers respect
13966my coding ability... until now. I'd really appreciate anything you
13967could do to help me out with this minor deficiency in the product.
13968
86a4c7ac 13969I've taken a look at the Verilog-Mode FAQ at
7cb1c4d7 13970http://www.veripool.org/verilog-mode-faq.html.
6341f357 13971
86a4c7ac
DN
13972And, I've considered filing the bug on the issue tracker at
13973http://www.veripool.org/verilog-mode-bugs
13974since I realize that public bugs are easier for you to track,
13975and for others to search, but would prefer to email.
13976
13977So, to reproduce the bug, start a fresh Emacs via " invocation-name "
37ea4b9b 13978-no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
6341f357
DN
13979the code included below.
13980
13981Given those lines, I expected [[Fill in here]] to happen;
13982but instead, [[Fill in here]] happens!.
13983
13984== The code: =="))))
13985
6edb5716
DN
13986(provide 'verilog-mode)
13987
6341f357
DN
13988;; Local Variables:
13989;; checkdoc-permit-comma-termination-flag:t
13990;; checkdoc-force-docstrings-flag:nil
13991;; End:
13992
13993;;; verilog-mode.el ends here