Add 2011 to FSF/AIST copyright years.
[bpt/emacs.git] / lisp / progmodes / verilog-mode.el
CommitLineData
6341f357 1;; verilog-mode.el --- major mode for editing verilog source in Emacs
6341f357 2
637b4d38 3;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
5df4f04c 4;; 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
6341f357 5
a03c2342
WS
6;; Author: Michael McNamara (mac@verilog.com),
7;; Wilson Snyder (wsnyder@wsnyder.org)
8;; Please see our web sites:
9;; http://www.verilog.com
10;; http://www.veripool.org
6341f357 11;;
6341f357
DN
12;; Keywords: languages
13
241760a3
SM
14;; Yoni Rabkin <yoni@rabkins.net> contacted the maintainer of this
15;; file on 19/3/2008, and the maintainer agreed that when a bug is
16;; filed in the Emacs bug reporting system against this file, a copy
17;; of the bug report be sent to the maintainer's email address.
18
60618039
DN
19;; This code supports Emacs 21.1 and later
20;; And XEmacs 21.1 and later
21;; Please do not make changes that break Emacs 21. Thanks!
22;;
23;;
24
637b4d38
GM
25;; This file is part of GNU Emacs.
26
b1fc2b50 27;; GNU Emacs is free software: you can redistribute it and/or modify
6341f357 28;; it under the terms of the GNU General Public License as published by
b1fc2b50
GM
29;; the Free Software Foundation, either version 3 of the License, or
30;; (at your option) any later version.
6341f357 31
637b4d38 32;; GNU Emacs is distributed in the hope that it will be useful,
6341f357
DN
33;; but WITHOUT ANY WARRANTY; without even the implied warranty of
34;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35;; GNU General Public License for more details.
36
37;; You should have received a copy of the GNU General Public License
b1fc2b50 38;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
6341f357
DN
39
40;;; Commentary:
41
60618039 42;; This mode borrows heavily from the Pascal-mode and the cc-mode of Emacs
6341f357
DN
43
44;; USAGE
45;; =====
46
60618039 47;; A major mode for editing Verilog HDL source code. When you have
6341f357
DN
48;; entered Verilog mode, you may get more info by pressing C-h m. You
49;; may also get online help describing various functions by: C-h f
50;; <Name of function you want described>
51
52;; KNOWN BUGS / BUG REPORTS
53;; =======================
54
55;; Verilog is a rapidly evolving language, and hence this mode is
60618039 56;; under continuous development. Hence this is beta code, and likely
a3a8b002
DN
57;; has bugs. Please report any issues to the issue tracker at
58;; http://www.veripool.org/verilog-mode
6341f357
DN
59;; Please use verilog-submit-bug-report to submit a report; type C-c
60;; C-b to invoke this and as a result I will have a much easier time
61;; of reproducing the bug you find, and hence fixing it.
62
63;; INSTALLING THE MODE
64;; ===================
65
66;; An older version of this mode may be already installed as a part of
67;; your environment, and one method of updating would be to update
60618039 68;; your Emacs environment. Sometimes this is difficult for local
6341f357
DN
69;; political/control reasons, and hence you can always install a
70;; private copy (or even a shared copy) which overrides the system
71;; default.
72
73;; You can get step by step help in installing this file by going to
74;; <http://www.verilog.com/emacs_install.html>
75
76;; The short list of installation instructions are: To set up
37ea4b9b 77;; automatic Verilog mode, put this file in your load path, and put
6341f357
DN
78;; the following in code (please un comment it first!) in your
79;; .emacs, or in your site's site-load.el
80
81; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
a03c2342 82; (add-to-list 'auto-mode-alist '("\\.[ds]?vh?\\'" . verilog-mode))
6341f357 83
a03c2342
WS
84;; Be sure to examine at the help for verilog-auto, and the other
85;; verilog-auto-* functions for some major coding time savers.
86;;
6341f357 87;; If you want to customize Verilog mode to fit your needs better,
a03c2342 88;; you may add the below lines (the values of the variables presented
60618039 89;; here are the defaults). Note also that if you use an Emacs that
6341f357 90;; supports custom, it's probably better to use the custom menu to
a03c2342
WS
91;; edit these. If working as a member of a large team these settings
92;; should be common across all users (in a site-start file), or set
93;; in Local Variables in every file. Otherwise, different people's
94;; AUTO expansion may result different whitespace changes.
6341f357 95;;
a03c2342
WS
96; ;; Enable syntax highlighting of **all** languages
97; (global-font-lock-mode t)
98;
6341f357
DN
99; ;; User customization for Verilog mode
100; (setq verilog-indent-level 3
101; verilog-indent-level-module 3
102; verilog-indent-level-declaration 3
103; verilog-indent-level-behavioral 3
104; verilog-indent-level-directive 1
105; verilog-case-indent 2
106; verilog-auto-newline t
107; verilog-auto-indent-on-newline t
108; verilog-tab-always-indent t
109; verilog-auto-endcomments t
110; verilog-minimum-comment-distance 40
111; verilog-indent-begin-after-if t
a3a8b002 112; verilog-auto-lineup 'declarations
6341f357
DN
113; verilog-highlight-p1800-keywords nil
114; verilog-linter "my_lint_shell_command"
115; )
116
117;; \f
118
119;;; History:
37ea4b9b 120;;
7cb1c4d7 121;; See commit history at http://www.veripool.org/verilog-mode.html
60618039
DN
122;; (This section is required to appease checkdoc.)
123
6341f357
DN
124;;; Code:
125
6341f357 126;; This variable will always hold the version number of the mode
8468f78b 127(defconst verilog-mode-version "650"
1418c701 128 "Version of this Verilog mode.")
8468f78b 129(defconst verilog-mode-release-date "2010-11-05-GNU"
1418c701 130 "Release date of this Verilog mode.")
60618039 131(defconst verilog-mode-release-emacs t
1418c701 132 "If non-nil, this version of Verilog mode was released with Emacs itself.")
6341f357
DN
133
134(defun verilog-version ()
135 "Inform caller of the version of this file."
136 (interactive)
7ea26faf 137 (message "Using verilog-mode version %s" verilog-mode-version))
6341f357
DN
138
139;; Insure we have certain packages, and deal with it if we don't
60618039 140;; Be sure to note which Emacs flavor and version added each feature.
6edb5716 141(eval-when-compile
7cb1c4d7 142 ;; Provide stuff if we are XEmacs
7ea26faf
DN
143 (when (featurep 'xemacs)
144 (condition-case nil
145 (require 'easymenu)
146 (error nil))
147 (condition-case nil
148 (require 'regexp-opt)
149 (error nil))
150 ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
151 (condition-case nil
152 (load "skeleton")
153 (error nil))
154 (condition-case nil
155 (if (fboundp 'when)
156 nil ;; fab
157 (defmacro when (cond &rest body)
158 (list 'if cond (cons 'progn body))))
159 (error nil))
160 (condition-case nil
161 (if (fboundp 'unless)
162 nil ;; fab
163 (defmacro unless (cond &rest body)
164 (cons 'if (cons cond (cons nil body)))))
165 (error nil))
166 (condition-case nil
167 (if (fboundp 'store-match-data)
168 nil ;; fab
169 (defmacro store-match-data (&rest args) nil))
170 (error nil))
7ea26faf
DN
171 (condition-case nil
172 (if (fboundp 'char-before)
173 nil ;; great
174 (defmacro char-before (&rest body)
175 (char-after (1- (point)))))
176 (error nil))
177 (condition-case nil
178 (require 'custom)
179 (error nil))
180 (condition-case nil
181 (if (fboundp 'match-string-no-properties)
182 nil ;; great
183 (defsubst match-string-no-properties (num &optional string)
184 "Return string of text matched by last search, without text properties.
6341f357
DN
185NUM specifies which parenthesized expression in the last regexp.
186 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
187Zero means the entire text matched by the whole regexp or whole string.
188STRING should be given if the last search was by `string-match' on STRING."
7ea26faf
DN
189 (if (match-beginning num)
190 (if string
191 (let ((result
192 (substring string
193 (match-beginning num) (match-end num))))
194 (set-text-properties 0 (length result) nil result)
195 result)
196 (buffer-substring-no-properties (match-beginning num)
197 (match-end num)
60618039
DN
198 (current-buffer)))))
199 )
7ea26faf
DN
200 (error nil))
201 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
202 nil ;; We've got what we needed
203 ;; We have the old custom-library, hack around it!
204 (defmacro defgroup (&rest args) nil)
205 (defmacro customize (&rest args)
206 (message
37ea4b9b 207 "Sorry, Customize is not available with this version of Emacs"))
7ea26faf
DN
208 (defmacro defcustom (var value doc &rest args)
209 `(defvar ,var ,value ,doc))
210 )
211 (if (fboundp 'defface)
212 nil ; great!
213 (defmacro defface (var values doc &rest args)
214 `(make-face ,var))
215 )
6341f357 216
7ea26faf
DN
217 (if (and (featurep 'custom) (fboundp 'customize-group))
218 nil ;; We've got what we needed
219 ;; We have an intermediate custom-library, hack around it!
220 (defmacro customize-group (var &rest args)
221 `(customize ,var))
a03c2342
WS
222 )
223
224 (unless (boundp 'inhibit-point-motion-hooks)
225 (defvar inhibit-point-motion-hooks nil))
226 (unless (boundp 'deactivate-mark)
227 (defvar deactivate-mark nil))
228 )
229 ;;
7cb1c4d7
DN
230 ;; OK, do this stuff if we are NOT XEmacs:
231 (unless (featurep 'xemacs)
232 (unless (fboundp 'region-active-p)
233 (defmacro region-active-p ()
234 `(and transient-mark-mode mark-active))))
235 )
6341f357 236
6341f357
DN
237;; Provide a regular expression optimization routine, using regexp-opt
238;; if provided by the user's elisp libraries
239(eval-and-compile
60618039
DN
240 ;; The below were disabled when GNU Emacs 22 was released;
241 ;; perhaps some still need to be there to support Emacs 21.
7ea26faf
DN
242 (if (featurep 'xemacs)
243 (if (fboundp 'regexp-opt)
244 ;; regexp-opt is defined, does it take 3 or 2 arguments?
245 (if (fboundp 'function-max-args)
246 (let ((args (function-max-args `regexp-opt)))
247 (cond
248 ((eq args 3) ;; It takes 3
249 (condition-case nil ; Hide this defun from emacses
6341f357 250 ;with just a two input regexp
7ea26faf
DN
251 (defun verilog-regexp-opt (a b)
252 "Deal with differing number of required arguments for `regexp-opt'.
6341f357 253 Call 'regexp-opt' on A and B."
60618039 254 (regexp-opt a b 't))
7ea26faf
DN
255 (error nil))
256 )
257 ((eq args 2) ;; It takes 2
258 (defun verilog-regexp-opt (a b)
259 "Call 'regexp-opt' on A and B."
260 (regexp-opt a b))
261 )
262 (t nil)))
263 ;; We can't tell; assume it takes 2
264 (defun verilog-regexp-opt (a b)
265 "Call 'regexp-opt' on A and B."
266 (regexp-opt a b))
267 )
268 ;; There is no regexp-opt, provide our own
269 (defun verilog-regexp-opt (strings &optional paren shy)
270 (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
271 (concat open (mapconcat 'regexp-quote strings "\\|") close)))
272 )
273 ;; Emacs.
274 (defalias 'verilog-regexp-opt 'regexp-opt)))
6341f357 275
a03c2342
WS
276(eval-and-compile
277 ;; Both xemacs and emacs
278 (condition-case nil
279 (unless (fboundp 'buffer-chars-modified-tick) ;; Emacs 22 added
280 (defmacro buffer-chars-modified-tick () (buffer-modified-tick)))
281 (error nil)))
282
38f584e9
DN
283(eval-when-compile
284 (defun verilog-regexp-words (a)
285 "Call 'regexp-opt' with word delimiters for the words A."
286 (concat "\\<" (verilog-regexp-opt a t) "\\>")))
a03c2342
WS
287(defun verilog-regexp-words (a)
288 "Call 'regexp-opt' with word delimiters for the words A."
289 ;; The FAQ references this function, so user LISP sometimes calls it
290 (concat "\\<" (verilog-regexp-opt a t) "\\>"))
6341f357 291
495ab0d5 292(defun verilog-easy-menu-filter (menu)
a3a8b002 293 "Filter `easy-menu-define' MENU to support new features."
495ab0d5
DN
294 (cond ((not (featurep 'xemacs))
295 menu) ;; GNU Emacs - passthru
296 ;; Xemacs doesn't support :help. Strip it.
297 ;; Recursively filter the a submenu
298 ((listp menu)
299 (mapcar 'verilog-easy-menu-filter menu))
300 ;; Look for [:help "blah"] and remove
301 ((vectorp menu)
302 (let ((i 0) (out []))
303 (while (< i (length menu))
304 (if (equal `:help (aref menu i))
305 (setq i (+ 2 i))
306 (setq out (vconcat out (vector (aref menu i)))
307 i (1+ i))))
308 out))
309 (t menu))) ;; Default - ok
310;;(verilog-easy-menu-filter
311;; `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
312;; "----" ["MB" nil :help "Help MB"]))
313
6341f357 314(defun verilog-customize ()
495ab0d5 315 "Customize variables and other settings used by Verilog-Mode."
6341f357
DN
316 (interactive)
317 (customize-group 'verilog-mode))
318
319(defun verilog-font-customize ()
495ab0d5 320 "Customize fonts used by Verilog-Mode."
6341f357 321 (interactive)
7ea26faf
DN
322 (if (fboundp 'customize-apropos)
323 (customize-apropos "font-lock-*" 'faces)))
6341f357 324
eaf7efe9
DN
325(defun verilog-booleanp (value)
326 "Return t if VALUE is boolean.
a3a8b002
DN
327This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
328This function may be removed when Emacs 21 is no longer supported."
eaf7efe9
DN
329 (or (equal value t) (equal value nil)))
330
a3a8b002
DN
331(defun verilog-insert-last-command-event ()
332 "Insert the `last-command-event'."
333 (insert (if (featurep 'xemacs)
334 ;; XEmacs 21.5 doesn't like last-command-event
335 last-command-char
336 ;; And GNU Emacs 22 has obsoleted last-command-char
337 last-command-event)))
338
d63b01e1
SM
339(defalias 'verilog-syntax-ppss
340 (if (fboundp 'syntax-ppss) 'syntax-ppss
341 (lambda (&optional pos) (parse-partial-sexp (point-min) (or pos (point))))))
342
6341f357 343(defgroup verilog-mode nil
37ea4b9b 344 "Facilitates easy editing of Verilog source text."
8e788369 345 :version "22.2"
6341f357
DN
346 :group 'languages)
347
348; (defgroup verilog-mode-fonts nil
349; "Facilitates easy customization fonts used in Verilog source text"
350; :link '(customize-apropos "font-lock-*" 'faces)
351; :group 'verilog-mode)
352
353(defgroup verilog-mode-indent nil
37ea4b9b 354 "Customize indentation and highlighting of Verilog source text."
6341f357
DN
355 :group 'verilog-mode)
356
357(defgroup verilog-mode-actions nil
37ea4b9b 358 "Customize actions on Verilog source text."
6341f357
DN
359 :group 'verilog-mode)
360
361(defgroup verilog-mode-auto nil
37ea4b9b 362 "Customize AUTO actions when expanding Verilog source text."
6341f357
DN
363 :group 'verilog-mode)
364
a03c2342
WS
365(defvar verilog-debug nil
366 "If set, enable debug messages for `verilog-mode' internals.")
367
6341f357
DN
368(defcustom verilog-linter
369 "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
37ea4b9b 370 "*Unix program and arguments to call to run a lint checker on Verilog source.
6341f357
DN
371Depending on the `verilog-set-compile-command', this may be invoked when
372you type \\[compile]. When the compile completes, \\[next-error] will take
373you to the next lint error."
374 :type 'string
375 :group 'verilog-mode-actions)
60618039 376;; We don't mark it safe, as it's used as a shell command
6341f357
DN
377
378(defcustom verilog-coverage
379 "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
37ea4b9b 380 "*Program and arguments to use to annotate for coverage Verilog source.
6341f357
DN
381Depending on the `verilog-set-compile-command', this may be invoked when
382you type \\[compile]. When the compile completes, \\[next-error] will take
383you to the next lint error."
384 :type 'string
385 :group 'verilog-mode-actions)
60618039 386;; We don't mark it safe, as it's used as a shell command
6341f357
DN
387
388(defcustom verilog-simulator
389 "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
37ea4b9b 390 "*Program and arguments to use to interpret Verilog source.
6341f357
DN
391Depending on the `verilog-set-compile-command', this may be invoked when
392you type \\[compile]. When the compile completes, \\[next-error] will take
393you to the next lint error."
394 :type 'string
395 :group 'verilog-mode-actions)
60618039 396;; We don't mark it safe, as it's used as a shell command
6341f357
DN
397
398(defcustom verilog-compiler
399 "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
37ea4b9b 400 "*Program and arguments to use to compile Verilog source.
6341f357
DN
401Depending on the `verilog-set-compile-command', this may be invoked when
402you type \\[compile]. When the compile completes, \\[next-error] will take
403you to the next lint error."
404 :type 'string
405 :group 'verilog-mode-actions)
60618039 406;; We don't mark it safe, as it's used as a shell command
6341f357 407
a03c2342
WS
408(defcustom verilog-preprocessor
409 ;; Very few tools give preprocessed output, so we'll default to Verilog-Perl
410 "vppreproc __FLAGS__ __FILE__"
411 "*Program and arguments to use to preprocess Verilog source.
412This is invoked with `verilog-preprocess', and depending on the
413`verilog-set-compile-command', may also be invoked when you type
414\\[compile]. When the compile completes, \\[next-error] will
415take you to the next lint error."
416 :type 'string
417 :group 'verilog-mode-actions)
418;; We don't mark it safe, as it's used as a shell command
419
420(defvar verilog-preprocess-history nil
421 "History for `verilog-preprocess'.")
422
6341f357
DN
423(defvar verilog-tool 'verilog-linter
424 "Which tool to use for building compiler-command.
a03c2342
WS
425Either nil, `verilog-linter, `verilog-compiler,
426`verilog-coverage, `verilog-preprocessor, or `verilog-simulator.
427Alternatively use the \"Choose Compilation Action\" menu. See
428`verilog-set-compile-command' for more information.")
6341f357
DN
429
430(defcustom verilog-highlight-translate-off nil
431 "*Non-nil means background-highlight code excluded from translation.
432That is, all code between \"// synopsys translate_off\" and
433\"// synopsys translate_on\" is highlighted using a different background color
434\(face `verilog-font-lock-translate-off-face').
435
436Note: This will slow down on-the-fly fontification (and thus editing).
437
438Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
439entry \"Fontify Buffer\"). XEmacs: turn off and on font locking."
440 :type 'boolean
441 :group 'verilog-mode-indent)
60618039 442;; Note we don't use :safe, as that would break on Emacsen before 22.0.
eaf7efe9 443(put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
6341f357 444
a3a8b002
DN
445(defcustom verilog-auto-lineup 'declarations
446 "*Type of statements to lineup across multiple lines.
447If 'all' is selected, then all line ups described below are done.
448
449If 'declaration', then just declarations are lined up with any
450preceding declarations, taking into account widths and the like,
451so or example the code:
452 reg [31:0] a;
453 reg b;
454would become
455 reg [31:0] a;
456 reg b;
457
458If 'assignment', then assignments are lined up with any preceding
459assignments, so for example the code
460 a_long_variable <= b + c;
461 d = e + f;
462would become
463 a_long_variable <= b + c;
464 d = e + f;
465
466In order to speed up editing, large blocks of statements are lined up
467only when a \\[verilog-pretty-expr] is typed; and large blocks of declarations
468are lineup only when \\[verilog-pretty-declarations] is typed."
469
470 :type '(radio (const :tag "Line up Assignments and Declarations" all)
471 (const :tag "Line up Assignment statements" assignments )
86a4c7ac 472 (const :tag "Line up Declarations" declarations)
a3a8b002
DN
473 (function :tag "Other"))
474 :group 'verilog-mode-indent )
475
6341f357
DN
476(defcustom verilog-indent-level 3
477 "*Indentation of Verilog statements with respect to containing block."
478 :group 'verilog-mode-indent
479 :type 'integer)
60618039 480(put 'verilog-indent-level 'safe-local-variable 'integerp)
6341f357
DN
481
482(defcustom verilog-indent-level-module 3
37ea4b9b 483 "*Indentation of Module level Verilog statements (eg always, initial).
6341f357
DN
484Set to 0 to get initial and always statements lined up on the left side of
485your screen."
486 :group 'verilog-mode-indent
487 :type 'integer)
60618039 488(put 'verilog-indent-level-module 'safe-local-variable 'integerp)
6341f357
DN
489
490(defcustom verilog-indent-level-declaration 3
491 "*Indentation of declarations with respect to containing block.
492Set to 0 to get them list right under containing block."
493 :group 'verilog-mode-indent
494 :type 'integer)
60618039 495(put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
6341f357
DN
496
497(defcustom verilog-indent-declaration-macros nil
498 "*How to treat macro expansions in a declaration.
499If nil, indent as:
500 input [31:0] a;
501 input `CP;
502 output c;
503If non nil, treat as:
504 input [31:0] a;
505 input `CP ;
506 output c;"
507 :group 'verilog-mode-indent
508 :type 'boolean)
eaf7efe9 509(put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
6341f357
DN
510
511(defcustom verilog-indent-lists t
512 "*How to treat indenting items in a list.
513If t (the default), indent as:
514 always @( posedge a or
515 reset ) begin
516
517If nil, treat as:
518 always @( posedge a or
519 reset ) begin"
520 :group 'verilog-mode-indent
521 :type 'boolean)
eaf7efe9 522(put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
6341f357
DN
523
524(defcustom verilog-indent-level-behavioral 3
525 "*Absolute indentation of first begin in a task or function block.
526Set to 0 to get such code to start at the left side of the screen."
527 :group 'verilog-mode-indent
528 :type 'integer)
60618039 529(put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
6341f357
DN
530
531(defcustom verilog-indent-level-directive 1
532 "*Indentation to add to each level of `ifdef declarations.
533Set to 0 to have all directives start at the left side of the screen."
534 :group 'verilog-mode-indent
535 :type 'integer)
60618039 536(put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
6341f357
DN
537
538(defcustom verilog-cexp-indent 2
539 "*Indentation of Verilog statements split across lines."
540 :group 'verilog-mode-indent
541 :type 'integer)
60618039 542(put 'verilog-cexp-indent 'safe-local-variable 'integerp)
6341f357
DN
543
544(defcustom verilog-case-indent 2
545 "*Indentation for case statements."
546 :group 'verilog-mode-indent
547 :type 'integer)
60618039 548(put 'verilog-case-indent 'safe-local-variable 'integerp)
6341f357
DN
549
550(defcustom verilog-auto-newline t
551 "*True means automatically newline after semicolons."
552 :group 'verilog-mode-indent
553 :type 'boolean)
eaf7efe9 554(put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
6341f357
DN
555
556(defcustom verilog-auto-indent-on-newline t
557 "*True means automatically indent line after newline."
558 :group 'verilog-mode-indent
559 :type 'boolean)
eaf7efe9 560(put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
6341f357
DN
561
562(defcustom verilog-tab-always-indent t
563 "*True means TAB should always re-indent the current line.
37ea4b9b 564A nil value means TAB will only reindent when at the beginning of the line."
6341f357
DN
565 :group 'verilog-mode-indent
566 :type 'boolean)
eaf7efe9 567(put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
6341f357
DN
568
569(defcustom verilog-tab-to-comment nil
570 "*True means TAB moves to the right hand column in preparation for a comment."
571 :group 'verilog-mode-actions
572 :type 'boolean)
eaf7efe9 573(put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
6341f357
DN
574
575(defcustom verilog-indent-begin-after-if t
576 "*If true, indent begin statements following if, else, while, for and repeat.
577Otherwise, line them up."
578 :group 'verilog-mode-indent
60618039 579 :type 'boolean)
eaf7efe9 580(put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
6341f357
DN
581
582
583(defcustom verilog-align-ifelse nil
584 "*If true, align `else' under matching `if'.
585Otherwise else is lined up with first character on line holding matching if."
586 :group 'verilog-mode-indent
60618039 587 :type 'boolean)
eaf7efe9 588(put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
6341f357
DN
589
590(defcustom verilog-minimum-comment-distance 10
591 "*Minimum distance (in lines) between begin and end required before a comment.
592Setting this variable to zero results in every end acquiring a comment; the
37ea4b9b 593default avoids too many redundant comments in tight quarters."
6341f357
DN
594 :group 'verilog-mode-indent
595 :type 'integer)
60618039 596(put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
6341f357 597
6341f357 598(defcustom verilog-highlight-p1800-keywords nil
60618039
DN
599 "*True means highlight words newly reserved by IEEE-1800.
600These will appear in `verilog-font-lock-p1800-face' in order to gently
601suggest changing where these words are used as variables to something else.
37ea4b9b 602A nil value means highlight these words as appropriate for the SystemVerilog
60618039 603IEEE-1800 standard. Note that changing this will require restarting Emacs
37ea4b9b 604to see the effect as font color choices are cached by Emacs."
6341f357
DN
605 :group 'verilog-mode-indent
606 :type 'boolean)
eaf7efe9 607(put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
6341f357 608
a1ebd734
DN
609(defcustom verilog-highlight-grouping-keywords nil
610 "*True means highlight grouping keywords 'begin' and 'end' more dramatically.
a3a8b002
DN
611If false, these words are in the `font-lock-type-face'; if True then they are in
612`verilog-font-lock-ams-face'. Some find that special highlighting on these
a1ebd734
DN
613grouping constructs allow the structure of the code to be understood at a glance."
614 :group 'verilog-mode-indent
615 :type 'boolean)
b1d0fc86 616(put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
a1ebd734 617
a03c2342
WS
618(defcustom verilog-highlight-modules nil
619 "*True means highlight module statements for `verilog-load-file-at-point'.
620When true, mousing over module names will allow jumping to the
621module definition. If false, this is not supported. Setting
622this is experimental, and may lead to bad performance."
623 :group 'verilog-mode-indent
624 :type 'boolean)
625(put 'verilog-highlight-modules 'safe-local-variable 'verilog-booleanp)
626
627(defcustom verilog-highlight-includes t
628 "*True means highlight module statements for `verilog-load-file-at-point'.
629When true, mousing over include file names will allow jumping to the
630file referenced. If false, this is not supported."
631 :group 'verilog-mode-indent
632 :type 'boolean)
633(put 'verilog-highlight-includes 'safe-local-variable 'verilog-booleanp)
634
6341f357
DN
635(defcustom verilog-auto-endcomments t
636 "*True means insert a comment /* ... */ after 'end's.
637The name of the function or case will be set between the braces."
638 :group 'verilog-mode-actions
60618039 639 :type 'boolean)
eaf7efe9 640(put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
6341f357 641
14862301
SM
642(defcustom verilog-auto-ignore-concat nil
643 "*True means ignore signals in {...} concatenations for AUTOWIRE etc.
644This will exclude signals referenced as pin connections in {...}
645from AUTOWIRE, AUTOOUTPUT and friends. This flag should be set
646for backward compatibility only and not set in new designs; it
647may be removed in future versions."
648 :group 'verilog-mode-actions
649 :type 'boolean)
650(put 'verilog-auto-ignore-concat 'safe-local-variable 'verilog-booleanp)
651
6341f357
DN
652(defcustom verilog-auto-read-includes nil
653 "*True means to automatically read includes before AUTOs.
654This will do a `verilog-read-defines' and `verilog-read-includes' before
655each AUTO expansion. This makes it easier to embed defines and includes,
656but can result in very slow reading times if there are many or large
657include files."
658 :group 'verilog-mode-actions
60618039 659 :type 'boolean)
eaf7efe9 660(put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
6341f357
DN
661
662(defcustom verilog-auto-save-policy nil
663 "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
664A value of `force' will always do a \\[verilog-auto] automatically if
665needed on every save. A value of `detect' will do \\[verilog-auto]
666automatically when it thinks necessary. A value of `ask' will query the
667user when it thinks updating is needed.
668
669You should not rely on the 'ask or 'detect policies, they are safeguards
670only. They do not detect when AUTOINSTs need to be updated because a
671sub-module's port list has changed."
672 :group 'verilog-mode-actions
673 :type '(choice (const nil) (const ask) (const detect) (const force)))
674
675(defcustom verilog-auto-star-expand t
676 "*Non-nil indicates to expand a SystemVerilog .* instance ports.
677They will be expanded in the same way as if there was a AUTOINST in the
678instantiation. See also `verilog-auto-star' and `verilog-auto-star-save'."
679 :group 'verilog-mode-actions
680 :type 'boolean)
eaf7efe9 681(put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
6341f357
DN
682
683(defcustom verilog-auto-star-save nil
684 "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
37ea4b9b
JB
685A nil value indicates direct connections will be removed before saving.
686Only meaningful to those created due to `verilog-auto-star-expand' being set.
6341f357
DN
687
688Instead of setting this, you may want to use /*AUTOINST*/, which will
689always be saved."
690 :group 'verilog-mode-actions
691 :type 'boolean)
eaf7efe9 692(put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
6341f357
DN
693
694(defvar verilog-auto-update-tick nil
695 "Modification tick at which autos were last performed.")
696
697(defvar verilog-auto-last-file-locals nil
698 "Text from file-local-variables during last evaluation.")
699
a3a8b002
DN
700;;; Compile support
701(require 'compile)
d88782c3 702(defvar verilog-error-regexp-added nil)
a03c2342 703
d88782c3
DN
704(defvar verilog-error-regexp-emacs-alist
705 '(
706 (verilog-xl-1
707 "\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
708 (verilog-xl-2
709 "([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 3)
710 (verilog-IES
a03c2342 711 ".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)" 2 3)
d88782c3
DN
712 (verilog-surefire-1
713 "[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
714 (verilog-surefire-2
715 "\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\),\\s-+\\(line \\)?\\([0-9]+\\):" 2 4 )
716 (verilog-verbose
717 "\
718\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
719:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
720 (verilog-xsim
721 "\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
722 (verilog-vcs-1
723 "\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
724 (verilog-vcs-2
725 "Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
726 (verilog-vcs-3
727 "\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
728 (verilog-vcs-4
729 "syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
730 (verilog-verilator
731 "%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
732 (verilog-leda
a03c2342 733 "^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 2)
d88782c3 734 )
a03c2342
WS
735 "List of regexps for Verilog compilers.
736See `compilation-error-regexp-alist' for the formatting. For Emacs 22+.")
737
738(defvar verilog-error-regexp-xemacs-alist
739 ;; Emacs form is '((v-tool "re" 1 2) ...)
740 ;; XEmacs form is '(verilog ("re" 1 2) ...)
741 ;; So we can just map from Emacs to Xemacs
742 (cons 'verilog (mapcar 'cdr verilog-error-regexp-emacs-alist))
743 "List of regexps for Verilog compilers.
744See `compilation-error-regexp-alist-alist' for the formatting. For XEmacs.")
6341f357
DN
745
746(defvar verilog-error-font-lock-keywords
747 '(
a03c2342
WS
748 ;; verilog-xl-1
749 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
750 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
751 ;; verilog-xl-2
752 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 bold t)
753 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 3 bold t)
754 ;; verilog-IES (nc-verilog)
755 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
756 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 3 bold t)
757 ;; verilog-surefire-1
6341f357
DN
758 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
759 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
a03c2342 760 ;; verilog-surefire-2
6341f357
DN
761 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
762 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
a03c2342 763 ;; verilog-verbose
6341f357
DN
764 ("\
765\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
766:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
767 ("\
768\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
769:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
a03c2342 770 ;; verilog-vcs-1
6341f357
DN
771 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
772 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
a03c2342 773 ;; verilog-vcs-2
6341f357
DN
774 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
775 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
a03c2342 776 ;; verilog-vcs-3
6341f357
DN
777 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
778 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
a03c2342 779 ;; verilog-vcs-4
6341f357
DN
780 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
781 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
a03c2342
WS
782 ;; verilog-verilator
783 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
784 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
785 ;; verilog-leda
786 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 bold t)
787 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 2 bold t)
6341f357 788 )
a03c2342
WS
789 "*Keywords to also highlight in Verilog *compilation* buffers.
790Only used in XEmacs; GNU Emacs uses `verilog-error-regexp-emacs-alist'.")
6341f357
DN
791
792(defcustom verilog-library-flags '("")
793 "*List of standard Verilog arguments to use for /*AUTOINST*/.
794These arguments are used to find files for `verilog-auto', and match
795the flags accepted by a standard Verilog-XL simulator.
796
797 -f filename Reads more `verilog-library-flags' from the filename.
798 +incdir+dir Adds the directory to `verilog-library-directories'.
799 -Idir Adds the directory to `verilog-library-directories'.
800 -y dir Adds the directory to `verilog-library-directories'.
801 +libext+.v Adds the extensions to `verilog-library-extensions'.
802 -v filename Adds the filename to `verilog-library-files'.
803
804 filename Adds the filename to `verilog-library-files'.
805 This is not recommended, -v is a better choice.
806
807You might want these defined in each file; put at the *END* of your file
808something like:
809
810 // Local Variables:
811 // verilog-library-flags:(\"-y dir -y otherdir\")
812 // End:
813
814Verilog-mode attempts to detect changes to this local variable, but they
37ea4b9b 815are only insured to be correct when the file is first visited. Thus if you
6341f357
DN
816have problems, use \\[find-alternate-file] RET to have these take effect.
817
818See also the variables mentioned above."
819 :group 'verilog-mode-auto
820 :type '(repeat string))
60618039 821(put 'verilog-library-flags 'safe-local-variable 'listp)
6341f357
DN
822
823(defcustom verilog-library-directories '(".")
824 "*List of directories when looking for files for /*AUTOINST*/.
825The directory may be relative to the current file, or absolute.
826Environment variables are also expanded in the directory names.
827Having at least the current directory is a good idea.
828
829You might want these defined in each file; put at the *END* of your file
830something like:
831
832 // Local Variables:
833 // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
834 // End:
835
836Verilog-mode attempts to detect changes to this local variable, but they
37ea4b9b 837are only insured to be correct when the file is first visited. Thus if you
6341f357
DN
838have problems, use \\[find-alternate-file] RET to have these take effect.
839
840See also `verilog-library-flags', `verilog-library-files'
841and `verilog-library-extensions'."
842 :group 'verilog-mode-auto
843 :type '(repeat file))
60618039 844(put 'verilog-library-directories 'safe-local-variable 'listp)
6341f357
DN
845
846(defcustom verilog-library-files '()
60618039
DN
847 "*List of files to search for modules.
848AUTOINST will use this when it needs to resolve a module name.
6341f357
DN
849This is a complete path, usually to a technology file with many standard
850cells defined in it.
851
852You might want these defined in each file; put at the *END* of your file
853something like:
854
855 // Local Variables:
856 // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
857 // End:
858
859Verilog-mode attempts to detect changes to this local variable, but they
37ea4b9b 860are only insured to be correct when the file is first visited. Thus if you
6341f357
DN
861have problems, use \\[find-alternate-file] RET to have these take effect.
862
863See also `verilog-library-flags', `verilog-library-directories'."
864 :group 'verilog-mode-auto
865 :type '(repeat directory))
60618039 866(put 'verilog-library-files 'safe-local-variable 'listp)
6341f357 867
7cb1c4d7 868(defcustom verilog-library-extensions '(".v" ".sv")
6341f357
DN
869 "*List of extensions to use when looking for files for /*AUTOINST*/.
870See also `verilog-library-flags', `verilog-library-directories'."
871 :type '(repeat string)
872 :group 'verilog-mode-auto)
60618039 873(put 'verilog-library-extensions 'safe-local-variable 'listp)
6341f357
DN
874
875(defcustom verilog-active-low-regexp nil
876 "*If set, treat signals matching this regexp as active low.
877This is used for AUTORESET and AUTOTIEOFF. For proper behavior,
878you will probably also need `verilog-auto-reset-widths' set."
879 :group 'verilog-mode-auto
880 :type 'string)
60618039 881(put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
6341f357
DN
882
883(defcustom verilog-auto-sense-include-inputs nil
884 "*If true, AUTOSENSE should include all inputs.
885If nil, only inputs that are NOT output signals in the same block are
886included."
60618039
DN
887 :group 'verilog-mode-auto
888 :type 'boolean)
eaf7efe9 889(put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
6341f357
DN
890
891(defcustom verilog-auto-sense-defines-constant nil
892 "*If true, AUTOSENSE should assume all defines represent constants.
893When true, the defines will not be included in sensitivity lists. To
894maintain compatibility with other sites, this should be set at the bottom
37ea4b9b 895of each Verilog file that requires it, rather than being set globally."
60618039
DN
896 :group 'verilog-mode-auto
897 :type 'boolean)
eaf7efe9 898(put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
6341f357
DN
899
900(defcustom verilog-auto-reset-widths t
901 "*If true, AUTORESET should determine the width of signals.
902This is then used to set the width of the zero (32'h0 for example). This
903is required by some lint tools that aren't smart enough to ignore widths of
904the constant zero. This may result in ugly code when parameters determine
37ea4b9b 905the MSB or LSB of a signal inside an AUTORESET."
6341f357
DN
906 :type 'boolean
907 :group 'verilog-mode-auto)
eaf7efe9 908(put 'verilog-auto-reset-widths 'safe-local-variable 'verilog-booleanp)
6341f357
DN
909
910(defcustom verilog-assignment-delay ""
911 "*Text used for delays in delayed assignments. Add a trailing space if set."
60618039
DN
912 :group 'verilog-mode-auto
913 :type 'string)
914(put 'verilog-assignment-delay 'safe-local-variable 'stringp)
6341f357 915
a3a8b002 916(defcustom verilog-auto-arg-sort nil
14862301
SM
917 "*If set, AUTOARG signal names will be sorted, not in delaration order.
918Declaration order is advantageous with order based instantiations
919and is the default for backward compatibility. Sorted order
920reduces changes when declarations are moved around in a file, and
921it's bad practice to rely on order based instantiations anyhow."
a3a8b002
DN
922 :group 'verilog-mode-auto
923 :type 'boolean)
924(put 'verilog-auto-arg-sort 'safe-local-variable 'verilog-booleanp)
925
a03c2342
WS
926(defcustom verilog-auto-inst-dot-name nil
927 "*If true, when creating ports with AUTOINST, use .name syntax.
928This will use \".port\" instead of \".port(port)\" when possible.
929This is only legal in SystemVerilog files, and will confuse older
930simulators. Setting `verilog-auto-inst-vector' to nil may also
931be desirable to increase how often .name will be used."
932 :group 'verilog-mode-auto
933 :type 'boolean)
934(put 'verilog-auto-inst-dot-name 'safe-local-variable 'verilog-booleanp)
935
4c5e69c6
DN
936(defcustom verilog-auto-inst-param-value nil
937 "*If set, AUTOINST will replace parameters with the parameter value.
938If nil, leave parameters as symbolic names.
939
940Parameters must be in Verilog 2001 format #(...), and if a parameter is not
941listed as such there (as when the default value is acceptable), it will not
942be replaced, and will remain symbolic.
943
944For example, imagine a submodule uses parameters to declare the size of its
945inputs. This is then used by a upper module:
946
a03c2342 947 module InstModule (o,i);
4c5e69c6
DN
948 parameter WIDTH;
949 input [WIDTH-1:0] i;
950 endmodule
951
952 module ExampInst;
953 InstModule
954 #(PARAM(10))
955 instName
956 (/*AUTOINST*/
957 .i (i[PARAM-1:0]));
958
959Note even though PARAM=10, the AUTOINST has left the parameter as a
960symbolic name. If `verilog-auto-inst-param-value' is set, this will
961instead expand to:
962
963 module ExampInst;
964 InstModule
965 #(PARAM(10))
966 instName
967 (/*AUTOINST*/
968 .i (i[9:0]));"
969 :group 'verilog-mode-auto
970 :type 'boolean)
7cb1c4d7 971(put 'verilog-auto-inst-param-value 'safe-local-variable 'verilog-booleanp)
4c5e69c6 972
6341f357
DN
973(defcustom verilog-auto-inst-vector t
974 "*If true, when creating default ports with AUTOINST, use bus subscripts.
975If nil, skip the subscript when it matches the entire bus as declared in
976the module (AUTOWIRE signals always are subscripted, you must manually
37ea4b9b
JB
977declare the wire to have the subscripts removed.) Setting this to nil may
978speed up some simulators, but is less general and harder to read, so avoid."
6341f357 979 :group 'verilog-mode-auto
60618039 980 :type 'boolean)
eaf7efe9 981(put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
6341f357
DN
982
983(defcustom verilog-auto-inst-template-numbers nil
984 "*If true, when creating templated ports with AUTOINST, add a comment.
985The comment will add the line number of the template that was used for that
986port declaration. Setting this aids in debugging, but nil is suggested for
987regular use to prevent large numbers of merge conflicts."
988 :group 'verilog-mode-auto
60618039 989 :type 'boolean)
eaf7efe9 990(put 'verilog-auto-inst-template-numbers 'safe-local-variable 'verilog-booleanp)
6341f357 991
4c5e69c6
DN
992(defcustom verilog-auto-inst-column 40
993 "*Indent-to column number for net name part of AUTOINST created pin."
994 :group 'verilog-mode-indent
995 :type 'integer)
996(put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
6341f357
DN
997
998(defcustom verilog-auto-input-ignore-regexp nil
999 "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
1000See the \\[verilog-faq] for examples on using this."
1001 :group 'verilog-mode-auto
60618039
DN
1002 :type 'string)
1003(put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
6341f357
DN
1004
1005(defcustom verilog-auto-inout-ignore-regexp nil
1006 "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
1007See the \\[verilog-faq] for examples on using this."
1008 :group 'verilog-mode-auto
60618039
DN
1009 :type 'string)
1010(put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
6341f357
DN
1011
1012(defcustom verilog-auto-output-ignore-regexp nil
1013 "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
1014See the \\[verilog-faq] for examples on using this."
1015 :group 'verilog-mode-auto
60618039
DN
1016 :type 'string)
1017(put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
6341f357 1018
a03c2342
WS
1019(defcustom verilog-auto-tieoff-ignore-regexp nil
1020 "*If set, when creating AUTOTIEOFF list, ignore signals matching this regexp.
1021See the \\[verilog-faq] for examples on using this."
1022 :group 'verilog-mode-auto
1023 :type 'string)
1024(put 'verilog-auto-tieoff-ignore-regexp 'safe-local-variable 'stringp)
1025
6341f357
DN
1026(defcustom verilog-auto-unused-ignore-regexp nil
1027 "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
1028See the \\[verilog-faq] for examples on using this."
1029 :group 'verilog-mode-auto
60618039
DN
1030 :type 'string)
1031(put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
6341f357
DN
1032
1033(defcustom verilog-typedef-regexp nil
1034 "*If non-nil, regular expression that matches Verilog-2001 typedef names.
1035For example, \"_t$\" matches typedefs named with _t, as in the C language."
1036 :group 'verilog-mode-auto
60618039
DN
1037 :type 'string)
1038(put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
6341f357
DN
1039
1040(defcustom verilog-mode-hook 'verilog-set-compile-command
37ea4b9b 1041 "*Hook run after Verilog mode is loaded."
6341f357
DN
1042 :type 'hook
1043 :group 'verilog-mode)
1044
1045(defcustom verilog-auto-hook nil
1046 "*Hook run after `verilog-mode' updates AUTOs."
60618039
DN
1047 :group 'verilog-mode-auto
1048 :type 'hook)
6341f357
DN
1049
1050(defcustom verilog-before-auto-hook nil
1051 "*Hook run before `verilog-mode' updates AUTOs."
60618039
DN
1052 :group 'verilog-mode-auto
1053 :type 'hook)
6341f357
DN
1054
1055(defcustom verilog-delete-auto-hook nil
1056 "*Hook run after `verilog-mode' deletes AUTOs."
60618039
DN
1057 :group 'verilog-mode-auto
1058 :type 'hook)
6341f357
DN
1059
1060(defcustom verilog-before-delete-auto-hook nil
1061 "*Hook run before `verilog-mode' deletes AUTOs."
60618039
DN
1062 :group 'verilog-mode-auto
1063 :type 'hook)
6341f357
DN
1064
1065(defcustom verilog-getopt-flags-hook nil
1066 "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
60618039
DN
1067 :group 'verilog-mode-auto
1068 :type 'hook)
6341f357
DN
1069
1070(defcustom verilog-before-getopt-flags-hook nil
1071 "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
60618039
DN
1072 :group 'verilog-mode-auto
1073 :type 'hook)
6341f357
DN
1074
1075(defvar verilog-imenu-generic-expression
1076 '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
1077 ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
37ea4b9b 1078 "Imenu expression for Verilog mode. See `imenu-generic-expression'.")
6341f357
DN
1079
1080;;
1081;; provide a verilog-header function.
1082;; Customization variables:
1083;;
1084(defvar verilog-date-scientific-format nil
1085 "*If non-nil, dates are written in scientific format (e.g. 1997/09/17).
1086If nil, in European format (e.g. 17.09.1997). The brain-dead American
1087format (e.g. 09/17/1997) is not supported.")
1088
1089(defvar verilog-company nil
37ea4b9b 1090 "*Default name of Company for Verilog header.
6341f357 1091If set will become buffer local.")
7ea26faf
DN
1092(make-variable-buffer-local 'verilog-company)
1093
6341f357 1094(defvar verilog-project nil
37ea4b9b 1095 "*Default name of Project for Verilog header.
6341f357 1096If set will become buffer local.")
7ea26faf
DN
1097(make-variable-buffer-local 'verilog-project)
1098
7d49d8e1 1099(defvar verilog-mode-map
6edb5716
DN
1100 (let ((map (make-sparse-keymap)))
1101 (define-key map ";" 'electric-verilog-semi)
1102 (define-key map [(control 59)] 'electric-verilog-semi-with-comment)
1103 (define-key map ":" 'electric-verilog-colon)
1104 ;;(define-key map "=" 'electric-verilog-equal)
1105 (define-key map "\`" 'electric-verilog-tick)
1106 (define-key map "\t" 'electric-verilog-tab)
1107 (define-key map "\r" 'electric-verilog-terminate-line)
1108 ;; backspace/delete key bindings
1109 (define-key map [backspace] 'backward-delete-char-untabify)
1110 (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
1111 (define-key map [delete] 'delete-char)
1112 (define-key map [(meta delete)] 'kill-word))
1113 (define-key map "\M-\C-b" 'electric-verilog-backward-sexp)
1114 (define-key map "\M-\C-f" 'electric-verilog-forward-sexp)
1115 (define-key map "\M-\r" `electric-verilog-terminate-and-indent)
1116 (define-key map "\M-\t" 'verilog-complete-word)
1117 (define-key map "\M-?" 'verilog-show-completions)
6edb5716
DN
1118 (define-key map "\C-c\`" 'verilog-lint-off)
1119 (define-key map "\C-c\*" 'verilog-delete-auto-star-implicit)
1120 (define-key map "\C-c\C-r" 'verilog-label-be)
1121 (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
1122 (define-key map "\C-c=" 'verilog-pretty-expr)
1123 (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
1124 (define-key map "\M-*" 'verilog-star-comment)
1125 (define-key map "\C-c\C-c" 'verilog-comment-region)
1126 (define-key map "\C-c\C-u" 'verilog-uncomment-region)
e1776067
DN
1127 (when (featurep 'xemacs)
1128 (define-key map [(meta control h)] 'verilog-mark-defun)
1129 (define-key map "\M-\C-a" 'verilog-beg-of-defun)
1130 (define-key map "\M-\C-e" 'verilog-end-of-defun))
6edb5716
DN
1131 (define-key map "\C-c\C-d" 'verilog-goto-defun)
1132 (define-key map "\C-c\C-k" 'verilog-delete-auto)
1133 (define-key map "\C-c\C-a" 'verilog-auto)
1134 (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
a03c2342 1135 (define-key map "\C-c\C-p" 'verilog-preprocess)
6edb5716
DN
1136 (define-key map "\C-c\C-z" 'verilog-inject-auto)
1137 (define-key map "\C-c\C-e" 'verilog-expand-vector)
30d48f20
DN
1138 (define-key map "\C-c\C-h" 'verilog-header)
1139 map)
6341f357 1140 "Keymap used in Verilog mode.")
6341f357
DN
1141
1142;; menus
7d55bf04
DN
1143(easy-menu-define
1144 verilog-menu verilog-mode-map "Menu for Verilog mode"
495ab0d5
DN
1145 (verilog-easy-menu-filter
1146 '("Verilog"
1147 ("Choose Compilation Action"
1148 ["None"
1149 (progn
1150 (setq verilog-tool nil)
1151 (verilog-set-compile-command))
1152 :style radio
1153 :selected (equal verilog-tool nil)
1154 :help "When invoking compilation, use compile-command"]
1155 ["Lint"
1156 (progn
1157 (setq verilog-tool 'verilog-linter)
1158 (verilog-set-compile-command))
1159 :style radio
1160 :selected (equal verilog-tool `verilog-linter)
1161 :help "When invoking compilation, use lint checker"]
1162 ["Coverage"
1163 (progn
1164 (setq verilog-tool 'verilog-coverage)
1165 (verilog-set-compile-command))
1166 :style radio
1167 :selected (equal verilog-tool `verilog-coverage)
1168 :help "When invoking compilation, annotate for coverage"]
1169 ["Simulator"
1170 (progn
1171 (setq verilog-tool 'verilog-simulator)
1172 (verilog-set-compile-command))
1173 :style radio
1174 :selected (equal verilog-tool `verilog-simulator)
1175 :help "When invoking compilation, interpret Verilog source"]
1176 ["Compiler"
1177 (progn
1178 (setq verilog-tool 'verilog-compiler)
1179 (verilog-set-compile-command))
1180 :style radio
1181 :selected (equal verilog-tool `verilog-compiler)
1182 :help "When invoking compilation, compile Verilog source"]
a03c2342
WS
1183 ["Preprocessor"
1184 (progn
1185 (setq verilog-tool 'verilog-preprocessor)
1186 (verilog-set-compile-command))
1187 :style radio
1188 :selected (equal verilog-tool `verilog-preprocessor)
1189 :help "When invoking compilation, preprocess Verilog source, see also `verilog-preprocess'"]
495ab0d5
DN
1190 )
1191 ("Move"
1192 ["Beginning of function" verilog-beg-of-defun
1193 :keys "C-M-a"
1194 :help "Move backward to the beginning of the current function or procedure"]
1195 ["End of function" verilog-end-of-defun
1196 :keys "C-M-e"
1197 :help "Move forward to the end of the current function or procedure"]
1198 ["Mark function" verilog-mark-defun
1199 :keys "C-M-h"
1200 :help "Mark the current Verilog function or procedure"]
1201 ["Goto function/module" verilog-goto-defun
1202 :help "Move to specified Verilog module/task/function"]
1203 ["Move to beginning of block" electric-verilog-backward-sexp
1204 :help "Move backward over one balanced expression"]
1205 ["Move to end of block" electric-verilog-forward-sexp
1206 :help "Move forward over one balanced expression"]
1207 )
1208 ("Comments"
1209 ["Comment Region" verilog-comment-region
1210 :help "Put marked area into a comment"]
1211 ["UnComment Region" verilog-uncomment-region
1212 :help "Uncomment an area commented with Comment Region"]
1213 ["Multi-line comment insert" verilog-star-comment
1214 :help "Insert Verilog /* */ comment at point"]
1215 ["Lint error to comment" verilog-lint-off
1216 :help "Convert a Verilog linter warning line into a disable statement"]
1217 )
1218 "----"
1219 ["Compile" compile
1220 :help "Perform compilation-action (above) on the current buffer"]
1221 ["AUTO, Save, Compile" verilog-auto-save-compile
1222 :help "Recompute AUTOs, save buffer, and compile"]
1223 ["Next Compile Error" next-error
1224 :help "Visit next compilation error message and corresponding source code"]
1225 ["Ignore Lint Warning at point" verilog-lint-off
1226 :help "Convert a Verilog linter warning line into a disable statement"]
1227 "----"
1228 ["Line up declarations around point" verilog-pretty-declarations
1229 :help "Line up declarations around point"]
1230 ["Line up equations around point" verilog-pretty-expr
1231 :help "Line up expressions around point"]
1232 ["Redo/insert comments on every end" verilog-label-be
1233 :help "Label matching begin ... end statements"]
1234 ["Expand [x:y] vector line" verilog-expand-vector
1235 :help "Take a signal vector on the current line and expand it to multiple lines"]
1236 ["Insert begin-end block" verilog-insert-block
1237 :help "Insert begin ... end"]
1238 ["Complete word" verilog-complete-word
1239 :help "Complete word at point"]
1240 "----"
1241 ["Recompute AUTOs" verilog-auto
1242 :help "Expand AUTO meta-comment statements"]
1243 ["Kill AUTOs" verilog-delete-auto
1244 :help "Remove AUTO expansions"]
1245 ["Inject AUTOs" verilog-inject-auto
1246 :help "Inject AUTOs into legacy non-AUTO buffer"]
1247 ("AUTO Help..."
1248 ["AUTO General" (describe-function 'verilog-auto)
1249 :help "Help introduction on AUTOs"]
1250 ["AUTO Library Flags" (describe-variable 'verilog-library-flags)
1251 :help "Help on verilog-library-flags"]
1252 ["AUTO Library Path" (describe-variable 'verilog-library-directories)
1253 :help "Help on verilog-library-directories"]
1254 ["AUTO Library Files" (describe-variable 'verilog-library-files)
1255 :help "Help on verilog-library-files"]
1256 ["AUTO Library Extensions" (describe-variable 'verilog-library-extensions)
1257 :help "Help on verilog-library-extensions"]
1258 ["AUTO `define Reading" (describe-function 'verilog-read-defines)
1259 :help "Help on reading `defines"]
1260 ["AUTO `include Reading" (describe-function 'verilog-read-includes)
1261 :help "Help on parsing `includes"]
1262 ["AUTOARG" (describe-function 'verilog-auto-arg)
1263 :help "Help on AUTOARG - declaring module port list"]
1264 ["AUTOASCIIENUM" (describe-function 'verilog-auto-ascii-enum)
1265 :help "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
86a4c7ac 1266 ["AUTOINOUTCOMP" (describe-function 'verilog-auto-inout-comp)
7cb1c4d7 1267 :help "Help on AUTOINOUTCOMP - copying complemented i/o from another file"]
495ab0d5
DN
1268 ["AUTOINOUTMODULE" (describe-function 'verilog-auto-inout-module)
1269 :help "Help on AUTOINOUTMODULE - copying i/o from another file"]
a3a8b002
DN
1270 ["AUTOINSERTLISP" (describe-function 'verilog-auto-insert-lisp)
1271 :help "Help on AUTOINSERTLISP - insert text from a lisp function"]
495ab0d5
DN
1272 ["AUTOINOUT" (describe-function 'verilog-auto-inout)
1273 :help "Help on AUTOINOUT - adding inouts from cells"]
1274 ["AUTOINPUT" (describe-function 'verilog-auto-input)
1275 :help "Help on AUTOINPUT - adding inputs from cells"]
1276 ["AUTOINST" (describe-function 'verilog-auto-inst)
1277 :help "Help on AUTOINST - adding pins for cells"]
1278 ["AUTOINST (.*)" (describe-function 'verilog-auto-star)
1279 :help "Help on expanding Verilog-2001 .* pins"]
1280 ["AUTOINSTPARAM" (describe-function 'verilog-auto-inst-param)
1281 :help "Help on AUTOINSTPARAM - adding parameter pins to cells"]
1282 ["AUTOOUTPUT" (describe-function 'verilog-auto-output)
1283 :help "Help on AUTOOUTPUT - adding outputs from cells"]
1284 ["AUTOOUTPUTEVERY" (describe-function 'verilog-auto-output-every)
1285 :help "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
1286 ["AUTOREG" (describe-function 'verilog-auto-reg)
1287 :help "Help on AUTOREG - declaring registers for non-wires"]
1288 ["AUTOREGINPUT" (describe-function 'verilog-auto-reg-input)
1289 :help "Help on AUTOREGINPUT - declaring inputs for non-wires"]
1290 ["AUTORESET" (describe-function 'verilog-auto-reset)
1291 :help "Help on AUTORESET - resetting always blocks"]
1292 ["AUTOSENSE" (describe-function 'verilog-auto-sense)
1293 :help "Help on AUTOSENSE - sensitivity lists for always blocks"]
1294 ["AUTOTIEOFF" (describe-function 'verilog-auto-tieoff)
1295 :help "Help on AUTOTIEOFF - tieing off unused outputs"]
1296 ["AUTOUNUSED" (describe-function 'verilog-auto-unused)
1297 :help "Help on AUTOUNUSED - terminating unused inputs"]
1298 ["AUTOWIRE" (describe-function 'verilog-auto-wire)
1299 :help "Help on AUTOWIRE - declaring wires for cells"]
1300 )
1301 "----"
1302 ["Submit bug report" verilog-submit-bug-report
1303 :help "Submit via mail a bug report on verilog-mode.el"]
1304 ["Version and FAQ" verilog-faq
1305 :help "Show the current version, and where to get the FAQ etc"]
1306 ["Customize Verilog Mode..." verilog-customize
1307 :help "Customize variables and other settings used by Verilog-Mode"]
1308 ["Customize Verilog Fonts & Colors" verilog-font-customize
1309 :help "Customize fonts used by Verilog-Mode."])))
7d55bf04
DN
1310
1311(easy-menu-define
1312 verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
495ab0d5
DN
1313 (verilog-easy-menu-filter
1314 '("Statements"
1315 ["Header" verilog-sk-header
1316 :help "Insert a header block at the top of file"]
1317 ["Comment" verilog-sk-comment
1318 :help "Insert a comment block"]
1319 "----"
1320 ["Module" verilog-sk-module
1321 :help "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
1322 ["Primitive" verilog-sk-primitive
1323 :help "Insert a primitive .. (.. );.. endprimitive block"]
1324 "----"
1325 ["Input" verilog-sk-input
1326 :help "Insert an input declaration"]
1327 ["Output" verilog-sk-output
1328 :help "Insert an output declaration"]
1329 ["Inout" verilog-sk-inout
1330 :help "Insert an inout declaration"]
1331 ["Wire" verilog-sk-wire
1332 :help "Insert a wire declaration"]
1333 ["Reg" verilog-sk-reg
1334 :help "Insert a register declaration"]
1335 ["Define thing under point as a register" verilog-sk-define-signal
1336 :help "Define signal under point as a register at the top of the module"]
1337 "----"
1338 ["Initial" verilog-sk-initial
1339 :help "Insert an initial begin .. end block"]
1340 ["Always" verilog-sk-always
1341 :help "Insert an always @(AS) begin .. end block"]
1342 ["Function" verilog-sk-function
1343 :help "Insert a function .. begin .. end endfunction block"]
1344 ["Task" verilog-sk-task
1345 :help "Insert a task .. begin .. end endtask block"]
1346 ["Specify" verilog-sk-specify
1347 :help "Insert a specify .. endspecify block"]
1348 ["Generate" verilog-sk-generate
1349 :help "Insert a generate .. endgenerate block"]
1350 "----"
1351 ["Begin" verilog-sk-begin
1352 :help "Insert a begin .. end block"]
1353 ["If" verilog-sk-if
1354 :help "Insert an if (..) begin .. end block"]
1355 ["(if) else" verilog-sk-else-if
1356 :help "Insert an else if (..) begin .. end block"]
1357 ["For" verilog-sk-for
1358 :help "Insert a for (...) begin .. end block"]
1359 ["While" verilog-sk-while
1360 :help "Insert a while (...) begin .. end block"]
1361 ["Fork" verilog-sk-fork
1362 :help "Insert a fork begin .. end .. join block"]
1363 ["Repeat" verilog-sk-repeat
1364 :help "Insert a repeat (..) begin .. end block"]
1365 ["Case" verilog-sk-case
1366 :help "Insert a case block, prompting for details"]
1367 ["Casex" verilog-sk-casex
1368 :help "Insert a casex (...) item: begin.. end endcase block"]
1369 ["Casez" verilog-sk-casez
1370 :help "Insert a casez (...) item: begin.. end endcase block"])))
6341f357
DN
1371
1372(defvar verilog-mode-abbrev-table nil
1373 "Abbrev table in use in Verilog-mode buffers.")
1374
1375(define-abbrev-table 'verilog-mode-abbrev-table ())
1376
b68a96b9
DN
1377;;
1378;; Macros
1379;;
1380
a03c2342
WS
1381(defsubst verilog-get-beg-of-line (&optional arg)
1382 (save-excursion
1383 (beginning-of-line arg)
1384 (point)))
1385
1386(defsubst verilog-get-end-of-line (&optional arg)
1387 (save-excursion
1388 (end-of-line arg)
1389 (point)))
1390
1391(defsubst verilog-within-string ()
1392 (save-excursion
1393 (nth 3 (parse-partial-sexp (verilog-get-beg-of-line) (point)))))
1394
b68a96b9
DN
1395(defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1396 "Replace occurrences of FROM-STRING with TO-STRING.
1397FIXEDCASE and LITERAL as in `replace-match`. STRING is what to replace.
1398The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1399will break, as the o's continuously replace. xa -> x works ok though."
1400 ;; Hopefully soon to a emacs built-in
1401 (let ((start 0))
1402 (while (string-match from-string string start)
1403 (setq string (replace-match to-string fixedcase literal string)
4c5e69c6 1404 start (min (length string) (+ (match-beginning 0) (length to-string)))))
b68a96b9
DN
1405 string))
1406
1407(defsubst verilog-string-remove-spaces (string)
1408 "Remove spaces surrounding STRING."
1409 (save-match-data
1410 (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1411 (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1412 string))
1413
1414(defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1415 ; checkdoc-params: (REGEXP BOUND NOERROR)
1416 "Like `re-search-forward', but skips over match in comments or strings."
7cb1c4d7
DN
1417 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1418 (while (and
1419 (re-search-forward REGEXP BOUND NOERROR)
1420 (setq mdata (match-data))
1421 (and (verilog-skip-forward-comment-or-string)
1422 (progn
1423 (setq mdata '(nil nil))
1424 (if BOUND
1425 (< (point) BOUND)
1426 t)))))
1427 (store-match-data mdata)
1428 (match-end 0)))
b68a96b9
DN
1429
1430(defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1431 ; checkdoc-params: (REGEXP BOUND NOERROR)
1432 "Like `re-search-backward', but skips over match in comments or strings."
7cb1c4d7
DN
1433 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1434 (while (and
1435 (re-search-backward REGEXP BOUND NOERROR)
1436 (setq mdata (match-data))
1437 (and (verilog-skip-backward-comment-or-string)
1438 (progn
1439 (setq mdata '(nil nil))
1440 (if BOUND
1441 (> (point) BOUND)
1442 t)))))
1443 (store-match-data mdata)
1444 (match-end 0)))
b68a96b9
DN
1445
1446(defsubst verilog-re-search-forward-quick (regexp bound noerror)
1447 "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1448but trashes match data and is faster for REGEXP that doesn't match often.
1449This may at some point use text properties to ignore comments,
1450so there may be a large up front penalty for the first search."
1451 (let (pt)
1452 (while (and (not pt)
1453 (re-search-forward regexp bound noerror))
1454 (if (not (verilog-inside-comment-p))
1455 (setq pt (match-end 0))))
1456 pt))
1457
1458(defsubst verilog-re-search-backward-quick (regexp bound noerror)
1459 ; checkdoc-params: (REGEXP BOUND NOERROR)
1460 "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1461but trashes match data and is faster for REGEXP that doesn't match often.
1462This may at some point use text properties to ignore comments,
1463so there may be a large up front penalty for the first search."
1464 (let (pt)
1465 (while (and (not pt)
1466 (re-search-backward regexp bound noerror))
1467 (if (not (verilog-inside-comment-p))
1468 (setq pt (match-end 0))))
1469 pt))
1470
a03c2342
WS
1471(defsubst verilog-re-search-forward-substr (substr regexp bound noerror)
1472 "Like `re-search-forward', but first search for SUBSTR constant.
1473Then searched for the normal REGEXP (which contains SUBSTR), with given
1474BOUND and NOERROR. The REGEXP must fit within a single line.
1475This speeds up complicated regexp matches."
1476 ;; Problem with overlap: search-forward BAR then FOOBARBAZ won't match.
1477 ;; thus require matches to be on one line, and use beginning-of-line.
1478 (let (done)
1479 (while (and (not done)
1480 (search-forward substr bound noerror))
1481 (save-excursion
1482 (beginning-of-line)
1483 (setq done (re-search-forward regexp (verilog-get-end-of-line) noerror)))
1484 (unless (and (<= (match-beginning 0) (point))
1485 (>= (match-end 0) (point)))
1486 (setq done nil)))
1487 (when done (goto-char done))
1488 done))
1489;;(verilog-re-search-forward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1490
1491(defsubst verilog-re-search-backward-substr (substr regexp bound noerror)
1492 "Like `re-search-backward', but first search for SUBSTR constant.
1493Then searched for the normal REGEXP (which contains SUBSTR), with given
1494BOUND and NOERROR. The REGEXP must fit within a single line.
1495This speeds up complicated regexp matches."
1496 ;; Problem with overlap: search-backward BAR then FOOBARBAZ won't match.
1497 ;; thus require matches to be on one line, and use beginning-of-line.
1498 (let (done)
1499 (while (and (not done)
1500 (search-backward substr bound noerror))
1501 (save-excursion
1502 (end-of-line)
1503 (setq done (re-search-backward regexp (verilog-get-beg-of-line) noerror)))
1504 (unless (and (<= (match-beginning 0) (point))
1505 (>= (match-end 0) (point)))
1506 (setq done nil)))
1507 (when done (goto-char done))
1508 done))
1509;;(verilog-re-search-backward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
b68a96b9 1510
60618039
DN
1511(defvar compile-command)
1512
6341f357
DN
1513;; compilation program
1514(defun verilog-set-compile-command ()
37ea4b9b 1515 "Function to compute shell command to compile Verilog.
6341f357
DN
1516
1517This reads `verilog-tool' and sets `compile-command'. This specifies the
1518program that executes when you type \\[compile] or
1519\\[verilog-auto-save-compile].
1520
a03c2342
WS
1521By default `verilog-tool' uses a Makefile if one exists in the
1522current directory. If not, it is set to the `verilog-linter',
1523`verilog-compiler', `verilog-coverage', `verilog-preprocessor',
1524or `verilog-simulator' variables, as selected with the Verilog ->
1525\"Choose Compilation Action\" menu.
6341f357
DN
1526
1527You should set `verilog-tool' or the other variables to the path and
1528arguments for your Verilog simulator. For example:
1529 \"vcs -p123 -O\"
1530or a string like:
1531 \"(cd /tmp; surecov %s)\".
1532
1533In the former case, the path to the current buffer is concat'ed to the
1534value of `verilog-tool'; in the later, the path to the current buffer is
1535substituted for the %s.
1536
a03c2342
WS
1537Where __FLAGS__ appears in the string `verilog-current-flags'
1538will be substituted.
1539
1540Where __FILE__ appears in the string, the variable
1541`buffer-file-name' of the current buffer, without the directory
1542portion, will be substituted."
6341f357
DN
1543 (interactive)
1544 (cond
1545 ((or (file-exists-p "makefile") ;If there is a makefile, use it
1546 (file-exists-p "Makefile"))
1547 (make-local-variable 'compile-command)
1548 (setq compile-command "make "))
1549 (t
1550 (make-local-variable 'compile-command)
1551 (setq compile-command
1552 (if verilog-tool
1553 (if (string-match "%s" (eval verilog-tool))
1554 (format (eval verilog-tool) (or buffer-file-name ""))
1555 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1556 ""))))
1557 (verilog-modify-compile-command))
1558
a03c2342
WS
1559(defun verilog-expand-command (command)
1560 "Replace meta-information in COMMAND and return it.
1561Where __FLAGS__ appears in the string `verilog-current-flags'
1562will be substituted. Where __FILE__ appears in the string, the
1563current buffer's file-name, without the directory portion, will
1564be substituted."
1565 (setq command (verilog-string-replace-matches
1566 ;; Note \\b only works if under verilog syntax table
1567 "\\b__FLAGS__\\b" (verilog-current-flags)
1568 t t command))
1569 (setq command (verilog-string-replace-matches
1570 "\\b__FILE__\\b" (file-name-nondirectory
1571 (or (buffer-file-name) ""))
1572 t t command))
1573 command)
1574
6341f357 1575(defun verilog-modify-compile-command ()
a03c2342 1576 "Update `compile-command' using `verilog-expand-command'."
6341f357
DN
1577 (when (and
1578 (stringp compile-command)
a03c2342 1579 (string-match "\\b\\(__FLAGS__\\|__FILE__\\)\\b" compile-command))
6341f357 1580 (make-local-variable 'compile-command)
a03c2342 1581 (setq compile-command (verilog-expand-command compile-command))))
6341f357 1582
d9e8a018
GM
1583(if (featurep 'xemacs)
1584 ;; Following code only gets called from compilation-mode-hook on XEmacs to add error handling.
1585 (defun verilog-error-regexp-add-xemacs ()
1586 "Teach XEmacs about verilog errors.
7ea26faf
DN
1587Called by `compilation-mode-hook'. This allows \\[next-error] to
1588find the errors."
d9e8a018
GM
1589 (interactive)
1590 (if (boundp 'compilation-error-regexp-systems-alist)
1591 (if (and
1592 (not (equal compilation-error-regexp-systems-list 'all))
1593 (not (member compilation-error-regexp-systems-list 'verilog)))
1594 (push 'verilog compilation-error-regexp-systems-list)))
1595 (if (boundp 'compilation-error-regexp-alist-alist)
1596 (if (not (assoc 'verilog compilation-error-regexp-alist-alist))
1597 (setcdr compilation-error-regexp-alist-alist
1598 (cons verilog-error-regexp-xemacs-alist
1599 (cdr compilation-error-regexp-alist-alist)))))
1600 (if (boundp 'compilation-font-lock-keywords)
1601 (progn
14862301 1602 (make-local-variable 'compilation-font-lock-keywords)
d9e8a018
GM
1603 (setq compilation-font-lock-keywords verilog-error-font-lock-keywords)
1604 (font-lock-set-defaults)))
1605 ;; Need to re-run compilation-error-regexp builder
1606 (if (fboundp 'compilation-build-compilation-error-regexp-alist)
1607 (compilation-build-compilation-error-regexp-alist))
1608 ))
d88782c3
DN
1609
1610;; Following code only gets called from compilation-mode-hook on Emacs to add error handling.
a3a8b002
DN
1611(defun verilog-error-regexp-add-emacs ()
1612 "Tell Emacs compile that we are Verilog.
1613Called by `compilation-mode-hook'. This allows \\[next-error] to
1614find the errors."
1615 (interactive)
d88782c3
DN
1616 (if (boundp 'compilation-error-regexp-alist-alist)
1617 (progn
1618 (if (not (assoc 'verilog-xl-1 compilation-error-regexp-alist-alist))
1619 (mapcar
1620 (lambda (item)
1621 (push (car item) compilation-error-regexp-alist)
1622 (push item compilation-error-regexp-alist-alist)
1623 )
1624 verilog-error-regexp-emacs-alist)))))
1625
1626(if (featurep 'xemacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-xemacs))
1627(if (featurep 'emacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-emacs))
6341f357
DN
1628
1629(defconst verilog-directive-re
a03c2342
WS
1630 (eval-when-compile
1631 (verilog-regexp-words
1632 '(
1633 "`case" "`default" "`define" "`else" "`elsif" "`endfor" "`endif"
1634 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1635 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1636 "`time_scale" "`undef" "`while" ))))
6341f357 1637
a3a8b002
DN
1638(defconst verilog-directive-re-1
1639 (concat "[ \t]*" verilog-directive-re))
1640
6341f357
DN
1641(defconst verilog-directive-begin
1642 "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1643
1644(defconst verilog-directive-middle
a03c2342 1645 "\\<`\\(else\\|elsif\\|default\\|case\\)\\>")
6341f357
DN
1646
1647(defconst verilog-directive-end
1648 "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1649
a3a8b002
DN
1650(defconst verilog-ovm-begin-re
1651 (eval-when-compile
1652 (verilog-regexp-opt
1653 '(
1654 "`ovm_component_utils_begin"
14862301 1655 "`ovm_component_param_utils_begin"
a3a8b002
DN
1656 "`ovm_field_utils_begin"
1657 "`ovm_object_utils_begin"
14862301 1658 "`ovm_object_param_utils_begin"
a3a8b002
DN
1659 "`ovm_sequence_utils_begin"
1660 "`ovm_sequencer_utils_begin"
1661 ) nil )))
1662
1663(defconst verilog-ovm-end-re
1664 (eval-when-compile
1665 (verilog-regexp-opt
1666 '(
1667 "`ovm_component_utils_end"
1668 "`ovm_field_utils_end"
1669 "`ovm_object_utils_end"
1670 "`ovm_sequence_utils_end"
1671 "`ovm_sequencer_utils_end"
1672 ) nil )))
1673
86a4c7ac
DN
1674(defconst verilog-vmm-begin-re
1675 (eval-when-compile
1676 (verilog-regexp-opt
1677 '(
1678 "`vmm_data_member_begin"
1679 "`vmm_env_member_begin"
1680 "`vmm_scenario_member_begin"
1681 "`vmm_subenv_member_begin"
1682 "`vmm_xactor_member_begin"
1683 ) nil ) ) )
1684
1685(defconst verilog-vmm-end-re
1686 (eval-when-compile
1687 (verilog-regexp-opt
1688 '(
1689 "`vmm_data_member_end"
1690 "`vmm_env_member_end"
1691 "`vmm_scenario_member_end"
1692 "`vmm_subenv_member_end"
1693 "`vmm_xactor_member_end"
1694 ) nil ) ) )
1695
1696(defconst verilog-vmm-statement-re
1697 (eval-when-compile
1698 (verilog-regexp-opt
1699 '(
1700;; "`vmm_xactor_member_enum_array"
1701 "`vmm_\\(data\\|env\\|scenario\\|subenv\\|xactor\\)_member_\\(scalar\\|string\\|enum\\|vmm_data\\|channel\\|xactor\\|subenv\\|user_defined\\)\\(_array\\)?"
1702;; "`vmm_xactor_member_scalar_array"
1703;; "`vmm_xactor_member_scalar"
1704 ) nil )))
1705
a3a8b002
DN
1706(defconst verilog-ovm-statement-re
1707 (eval-when-compile
1708 (verilog-regexp-opt
1709 '(
1710 ;; Statements
1711 "`DUT_ERROR"
1712 "`MESSAGE"
1713 "`dut_error"
1714 "`message"
1715 "`ovm_analysis_imp_decl"
1716 "`ovm_blocking_get_imp_decl"
1717 "`ovm_blocking_get_peek_imp_decl"
1718 "`ovm_blocking_master_imp_decl"
1719 "`ovm_blocking_peek_imp_decl"
1720 "`ovm_blocking_put_imp_decl"
1721 "`ovm_blocking_slave_imp_decl"
1722 "`ovm_blocking_transport_imp_decl"
1723 "`ovm_component_registry"
1724 "`ovm_component_registry_param"
1725 "`ovm_component_utils"
1726 "`ovm_create"
1727 "`ovm_create_seq"
1728 "`ovm_declare_sequence_lib"
1729 "`ovm_do"
1730 "`ovm_do_seq"
1731 "`ovm_do_seq_with"
1732 "`ovm_do_with"
1733 "`ovm_error"
1734 "`ovm_fatal"
1735 "`ovm_field_aa_int_byte"
1736 "`ovm_field_aa_int_byte_unsigned"
1737 "`ovm_field_aa_int_int"
1738 "`ovm_field_aa_int_int_unsigned"
1739 "`ovm_field_aa_int_integer"
1740 "`ovm_field_aa_int_integer_unsigned"
1741 "`ovm_field_aa_int_key"
1742 "`ovm_field_aa_int_longint"
1743 "`ovm_field_aa_int_longint_unsigned"
1744 "`ovm_field_aa_int_shortint"
1745 "`ovm_field_aa_int_shortint_unsigned"
1746 "`ovm_field_aa_int_string"
1747 "`ovm_field_aa_object_int"
1748 "`ovm_field_aa_object_string"
1749 "`ovm_field_aa_string_int"
1750 "`ovm_field_aa_string_string"
1751 "`ovm_field_array_int"
1752 "`ovm_field_array_object"
1753 "`ovm_field_array_string"
1754 "`ovm_field_enum"
1755 "`ovm_field_event"
1756 "`ovm_field_int"
1757 "`ovm_field_object"
1758 "`ovm_field_queue_int"
1759 "`ovm_field_queue_object"
1760 "`ovm_field_queue_string"
1761 "`ovm_field_sarray_int"
1762 "`ovm_field_string"
1763 "`ovm_field_utils"
1764 "`ovm_file"
1765 "`ovm_get_imp_decl"
1766 "`ovm_get_peek_imp_decl"
1767 "`ovm_info"
1768 "`ovm_info1"
1769 "`ovm_info2"
1770 "`ovm_info3"
1771 "`ovm_info4"
1772 "`ovm_line"
1773 "`ovm_master_imp_decl"
1774 "`ovm_msg_detail"
1775 "`ovm_non_blocking_transport_imp_decl"
1776 "`ovm_nonblocking_get_imp_decl"
1777 "`ovm_nonblocking_get_peek_imp_decl"
1778 "`ovm_nonblocking_master_imp_decl"
1779 "`ovm_nonblocking_peek_imp_decl"
1780 "`ovm_nonblocking_put_imp_decl"
1781 "`ovm_nonblocking_slave_imp_decl"
1782 "`ovm_object_registry"
1783 "`ovm_object_registry_param"
1784 "`ovm_object_utils"
1785 "`ovm_peek_imp_decl"
1786 "`ovm_phase_func_decl"
1787 "`ovm_phase_task_decl"
1788 "`ovm_print_aa_int_object"
1789 "`ovm_print_aa_string_int"
1790 "`ovm_print_aa_string_object"
1791 "`ovm_print_aa_string_string"
1792 "`ovm_print_array_int"
1793 "`ovm_print_array_object"
1794 "`ovm_print_array_string"
1795 "`ovm_print_object_queue"
1796 "`ovm_print_queue_int"
1797 "`ovm_print_string_queue"
1798 "`ovm_put_imp_decl"
1799 "`ovm_rand_send"
1800 "`ovm_rand_send_with"
1801 "`ovm_send"
1802 "`ovm_sequence_utils"
1803 "`ovm_slave_imp_decl"
1804 "`ovm_transport_imp_decl"
1805 "`ovm_update_sequence_lib"
1806 "`ovm_update_sequence_lib_and_item"
1807 "`ovm_warning"
1808 "`static_dut_error"
1809 "`static_message") nil )))
1810
6341f357
DN
1811
1812;;
1813;; Regular expressions used to calculate indent, etc.
1814;;
1815(defconst verilog-symbol-re "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
6341f357
DN
1816;; Want to match
1817;; aa :
1818;; aa,bb :
1819;; a[34:32] :
1820;; a,
1821;; b :
1822
14862301 1823(defconst verilog-label-re (concat verilog-symbol-re "\\s-*:\\s-*"))
a03c2342
WS
1824(defconst verilog-property-re
1825 (concat "\\(" verilog-label-re "\\)?"
1826 "\\(\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(assert\\)"))
1827 ;; "\\(assert\\|assume\\|cover\\)\\s-+property\\>"
1828
6341f357
DN
1829(defconst verilog-no-indent-begin-re
1830 "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
1831
1832(defconst verilog-ends-re
1833 ;; Parenthesis indicate type of keyword found
1834 (concat
1835 "\\(\\<else\\>\\)\\|" ; 1
1836 "\\(\\<if\\>\\)\\|" ; 2
86a4c7ac
DN
1837 "\\(\\<assert\\>\\)\\|" ; 3
1838 "\\(\\<end\\>\\)\\|" ; 3.1
6341f357
DN
1839 "\\(\\<endcase\\>\\)\\|" ; 4
1840 "\\(\\<endfunction\\>\\)\\|" ; 5
1841 "\\(\\<endtask\\>\\)\\|" ; 6
1842 "\\(\\<endspecify\\>\\)\\|" ; 7
1843 "\\(\\<endtable\\>\\)\\|" ; 8
1844 "\\(\\<endgenerate\\>\\)\\|" ; 9
1845 "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
1846 "\\(\\<endclass\\>\\)\\|" ; 11
a3a8b002 1847 "\\(\\<endgroup\\>\\)\\|" ; 12
86a4c7ac
DN
1848 ;; VMM
1849 "\\(\\<`vmm_data_member_end\\>\\)\\|"
1850 "\\(\\<`vmm_env_member_end\\>\\)\\|"
1851 "\\(\\<`vmm_scenario_member_end\\>\\)\\|"
1852 "\\(\\<`vmm_subenv_member_end\\>\\)\\|"
1853 "\\(\\<`vmm_xactor_member_end\\>\\)\\|"
a3a8b002
DN
1854 ;; OVM
1855 "\\(\\<`ovm_component_utils_end\\>\\)\\|"
1856 "\\(\\<`ovm_field_utils_end\\>\\)\\|"
1857 "\\(\\<`ovm_object_utils_end\\>\\)\\|"
1858 "\\(\\<`ovm_sequence_utils_end\\>\\)\\|"
1859 "\\(\\<`ovm_sequencer_utils_end\\>\\)"
1860
6341f357
DN
1861 ))
1862
1863(defconst verilog-auto-end-comment-lines-re
1864 ;; Matches to names in this list cause auto-end-commentation
1865 (concat "\\("
1866 verilog-directive-re "\\)\\|\\("
1867 (eval-when-compile
1868 (verilog-regexp-words
1869 `( "begin"
1870 "else"
1871 "end"
1872 "endcase"
1873 "endclass"
1874 "endclocking"
1875 "endgroup"
1876 "endfunction"
1877 "endmodule"
1878 "endprogram"
1879 "endprimitive"
1880 "endinterface"
1881 "endpackage"
1882 "endsequence"
1883 "endspecify"
1884 "endtable"
1885 "endtask"
1886 "join"
1887 "join_any"
1888 "join_none"
1889 "module"
1890 "macromodule"
1891 "primitive"
1892 "interface"
1893 "package")))
1894 "\\)"))
1895
1896;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
1897;;; verilog-end-block-ordered-re matches exactly the same strings.
1898(defconst verilog-end-block-ordered-re
1899 ;; Parenthesis indicate type of keyword found
1900 (concat "\\(\\<endcase\\>\\)\\|" ; 1
1901 "\\(\\<end\\>\\)\\|" ; 2
1902 "\\(\\<end" ; 3, but not used
1903 "\\(" ; 4, but not used
1904 "\\(function\\)\\|" ; 5
1905 "\\(task\\)\\|" ; 6
1906 "\\(module\\)\\|" ; 7
1907 "\\(primitive\\)\\|" ; 8
1908 "\\(interface\\)\\|" ; 9
1909 "\\(package\\)\\|" ; 10
1910 "\\(class\\)\\|" ; 11
1911 "\\(group\\)\\|" ; 12
1912 "\\(program\\)\\|" ; 13
1913 "\\(sequence\\)\\|" ; 14
1914 "\\(clocking\\)\\|" ; 15
1915 "\\)\\>\\)"))
1916(defconst verilog-end-block-re
1917 (eval-when-compile
1918 (verilog-regexp-words
1919
1920 `("end" ;; closes begin
1921 "endcase" ;; closes any of case, casex casez or randcase
1922 "join" "join_any" "join_none" ;; closes fork
1923 "endclass"
1924 "endtable"
1925 "endspecify"
1926 "endfunction"
1927 "endgenerate"
1928 "endtask"
1929 "endgroup"
1930 "endproperty"
1931 "endinterface"
1932 "endpackage"
1933 "endprogram"
1934 "endsequence"
1935 "endclocking"
a3a8b002
DN
1936 ;; OVM
1937 "`ovm_component_utils_end"
1938 "`ovm_field_utils_end"
1939 "`ovm_object_utils_end"
1940 "`ovm_sequence_utils_end"
1941 "`ovm_sequencer_utils_end"
86a4c7ac
DN
1942 ;; VMM
1943 "`vmm_data_member_end"
1944 "`vmm_env_member_end"
1945 "`vmm_scenario_member_end"
1946 "`vmm_subenv_member_end"
1947 "`vmm_xactor_member_end"
60618039 1948 ))))
6341f357
DN
1949
1950
1951(defconst verilog-endcomment-reason-re
1952 ;; Parenthesis indicate type of keyword found
1953 (concat
a3a8b002
DN
1954 "\\(\\<begin\\>\\)\\|" ; 1
1955 "\\(\\<else\\>\\)\\|" ; 2
1956 "\\(\\<end\\>\\s-+\\<else\\>\\)\\|" ; 3
1957 "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|" ; 4
1958 "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|" ; 5
1959 "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|" ; 6
1960 "\\(\\<fork\\>\\)\\|" ; 7
14862301 1961 "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
6341f357 1962 "\\(\\<if\\>\\)\\|"
a03c2342
WS
1963 verilog-property-re "\\|"
1964 "\\(\\(" verilog-label-re "\\)?\\<assert\\>\\)\\|"
6341f357 1965 "\\(\\<clocking\\>\\)\\|"
14862301
SM
1966 "\\(\\<task\\>\\)\\|"
1967 "\\(\\<function\\>\\)\\|"
6341f357
DN
1968 "\\(\\<initial\\>\\)\\|"
1969 "\\(\\<interface\\>\\)\\|"
1970 "\\(\\<package\\>\\)\\|"
1971 "\\(\\<final\\>\\)\\|"
6341f357
DN
1972 "\\(@\\)\\|"
1973 "\\(\\<while\\>\\)\\|"
1974 "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
1975 "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
1976 "#"))
1977
1978(defconst verilog-named-block-re "begin[ \t]*:")
1979
1980;; These words begin a block which can occur inside a module which should be indented,
1981;; and closed with the respective word from the end-block list
1982
1983(defconst verilog-beg-block-re
1984 (eval-when-compile
1985 (verilog-regexp-words
1986 `("begin"
1987 "case" "casex" "casez" "randcase"
1988 "clocking"
1989 "generate"
1990 "fork"
1991 "function"
1992 "property"
1993 "specify"
1994 "table"
1995 "task"
a3a8b002
DN
1996 ;;; OVM
1997 "`ovm_component_utils_begin"
14862301 1998 "`ovm_component_param_utils_begin"
a3a8b002
DN
1999 "`ovm_field_utils_begin"
2000 "`ovm_object_utils_begin"
14862301 2001 "`ovm_object_param_utils_begin"
a3a8b002
DN
2002 "`ovm_sequence_utils_begin"
2003 "`ovm_sequencer_utils_begin"
86a4c7ac
DN
2004 ;; VMM
2005 "`vmm_data_member_begin"
2006 "`vmm_env_member_begin"
2007 "`vmm_scenario_member_begin"
2008 "`vmm_subenv_member_begin"
2009 "`vmm_xactor_member_begin"
6341f357
DN
2010 ))))
2011;; These are the same words, in a specific order in the regular
2012;; expression so that matching will work nicely for
2013;; verilog-forward-sexp and verilog-calc-indent
6341f357 2014(defconst verilog-beg-block-re-ordered
4c5e69c6
DN
2015 ( concat "\\(\\<begin\\>\\)" ;1
2016 "\\|\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
2017 "\\|\\(\\(\\<disable\\>\\s-+\\)?fork\\>\\)" ;4,5
2018 "\\|\\(\\<class\\>\\)" ;6
2019 "\\|\\(\\<table\\>\\)" ;7
2020 "\\|\\(\\<specify\\>\\)" ;8
2021 "\\|\\(\\<function\\>\\)" ;9
a3a8b002
DN
2022 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<function\\>\\)" ;10
2023 "\\|\\(\\<task\\>\\)" ;14
2024 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)" ;15
2025 "\\|\\(\\<generate\\>\\)" ;18
2026 "\\|\\(\\<covergroup\\>\\)" ;16 20
2027 "\\|\\(\\(\\(\\<cover\\>\\s-+\\)\\|\\(\\<assert\\>\\s-+\\)\\)*\\<property\\>\\)" ;17 21
2028 "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;21 25
2029 "\\|\\(\\<clocking\\>\\)" ;22 27
2030 "\\|\\(\\<`ovm_[a-z_]+_begin\\>\\)" ;28
86a4c7ac 2031 "\\|\\(\\<`vmm_[a-z_]+_member_begin\\>\\)"
a3a8b002
DN
2032 ;;
2033
4c5e69c6 2034 ))
6341f357
DN
2035
2036(defconst verilog-end-block-ordered-rry
2037 [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2038 "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
2039 "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2040 "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
2041 "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
2042 "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
2043 "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
2044 "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
2045 "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
2046 "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
2047 "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
2048 "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
2049 "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
2050 ] )
2051
2052(defconst verilog-nameable-item-re
2053 (eval-when-compile
2054 (verilog-regexp-words
2055 `("begin"
2056 "fork"
2057 "join" "join_any" "join_none"
2058 "end"
2059 "endcase"
2060 "endconfig"
2061 "endclass"
2062 "endclocking"
2063 "endfunction"
2064 "endgenerate"
2065 "endmodule"
86a4c7ac 2066 "endprimitive"
6341f357
DN
2067 "endinterface"
2068 "endpackage"
2069 "endspecify"
2070 "endtable"
2071 "endtask" )
2072 )))
2073
2074(defconst verilog-declaration-opener
2075 (eval-when-compile
2076 (verilog-regexp-words
2077 `("module" "begin" "task" "function"))))
2078
2079(defconst verilog-declaration-prefix-re
2080 (eval-when-compile
2081 (verilog-regexp-words
2082 `(
2083 ;; port direction
6edb5716 2084 "inout" "input" "output" "ref"
6341f357
DN
2085 ;; changeableness
2086 "const" "static" "protected" "local"
2087 ;; parameters
6edb5716 2088 "localparam" "parameter" "var"
6341f357
DN
2089 ;; type creation
2090 "typedef"
2091 ))))
2092(defconst verilog-declaration-core-re
2093 (eval-when-compile
2094 (verilog-regexp-words
2095 `(
7e2a6000 2096 ;; port direction (by themselves)
871c637e 2097 "inout" "input" "output"
6341f357
DN
2098 ;; integer_atom_type
2099 "byte" "shortint" "int" "longint" "integer" "time"
2100 ;; integer_vector_type
2101 "bit" "logic" "reg"
2102 ;; non_integer_type
2103 "shortreal" "real" "realtime"
2104 ;; net_type
2105 "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
2106 ;; misc
2107 "string" "event" "chandle" "virtual" "enum" "genvar"
2108 "struct" "union"
2109 ;; builtin classes
6edb5716 2110 "mailbox" "semaphore"
6341f357 2111 ))))
6edb5716 2112(defconst verilog-declaration-re
6341f357
DN
2113 (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
2114(defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
2115(defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
2116(defconst verilog-optional-signed-range-re
2117 (concat
2118 "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
2119(defconst verilog-macroexp-re "`\\sw+")
2120
2121(defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
2122(defconst verilog-declaration-re-2-no-macro
2123 (concat "\\s-*" verilog-declaration-re
2124 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2125 "\\)?"))
2126(defconst verilog-declaration-re-2-macro
2127 (concat "\\s-*" verilog-declaration-re
2128 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2129 "\\|\\(" verilog-macroexp-re "\\)"
2130 "\\)?"))
2131(defconst verilog-declaration-re-1-macro
2132 (concat "^" verilog-declaration-re-2-macro))
2133
2134(defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
2135
2136(defconst verilog-defun-re
2137 (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
2138(defconst verilog-end-defun-re
2139 (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
2140(defconst verilog-zero-indent-re
2141 (concat verilog-defun-re "\\|" verilog-end-defun-re))
2142
2143(defconst verilog-behavioral-block-beg-re
2a9eb3f5
DN
2144 (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
2145 "function" "task"))))
a3a8b002 2146(defconst verilog-coverpoint-re "\\w+\\s*:\\s*\\(coverpoint\\|cross\\constraint\\)" )
6341f357
DN
2147(defconst verilog-indent-re
2148 (eval-when-compile
2149 (verilog-regexp-words
2150 `(
2151 "{"
2152 "always" "always_latch" "always_ff" "always_comb"
2153 "begin" "end"
2154; "unique" "priority"
2155 "case" "casex" "casez" "randcase" "endcase"
2156 "class" "endclass"
2157 "clocking" "endclocking"
2158 "config" "endconfig"
2159 "covergroup" "endgroup"
2160 "fork" "join" "join_any" "join_none"
2161 "function" "endfunction"
2162 "final"
2163 "generate" "endgenerate"
2164 "initial"
2165 "interface" "endinterface"
2166 "module" "macromodule" "endmodule"
2167 "package" "endpackage"
2168 "primitive" "endprimative"
2169 "program" "endprogram"
2170 "property" "endproperty"
2171 "sequence" "randsequence" "endsequence"
2172 "specify" "endspecify"
2173 "table" "endtable"
2174 "task" "endtask"
4c5e69c6 2175 "virtual"
6341f357
DN
2176 "`case"
2177 "`default"
2178 "`define" "`undef"
a03c2342 2179 "`if" "`ifdef" "`ifndef" "`else" "`elsif" "`endif"
6341f357
DN
2180 "`while" "`endwhile"
2181 "`for" "`endfor"
2182 "`format"
2183 "`include"
2184 "`let"
2185 "`protect" "`endprotect"
2186 "`switch" "`endswitch"
2187 "`timescale"
2188 "`time_scale"
a3a8b002
DN
2189 ;; OVM Begin tokens
2190 "`ovm_component_utils_begin"
14862301 2191 "`ovm_component_param_utils_begin"
a3a8b002
DN
2192 "`ovm_field_utils_begin"
2193 "`ovm_object_utils_begin"
14862301 2194 "`ovm_object_param_utils_begin"
a3a8b002
DN
2195 "`ovm_sequence_utils_begin"
2196 "`ovm_sequencer_utils_begin"
2197 ;; OVM End tokens
2198 "`ovm_component_utils_end"
2199 "`ovm_field_utils_end"
2200 "`ovm_object_utils_end"
2201 "`ovm_sequence_utils_end"
2202 "`ovm_sequencer_utils_end"
86a4c7ac
DN
2203 ;; VMM Begin tokens
2204 "`vmm_data_member_begin"
2205 "`vmm_env_member_begin"
2206 "`vmm_scenario_member_begin"
2207 "`vmm_subenv_member_begin"
2208 "`vmm_xactor_member_begin"
2209 ;; VMM End tokens
2210 "`vmm_data_member_end"
2211 "`vmm_env_member_end"
2212 "`vmm_scenario_member_end"
2213 "`vmm_subenv_member_end"
2214 "`vmm_xactor_member_end"
6341f357
DN
2215 ))))
2216
a3a8b002
DN
2217(defconst verilog-defun-level-not-generate-re
2218 (eval-when-compile
2219 (verilog-regexp-words
2220 `( "module" "macromodule" "primitive" "class" "program"
2221 "interface" "package" "config"))))
2222
6341f357
DN
2223(defconst verilog-defun-level-re
2224 (eval-when-compile
2225 (verilog-regexp-words
a3a8b002
DN
2226 (append
2227 `( "module" "macromodule" "primitive" "class" "program"
2228 "interface" "package" "config")
2229 `( "initial" "final" "always" "always_comb" "always_ff"
2230 "always_latch" "endtask" "endfunction" )))))
6341f357 2231
a3a8b002 2232(defconst verilog-defun-level-generate-only-re
6341f357
DN
2233 (eval-when-compile
2234 (verilog-regexp-words
a3a8b002
DN
2235 `( "initial" "final" "always" "always_comb" "always_ff"
2236 "always_latch" "endtask" "endfunction" ))))
6341f357
DN
2237
2238(defconst verilog-cpp-level-re
2239 (eval-when-compile
2240 (verilog-regexp-words
2241 `(
2242 "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
2243 ))))
a03c2342
WS
2244(defconst verilog-disable-fork-re "disable\\s-+fork\\>")
2245(defconst verilog-fork-wait-re "fork\\s-+wait\\>")
6341f357
DN
2246(defconst verilog-extended-case-re "\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?")
2247(defconst verilog-extended-complete-re
a03c2342 2248 (concat "\\(\\<extern\\s-+\\|\\<\\(\\<pure\\>\\s-+\\)?virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)"
6341f357 2249 "\\|\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)"
a3a8b002 2250 "\\|\\(\\<import\\>\\s-+\\)?\"DPI-C\"\\s-+\\(function\\>\\|task\\>\\)"
6341f357
DN
2251 "\\|" verilog-extended-case-re ))
2252(defconst verilog-basic-complete-re
2253 (eval-when-compile
2254 (verilog-regexp-words
2255 `(
2256 "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
2257 "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
14862301 2258 "if" "for" "forever" "foreach" "else" "parameter" "do" "localparam" "assert"
6341f357
DN
2259 ))))
2260(defconst verilog-complete-reg
2261 (concat
2262 verilog-extended-complete-re
2263 "\\|"
2264 verilog-basic-complete-re))
2265
2266(defconst verilog-end-statement-re
2267 (concat "\\(" verilog-beg-block-re "\\)\\|\\("
2268 verilog-end-block-re "\\)"))
2269
2270(defconst verilog-endcase-re
a3a8b002 2271 (concat verilog-extended-case-re "\\|"
6341f357
DN
2272 "\\(endcase\\)\\|"
2273 verilog-defun-re
2274 ))
2275
2276(defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
2277 "String used to mark beginning of excluded text.")
2278(defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
2279 "String used to mark end of excluded text.")
2280(defconst verilog-preprocessor-re
2281 (eval-when-compile
2282 (verilog-regexp-words
2283 `(
2284 "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
2285 ))))
2286
2287(defconst verilog-keywords
2288 '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
2289 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
2290 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
2291 "`time_scale" "`undef" "`while"
2292
2293 "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
2294 "assert" "assign" "assume" "automatic" "before" "begin" "bind"
2295 "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
2296 "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
2297 "config" "const" "constraint" "context" "continue" "cover"
2298 "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
2299 "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
2300 "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
2301 "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
2302 "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
2303 "endtask" "enum" "event" "expect" "export" "extends" "extern"
2304 "final" "first_match" "for" "force" "foreach" "forever" "fork"
2305 "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
2306 "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
2307 "include" "initial" "inout" "input" "inside" "instance" "int"
2308 "integer" "interface" "intersect" "join" "join_any" "join_none"
2309 "large" "liblist" "library" "local" "localparam" "logic"
2310 "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
2311 "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
2312 "notif0" "notif1" "null" "or" "output" "package" "packed"
2313 "parameter" "pmos" "posedge" "primitive" "priority" "program"
2314 "property" "protected" "pull0" "pull1" "pulldown" "pullup"
2315 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2316 "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
2317 "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
2318 "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
2319 "showcancelled" "signed" "small" "solve" "specify" "specparam"
2320 "static" "string" "strong0" "strong1" "struct" "super" "supply0"
2321 "supply1" "table" "tagged" "task" "this" "throughout" "time"
2322 "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
2323 "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
2324 "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
2325 "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
2326 "wire" "with" "within" "wor" "xnor" "xor"
a03c2342
WS
2327 ;; 1800-2009
2328 "accept_on" "checker" "endchecker" "eventually" "global" "implies"
2329 "let" "nexttime" "reject_on" "restrict" "s_always" "s_eventually"
2330 "s_nexttime" "s_until" "s_until_with" "strong" "sync_accept_on"
2331 "sync_reject_on" "unique0" "until" "until_with" "untyped" "weak"
6341f357
DN
2332 )
2333 "List of Verilog keywords.")
2334
6341f357
DN
2335(defconst verilog-comment-start-regexp "//\\|/\\*"
2336 "Dual comment value for `comment-start-regexp'.")
2337
e1776067
DN
2338(defvar verilog-mode-syntax-table
2339 (let ((table (make-syntax-table)))
2340 ;; Populate the syntax TABLE.
2341 (modify-syntax-entry ?\\ "\\" table)
2342 (modify-syntax-entry ?+ "." table)
2343 (modify-syntax-entry ?- "." table)
2344 (modify-syntax-entry ?= "." table)
2345 (modify-syntax-entry ?% "." table)
2346 (modify-syntax-entry ?< "." table)
2347 (modify-syntax-entry ?> "." table)
2348 (modify-syntax-entry ?& "." table)
2349 (modify-syntax-entry ?| "." table)
2350 (modify-syntax-entry ?` "w" table)
2351 (modify-syntax-entry ?_ "w" table)
2352 (modify-syntax-entry ?\' "." table)
2353
2354 ;; Set up TABLE to handle block and line style comments.
2355 (if (featurep 'xemacs)
2356 (progn
2357 ;; XEmacs (formerly Lucid) has the best implementation
2358 (modify-syntax-entry ?/ ". 1456" table)
2359 (modify-syntax-entry ?* ". 23" table)
2360 (modify-syntax-entry ?\n "> b" table))
d63b01e1 2361 ;; Emacs does things differently, but we can work with it
e1776067
DN
2362 (modify-syntax-entry ?/ ". 124b" table)
2363 (modify-syntax-entry ?* ". 23" table)
2364 (modify-syntax-entry ?\n "> b" table))
2365 table)
37ea4b9b 2366 "Syntax table used in Verilog mode buffers.")
6341f357 2367
7ea26faf 2368(defvar verilog-font-lock-keywords nil
6341f357
DN
2369 "Default highlighting for Verilog mode.")
2370
7ea26faf 2371(defvar verilog-font-lock-keywords-1 nil
6341f357
DN
2372 "Subdued level highlighting for Verilog mode.")
2373
7ea26faf 2374(defvar verilog-font-lock-keywords-2 nil
6341f357
DN
2375 "Medium level highlighting for Verilog mode.
2376See also `verilog-font-lock-extra-types'.")
2377
7ea26faf 2378(defvar verilog-font-lock-keywords-3 nil
6341f357
DN
2379 "Gaudy level highlighting for Verilog mode.
2380See also `verilog-font-lock-extra-types'.")
2381(defvar verilog-font-lock-translate-off-face
2382 'verilog-font-lock-translate-off-face
2383 "Font to use for translated off regions.")
2384(defface verilog-font-lock-translate-off-face
2385 '((((class color)
2386 (background light))
2387 (:background "gray90" :italic t ))
2388 (((class color)
2389 (background dark))
2390 (:background "gray10" :italic t ))
2391 (((class grayscale) (background light))
2392 (:foreground "DimGray" :italic t))
2393 (((class grayscale) (background dark))
2394 (:foreground "LightGray" :italic t))
2395 (t (:italis t)))
2396 "Font lock mode face used to background highlight translate-off regions."
2397 :group 'font-lock-highlighting-faces)
2398
2399(defvar verilog-font-lock-p1800-face
2400 'verilog-font-lock-p1800-face
2401 "Font to use for p1800 keywords.")
2402(defface verilog-font-lock-p1800-face
2403 '((((class color)
2404 (background light))
2405 (:foreground "DarkOrange3" :bold t ))
2406 (((class color)
2407 (background dark))
2408 (:foreground "orange1" :bold t ))
2409 (t (:italic t)))
2410 "Font lock mode face used to highlight P1800 keywords."
2411 :group 'font-lock-highlighting-faces)
2412
2413(defvar verilog-font-lock-ams-face
2414 'verilog-font-lock-ams-face
2415 "Font to use for Analog/Mixed Signal keywords.")
2416(defface verilog-font-lock-ams-face
2417 '((((class color)
2418 (background light))
2419 (:foreground "Purple" :bold t ))
2420 (((class color)
2421 (background dark))
2422 (:foreground "orange1" :bold t ))
2423 (t (:italic t)))
2424 "Font lock mode face used to highlight AMS keywords."
2425 :group 'font-lock-highlighting-faces)
2426
2a9eb3f5
DN
2427(defvar verilog-font-grouping-keywords-face
2428 'verilog-font-lock-grouping-keywords-face
2429 "Font to use for Verilog Grouping Keywords (such as begin..end).")
2430(defface verilog-font-lock-grouping-keywords-face
2431 '((((class color)
2432 (background light))
2433 (:foreground "red4" :bold t ))
2434 (((class color)
2435 (background dark))
2436 (:foreground "red4" :bold t ))
2437 (t (:italic t)))
2438 "Font lock mode face used to highlight verilog grouping keywords."
2439 :group 'font-lock-highlighting-faces)
2440
6341f357
DN
2441(let* ((verilog-type-font-keywords
2442 (eval-when-compile
2443 (verilog-regexp-opt
2444 '(
2445 "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
2446 "event" "genvar" "inout" "input" "integer" "localparam"
2447 "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
a03c2342 2448 "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
6341f357
DN
2449 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
2450 "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
2451 "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
2452 "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
2453 "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
2454 ) nil )))
2455
2456 (verilog-pragma-keywords
2457 (eval-when-compile
2458 (verilog-regexp-opt
9c059794 2459 '("surefire" "synopsys" "rtl_synthesis" "verilint" "leda" "0in") nil
6341f357
DN
2460 )))
2461
a03c2342 2462 (verilog-1800-2005-keywords
6341f357
DN
2463 (eval-when-compile
2464 (verilog-regexp-opt
2465 '("alias" "assert" "assume" "automatic" "before" "bind"
2466 "bins" "binsof" "break" "byte" "cell" "chandle" "class"
2467 "clocking" "config" "const" "constraint" "context" "continue"
2468 "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
2469 "dist" "do" "edge" "endclass" "endclocking" "endconfig"
2470 "endgroup" "endprogram" "endproperty" "endsequence" "enum"
2471 "expect" "export" "extends" "extern" "first_match" "foreach"
2472 "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
2473 "illegal_bins" "import" "incdir" "include" "inside" "instance"
2474 "int" "intersect" "large" "liblist" "library" "local" "longint"
2475 "matches" "medium" "modport" "new" "noshowcancelled" "null"
2476 "packed" "program" "property" "protected" "pull0" "pull1"
2477 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2478 "randcase" "randsequence" "ref" "release" "return" "scalared"
2479 "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
2480 "specparam" "static" "string" "strong0" "strong1" "struct"
2481 "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
2482 "type" "union" "unsigned" "use" "var" "virtual" "void"
2483 "wait_order" "weak0" "weak1" "wildcard" "with" "within"
2484 ) nil )))
2485
a03c2342
WS
2486 (verilog-1800-2009-keywords
2487 (eval-when-compile
2488 (verilog-regexp-opt
2489 '("accept_on" "checker" "endchecker" "eventually" "global"
2490 "implies" "let" "nexttime" "reject_on" "restrict" "s_always"
2491 "s_eventually" "s_nexttime" "s_until" "s_until_with" "strong"
2492 "sync_accept_on" "sync_reject_on" "unique0" "until"
2493 "until_with" "untyped" "weak" ) nil )))
2494
6341f357
DN
2495 (verilog-ams-keywords
2496 (eval-when-compile
2497 (verilog-regexp-opt
2498 '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
2499 "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
2500 "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
2501 "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
2502 "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
2503 "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
2504 "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
2505 "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
2506 "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
2507 "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
2508 "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
2509
2510 (verilog-font-keywords
2511 (eval-when-compile
2512 (verilog-regexp-opt
2513 '(
2a9eb3f5
DN
2514 "assign" "case" "casex" "casez" "randcase" "deassign"
2515 "default" "disable" "else" "endcase" "endfunction"
6341f357
DN
2516 "endgenerate" "endinterface" "endmodule" "endprimitive"
2517 "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
2518 "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
2519 "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
2520 "package" "endpackage" "always" "always_comb" "always_ff"
2521 "always_latch" "posedge" "primitive" "priority" "release"
2522 "repeat" "specify" "table" "task" "unique" "wait" "while"
2523 "class" "program" "endclass" "endprogram"
2a9eb3f5
DN
2524 ) nil )))
2525
2526 (verilog-font-grouping-keywords
2527 (eval-when-compile
2528 (verilog-regexp-opt
2529 '( "begin" "end" ) nil ))))
6341f357
DN
2530
2531 (setq verilog-font-lock-keywords
2532 (list
2533 ;; Fontify all builtin keywords
2534 (concat "\\<\\(" verilog-font-keywords "\\|"
2535 ;; And user/system tasks and functions
a1ebd734
DN
2536 "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
2537 "\\)\\>")
b1d0fc86
DN
2538 ;; Fontify all types
2539 (if verilog-highlight-grouping-keywords
2540 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2541 'verilog-font-lock-ams-face)
2542 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2543 'font-lock-type-face))
2544 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
a1ebd734 2545 'font-lock-type-face)
a03c2342
WS
2546 ;; Fontify IEEE-1800-2005 keywords appropriately
2547 (if verilog-highlight-p1800-keywords
2548 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
2549 'verilog-font-lock-p1800-face)
2550 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
2551 'font-lock-type-face))
2552 ;; Fontify IEEE-1800-2009 keywords appropriately
6341f357 2553 (if verilog-highlight-p1800-keywords
a03c2342 2554 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
6341f357 2555 'verilog-font-lock-p1800-face)
a03c2342 2556 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
6341f357
DN
2557 'font-lock-type-face))
2558 ;; Fontify Verilog-AMS keywords
2559 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
60618039 2560 'verilog-font-lock-ams-face)))
6341f357
DN
2561
2562 (setq verilog-font-lock-keywords-1
2563 (append verilog-font-lock-keywords
2564 (list
2565 ;; Fontify module definitions
2566 (list
2567 "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
2568 '(1 font-lock-keyword-face)
2569 '(3 font-lock-function-name-face 'prepend))
2570 ;; Fontify function definitions
2571 (list
2572 (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
2573 '(1 font-lock-keyword-face)
4da3541b 2574 '(3 font-lock-constant-face prepend))
6341f357
DN
2575 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
2576 (1 font-lock-keyword-face)
4da3541b 2577 (2 font-lock-constant-face append))
6341f357 2578 '("\\<function\\>\\s-+\\(\\sw+\\)"
4da3541b 2579 1 'font-lock-constant-face append))))
6341f357
DN
2580
2581 (setq verilog-font-lock-keywords-2
2582 (append verilog-font-lock-keywords-1
2583 (list
2584 ;; Fontify pragmas
2585 (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
2586 ;; Fontify escaped names
2587 '("\\(\\\\\\S-*\\s-\\)" 0 font-lock-function-name-face)
2588 ;; Fontify macro definitions/ uses
2589 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
2590 'font-lock-preprocessor-face
2591 'font-lock-type-face))
2592 ;; Fontify delays/numbers
2593 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
2594 0 font-lock-type-face append)
2595 ;; Fontify instantiation names
a03c2342 2596 '("\\([A-Za-z][A-Za-z0-9_]*\\)\\s-*(" 1 font-lock-function-name-face)
6341f357
DN
2597 )))
2598
2599 (setq verilog-font-lock-keywords-3
2600 (append verilog-font-lock-keywords-2
2601 (when verilog-highlight-translate-off
2602 (list
2603 ;; Fontify things in translate off regions
7ea26faf
DN
2604 '(verilog-match-translate-off
2605 (0 'verilog-font-lock-translate-off-face prepend))
2606 )))))
6341f357 2607
a03c2342
WS
2608;;
2609;; Buffer state preservation
2610
2611(defmacro verilog-save-buffer-state (&rest body)
2612 "Execute BODY forms, saving state around insignificant change.
2613Changes in text properties like `face' or `syntax-table' are
2614considered insignificant. This macro allows text properties to
2615be changed, even in a read-only buffer.
2616
2617A change is considered significant if it affects the buffer text
2618in any way that isn't completely restored again. Any
2619user-visible changes to the buffer must not be within a
2620`verilog-save-buffer-state'."
2621 ;; From c-save-buffer-state
2622 `(let* ((modified (buffer-modified-p))
2623 (buffer-undo-list t)
2624 (inhibit-read-only t)
2625 (inhibit-point-motion-hooks t)
2626 before-change-functions
2627 after-change-functions
2628 deactivate-mark
2629 buffer-file-name ; Prevent primitives checking
2630 buffer-file-truename) ; for file modification
2631 (unwind-protect
2632 (progn ,@body)
2633 (and (not modified)
2634 (buffer-modified-p)
2635 (set-buffer-modified-p nil)))))
2636
2637(defmacro verilog-save-no-change-functions (&rest body)
2638 "Execute BODY forms, disabling all change hooks in BODY.
2639For insigificant changes, see instead `verilog-save-buffer-state'."
2640 `(let* ((inhibit-point-motion-hooks t)
2641 before-change-functions
2642 after-change-functions)
2643 (progn ,@body)))
2644
2645;;
2646;; Comment detection and caching
2647
2648(defvar verilog-scan-cache-preserving nil
2649 "If set, the specified buffer's comment properties are static.
2650Buffer changes will be ignored. See `verilog-inside-comment-p'
2651and `verilog-scan'.")
2652
2653(defvar verilog-scan-cache-tick nil
2654 "Modification tick at which `verilog-scan' was last completed.")
2655(make-variable-buffer-local 'verilog-scan-cache-tick)
2656
2657(defun verilog-scan-cache-ok-p ()
2658 "Return t iff the scan cache is up to date."
2659 (or (and verilog-scan-cache-preserving
2660 (eq verilog-scan-cache-preserving (current-buffer))
2661 verilog-scan-cache-tick)
2662 (equal verilog-scan-cache-tick (buffer-chars-modified-tick))))
2663
2664(defmacro verilog-save-scan-cache (&rest body)
2665 "Execute the BODY forms, allowing scan cache preservation within BODY.
2666This requires that insertions must use `verilog-insert'."
2667 ;; If the buffer is out of date, trash it, as we'll not check later the tick
2668 ;; Note this must work properly if there's multiple layers of calls
2669 ;; to verilog-save-scan-cache even with differing ticks.
2670 `(progn
2671 (unless (verilog-scan-cache-ok-p) ;; Must be before let
2672 (setq verilog-scan-cache-tick nil))
2673 (let* ((verilog-scan-cache-preserving (current-buffer)))
2674 (progn ,@body))))
2675
2676(defun verilog-scan-region (beg end)
2677 "Parse comments between BEG and END for `verilog-inside-comment-p'.
2678This creates v-cmt properties where comments are in force."
2679 ;; Why properties and not overlays? Overlays have much slower non O(1)
2680 ;; lookup times.
2681 ;; This function is warm - called on every verilog-insert
2682 (save-excursion
2683 (save-match-data
2684 (verilog-save-buffer-state
2685 (let (pt)
2686 (goto-char beg)
2687 (while (< (point) end)
2688 (cond ((looking-at "//")
2689 (setq pt (point))
2690 (or (search-forward "\n" end t)
2691 (goto-char end))
2692 ;; "1+": The leading // or /* itself isn't considered as
2693 ;; being "inside" the comment, so that a (search-backward)
2694 ;; that lands at the start of the // won't mis-indicate
2695 ;; it's inside a comment
2696 (put-text-property (1+ pt) (point) 'v-cmt t))
2697 ((looking-at "/\\*")
2698 (setq pt (point))
2699 (or (search-forward "*/" end t)
2700 ;; No error - let later code indicate it so we can
2701 ;; use inside functions on-the-fly
2702 ;;(error "%s: Unmatched /* */, at char %d"
2703 ;; (verilog-point-text) (point))
2704 (goto-char end))
2705 (put-text-property (1+ pt) (point) 'v-cmt t))
2706 (t
2707 (forward-char 1)
2708 (if (re-search-forward "/[/*]" end t)
2709 (backward-char 2)
2710 (goto-char end))))))))))
2711
2712(defun verilog-scan ()
2713 "Parse the buffer, marking all comments with properties.
2714Also assumes any text inserted since `verilog-scan-cache-tick'
2715either is ok to parse as a non-comment, or `verilog-insert' was used."
2716 (unless (verilog-scan-cache-ok-p)
2717 (save-excursion
2718 (verilog-save-buffer-state
2719 (when verilog-debug
2720 (message "Scanning %s cache=%s cachetick=%S tick=%S" (current-buffer)
2721 verilog-scan-cache-preserving verilog-scan-cache-tick
2722 (buffer-chars-modified-tick)))
2723 (remove-text-properties (point-min) (point-max) '(v-cmt nil))
2724 (verilog-scan-region (point-min) (point-max))
2725 (setq verilog-scan-cache-tick (buffer-chars-modified-tick))
2726 (when verilog-debug (message "Scaning... done"))))))
6341f357 2727
6341f357 2728(defun verilog-inside-comment-p ()
a03c2342
WS
2729 "Check if point inside a comment.
2730This may require a slow pre-parse of the buffer with `verilog-scan'
2731to establish comment properties on all text."
2732 ;; This function is very hot
2733 (verilog-scan)
2734 (get-text-property (point) 'v-cmt))
2735
2736(defun verilog-insert (&rest stuff)
2737 "Insert STUFF arguments, tracking comments for `verilog-inside-comment-p'.
2738Any insert that includes a comment must have the entire commente
2739inserted using a single call to `verilog-insert'."
2740 (let ((pt (point)))
2741 (while stuff
2742 (insert (car stuff))
2743 (setq stuff (cdr stuff)))
2744 (verilog-scan-region pt (point))))
2745
2746;; More searching
6341f357
DN
2747
2748(defun verilog-declaration-end ()
2749 (search-forward ";"))
2750
2751(defun verilog-point-text (&optional pointnum)
2752 "Return text describing where POINTNUM or current point is (for errors).
2753Use filename, if current buffer being edited shorten to just buffer name."
2754 (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
2755 (buffer-name))
2756 buffer-file-name
2757 (buffer-name))
2758 ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
2759
2760(defun electric-verilog-backward-sexp ()
495ab0d5 2761 "Move backward over one balanced expression."
6341f357
DN
2762 (interactive)
2763 ;; before that see if we are in a comment
60618039
DN
2764 (verilog-backward-sexp))
2765
6341f357 2766(defun electric-verilog-forward-sexp ()
495ab0d5 2767 "Move forward over one balanced expression."
6341f357
DN
2768 (interactive)
2769 ;; before that see if we are in a comment
60618039
DN
2770 (verilog-forward-sexp))
2771
6341f357
DN
2772;;;used by hs-minor-mode
2773(defun verilog-forward-sexp-function (arg)
2774 (if (< arg 0)
2775 (verilog-backward-sexp)
2776 (verilog-forward-sexp)))
2777
2778
2779(defun verilog-backward-sexp ()
2780 (let ((reg)
2781 (elsec 1)
2782 (found nil)
60618039 2783 (st (point)))
6341f357
DN
2784 (if (not (looking-at "\\<"))
2785 (forward-word -1))
2786 (cond
60618039 2787 ((verilog-skip-backward-comment-or-string))
6341f357
DN
2788 ((looking-at "\\<else\\>")
2789 (setq reg (concat
2790 verilog-end-block-re
2791 "\\|\\(\\<else\\>\\)"
60618039 2792 "\\|\\(\\<if\\>\\)"))
6341f357
DN
2793 (while (and (not found)
2794 (verilog-re-search-backward reg nil 'move))
2795 (cond
2796 ((match-end 1) ; matched verilog-end-block-re
2797 ; try to leap back to matching outward block by striding across
2798 ; indent level changing tokens then immediately
2799 ; previous line governs indentation.
2800 (verilog-leap-to-head))
2801 ((match-end 2) ; else, we're in deep
2802 (setq elsec (1+ elsec)))
2803 ((match-end 3) ; found it
2804 (setq elsec (1- elsec))
2805 (if (= 0 elsec)
2806 ;; Now previous line describes syntax
60618039 2807 (setq found 't))))))
6341f357
DN
2808 ((looking-at verilog-end-block-re)
2809 (verilog-leap-to-head))
2810 ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
2811 (cond
2812 ((match-end 1)
2813 (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
2814 ((match-end 2)
2815 (verilog-re-search-backward "\\<primitive\\>" nil 'move))
2816 ((match-end 3)
2817 (verilog-re-search-backward "\\<class\\>" nil 'move))
2818 ((match-end 4)
2819 (verilog-re-search-backward "\\<program\\>" nil 'move))
2820 ((match-end 5)
2821 (verilog-re-search-backward "\\<interface\\>" nil 'move))
2822 ((match-end 6)
2823 (verilog-re-search-backward "\\<package\\>" nil 'move))
2824 (t
2825 (goto-char st)
2826 (backward-sexp 1))))
2827 (t
2828 (goto-char st)
60618039 2829 (backward-sexp)))))
6341f357
DN
2830
2831(defun verilog-forward-sexp ()
2832 (let ((reg)
2833 (md 2)
4c5e69c6
DN
2834 (st (point))
2835 (nest 'yes))
6341f357
DN
2836 (if (not (looking-at "\\<"))
2837 (forward-word -1))
2838 (cond
2839 ((verilog-skip-forward-comment-or-string)
60618039 2840 (verilog-forward-syntactic-ws))
4c5e69c6 2841 ((looking-at verilog-beg-block-re-ordered)
6341f357 2842 (cond
4c5e69c6
DN
2843 ((match-end 1);
2844 ;; Search forward for matching end
6341f357 2845 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
4c5e69c6
DN
2846 ((match-end 2)
2847 ;; Search forward for matching endcase
2a9eb3f5
DN
2848 (setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2849 (setq md 3) ;; ender is third item in regexp
2850 )
4c5e69c6 2851 ((match-end 4)
a03c2342
WS
2852 ;; might be "disable fork" or "fork wait"
2853 (let
2854 (here)
2855 (if (looking-at verilog-fork-wait-re)
2856 (progn ;; it is a fork wait; ignore it
2857 (goto-char (match-end 0))
2858 (setq reg nil))
2859 (if (or
2860 (looking-at verilog-disable-fork-re)
2861 (and (looking-at "fork")
2862 (progn
2863 (setq here (point)) ;; sometimes a fork is just a fork
2864 (forward-word -1)
2865 (looking-at verilog-disable-fork-re))))
2866 (progn ;; it is a disable fork; ignore it
2867 (goto-char (match-end 0))
2868 (forward-word 1)
2869 (setq reg nil))
2870 (progn ;; it is a nice simple fork
2871 (goto-char here) ;; return from looking for "disable fork"
2872 ;; Search forward for matching join
2873 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))))))
4c5e69c6
DN
2874 ((match-end 6)
2875 ;; Search forward for matching endclass
6341f357 2876 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
a3a8b002 2877
4c5e69c6
DN
2878 ((match-end 7)
2879 ;; Search forward for matching endtable
2880 (setq reg "\\<endtable\\>" )
2881 (setq nest 'no))
2882 ((match-end 8)
2883 ;; Search forward for matching endspecify
2884 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
2885 ((match-end 9)
2886 ;; Search forward for matching endfunction
2887 (setq reg "\\<endfunction\\>" )
2888 (setq nest 'no))
2889 ((match-end 10)
a3a8b002
DN
2890 ;; Search forward for matching endfunction
2891 (setq reg "\\<endfunction\\>" )
2892 (setq nest 'no))
2893 ((match-end 14)
4c5e69c6
DN
2894 ;; Search forward for matching endtask
2895 (setq reg "\\<endtask\\>" )
2896 (setq nest 'no))
a3a8b002 2897 ((match-end 15)
4c5e69c6
DN
2898 ;; Search forward for matching endtask
2899 (setq reg "\\<endtask\\>" )
2900 (setq nest 'no))
a3a8b002 2901 ((match-end 19)
4c5e69c6
DN
2902 ;; Search forward for matching endgenerate
2903 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
a3a8b002 2904 ((match-end 20)
4c5e69c6
DN
2905 ;; Search forward for matching endgroup
2906 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
a3a8b002 2907 ((match-end 21)
4c5e69c6
DN
2908 ;; Search forward for matching endproperty
2909 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
a3a8b002 2910 ((match-end 25)
4c5e69c6
DN
2911 ;; Search forward for matching endsequence
2912 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
2913 (setq md 3)) ; 3 to get to endsequence in the reg above
a3a8b002 2914 ((match-end 27)
4c5e69c6
DN
2915 ;; Search forward for matching endclocking
2916 (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
2a9eb3f5
DN
2917 (if (and reg
2918 (forward-word 1))
6341f357 2919 (catch 'skip
a3a8b002 2920 (if (eq nest 'yes)
a03c2342
WS
2921 (let ((depth 1)
2922 here )
4c5e69c6
DN
2923 (while (verilog-re-search-forward reg nil 'move)
2924 (cond
a03c2342 2925 ((match-end md) ; a closer in regular expression, so we are climbing out
4c5e69c6
DN
2926 (setq depth (1- depth))
2927 (if (= 0 depth) ; we are out!
2928 (throw 'skip 1)))
a03c2342
WS
2929 ((match-end 1) ; an opener in the r-e, so we are in deeper now
2930 (setq here (point)) ; remember where we started
2931 (goto-char (match-beginning 1))
2932 (cond
2933 ((looking-at verilog-fork-wait-re)
2934 (goto-char (match-end 0))) ; false alarm
2935 ((if (or
2936 (looking-at verilog-disable-fork-re)
2937 (and (looking-at "fork")
2938 (progn
2939 (forward-word -1)
2940 (looking-at verilog-disable-fork-re))))
2941 (progn ;; it is a disable fork; another false alarm
2942 (goto-char (match-end 0)))
2943 (progn ;; it is a simple fork (or has nothing to do with fork)
2944 (goto-char here)
2945 (setq depth (1+ depth))))))))))
4c5e69c6
DN
2946 (if (verilog-re-search-forward reg nil 'move)
2947 (throw 'skip 1))))))
a3a8b002 2948
6341f357
DN
2949 ((looking-at (concat
2950 "\\(\\<\\(macro\\)?module\\>\\)\\|"
2951 "\\(\\<primitive\\>\\)\\|"
2952 "\\(\\<class\\>\\)\\|"
2953 "\\(\\<program\\>\\)\\|"
2954 "\\(\\<interface\\>\\)\\|"
2955 "\\(\\<package\\>\\)"))
2956 (cond
2957 ((match-end 1)
2958 (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
2959 ((match-end 2)
2960 (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
2961 ((match-end 3)
2962 (verilog-re-search-forward "\\<endclass\\>" nil 'move))
2963 ((match-end 4)
2964 (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
2965 ((match-end 5)
2966 (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
2967 ((match-end 6)
2968 (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
2969 (t
2970 (goto-char st)
2971 (if (= (following-char) ?\) )
2972 (forward-char 1)
2973 (forward-sexp 1)))))
2974 (t
2975 (goto-char st)
2976 (if (= (following-char) ?\) )
2977 (forward-char 1)
60618039 2978 (forward-sexp 1))))))
6341f357
DN
2979
2980(defun verilog-declaration-beg ()
2981 (verilog-re-search-backward verilog-declaration-re (bobp) t))
2982
6341f357
DN
2983;;
2984;;
2985;; Mode
2986;;
2987(defvar verilog-which-tool 1)
6edb5716 2988;;;###autoload
6341f357
DN
2989(defun verilog-mode ()
2990 "Major mode for editing Verilog code.
2991\\<verilog-mode-map>
2992See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
2993AUTOs can improve coding efficiency.
2994
2995Use \\[verilog-faq] for a pointer to frequently asked questions.
2996
2997NEWLINE, TAB indents for Verilog code.
2998Delete converts tabs to spaces as it moves back.
2999
3000Supports highlighting.
3001
3002Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
3003with no args, if that value is non-nil.
3004
3005Variables controlling indentation/edit style:
3006
3007 variable `verilog-indent-level' (default 3)
3008 Indentation of Verilog statements with respect to containing block.
3009 `verilog-indent-level-module' (default 3)
3010 Absolute indentation of Module level Verilog statements.
3011 Set to 0 to get initial and always statements lined up
3012 on the left side of your screen.
3013 `verilog-indent-level-declaration' (default 3)
3014 Indentation of declarations with respect to containing block.
3015 Set to 0 to get them list right under containing block.
3016 `verilog-indent-level-behavioral' (default 3)
3017 Indentation of first begin in a task or function block
37ea4b9b
JB
3018 Set to 0 to get such code to lined up underneath the task or
3019 function keyword.
6341f357 3020 `verilog-indent-level-directive' (default 1)
37ea4b9b 3021 Indentation of `ifdef/`endif blocks.
6341f357
DN
3022 `verilog-cexp-indent' (default 1)
3023 Indentation of Verilog statements broken across lines i.e.:
3024 if (a)
3025 begin
3026 `verilog-case-indent' (default 2)
3027 Indentation for case statements.
3028 `verilog-auto-newline' (default nil)
3029 Non-nil means automatically newline after semicolons and the punctuation
3030 mark after an end.
3031 `verilog-auto-indent-on-newline' (default t)
37ea4b9b 3032 Non-nil means automatically indent line after newline.
6341f357
DN
3033 `verilog-tab-always-indent' (default t)
3034 Non-nil means TAB in Verilog mode should always reindent the current line,
3035 regardless of where in the line point is when the TAB command is used.
3036 `verilog-indent-begin-after-if' (default t)
3037 Non-nil means to indent begin statements following a preceding
37ea4b9b 3038 if, else, while, for and repeat statements, if any. Otherwise,
6341f357
DN
3039 the begin is lined up with the preceding token. If t, you get:
3040 if (a)
3041 begin // amount of indent based on `verilog-cexp-indent'
3042 otherwise you get:
3043 if (a)
3044 begin
3045 `verilog-auto-endcomments' (default t)
3046 Non-nil means a comment /* ... */ is set after the ends which ends
3047 cases, tasks, functions and modules.
3048 The type and name of the object will be set between the braces.
3049 `verilog-minimum-comment-distance' (default 10)
3050 Minimum distance (in lines) between begin and end required before a comment
3051 will be inserted. Setting this variable to zero results in every
3052 end acquiring a comment; the default avoids too many redundant
3053 comments in tight quarters.
a3a8b002 3054 `verilog-auto-lineup' (default 'declarations)
6341f357
DN
3055 List of contexts where auto lineup of code should be done.
3056
3057Variables controlling other actions:
3058
3059 `verilog-linter' (default surelint)
3060 Unix program to call to run the lint checker. This is the default
3061 command for \\[compile-command] and \\[verilog-auto-save-compile].
3062
3063See \\[customize] for the complete list of variables.
3064
3065AUTO expansion functions are, in part:
3066
3067 \\[verilog-auto] Expand AUTO statements.
3068 \\[verilog-delete-auto] Remove the AUTOs.
3069 \\[verilog-inject-auto] Insert AUTOs for the first time.
3070
3071Some other functions are:
3072
3073 \\[verilog-complete-word] Complete word with appropriate possibilities.
3074 \\[verilog-mark-defun] Mark function.
3075 \\[verilog-beg-of-defun] Move to beginning of current function.
3076 \\[verilog-end-of-defun] Move to end of current function.
3077 \\[verilog-label-be] Label matching begin ... end, fork ... join, etc statements.
3078
3079 \\[verilog-comment-region] Put marked area in a comment.
3080 \\[verilog-uncomment-region] Uncomment an area commented with \\[verilog-comment-region].
495ab0d5 3081 \\[verilog-insert-block] Insert begin ... end.
6341f357
DN
3082 \\[verilog-star-comment] Insert /* ... */.
3083
495ab0d5 3084 \\[verilog-sk-always] Insert an always @(AS) begin .. end block.
6341f357
DN
3085 \\[verilog-sk-begin] Insert a begin .. end block.
3086 \\[verilog-sk-case] Insert a case block, prompting for details.
3087 \\[verilog-sk-for] Insert a for (...) begin .. end block, prompting for details.
3088 \\[verilog-sk-generate] Insert a generate .. endgenerate block.
495ab0d5 3089 \\[verilog-sk-header] Insert a header block at the top of file.
6341f357
DN
3090 \\[verilog-sk-initial] Insert an initial begin .. end block.
3091 \\[verilog-sk-fork] Insert a fork begin .. end .. join block.
3092 \\[verilog-sk-module] Insert a module .. (/*AUTOARG*/);.. endmodule block.
3093 \\[verilog-sk-primitive] Insert a primitive .. (.. );.. endprimitive block.
3094 \\[verilog-sk-repeat] Insert a repeat (..) begin .. end block.
3095 \\[verilog-sk-specify] Insert a specify .. endspecify block.
3096 \\[verilog-sk-task] Insert a task .. begin .. end endtask block.
3097 \\[verilog-sk-while] Insert a while (...) begin .. end block, prompting for details.
3098 \\[verilog-sk-casex] Insert a casex (...) item: begin.. end endcase block, prompting for details.
3099 \\[verilog-sk-casez] Insert a casez (...) item: begin.. end endcase block, prompting for details.
3100 \\[verilog-sk-if] Insert an if (..) begin .. end block.
3101 \\[verilog-sk-else-if] Insert an else if (..) begin .. end block.
3102 \\[verilog-sk-comment] Insert a comment block.
3103 \\[verilog-sk-assign] Insert an assign .. = ..; statement.
3104 \\[verilog-sk-function] Insert a function .. begin .. end endfunction block.
3105 \\[verilog-sk-input] Insert an input declaration, prompting for details.
3106 \\[verilog-sk-output] Insert an output declaration, prompting for details.
3107 \\[verilog-sk-state-machine] Insert a state machine definition, prompting for details.
3108 \\[verilog-sk-inout] Insert an inout declaration, prompting for details.
3109 \\[verilog-sk-wire] Insert a wire declaration, prompting for details.
3110 \\[verilog-sk-reg] Insert a register declaration, prompting for details.
3111 \\[verilog-sk-define-signal] Define signal under point as a register at the top of the module.
3112
3113All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
3114Key bindings specific to `verilog-mode-map' are:
3115
3116\\{verilog-mode-map}"
3117 (interactive)
3118 (kill-all-local-variables)
3119 (use-local-map verilog-mode-map)
3120 (setq major-mode 'verilog-mode)
3121 (setq mode-name "Verilog")
3122 (setq local-abbrev-table verilog-mode-abbrev-table)
60618039 3123 (set (make-local-variable 'beginning-of-defun-function)
6edb5716 3124 'verilog-beg-of-defun)
60618039 3125 (set (make-local-variable 'end-of-defun-function)
6edb5716 3126 'verilog-end-of-defun)
6341f357
DN
3127 (set-syntax-table verilog-mode-syntax-table)
3128 (make-local-variable 'indent-line-function)
3129 (setq indent-line-function 'verilog-indent-line-relative)
3130 (setq comment-indent-function 'verilog-comment-indent)
3131 (make-local-variable 'parse-sexp-ignore-comments)
3132 (setq parse-sexp-ignore-comments nil)
3133 (make-local-variable 'comment-start)
3134 (make-local-variable 'comment-end)
3135 (make-local-variable 'comment-multi-line)
3136 (make-local-variable 'comment-start-skip)
3137 (setq comment-start "// "
3138 comment-end ""
3139 comment-start-skip "/\\*+ *\\|// *"
3140 comment-multi-line nil)
3141 ;; Set up for compilation
3142 (setq verilog-which-tool 1)
3143 (setq verilog-tool 'verilog-linter)
3144 (verilog-set-compile-command)
3145 (when (boundp 'hack-local-variables-hook) ;; Also modify any file-local-variables
3146 (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
3147
3148 ;; Setting up menus
6edb5716 3149 (when (featurep 'xemacs)
7d55bf04
DN
3150 (easy-menu-add verilog-stmt-menu)
3151 (easy-menu-add verilog-menu)
3152 (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
60618039 3153
d63b01e1 3154 ;; Stuff for GNU Emacs
7ea26faf 3155 (set (make-local-variable 'font-lock-defaults)
7664ec44 3156 `((verilog-font-lock-keywords verilog-font-lock-keywords-1
7ea26faf
DN
3157 verilog-font-lock-keywords-2
3158 verilog-font-lock-keywords-3)
7664ec44 3159 nil nil nil
a3a8b002
DN
3160 ,(if (functionp 'syntax-ppss)
3161 ;; verilog-beg-of-defun uses syntax-ppss, and syntax-ppss uses
3162 ;; font-lock-beginning-of-syntax-function, so
3163 ;; font-lock-beginning-of-syntax-function, can't use
7664ec44 3164 ;; verilog-beg-of-defun.
a3a8b002
DN
3165 nil
3166 'verilog-beg-of-defun)))
6341f357 3167 ;;------------------------------------------------------------
a03c2342 3168 ;; now hook in 'verilog-highlight-include-files (eldo-mode.el&spice-mode.el)
6341f357 3169 ;; all buffer local:
a03c2342
WS
3170 (unless noninteractive ;; Else can't see the result, and change hooks are slow
3171 (when (featurep 'xemacs)
3172 (make-local-hook 'font-lock-mode-hook)
3173 (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
3174 (make-local-hook 'after-change-functions))
3175 (add-hook 'font-lock-mode-hook 'verilog-highlight-buffer t t)
3176 (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-highlight-buffer t t) ; not in Emacs
3177 (add-hook 'after-change-functions 'verilog-highlight-region t t))
6341f357 3178
37ea4b9b 3179 ;; Tell imenu how to handle Verilog.
6341f357
DN
3180 (make-local-variable 'imenu-generic-expression)
3181 (setq imenu-generic-expression verilog-imenu-generic-expression)
9c059794
DN
3182 ;; Tell which-func-modes that imenu knows about verilog
3183 (when (boundp 'which-function-modes)
3184 (add-to-list 'which-func-modes 'verilog-mode))
6341f357 3185 ;; hideshow support
9c059794
DN
3186 (when (boundp 'hs-special-modes-alist)
3187 (unless (assq 'verilog-mode hs-special-modes-alist)
3188 (setq hs-special-modes-alist
3189 (cons '(verilog-mode-mode "\\<begin\\>" "\\<end\\>" nil
3190 verilog-forward-sexp-function)
3191 hs-special-modes-alist))))
6341f357
DN
3192
3193 ;; Stuff for autos
3194 (add-hook 'write-contents-hooks 'verilog-auto-save-check) ; already local
6341f357
DN
3195 (run-hooks 'verilog-mode-hook))
3196\f
3197
3198;;
3199;; Electric functions
3200;;
3201(defun electric-verilog-terminate-line (&optional arg)
3202 "Terminate line and indent next line.
3203With optional ARG, remove existing end of line comments."
3204 (interactive)
3205 ;; before that see if we are in a comment
d63b01e1 3206 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
3207 (cond
3208 ((nth 7 state) ; Inside // comment
3209 (if (eolp)
3210 (progn
3211 (delete-horizontal-space)
3212 (newline))
3213 (progn
3214 (newline)
7ea26faf 3215 (insert "// ")
6341f357
DN
3216 (beginning-of-line)))
3217 (verilog-indent-line))
3218 ((nth 4 state) ; Inside any comment (hence /**/)
3219 (newline)
3220 (verilog-more-comment))
3221 ((eolp)
3222 ;; First, check if current line should be indented
3223 (if (save-excursion
3224 (delete-horizontal-space)
3225 (beginning-of-line)
3226 (skip-chars-forward " \t")
3227 (if (looking-at verilog-auto-end-comment-lines-re)
3228 (let ((indent-str (verilog-indent-line)))
3229 ;; Maybe we should set some endcomments
3230 (if verilog-auto-endcomments
3231 (verilog-set-auto-endcomments indent-str arg))
3232 (end-of-line)
3233 (delete-horizontal-space)
3234 (if arg
3235 ()
3236 (newline))
3237 nil)
3238 (progn
3239 (end-of-line)
3240 (delete-horizontal-space)
60618039 3241 't)))
6341f357
DN
3242 ;; see if we should line up assignments
3243 (progn
a3a8b002
DN
3244 (if (or (eq 'all verilog-auto-lineup)
3245 (eq 'assignments verilog-auto-lineup))
3246 (verilog-pretty-expr t "\\(<\\|:\\)?=" ))
60618039
DN
3247 (newline))
3248 (forward-line 1))
6341f357
DN
3249 ;; Indent next line
3250 (if verilog-auto-indent-on-newline
60618039 3251 (verilog-indent-line)))
6341f357 3252 (t
60618039 3253 (newline)))))
6341f357
DN
3254
3255(defun electric-verilog-terminate-and-indent ()
3256 "Insert a newline and indent for the next statement."
3257 (interactive)
3258 (electric-verilog-terminate-line 1))
3259
3260(defun electric-verilog-semi ()
3261 "Insert `;' character and reindent the line."
3262 (interactive)
a3a8b002 3263 (verilog-insert-last-command-event)
6341f357
DN
3264
3265 (if (or (verilog-in-comment-or-string-p)
3266 (verilog-in-escaped-name-p))
3267 ()
3268 (save-excursion
3269 (beginning-of-line)
3270 (verilog-forward-ws&directives)
60618039 3271 (verilog-indent-line))
6341f357
DN
3272 (if (and verilog-auto-newline
3273 (not (verilog-parenthesis-depth)))
3274 (electric-verilog-terminate-line))))
3275
3276(defun electric-verilog-semi-with-comment ()
3277 "Insert `;' character, reindent the line and indent for comment."
3278 (interactive)
3279 (insert "\;")
3280 (save-excursion
3281 (beginning-of-line)
3282 (verilog-indent-line))
3283 (indent-for-comment))
3284
3285(defun electric-verilog-colon ()
3286 "Insert `:' and do all indentations except line indent on this line."
3287 (interactive)
a3a8b002 3288 (verilog-insert-last-command-event)
6341f357
DN
3289 ;; Do nothing if within string.
3290 (if (or
3291 (verilog-within-string)
3292 (not (verilog-in-case-region-p)))
3293 ()
3294 (save-excursion
3295 (let ((p (point))
3296 (lim (progn (verilog-beg-of-statement) (point))))
3297 (goto-char p)
3298 (verilog-backward-case-item lim)
3299 (verilog-indent-line)))
3300;; (let ((verilog-tab-always-indent nil))
3301;; (verilog-indent-line))
3302 ))
3303
3304;;(defun electric-verilog-equal ()
3305;; "Insert `=', and do indentation if within block."
3306;; (interactive)
a3a8b002 3307;; (verilog-insert-last-command-event)
6341f357
DN
3308;; Could auto line up expressions, but not yet
3309;; (if (eq (car (verilog-calculate-indent)) 'block)
3310;; (let ((verilog-tab-always-indent nil))
3311;; (verilog-indent-command)))
3312;; )
3313
3314(defun electric-verilog-tick ()
3315 "Insert back-tick, and indent to column 0 if this is a CPP directive."
3316 (interactive)
a3a8b002 3317 (verilog-insert-last-command-event)
6341f357 3318 (save-excursion
a3a8b002
DN
3319 (if (verilog-in-directive-p)
3320 (verilog-indent-line))))
6341f357
DN
3321
3322(defun electric-verilog-tab ()
3323 "Function called when TAB is pressed in Verilog mode."
3324 (interactive)
3325 ;; If verilog-tab-always-indent, indent the beginning of the line.
7cb1c4d7
DN
3326 (cond
3327 ;; The region is active, indent it.
3328 ((and (region-active-p)
3329 (not (eq (region-beginning) (region-end))))
3330 (indent-region (region-beginning) (region-end) nil))
3331 ((or verilog-tab-always-indent
3332 (save-excursion
3333 (skip-chars-backward " \t")
3334 (bolp)))
3335 (let* ((oldpnt (point))
3336 (boi-point
3337 (save-excursion
3338 (beginning-of-line)
3339 (skip-chars-forward " \t")
3340 (verilog-indent-line)
3341 (back-to-indentation)
3342 (point))))
3343 (if (< (point) boi-point)
3344 (back-to-indentation)
3345 (cond ((not verilog-tab-to-comment))
3346 ((not (eolp))
3347 (end-of-line))
3348 (t
3349 (indent-for-comment)
3350 (when (and (eolp) (= oldpnt (point)))
6341f357 3351 ; kill existing comment
7cb1c4d7
DN
3352 (beginning-of-line)
3353 (re-search-forward comment-start-skip oldpnt 'move)
3354 (goto-char (match-beginning 0))
3355 (skip-chars-backward " \t")
3356 (kill-region (point) oldpnt)))))))
3357 (t (progn (insert "\t")))))
a3a8b002 3358
6341f357
DN
3359\f
3360
3361;;
3362;; Interactive functions
3363;;
3364
3365(defun verilog-indent-buffer ()
3366 "Indent-region the entire buffer as Verilog code.
3367To call this from the command line, see \\[verilog-batch-indent]."
3368 (interactive)
3369 (verilog-mode)
3370 (indent-region (point-min) (point-max) nil))
3371
3372(defun verilog-insert-block ()
3373 "Insert Verilog begin ... end; block in the code with right indentation."
3374 (interactive)
3375 (verilog-indent-line)
3376 (insert "begin")
3377 (electric-verilog-terminate-line)
3378 (save-excursion
3379 (electric-verilog-terminate-line)
3380 (insert "end")
3381 (beginning-of-line)
3382 (verilog-indent-line)))
3383
3384(defun verilog-star-comment ()
3385 "Insert Verilog star comment at point."
3386 (interactive)
3387 (verilog-indent-line)
3388 (insert "/*")
3389 (save-excursion
3390 (newline)
3391 (insert " */"))
3392 (newline)
3393 (insert " * "))
3394
7ea26faf 3395(defun verilog-insert-1 (fmt max)
60618039 3396 "Use format string FMT to insert integers 0 to MAX - 1.
7ea26faf
DN
3397Inserts one integer per line, at the current column. Stops early
3398if it reaches the end of the buffer."
3399 (let ((col (current-column))
3400 (n 0))
3401 (save-excursion
3402 (while (< n max)
3403 (insert (format fmt n))
3404 (forward-line 1)
3405 ;; Note that this function does not bother to check for lines
3406 ;; shorter than col.
3407 (if (eobp)
3408 (setq n max)
3409 (setq n (1+ n))
3410 (move-to-column col))))))
3411
3412(defun verilog-insert-indices (max)
3413 "Insert a set of indices into a rectangle.
3414The upper left corner is defined by point. Indices begin with 0
3415and extend to the MAX - 1. If no prefix arg is given, the user
3416is prompted for a value. The indices are surrounded by square
3417brackets \[]. For example, the following code with the point
3418located after the first 'a' gives:
6341f357
DN
3419
3420 a = b a[ 0] = b
3421 a = b a[ 1] = b
3422 a = b a[ 2] = b
3423 a = b a[ 3] = b
3424 a = b ==> insert-indices ==> a[ 4] = b
3425 a = b a[ 5] = b
3426 a = b a[ 6] = b
3427 a = b a[ 7] = b
3428 a = b a[ 8] = b"
3429
60618039 3430 (interactive "NMAX: ")
7ea26faf 3431 (verilog-insert-1 "[%3d]" max))
6341f357 3432
7ea26faf 3433(defun verilog-generate-numbers (max)
6341f357
DN
3434 "Insert a set of generated numbers into a rectangle.
3435The upper left corner is defined by point. The numbers are padded to three
3436digits, starting with 000 and extending to (MAX - 1). If no prefix argument
7ea26faf 3437is supplied, then the user is prompted for the MAX number. Consider the
6341f357
DN
3438following code fragment:
3439
7ea26faf
DN
3440 buf buf buf buf000
3441 buf buf buf buf001
3442 buf buf buf buf002
3443 buf buf buf buf003
3444 buf buf ==> generate-numbers ==> buf buf004
3445 buf buf buf buf005
3446 buf buf buf buf006
3447 buf buf buf buf007
3448 buf buf buf buf008"
3449
60618039 3450 (interactive "NMAX: ")
7ea26faf 3451 (verilog-insert-1 "%3.3d" max))
6341f357
DN
3452
3453(defun verilog-mark-defun ()
37ea4b9b 3454 "Mark the current Verilog function (or procedure).
6341f357
DN
3455This puts the mark at the end, and point at the beginning."
3456 (interactive)
7d55bf04
DN
3457 (if (featurep 'xemacs)
3458 (progn
3459 (push-mark (point))
3460 (verilog-end-of-defun)
3461 (push-mark (point))
3462 (verilog-beg-of-defun)
3463 (if (fboundp 'zmacs-activate-region)
3464 (zmacs-activate-region)))
3465 (mark-defun)))
6341f357
DN
3466
3467(defun verilog-comment-region (start end)
3468 ; checkdoc-params: (start end)
3469 "Put the region into a Verilog comment.
3470The comments that are in this area are \"deformed\":
3471`*)' becomes `!(*' and `}' becomes `!{'.
3472These deformed comments are returned to normal if you use
3473\\[verilog-uncomment-region] to undo the commenting.
3474
3475The commented area starts with `verilog-exclude-str-start', and ends with
3476`verilog-exclude-str-end'. But if you change these variables,
3477\\[verilog-uncomment-region] won't recognize the comments."
3478 (interactive "r")
3479 (save-excursion
3480 ;; Insert start and endcomments
3481 (goto-char end)
3482 (if (and (save-excursion (skip-chars-forward " \t") (eolp))
3483 (not (save-excursion (skip-chars-backward " \t") (bolp))))
3484 (forward-line 1)
3485 (beginning-of-line))
3486 (insert verilog-exclude-str-end)
3487 (setq end (point))
3488 (newline)
3489 (goto-char start)
3490 (beginning-of-line)
3491 (insert verilog-exclude-str-start)
3492 (newline)
3493 ;; Replace end-comments within commented area
3494 (goto-char end)
3495 (save-excursion
3496 (while (re-search-backward "\\*/" start t)
3497 (replace-match "*-/" t t)))
3498 (save-excursion
3499 (let ((s+1 (1+ start)))
3500 (while (re-search-backward "/\\*" s+1 t)
60618039 3501 (replace-match "/-*" t t))))))
6341f357
DN
3502
3503(defun verilog-uncomment-region ()
3504 "Uncomment a commented area; change deformed comments back to normal.
3505This command does nothing if the pointer is not in a commented
3506area. See also `verilog-comment-region'."
3507 (interactive)
3508 (save-excursion
3509 (let ((start (point))
3510 (end (point)))
3511 ;; Find the boundaries of the comment
3512 (save-excursion
3513 (setq start (progn (search-backward verilog-exclude-str-start nil t)
3514 (point)))
3515 (setq end (progn (search-forward verilog-exclude-str-end nil t)
3516 (point))))
3517 ;; Check if we're really inside a comment
3518 (if (or (equal start (point)) (<= end (point)))
3519 (message "Not standing within commented area.")
3520 (progn
3521 ;; Remove endcomment
3522 (goto-char end)
3523 (beginning-of-line)
3524 (let ((pos (point)))
3525 (end-of-line)
3526 (delete-region pos (1+ (point))))
3527 ;; Change comments back to normal
3528 (save-excursion
3529 (while (re-search-backward "\\*-/" start t)
3530 (replace-match "*/" t t)))
3531 (save-excursion
3532 (while (re-search-backward "/-\\*" start t)
3533 (replace-match "/*" t t)))
3534 ;; Remove start comment
3535 (goto-char start)
3536 (beginning-of-line)
3537 (let ((pos (point)))
3538 (end-of-line)
3539 (delete-region pos (1+ (point)))))))))
3540
3541(defun verilog-beg-of-defun ()
3542 "Move backward to the beginning of the current function or procedure."
3543 (interactive)
3544 (verilog-re-search-backward verilog-defun-re nil 'move))
3545
3546(defun verilog-end-of-defun ()
3547 "Move forward to the end of the current function or procedure."
3548 (interactive)
3549 (verilog-re-search-forward verilog-end-defun-re nil 'move))
3550
3551(defun verilog-get-beg-of-defun (&optional warn)
3552 (save-excursion
3553 (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
3554 (point))
3555 (t
3556 (error "%s: Can't find module beginning" (verilog-point-text))
3557 (point-max)))))
3558(defun verilog-get-end-of-defun (&optional warn)
3559 (save-excursion
3560 (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
3561 (point))
3562 (t
3563 (error "%s: Can't find endmodule" (verilog-point-text))
3564 (point-max)))))
3565
3566(defun verilog-label-be (&optional arg)
3567 "Label matching begin ... end, fork ... join and case ... endcase statements.
3568With ARG, first kill any existing labels."
3569 (interactive)
3570 (let ((cnt 0)
3571 (oldpos (point))
3572 (b (progn
3573 (verilog-beg-of-defun)
3574 (point-marker)))
3575 (e (progn
3576 (verilog-end-of-defun)
60618039 3577 (point-marker))))
6341f357
DN
3578 (goto-char (marker-position b))
3579 (if (> (- e b) 200)
3580 (message "Relabeling module..."))
3581 (while (and
3582 (> (marker-position e) (point))
3583 (verilog-re-search-forward
3584 (concat
3585 "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
3586 "\\|\\(`endif\\)\\|\\(`else\\)")
3587 nil 'move))
3588 (goto-char (match-beginning 0))
3589 (let ((indent-str (verilog-indent-line)))
3590 (verilog-set-auto-endcomments indent-str 't)
3591 (end-of-line)
60618039 3592 (delete-horizontal-space))
6341f357
DN
3593 (setq cnt (1+ cnt))
3594 (if (= 9 (% cnt 10))
60618039 3595 (message "%d..." cnt)))
6341f357
DN
3596 (goto-char oldpos)
3597 (if (or
3598 (> (- e b) 200)
3599 (> cnt 20))
60618039 3600 (message "%d lines auto commented" cnt))))
6341f357
DN
3601
3602(defun verilog-beg-of-statement ()
3603 "Move backward to beginning of statement."
3604 (interactive)
3605 ;; Move back token by token until we see the end
3606 ;; of some ealier line.
a03c2342
WS
3607 (let (h)
3608 (while
3609 ;; If the current point does not begin a new
3610 ;; statement, as in the character ahead of us is a ';', or SOF
3611 ;; or the string after us unambiguously starts a statement,
3612 ;; or the token before us unambiguously ends a statement,
3613 ;; then move back a token and test again.
3614 (not (or
3615 ;; stop if beginning of buffer
3616 (bolp)
3617 ;; stop if we find a ;
3618 (= (preceding-char) ?\;)
3619 ;; stop if we see a named coverpoint
3620 (looking-at "\\w+\\W*:\\W*\\(coverpoint\\|cross\\|constraint\\)")
3621 ;; keep going if we are in the middle of a word
3622 (not (or (looking-at "\\<") (forward-word -1)))
3623 ;; stop if we see an assertion (perhaps labled)
3624 (and
3625 (looking-at "\\(\\<\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(\\<assert\\>\\)")
3626 (progn
3627 (setq h (point))
3628 (save-excursion
3629 (verilog-backward-token)
3630 (if (looking-at verilog-label-re)
3631 (setq h (point))))
3632 (goto-char h)))
3633 ;; stop if we see a complete reg, perhaps an extended one
3634 (and
3635 (looking-at verilog-complete-reg)
3636 (let* ((p (point)))
3637 (while (and (looking-at verilog-extended-complete-re)
3638 (progn (setq p (point))
3639 (verilog-backward-token)
3640 (/= p (point)))))
3641 (goto-char p)))
3642 ;; stop if we see a complete reg (previous found extended ones)
3643 (looking-at verilog-basic-complete-re)
3644 ;; stop if previous token is an ender
3645 (save-excursion
3646 (verilog-backward-token)
3647 (or
3648 (looking-at verilog-end-block-re)
3649 (looking-at verilog-preprocessor-re))))) ;; end of test
6341f357
DN
3650 (verilog-backward-syntactic-ws)
3651 (verilog-backward-token))
a03c2342
WS
3652 ;; Now point is where the previous line ended.
3653 (verilog-forward-syntactic-ws)))
6341f357
DN
3654
3655(defun verilog-beg-of-statement-1 ()
3656 "Move backward to beginning of statement."
3657 (interactive)
a3a8b002
DN
3658 (if (verilog-in-comment-p)
3659 (verilog-backward-syntactic-ws))
6341f357 3660 (let ((pt (point)))
a3a8b002
DN
3661 (catch 'done
3662 (while (not (looking-at verilog-complete-reg))
3663 (setq pt (point))
3664 (verilog-backward-syntactic-ws)
3665 (if (or (bolp)
a03c2342
WS
3666 (= (preceding-char) ?\;)
3667 (save-excursion
3668 (verilog-backward-token)
3669 (looking-at verilog-ends-re)))
a3a8b002
DN
3670 (progn
3671 (goto-char pt)
3672 (throw 'done t))
3673 (verilog-backward-token))))
3674 (verilog-forward-syntactic-ws)))
3675;
3676; (while (and
3677; (not (looking-at verilog-complete-reg))
3678; (not (bolp))
3679; (not (= (preceding-char) ?\;)))
3680; (verilog-backward-token)
3681; (verilog-backward-syntactic-ws)
3682; (setq pt (point)))
3683; (goto-char pt)
3684; ;(verilog-forward-syntactic-ws)
6341f357
DN
3685
3686(defun verilog-end-of-statement ()
3687 "Move forward to end of current statement."
3688 (interactive)
3689 (let ((nest 0) pos)
a3a8b002
DN
3690 (cond
3691 ((verilog-in-directive-p)
3692 (forward-line 1)
3693 (backward-char 1))
3694
3695 ((looking-at verilog-beg-block-re)
3696 (verilog-forward-sexp))
3697
3698 ((equal (char-after) ?\})
3699 (forward-char))
3700
3701 ;; Skip to end of statement
3702 ((condition-case nil
3703 (setq pos
3704 (catch 'found
3705 (while t
3706 (forward-sexp 1)
3707 (verilog-skip-forward-comment-or-string)
3708 (if (eolp)
3709 (forward-line 1))
3710 (cond ((looking-at "[ \t]*;")
3711 (skip-chars-forward "^;")
3712 (forward-char 1)
3713 (throw 'found (point)))
3714 ((save-excursion
3715 (forward-sexp -1)
3716 (looking-at verilog-beg-block-re))
3717 (goto-char (match-beginning 0))
3718 (throw 'found nil))
3719 ((looking-at "[ \t]*)")
3720 (throw 'found (point)))
3721 ((eobp)
3722 (throw 'found (point)))
3723 )))
3724
3725 )
3726 (error nil))
3727 (if (not pos)
3728 ;; Skip a whole block
3729 (catch 'found
3730 (while t
3731 (verilog-re-search-forward verilog-end-statement-re nil 'move)
3732 (setq nest (if (match-end 1)
3733 (1+ nest)
3734 (1- nest)))
3735 (cond ((eobp)
3736 (throw 'found (point)))
3737 ((= 0 nest)
3738 (throw 'found (verilog-end-of-statement))))))
3739 pos)))))
6341f357
DN
3740
3741(defun verilog-in-case-region-p ()
37ea4b9b
JB
3742 "Return true if in a case region.
3743More specifically, point @ in the line foo : @ begin"
6341f357
DN
3744 (interactive)
3745 (save-excursion
3746 (if (and
3747 (progn (verilog-forward-syntactic-ws)
3748 (looking-at "\\<begin\\>"))
3749 (progn (verilog-backward-syntactic-ws)
3750 (= (preceding-char) ?\:)))
3751 (catch 'found
3752 (let ((nest 1))
3753 (while t
3754 (verilog-re-search-backward
3755 (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
3756 "\\(\\<endcase\\>\\)\\>")
3757 nil 'move)
3758 (cond
3759 ((match-end 3)
3760 (setq nest (1+ nest)))
3761 ((match-end 2)
3762 (if (= nest 1)
3763 (throw 'found 1))
3764 (setq nest (1- nest)))
3765 (t
60618039 3766 (throw 'found (= nest 0)))))))
6341f357 3767 nil)))
a03c2342
WS
3768(defun verilog-backward-up-list (arg)
3769 "Like backward-up-list, but deal with comments."
3770 (let (saved-psic parse-sexp-ignore-comments)
3771 (setq parse-sexp-ignore-comments 1)
3772 (backward-up-list arg)
3773 (setq parse-sexp-ignore-comments saved-psic)
3774 ))
3775
6341f357 3776(defun verilog-in-struct-region-p ()
37ea4b9b
JB
3777 "Return true if in a struct region.
3778More specifically, in a list after a struct|union keyword."
6341f357
DN
3779 (interactive)
3780 (save-excursion
d63b01e1 3781 (let* ((state (verilog-syntax-ppss))
6341f357
DN
3782 (depth (nth 0 state)))
3783 (if depth
a03c2342 3784 (progn (verilog-backward-up-list depth)
6341f357 3785 (verilog-beg-of-statement)
60618039 3786 (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>"))))))
6341f357
DN
3787
3788(defun verilog-in-generate-region-p ()
37ea4b9b
JB
3789 "Return true if in a generate region.
3790More specifically, after a generate and before an endgenerate."
6341f357 3791 (interactive)
a3a8b002 3792 (let ((nest 1))
6341f357 3793 (save-excursion
a3a8b002
DN
3794 (catch 'done
3795 (while (and
3796 (/= nest 0)
3797 (verilog-re-search-backward
3798 "\\<\\(module\\)\\|\\(generate\\)\\|\\(endgenerate\\)\\>" nil 'move)
3799 (cond
3800 ((match-end 1) ; module - we have crawled out
3801 (throw 'done 1))
3802 ((match-end 2) ; generate
3803 (setq nest (1- nest)))
3804 ((match-end 3) ; endgenerate
3805 (setq nest (1+ nest))))))))
6341f357
DN
3806 (= nest 0) )) ; return nest
3807
3808(defun verilog-in-fork-region-p ()
3809 "Return true if between a fork and join."
3810 (interactive)
3811 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
60618039 3812 (nest 1))
6341f357
DN
3813 (save-excursion
3814 (while (and
3815 (/= nest 0)
3816 (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
3817 (cond
3818 ((match-end 1) ; fork
3819 (setq nest (1- nest)))
3820 ((match-end 2) ; join
60618039 3821 (setq nest (1+ nest)))))))
6341f357
DN
3822 (= nest 0) )) ; return nest
3823
3824(defun verilog-backward-case-item (lim)
3825 "Skip backward to nearest enclosing case item.
3826Limit search to point LIM."
3827 (interactive)
3828 (let ((str 'nil)
3829 (lim1
3830 (progn
3831 (save-excursion
3832 (verilog-re-search-backward verilog-endcomment-reason-re
3833 lim 'move)
3834 (point)))))
3835 ;; Try to find the real :
3836 (if (save-excursion (search-backward ":" lim1 t))
3837 (let ((colon 0)
3838 b e )
3839 (while
3840 (and
3841 (< colon 1)
3842 (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
3843 lim1 'move))
3844 (cond
3845 ((match-end 1) ;; [
3846 (setq colon (1+ colon))
3847 (if (>= colon 0)
3848 (error "%s: unbalanced [" (verilog-point-text))))
3849 ((match-end 2) ;; ]
3850 (setq colon (1- colon)))
3851
3852 ((match-end 3) ;; :
60618039 3853 (setq colon (1+ colon)))))
6341f357
DN
3854 ;; Skip back to beginning of case item
3855 (skip-chars-backward "\t ")
3856 (verilog-skip-backward-comment-or-string)
3857 (setq e (point))
3858 (setq b
3859 (progn
3860 (if
3861 (verilog-re-search-backward
3862 "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
3863 (progn
3864 (cond
3865 ((match-end 1)
3866 (goto-char (match-end 1))
3867 (verilog-forward-ws&directives)
3868 (if (looking-at "(")
3869 (progn
3870 (forward-sexp)
3871 (verilog-forward-ws&directives)))
3872 (point))
3873 (t
3874 (goto-char (match-end 0))
3875 (verilog-forward-ws&directives)
60618039
DN
3876 (point))))
3877 (error "Malformed case item"))))
6341f357
DN
3878 (setq str (buffer-substring b e))
3879 (if
3880 (setq e
3881 (string-match
3882 "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3883 (setq str (concat (substring str 0 e) "...")))
3884 str)
3885 'nil)))
3886\f
3887
3888;;
3889;; Other functions
3890;;
3891
6ca0ff73 3892(defun verilog-kill-existing-comment ()
6341f357
DN
3893 "Kill auto comment on this line."
3894 (save-excursion
3895 (let* (
3896 (e (progn
3897 (end-of-line)
3898 (point)))
3899 (b (progn
3900 (beginning-of-line)
3901 (search-forward "//" e t))))
3902 (if b
3903 (delete-region (- b 2) e)))))
3904
3905(defconst verilog-directive-nest-re
3906 (concat "\\(`else\\>\\)\\|"
3907 "\\(`endif\\>\\)\\|"
3908 "\\(`if\\>\\)\\|"
3909 "\\(`ifdef\\>\\)\\|"
a03c2342
WS
3910 "\\(`ifndef\\>\\)\\|"
3911 "\\(`elsif\\>\\)"))
6341f357
DN
3912(defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
3913 "Add ending comment with given INDENT-STR.
3914With KILL-EXISTING-COMMENT, remove what was there before.
3915Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
3916Insert `// case expr ' if this line ends a case block.
3917Insert `// ifdef FOO ' if this line ends code conditional on FOO.
37ea4b9b
JB
3918Insert `// NAME ' if this line ends a function, task, module,
3919primitive or interface named NAME."
6341f357
DN
3920 (save-excursion
3921 (cond
3922 (; Comment close preprocessor directives
3923 (and
3924 (looking-at "\\(`endif\\)\\|\\(`else\\)")
3925 (or kill-existing-comment
3926 (not (save-excursion
3927 (end-of-line)
3928 (search-backward "//" (verilog-get-beg-of-line) t)))))
3929 (let ((nest 1) b e
3930 m
60618039 3931 (else (if (match-end 2) "!" " ")))
6341f357
DN
3932 (end-of-line)
3933 (if kill-existing-comment
6ca0ff73 3934 (verilog-kill-existing-comment))
6341f357
DN
3935 (delete-horizontal-space)
3936 (save-excursion
3937 (backward-sexp 1)
3938 (while (and (/= nest 0)
3939 (verilog-re-search-backward verilog-directive-nest-re nil 'move))
3940 (cond
3941 ((match-end 1) ; `else
3942 (if (= nest 1)
3943 (setq else "!")))
3944 ((match-end 2) ; `endif
3945 (setq nest (1+ nest)))
3946 ((match-end 3) ; `if
3947 (setq nest (1- nest)))
3948 ((match-end 4) ; `ifdef
3949 (setq nest (1- nest)))
3950 ((match-end 5) ; `ifndef
a03c2342
WS
3951 (setq nest (1- nest)))
3952 ((match-end 6) ; `elsif
3953 (if (= nest 1)
3954 (progn
3955 (setq else "!")
3956 (setq nest 0))))))
6341f357
DN
3957 (if (match-end 0)
3958 (setq
3959 m (buffer-substring
3960 (match-beginning 0)
3961 (match-end 0))
3962 b (progn
3963 (skip-chars-forward "^ \t")
3964 (verilog-forward-syntactic-ws)
3965 (point))
3966 e (progn
3967 (skip-chars-forward "a-zA-Z0-9_")
60618039 3968 (point)))))
6341f357
DN
3969 (if b
3970 (if (> (count-lines (point) b) verilog-minimum-comment-distance)
3971 (insert (concat " // " else m " " (buffer-substring b e))))
3972 (progn
a03c2342 3973 (insert " // unmatched `else, `elsif or `endif")
60618039 3974 (ding 't)))))
6341f357
DN
3975
3976 (; Comment close case/class/function/task/module and named block
3977 (and (looking-at "\\<end")
3978 (or kill-existing-comment
3979 (not (save-excursion
3980 (end-of-line)
3981 (search-backward "//" (verilog-get-beg-of-line) t)))))
3982 (let ((type (car indent-str)))
3983 (unless (eq type 'declaration)
3984 (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
3985 (if (looking-at verilog-end-block-ordered-re)
3986 (cond
3987 (;- This is a case block; search back for the start of this case
3988 (match-end 1) ;; of verilog-end-block-ordered-re
3989
3990 (let ((err 't)
3991 (str "UNMATCHED!!"))
3992 (save-excursion
3993 (verilog-leap-to-head)
3994 (cond
3995 ((looking-at "\\<randcase\\>")
3996 (setq str "randcase")
7ea26faf 3997 (setq err nil))
a3a8b002
DN
3998 ((looking-at "\\(\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?\\)")
3999 (goto-char (match-end 0))
4000 (setq str (concat (match-string 0) " " (verilog-get-expr)))
4001 (setq err nil))
4002 ))
6341f357
DN
4003 (end-of-line)
4004 (if kill-existing-comment
6ca0ff73 4005 (verilog-kill-existing-comment))
6341f357
DN
4006 (delete-horizontal-space)
4007 (insert (concat " // " str ))
7ea26faf 4008 (if err (ding 't))))
6341f357
DN
4009
4010 (;- This is a begin..end block
4011 (match-end 2) ;; of verilog-end-block-ordered-re
4012 (let ((str " // UNMATCHED !!")
4013 (err 't)
4014 (here (point))
4015 there
60618039 4016 cntx)
6341f357
DN
4017 (save-excursion
4018 (verilog-leap-to-head)
4019 (setq there (point))
4020 (if (not (match-end 0))
4021 (progn
4022 (goto-char here)
4023 (end-of-line)
4024 (if kill-existing-comment
6ca0ff73 4025 (verilog-kill-existing-comment))
6341f357
DN
4026 (delete-horizontal-space)
4027 (insert str)
60618039 4028 (ding 't))
6341f357
DN
4029 (let ((lim
4030 (save-excursion (verilog-beg-of-defun) (point)))
60618039 4031 (here (point)))
6341f357
DN
4032 (cond
4033 (;-- handle named block differently
4034 (looking-at verilog-named-block-re)
4035 (search-forward ":")
4036 (setq there (point))
4037 (setq str (verilog-get-expr))
4038 (setq err nil)
4039 (setq str (concat " // block: " str )))
4040
4041 ((verilog-in-case-region-p) ;-- handle case item differently
4042 (goto-char here)
4043 (setq str (verilog-backward-case-item lim))
4044 (setq there (point))
4045 (setq err nil)
4046 (setq str (concat " // case: " str )))
4047
4048 (;- try to find "reason" for this begin
4049 (cond
4050 (;
4051 (eq here (progn
a03c2342
WS
4052 ;; (verilog-backward-token)
4053 (verilog-beg-of-statement)
6341f357
DN
4054 (point)))
4055 (setq err nil)
4056 (setq str ""))
4057 ((looking-at verilog-endcomment-reason-re)
4058 (setq there (match-end 0))
a3a8b002 4059 (setq cntx (concat (match-string 0) " "))
6341f357
DN
4060 (cond
4061 (;- begin
a3a8b002 4062 (match-end 1)
6341f357
DN
4063 (setq err nil)
4064 (save-excursion
4065 (if (and (verilog-continued-line)
4066 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
4067 (progn
4068 (goto-char (match-end 0))
4069 (setq there (point))
4070 (setq str
a3a8b002 4071 (concat " // " (match-string 0) " " (verilog-get-expr))))
6341f357
DN
4072 (setq str ""))))
4073
4074 (;- else
a3a8b002 4075 (match-end 2)
6341f357 4076 (let ((nest 0)
a03c2342 4077 ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
6341f357
DN
4078 (catch 'skip
4079 (while (verilog-re-search-backward reg nil 'move)
4080 (cond
4081 ((match-end 1) ; begin
4082 (setq nest (1- nest)))
4083 ((match-end 2) ; end
4084 (setq nest (1+ nest)))
4085 ((match-end 3)
4086 (if (= 0 nest)
4087 (progn
4088 (goto-char (match-end 0))
4089 (setq there (point))
4090 (setq err nil)
4091 (setq str (verilog-get-expr))
4092 (setq str (concat " // else: !if" str ))
a03c2342
WS
4093 (throw 'skip 1))))
4094 ((match-end 4)
4095 (if (= 0 nest)
4096 (progn
4097 (goto-char (match-end 0))
4098 (setq there (point))
4099 (setq err nil)
4100 (setq str (verilog-get-expr))
4101 (setq str (concat " // else: !assert " str ))
60618039 4102 (throw 'skip 1)))))))))
6341f357 4103 (;- end else
a3a8b002 4104 (match-end 3)
6341f357
DN
4105 (goto-char there)
4106 (let ((nest 0)
a03c2342 4107 (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
6341f357
DN
4108 (catch 'skip
4109 (while (verilog-re-search-backward reg nil 'move)
4110 (cond
4111 ((match-end 1) ; begin
4112 (setq nest (1- nest)))
4113 ((match-end 2) ; end
4114 (setq nest (1+ nest)))
4115 ((match-end 3)
4116 (if (= 0 nest)
4117 (progn
4118 (goto-char (match-end 0))
4119 (setq there (point))
4120 (setq err nil)
4121 (setq str (verilog-get-expr))
4122 (setq str (concat " // else: !if" str ))
a03c2342
WS
4123 (throw 'skip 1))))
4124 ((match-end 4)
4125 (if (= 0 nest)
4126 (progn
4127 (goto-char (match-end 0))
4128 (setq there (point))
4129 (setq err nil)
4130 (setq str (verilog-get-expr))
4131 (setq str (concat " // else: !assert " str ))
60618039 4132 (throw 'skip 1)))))))))
a03c2342 4133
a3a8b002
DN
4134 (; always_comb, always_ff, always_latch
4135 (or (match-end 4) (match-end 5) (match-end 6))
4136 (goto-char (match-end 0))
4137 (setq there (point))
4138 (setq err nil)
4139 (setq str (concat " // " cntx )))
6341f357
DN
4140
4141 (;- task/function/initial et cetera
4142 t
4143 (match-end 0)
4144 (goto-char (match-end 0))
4145 (setq there (point))
4146 (setq err nil)
a3a8b002 4147 (setq str (concat " // " cntx (verilog-get-expr))))
6341f357
DN
4148
4149 (;-- otherwise...
60618039 4150 (setq str " // auto-endcomment confused "))))
6341f357
DN
4151
4152 ((and
4153 (verilog-in-case-region-p) ;-- handle case item differently
4154 (progn
4155 (setq there (point))
4156 (goto-char here)
4157 (setq str (verilog-backward-case-item lim))))
4158 (setq err nil)
4159 (setq str (concat " // case: " str )))
4160
4161 ((verilog-in-fork-region-p)
4162 (setq err nil)
4163 (setq str " // fork branch" ))
4164
4165 ((looking-at "\\<end\\>")
4166 ;; HERE
4167 (forward-word 1)
4168 (verilog-forward-syntactic-ws)
4169 (setq err nil)
4170 (setq str (verilog-get-expr))
4171 (setq str (concat " // " cntx str )))
4172
4173 ))))
4174 (goto-char here)
4175 (end-of-line)
4176 (if kill-existing-comment
6ca0ff73 4177 (verilog-kill-existing-comment))
6341f357
DN
4178 (delete-horizontal-space)
4179 (if (or err
4180 (> (count-lines here there) verilog-minimum-comment-distance))
4181 (insert str))
4182 (if err (ding 't))
4183 ))))
4184 (;- this is endclass, which can be nested
4185 (match-end 11) ;; of verilog-end-block-ordered-re
4186 ;;(goto-char there)
4187 (let ((nest 0)
60618039
DN
4188 (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
4189 string)
6341f357
DN
4190 (save-excursion
4191 (catch 'skip
4192 (while (verilog-re-search-backward reg nil 'move)
4193 (cond
4194 ((match-end 3) ; endclass
4195 (ding 't)
4196 (setq string "unmatched endclass")
4197 (throw 'skip 1))
4198
4199 ((match-end 2) ; endclass
4200 (setq nest (1+ nest)))
4201
4202 ((match-end 1) ; class
4203 (setq nest (1- nest))
4204 (if (< nest 0)
4205 (progn
4206 (goto-char (match-end 0))
4207 (let (b e)
4208 (setq b (progn
4209 (skip-chars-forward "^ \t")
4210 (verilog-forward-ws&directives)
4211 (point))
4212 e (progn
4213 (skip-chars-forward "a-zA-Z0-9_")
4214 (point)))
4215 (setq string (buffer-substring b e)))
4216 (throw 'skip 1))))
4217 ))))
4218 (end-of-line)
60618039 4219 (insert (concat " // " string ))))
6341f357
DN
4220
4221 (;- this is end{function,generate,task,module,primitive,table,generate}
4222 ;- which can not be nested.
4223 t
9c059794 4224 (let (string reg (name-re nil))
6341f357
DN
4225 (end-of-line)
4226 (if kill-existing-comment
4227 (save-match-data
6ca0ff73 4228 (verilog-kill-existing-comment)))
6341f357
DN
4229 (delete-horizontal-space)
4230 (backward-sexp)
4231 (cond
4232 ((match-end 5) ;; of verilog-end-block-ordered-re
4233 (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
9c059794
DN
4234 (setq name-re "\\w+\\s-*(")
4235 )
6341f357
DN
4236 ((match-end 6) ;; of verilog-end-block-ordered-re
4237 (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
4238 ((match-end 7) ;; of verilog-end-block-ordered-re
4239 (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
4240 ((match-end 8) ;; of verilog-end-block-ordered-re
4241 (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4242 ((match-end 9) ;; of verilog-end-block-ordered-re
4243 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
4244 ((match-end 10) ;; of verilog-end-block-ordered-re
4245 (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4246 ((match-end 11) ;; of verilog-end-block-ordered-re
4247 (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4248 ((match-end 12) ;; of verilog-end-block-ordered-re
4249 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4250 ((match-end 13) ;; of verilog-end-block-ordered-re
4251 (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4252 ((match-end 14) ;; of verilog-end-block-ordered-re
4253 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4254 ((match-end 15) ;; of verilog-end-block-ordered-re
4255 (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
4256
60618039 4257 (t (error "Problem in verilog-set-auto-endcomments")))
6341f357
DN
4258 (let (b e)
4259 (save-excursion
4260 (verilog-re-search-backward reg nil 'move)
4261 (cond
4262 ((match-end 1)
4263 (setq b (progn
4264 (skip-chars-forward "^ \t")
4265 (verilog-forward-ws&directives)
a03c2342
WS
4266 (if (looking-at "static\\|automatic")
4267 (progn
4268 (goto-char (match-end 0))
4269 (verilog-forward-ws&directives)))
9c059794 4270 (if (and name-re (verilog-re-search-forward name-re nil 'move))
6341f357 4271 (progn
9c059794 4272 (goto-char (match-beginning 0))
60618039 4273 (verilog-forward-ws&directives)))
6341f357
DN
4274 (point))
4275 e (progn
4276 (skip-chars-forward "a-zA-Z0-9_")
4277 (point)))
4278 (setq string (buffer-substring b e)))
4279 (t
4280 (ding 't)
4281 (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
4282 (end-of-line)
4283 (insert (concat " // " string )))
4284 ))))))))))
4285
4286(defun verilog-get-expr()
37ea4b9b 4287 "Grab expression at point, e.g, case ( a | b & (c ^d))."
6341f357
DN
4288 (let* ((b (progn
4289 (verilog-forward-syntactic-ws)
4290 (skip-chars-forward " \t")
4291 (point)))
4292 (e (let ((par 1))
4293 (cond
4294 ((looking-at "@")
4295 (forward-char 1)
4296 (verilog-forward-syntactic-ws)
4297 (if (looking-at "(")
4298 (progn
4299 (forward-char 1)
4300 (while (and (/= par 0)
4301 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4302 (cond
4303 ((match-end 1)
4304 (setq par (1+ par)))
4305 ((match-end 2)
4306 (setq par (1- par)))))))
4307 (point))
4308 ((looking-at "(")
4309 (forward-char 1)
4310 (while (and (/= par 0)
4311 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4312 (cond
4313 ((match-end 1)
4314 (setq par (1+ par)))
4315 ((match-end 2)
4316 (setq par (1- par)))))
4317 (point))
4318 ((looking-at "\\[")
4319 (forward-char 1)
4320 (while (and (/= par 0)
4321 (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
4322 (cond
4323 ((match-end 1)
4324 (setq par (1+ par)))
4325 ((match-end 2)
4326 (setq par (1- par)))))
4327 (verilog-forward-syntactic-ws)
4328 (skip-chars-forward "^ \t\n\f")
4329 (point))
4330 ((looking-at "/[/\\*]")
4331 b)
4332 ('t
4333 (skip-chars-forward "^: \t\n\f")
60618039 4334 (point)))))
6341f357
DN
4335 (str (buffer-substring b e)))
4336 (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
4337 (setq str (concat (substring str 0 e) "...")))
4338 str))
4339
4340(defun verilog-expand-vector ()
4341 "Take a signal vector on the current line and expand it to multiple lines.
4342Useful for creating tri's and other expanded fields."
4343 (interactive)
4344 (verilog-expand-vector-internal "[" "]"))
4345
4346(defun verilog-expand-vector-internal (bra ket)
4347 "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
4348 (save-excursion
4349 (forward-line 0)
4350 (let ((signal-string (buffer-substring (point)
4351 (progn
4352 (end-of-line) (point)))))
7ea26faf
DN
4353 (if (string-match
4354 (concat "\\(.*\\)"
4355 (regexp-quote bra)
4356 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
60618039
DN
4357 (regexp-quote ket)
4358 "\\(.*\\)$") signal-string)
6341f357 4359 (let* ((sig-head (match-string 1 signal-string))
7ea26faf 4360 (vec-start (string-to-number (match-string 2 signal-string)))
6341f357
DN
4361 (vec-end (if (= (match-beginning 3) (match-end 3))
4362 vec-start
7ea26faf
DN
4363 (string-to-number
4364 (substring signal-string (1+ (match-beginning 3))
4365 (match-end 3)))))
4366 (vec-range
4367 (if (= (match-beginning 4) (match-end 4))
4368 1
4369 (string-to-number
4370 (substring signal-string (+ 2 (match-beginning 4))
4371 (match-end 4)))))
6341f357
DN
4372 (sig-tail (match-string 5 signal-string))
4373 vec)
4374 ;; Decode vectors
4375 (setq vec nil)
4376 (if (< vec-range 0)
4377 (let ((tmp vec-start))
4378 (setq vec-start vec-end
4379 vec-end tmp
4380 vec-range (- vec-range))))
4381 (if (< vec-end vec-start)
4382 (while (<= vec-end vec-start)
4383 (setq vec (append vec (list vec-start)))
4384 (setq vec-start (- vec-start vec-range)))
4385 (while (<= vec-start vec-end)
4386 (setq vec (append vec (list vec-start)))
4387 (setq vec-start (+ vec-start vec-range))))
4388 ;;
4389 ;; Delete current line
4390 (delete-region (point) (progn (forward-line 0) (point)))
4391 ;;
4392 ;; Expand vector
4393 (while vec
7ea26faf
DN
4394 (insert (concat sig-head bra
4395 (int-to-string (car vec)) ket sig-tail "\n"))
6341f357
DN
4396 (setq vec (cdr vec)))
4397 (delete-char -1)
4398 ;;
4399 )))))
4400
4401(defun verilog-strip-comments ()
37ea4b9b 4402 "Strip all comments from the Verilog code."
6341f357
DN
4403 (interactive)
4404 (goto-char (point-min))
4405 (while (re-search-forward "//" nil t)
4406 (if (verilog-within-string)
4407 (re-search-forward "\"" nil t)
4408 (if (verilog-in-star-comment-p)
4409 (re-search-forward "\*/" nil t)
4410 (let ((bpt (- (point) 2)))
4411 (end-of-line)
4412 (delete-region bpt (point))))))
4413 ;;
4414 (goto-char (point-min))
4415 (while (re-search-forward "/\\*" nil t)
4416 (if (verilog-within-string)
4417 (re-search-forward "\"" nil t)
4418 (let ((bpt (- (point) 2)))
4419 (re-search-forward "\\*/")
4420 (delete-region bpt (point))))))
4421
4422(defun verilog-one-line ()
37ea4b9b 4423 "Convert structural Verilog instances to occupy one line."
6341f357
DN
4424 (interactive)
4425 (goto-char (point-min))
4426 (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
4427 (replace-match "\\1 " nil nil)))
4428
4429(defun verilog-linter-name ()
4430 "Return name of linter, either surelint or verilint."
4431 (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4432 compile-command))
4433 (lint-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4434 verilog-linter)))
4435 (cond ((equal compile-word1 "surelint") `surelint)
4436 ((equal compile-word1 "verilint") `verilint)
4437 ((equal lint-word1 "surelint") `surelint)
4438 ((equal lint-word1 "verilint") `verilint)
4439 (t `surelint)))) ;; back compatibility
4440
4441(defun verilog-lint-off ()
4442 "Convert a Verilog linter warning line into a disable statement.
4443For example:
4444 pci_bfm_null.v, line 46: Unused input: pci_rst_
4445becomes a comment for the appropriate tool.
4446
4447The first word of the `compile-command' or `verilog-linter'
37ea4b9b 4448variables is used to determine which product is being used.
6341f357
DN
4449
4450See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
4451 (interactive)
4452 (let ((linter (verilog-linter-name)))
4453 (cond ((equal linter `surelint)
4454 (verilog-surelint-off))
4455 ((equal linter `verilint)
4456 (verilog-verilint-off))
4457 (t (error "Linter name not set")))))
4458
7ea26faf 4459(defvar compilation-last-buffer)
a3a8b002 4460(defvar next-error-last-buffer)
7ea26faf 4461
6341f357
DN
4462(defun verilog-surelint-off ()
4463 "Convert a SureLint warning line into a disable statement.
4464Run from Verilog source window; assumes there is a *compile* buffer
4465with point set appropriately.
4466
4467For example:
4468 WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
4469becomes:
4470 // surefire lint_line_off UDDONX"
4471 (interactive)
7ea26faf
DN
4472 (let ((buff (if (boundp 'next-error-last-buffer)
4473 next-error-last-buffer
4474 compilation-last-buffer)))
4475 (when (buffer-live-p buff)
4476 ;; FIXME with-current-buffer?
4477 (save-excursion
4478 (switch-to-buffer buff)
4479 (beginning-of-line)
4480 (when
4481 (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
4482 (let* ((code (match-string 2))
4483 (file (match-string 3))
4484 (line (match-string 4))
4485 (buffer (get-file-buffer file))
4486 dir filename)
4487 (unless buffer
4488 (progn
4489 (setq buffer
4490 (and (file-exists-p file)
4491 (find-file-noselect file)))
4492 (or buffer
4493 (let* ((pop-up-windows t))
4494 (let ((name (expand-file-name
4495 (read-file-name
4496 (format "Find this error in: (default %s) "
4497 file)
4498 dir file t))))
4499 (if (file-directory-p name)
4500 (setq name (expand-file-name filename name)))
4501 (setq buffer
4502 (and (file-exists-p name)
4503 (find-file-noselect name))))))))
4504 (switch-to-buffer buffer)
5f68c1b7
GM
4505 (goto-char (point-min))
4506 (forward-line (- (string-to-number line)))
7ea26faf
DN
4507 (end-of-line)
4508 (catch 'already
4509 (cond
4510 ((verilog-in-slash-comment-p)
4511 (re-search-backward "//")
4512 (cond
4513 ((looking-at "// surefire lint_off_line ")
4514 (goto-char (match-end 0))
4515 (let ((lim (save-excursion (end-of-line) (point))))
4516 (if (re-search-forward code lim 'move)
4517 (throw 'already t)
4518 (insert (concat " " code)))))
4519 (t
4520 )))
4521 ((verilog-in-star-comment-p)
4522 (re-search-backward "/\*")
60618039 4523 (insert (format " // surefire lint_off_line %6s" code )))
7ea26faf
DN
4524 (t
4525 (insert (format " // surefire lint_off_line %6s" code ))
4526 )))))))))
6341f357
DN
4527
4528(defun verilog-verilint-off ()
4529 "Convert a Verilint warning line into a disable statement.
4530
4531For example:
4532 (W240) pci_bfm_null.v, line 46: Unused input: pci_rst_
4533becomes:
4534 //Verilint 240 off // WARNING: Unused input"
4535 (interactive)
4536 (save-excursion
4537 (beginning-of-line)
4538 (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
4539 (replace-match (format
4540 ;; %3s makes numbers 1-999 line up nicely
4541 "\\1//Verilint %3s off // WARNING: \\3"
4542 (match-string 2)))
4543 (beginning-of-line)
4544 (verilog-indent-line))))
4545
4546(defun verilog-auto-save-compile ()
4547 "Update automatics with \\[verilog-auto], save the buffer, and compile."
4548 (interactive)
4549 (verilog-auto) ; Always do it for safety
4550 (save-buffer)
4551 (compile compile-command))
4552
a03c2342
WS
4553(defun verilog-preprocess (&optional command filename)
4554 "Preprocess the buffer, similar to `compile', but leave output in Verilog-Mode.
4555Takes optional COMMAND or defaults to `verilog-preprocessor', and
4556FILENAME or defaults to `buffer-file-name`."
4557 (interactive
4558 (list
4559 (let ((default (verilog-expand-command verilog-preprocessor)))
4560 (set (make-local-variable `verilog-preprocessor)
4561 (read-from-minibuffer "Run Preprocessor (like this): "
4562 default nil nil
4563 'verilog-preprocess-history default)))))
4564 (unless command (setq command (verilog-expand-command verilog-preprocessor)))
8468f78b
WS
4565 (let* ((fontlocked (and (boundp 'font-lock-mode) font-lock-mode))
4566 (dir (file-name-directory (or filename buffer-file-name)))
a03c2342
WS
4567 (file (file-name-nondirectory (or filename buffer-file-name)))
4568 (cmd (concat "cd " dir "; " command " " file)))
4569 (with-output-to-temp-buffer "*Verilog-Preprocessed*"
8468f78b 4570 (with-current-buffer (get-buffer "*Verilog-Preprocessed*")
a03c2342
WS
4571 (insert (concat "// " cmd "\n"))
4572 (shell-command cmd "*Verilog-Preprocessed*")
4573 (verilog-mode)
8468f78b
WS
4574 ;; Without this force, it takes a few idle seconds
4575 ;; to get the color, which is very jarring
4576 (when fontlocked (font-lock-fontify-buffer))))))
6341f357
DN
4577\f
4578
4579;;
4580;; Batch
4581;;
4582
4583(defmacro verilog-batch-error-wrapper (&rest body)
4584 "Execute BODY and add error prefix to any errors found.
4585This lets programs calling batch mode to easily extract error messages."
6edb5716
DN
4586 `(condition-case err
4587 (progn ,@body)
4588 (error
4589 (error "%%Error: %s%s" (error-message-string err)
d63b01e1 4590 (if (featurep 'xemacs) "\n" ""))))) ;; XEmacs forgets to add a newline
6341f357
DN
4591
4592(defun verilog-batch-execute-func (funref)
4593 "Internal processing of a batch command, running FUNREF on all command arguments."
4594 (verilog-batch-error-wrapper
14862301
SM
4595 ;; Setting global variables like that is *VERY NASTY* !!! --Stef
4596 ;; However, this function is called only when Emacs is being used as
4597 ;; a standalone language instead of as an editor, so we'll live.
4598 ;;
6341f357
DN
4599 ;; General globals needed
4600 (setq make-backup-files nil)
4601 (setq-default make-backup-files nil)
4602 (setq enable-local-variables t)
4603 (setq enable-local-eval t)
4604 ;; Make sure any sub-files we read get proper mode
14acf2f5 4605 (setq-default major-mode 'verilog-mode)
6341f357 4606 ;; Ditto files already read in
7ea26faf 4607 (mapc (lambda (buf)
60618039 4608 (when (buffer-file-name buf)
14acf2f5 4609 (with-current-buffer buf
60618039
DN
4610 (verilog-mode))))
4611 (buffer-list))
6341f357
DN
4612 ;; Process the files
4613 (mapcar '(lambda (buf)
4614 (when (buffer-file-name buf)
4615 (save-excursion
4616 (if (not (file-exists-p (buffer-file-name buf)))
7ea26faf
DN
4617 (error
4618 (concat "File not found: " (buffer-file-name buf))))
6341f357
DN
4619 (message (concat "Processing " (buffer-file-name buf)))
4620 (set-buffer buf)
4621 (funcall funref)
4622 (save-buffer))))
4623 (buffer-list))))
4624
4625(defun verilog-batch-auto ()
4626 "For use with --batch, perform automatic expansions as a stand-alone tool.
37ea4b9b 4627This sets up the appropriate Verilog mode environment, updates automatics
6341f357
DN
4628with \\[verilog-auto] on all command-line files, and saves the buffers.
4629For proper results, multiple filenames need to be passed on the command
4630line in bottom-up order."
4631 (unless noninteractive
4632 (error "Use verilog-batch-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4633 (verilog-batch-execute-func `verilog-auto))
4634
4635(defun verilog-batch-delete-auto ()
4636 "For use with --batch, perform automatic deletion as a stand-alone tool.
37ea4b9b 4637This sets up the appropriate Verilog mode environment, deletes automatics
6341f357
DN
4638with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
4639 (unless noninteractive
4640 (error "Use verilog-batch-delete-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4641 (verilog-batch-execute-func `verilog-delete-auto))
4642
4643(defun verilog-batch-inject-auto ()
4644 "For use with --batch, perform automatic injection as a stand-alone tool.
37ea4b9b 4645This sets up the appropriate Verilog mode environment, injects new automatics
6341f357
DN
4646with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
4647For proper results, multiple filenames need to be passed on the command
4648line in bottom-up order."
4649 (unless noninteractive
4650 (error "Use verilog-batch-inject-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4651 (verilog-batch-execute-func `verilog-inject-auto))
4652
4653(defun verilog-batch-indent ()
4654 "For use with --batch, reindent an a entire file as a stand-alone tool.
37ea4b9b 4655This sets up the appropriate Verilog mode environment, calls
6341f357
DN
4656\\[verilog-indent-buffer] on all command-line files, and saves the buffers."
4657 (unless noninteractive
4658 (error "Use verilog-batch-indent only with --batch")) ;; Otherwise we'd mess up buffer modes
4659 (verilog-batch-execute-func `verilog-indent-buffer))
4660\f
4661
4662;;
4663;; Indentation
4664;;
4665(defconst verilog-indent-alist
4666 '((block . (+ ind verilog-indent-level))
4667 (case . (+ ind verilog-case-indent))
4668 (cparenexp . (+ ind verilog-indent-level))
4669 (cexp . (+ ind verilog-cexp-indent))
4670 (defun . verilog-indent-level-module)
4671 (declaration . verilog-indent-level-declaration)
4672 (directive . (verilog-calculate-indent-directive))
4673 (tf . verilog-indent-level)
4674 (behavioral . (+ verilog-indent-level-behavioral verilog-indent-level-module))
4675 (statement . ind)
4676 (cpp . 0)
4677 (comment . (verilog-comment-indent))
4678 (unknown . 3)
4679 (string . 0)))
4680
4681(defun verilog-continued-line-1 (lim)
4682 "Return true if this is a continued line.
4683Set point to where line starts. Limit search to point LIM."
4684 (let ((continued 't))
4685 (if (eq 0 (forward-line -1))
4686 (progn
4687 (end-of-line)
4688 (verilog-backward-ws&directives lim)
4689 (if (bobp)
4690 (setq continued nil)
4691 (setq continued (verilog-backward-token))))
4692 (setq continued nil))
4693 continued))
4694
4695(defun verilog-calculate-indent ()
4696 "Calculate the indent of the current Verilog line.
4697Examine previous lines. Once a line is found that is definitive as to the
37ea4b9b
JB
4698type of the current line, return that lines' indent level and its type.
4699Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
6341f357
DN
4700 (save-excursion
4701 (let* ((starting_position (point))
4702 (par 0)
4703 (begin (looking-at "[ \t]*begin\\>"))
4704 (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
4705 (type (catch 'nesting
4706 ;; Keep working backwards until we can figure out
4707 ;; what type of statement this is.
4708 ;; Basically we need to figure out
4709 ;; 1) if this is a continuation of the previous line;
4710 ;; 2) are we in a block scope (begin..end)
4711
4712 ;; if we are in a comment, done.
4713 (if (verilog-in-star-comment-p)
4714 (throw 'nesting 'comment))
4715
4716 ;; if we have a directive, done.
a3a8b002
DN
4717 (if (save-excursion (beginning-of-line)
4718 (and (looking-at verilog-directive-re-1)
a03c2342 4719 (not (or (looking-at "[ \t]*`ovm_")
86a4c7ac 4720 (looking-at "[ \t]*`vmm_")))))
6341f357 4721 (throw 'nesting 'directive))
a3a8b002
DN
4722 ;; indent structs as if there were module level
4723 (if (verilog-in-struct-p)
4724 (throw 'nesting 'block))
6341f357
DN
4725
4726 ;; unless we are in the newfangled coverpoint or constraint blocks
4727 ;; if we are in a parenthesized list, and the user likes to indent these, return.
4728 (if (and
a3a8b002
DN
4729 verilog-indent-lists
4730 (verilog-in-paren)
4731 (not (verilog-in-coverage-p))
4732 )
6341f357 4733 (progn (setq par 1)
a3a8b002 4734 (throw 'nesting 'block)))
6341f357
DN
4735
4736 ;; See if we are continuing a previous line
4737 (while t
4738 ;; trap out if we crawl off the top of the buffer
4739 (if (bobp) (throw 'nesting 'cpp))
4740
4741 (if (verilog-continued-line-1 lim)
4742 (let ((sp (point)))
4743 (if (and
4744 (not (looking-at verilog-complete-reg))
4745 (verilog-continued-line-1 lim))
4746 (progn (goto-char sp)
4747 (throw 'nesting 'cexp))
4748
4749 (goto-char sp))
4750
4751 (if (and begin
4752 (not verilog-indent-begin-after-if)
4753 (looking-at verilog-no-indent-begin-re))
4754 (progn
4755 (beginning-of-line)
4756 (skip-chars-forward " \t")
4757 (throw 'nesting 'statement))
4758 (progn
4759 (throw 'nesting 'cexp))))
4760 ;; not a continued line
4761 (goto-char starting_position))
4762
4763 (if (looking-at "\\<else\\>")
4764 ;; search back for governing if, striding across begin..end pairs
4765 ;; appropriately
4766 (let ((elsec 1))
4767 (while (verilog-re-search-backward verilog-ends-re nil 'move)
4768 (cond
4769 ((match-end 1) ; else, we're in deep
4770 (setq elsec (1+ elsec)))
4771 ((match-end 2) ; if
4772 (setq elsec (1- elsec))
4773 (if (= 0 elsec)
4774 (if verilog-align-ifelse
4775 (throw 'nesting 'statement)
4776 (progn ;; back up to first word on this line
4777 (beginning-of-line)
4778 (verilog-forward-syntactic-ws)
4779 (throw 'nesting 'statement)))))
86a4c7ac
DN
4780 ((match-end 3) ; assert block
4781 (setq elsec (1- elsec))
4782 (verilog-beg-of-statement) ;; doesn't get to beginning
a03c2342 4783 (if (looking-at verilog-property-re)
86a4c7ac
DN
4784 (throw 'nesting 'statement) ; We don't need an endproperty for these
4785 (throw 'nesting 'block) ;We still need a endproperty
4786 ))
6341f357
DN
4787 (t ; endblock
4788 ; try to leap back to matching outward block by striding across
4789 ; indent level changing tokens then immediately
4790 ; previous line governs indentation.
4791 (let (( reg) (nest 1))
4792;; verilog-ends => else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
4793 (cond
86a4c7ac 4794 ((match-end 4) ; end
6341f357
DN
4795 ;; Search back for matching begin
4796 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
86a4c7ac 4797 ((match-end 5) ; endcase
6341f357
DN
4798 ;; Search back for matching case
4799 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
86a4c7ac 4800 ((match-end 6) ; endfunction
6341f357
DN
4801 ;; Search back for matching function
4802 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
86a4c7ac 4803 ((match-end 7) ; endtask
6341f357
DN
4804 ;; Search back for matching task
4805 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
86a4c7ac 4806 ((match-end 8) ; endspecify
6341f357
DN
4807 ;; Search back for matching specify
4808 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
86a4c7ac 4809 ((match-end 9) ; endtable
6341f357
DN
4810 ;; Search back for matching table
4811 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
86a4c7ac 4812 ((match-end 10) ; endgenerate
6341f357
DN
4813 ;; Search back for matching generate
4814 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
86a4c7ac 4815 ((match-end 11) ; joins
6341f357
DN
4816 ;; Search back for matching fork
4817 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
86a4c7ac 4818 ((match-end 12) ; class
6341f357
DN
4819 ;; Search back for matching class
4820 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
86a4c7ac 4821 ((match-end 13) ; covergroup
6341f357 4822 ;; Search back for matching covergroup
60618039 4823 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
6341f357
DN
4824 (catch 'skip
4825 (while (verilog-re-search-backward reg nil 'move)
4826 (cond
4827 ((match-end 1) ; begin
4828 (setq nest (1- nest))
4829 (if (= 0 nest)
4830 (throw 'skip 1)))
4831 ((match-end 2) ; end
4832 (setq nest (1+ nest)))))
60618039
DN
4833 )))))))
4834 (throw 'nesting (verilog-calc-1)))
6341f357
DN
4835 );; catch nesting
4836 );; type
4837 )
4838 ;; Return type of block and indent level.
4839 (if (not type)
4840 (setq type 'cpp))
4841 (if (> par 0) ; Unclosed Parenthesis
4842 (list 'cparenexp par)
4843 (cond
4844 ((eq type 'case)
4845 (list type (verilog-case-indent-level)))
4846 ((eq type 'statement)
4847 (list type (current-column)))
4848 ((eq type 'defun)
4849 (list type 0))
4850 (t
60618039
DN
4851 (list type (verilog-current-indent-level))))))))
4852
6341f357
DN
4853(defun verilog-wai ()
4854 "Show matching nesting block for debugging."
4855 (interactive)
4856 (save-excursion
4c5e69c6
DN
4857 (let* ((type (verilog-calc-1))
4858 depth)
4859 ;; Return type of block and indent level.
4860 (if (not type)
4861 (setq type 'cpp))
4862 (if (and
4863 verilog-indent-lists
a3a8b002
DN
4864 (not(or (verilog-in-coverage-p)
4865 (verilog-in-struct-p)))
4c5e69c6
DN
4866 (verilog-in-paren))
4867 (setq depth 1)
4868 (cond
4869 ((eq type 'case)
4870 (setq depth (verilog-case-indent-level)))
4871 ((eq type 'statement)
4872 (setq depth (current-column)))
4873 ((eq type 'defun)
4874 (setq depth 0))
4875 (t
4876 (setq depth (verilog-current-indent-level)))))
4877 (message "You are at nesting %s depth %d" type depth))))
6341f357
DN
4878
4879(defun verilog-calc-1 ()
4880 (catch 'nesting
a3a8b002
DN
4881 (let ((re (concat "\\({\\|}\\|" verilog-indent-re "\\)")))
4882 (while (verilog-re-search-backward re nil 'move)
4883 (catch 'continue
4884 (cond
4885 ((equal (char-after) ?\{)
4886 (if (verilog-at-constraint-p)
4887 (throw 'nesting 'block)))
6341f357 4888
a3a8b002
DN
4889 ((equal (char-after) ?\})
4890 (let ((there (verilog-at-close-constraint-p)))
86a4c7ac 4891 (if there ;; we are at the } that closes a constraint. Find the { that opens it
a3a8b002
DN
4892 (progn
4893 (forward-char 1)
4894 (backward-list 1)
4895 (verilog-beg-of-statement)))))
6341f357 4896
a3a8b002
DN
4897 ((looking-at verilog-beg-block-re-ordered)
4898 (cond
4899 ((match-end 2) ; *sigh* could be "unique case" or "priority casex"
4900 (let ((here (point)))
4901 (verilog-beg-of-statement)
4902 (if (looking-at verilog-extended-case-re)
4903 (throw 'nesting 'case)
4904 (goto-char here)))
4905 (throw 'nesting 'case))
4906
4907 ((match-end 4) ; *sigh* could be "disable fork"
4908 (let ((here (point)))
4909 (verilog-beg-of-statement)
a03c2342
WS
4910 (if (or (looking-at verilog-disable-fork-re)
4911 (looking-at verilog-fork-wait-re))
4912 t ; this is a normal statement
a3a8b002
DN
4913 (progn ; or is fork, starts a new block
4914 (goto-char here)
4915 (throw 'nesting 'block)))))
4916
a03c2342
WS
4917 ((match-end 27) ; *sigh* might be a clocking declaration
4918 (let ((here (point)))
4919 (if (verilog-in-paren)
4920 t ; this is a normal statement
4921 (progn ; or is fork, starts a new block
4922 (goto-char here)
4923 (throw 'nesting 'block)))))
a3a8b002
DN
4924
4925 ;; need to consider typedef struct here...
4926 ((looking-at "\\<class\\|struct\\|function\\|task\\>")
6341f357
DN
4927 ; *sigh* These words have an optional prefix:
4928 ; extern {virtual|protected}? function a();
6341f357
DN
4929 ; typedef class foo;
4930 ; and we don't want to confuse this with
4931 ; function a();
4932 ; property
4933 ; ...
4934 ; endfunction
a3a8b002
DN
4935 (verilog-beg-of-statement)
4936 (if (looking-at verilog-beg-block-re-ordered)
4937 (throw 'nesting 'block)
4938 (throw 'nesting 'defun)))
7cb1c4d7 4939
a3a8b002
DN
4940 ((looking-at "\\<property\\>")
4941 ; *sigh*
7cb1c4d7 4942 ; {assert|assume|cover} property (); are complete
14862301 4943 ; and could also be labeled: - foo: assert property
7cb1c4d7
DN
4944 ; but
4945 ; property ID () ... needs end_property
a3a8b002 4946 (verilog-beg-of-statement)
a03c2342 4947 (if (looking-at verilog-property-re)
14862301 4948 (throw 'continue 'statement) ; We don't need an endproperty for these
a3a8b002
DN
4949 (throw 'nesting 'block) ;We still need a endproperty
4950 ))
6341f357 4951
a3a8b002 4952 (t (throw 'nesting 'block))))
6341f357 4953
a3a8b002
DN
4954 ((looking-at verilog-end-block-re)
4955 (verilog-leap-to-head)
4956 (if (verilog-in-case-region-p)
4957 (progn
4958 (verilog-leap-to-case-head)
4959 (if (looking-at verilog-extended-case-re)
4960 (throw 'nesting 'case)))))
6341f357 4961
a3a8b002
DN
4962 ((looking-at verilog-defun-level-re)
4963 (if (looking-at verilog-defun-level-generate-only-re)
4964 (if (verilog-in-generate-region-p)
14862301 4965 (throw 'continue 'foo) ; always block in a generate - keep looking
a3a8b002
DN
4966 (throw 'nesting 'defun))
4967 (throw 'nesting 'defun)))
4968
4969 ((looking-at verilog-cpp-level-re)
4970 (throw 'nesting 'cpp))
4971
4972 ((bobp)
4973 (throw 'nesting 'cpp)))))
4974
4975 (throw 'nesting 'cpp))))
6341f357
DN
4976
4977(defun verilog-calculate-indent-directive ()
4978 "Return indentation level for directive.
4979For speed, the searcher looks at the last directive, not the indent
4980of the appropriate enclosing block."
4981 (let ((base -1) ;; Indent of the line that determines our indentation
60618039 4982 (ind 0)) ;; Relative offset caused by other directives (like `endif on same line as `else)
6341f357
DN
4983 ;; Start at current location, scan back for another directive
4984
4985 (save-excursion
4986 (beginning-of-line)
4987 (while (and (< base 0)
4988 (verilog-re-search-backward verilog-directive-re nil t))
4989 (cond ((save-excursion (skip-chars-backward " \t") (bolp))
60618039 4990 (setq base (current-indentation))))
6341f357
DN
4991 (cond ((and (looking-at verilog-directive-end) (< base 0)) ;; Only matters when not at BOL
4992 (setq ind (- ind verilog-indent-level-directive)))
4993 ((and (looking-at verilog-directive-middle) (>= base 0)) ;; Only matters when at BOL
4994 (setq ind (+ ind verilog-indent-level-directive)))
4995 ((looking-at verilog-directive-begin)
4996 (setq ind (+ ind verilog-indent-level-directive)))))
4997 ;; Adjust indent to starting indent of critical line
4998 (setq ind (max 0 (+ ind base))))
4999
5000 (save-excursion
5001 (beginning-of-line)
5002 (skip-chars-forward " \t")
5003 (cond ((or (looking-at verilog-directive-middle)
5004 (looking-at verilog-directive-end))
5005 (setq ind (max 0 (- ind verilog-indent-level-directive))))))
5006 ind))
5007
5008(defun verilog-leap-to-case-head ()
5009 (let ((nest 1))
5010 (while (/= 0 nest)
a3a8b002
DN
5011 (verilog-re-search-backward
5012 (concat
5013 "\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?\\<case[xz]?\\>\\)"
5014 "\\|\\(\\<endcase\\>\\)" )
5015 nil 'move)
6341f357
DN
5016 (cond
5017 ((match-end 1)
a3a8b002
DN
5018 (let ((here (point)))
5019 (verilog-beg-of-statement)
5020 (unless (looking-at verilog-extended-case-re)
5021 (goto-char here)))
6341f357 5022 (setq nest (1- nest)))
a3a8b002 5023 ((match-end 3)
6341f357
DN
5024 (setq nest (1+ nest)))
5025 ((bobp)
5026 (ding 't)
5027 (setq nest 0))))))
5028
5029(defun verilog-leap-to-head ()
37ea4b9b
JB
5030 "Move point to the head of this block.
5031Jump from end to matching begin, from endcase to matching case, and so on."
6341f357
DN
5032 (let ((reg nil)
5033 snest
4c5e69c6 5034 (nesting 'yes)
6341f357
DN
5035 (nest 1))
5036 (cond
5037 ((looking-at "\\<end\\>")
5038 ;; 1: Search back for matching begin
5039 (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
5040 "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
4c5e69c6 5041 ((looking-at "\\<endtask\\>")
a3a8b002 5042 ;; 2: Search back for matching task
4c5e69c6
DN
5043 (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
5044 (setq nesting 'no))
6341f357 5045 ((looking-at "\\<endcase\\>")
a3a8b002
DN
5046 (catch 'nesting
5047 (verilog-leap-to-case-head) )
5048 (setq reg nil) ; to force skip
5049 )
5050
6341f357 5051 ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
a3a8b002 5052 ;; 4: Search back for matching fork
6341f357
DN
5053 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5054 ((looking-at "\\<endclass\\>")
a3a8b002 5055 ;; 5: Search back for matching class
6341f357
DN
5056 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
5057 ((looking-at "\\<endtable\\>")
a3a8b002 5058 ;; 6: Search back for matching table
6341f357
DN
5059 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
5060 ((looking-at "\\<endspecify\\>")
a3a8b002 5061 ;; 7: Search back for matching specify
6341f357
DN
5062 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
5063 ((looking-at "\\<endfunction\\>")
a3a8b002
DN
5064 ;; 8: Search back for matching function
5065 (setq reg "\\(\\<function\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<function\\>\\)")
5066 (setq nesting 'no))
5067 ;;(setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
6341f357
DN
5068 ((looking-at "\\<endgenerate\\>")
5069 ;; 8: Search back for matching generate
5070 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
6341f357
DN
5071 ((looking-at "\\<endgroup\\>")
5072 ;; 10: Search back for matching covergroup
5073 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
5074 ((looking-at "\\<endproperty\\>")
5075 ;; 11: Search back for matching property
5076 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
a3a8b002
DN
5077 ((looking-at verilog-ovm-end-re)
5078 ;; 12: Search back for matching sequence
5079 (setq reg (concat "\\(" verilog-ovm-begin-re "\\|" verilog-ovm-end-re "\\)")))
86a4c7ac
DN
5080 ((looking-at verilog-vmm-end-re)
5081 ;; 12: Search back for matching sequence
5082 (setq reg (concat "\\(" verilog-vmm-begin-re "\\|" verilog-vmm-end-re "\\)")))
6341f357
DN
5083 ((looking-at "\\<endinterface\\>")
5084 ;; 12: Search back for matching interface
5085 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
5086 ((looking-at "\\<endsequence\\>")
5087 ;; 12: Search back for matching sequence
5088 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
5089 ((looking-at "\\<endclocking\\>")
5090 ;; 12: Search back for matching clocking
60618039 5091 (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
6341f357
DN
5092 (if reg
5093 (catch 'skip
4c5e69c6
DN
5094 (if (eq nesting 'yes)
5095 (let (sreg)
5096 (while (verilog-re-search-backward reg nil 'move)
5097 (cond
5098 ((match-end 1) ; begin
0e5c8aed
DN
5099 (if (looking-at "fork")
5100 (let ((here (point)))
5101 (verilog-beg-of-statement)
5102 (unless (looking-at verilog-disable-fork-re)
5103 (goto-char here)
5104 (setq nest (1- nest))))
5105 (setq nest (1- nest)))
4c5e69c6
DN
5106 (if (= 0 nest)
5107 ;; Now previous line describes syntax
5108 (throw 'skip 1))
5109 (if (and snest
5110 (= snest nest))
5111 (setq reg sreg)))
5112 ((match-end 2) ; end
5113 (setq nest (1+ nest)))
5114 ((match-end 3)
5115 ;; endcase, jump to case
5116 (setq snest nest)
5117 (setq nest (1+ nest))
5118 (setq sreg reg)
5119 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
5120 ((match-end 4)
5121 ;; join, jump to fork
5122 (setq snest nest)
5123 (setq nest (1+ nest))
5124 (setq sreg reg)
5125 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5126 )))
5127 ;no nesting
5128 (if (and
a3a8b002 5129 (verilog-re-search-backward reg nil 'move)
4c5e69c6
DN
5130 (match-end 1)) ; task -> could be virtual and/or protected
5131 (progn
5132 (verilog-beg-of-statement)
5133 (throw 'skip 1))
5134 (throw 'skip 1)))))))
6341f357
DN
5135
5136(defun verilog-continued-line ()
5137 "Return true if this is a continued line.
37ea4b9b 5138Set point to where line starts."
6341f357
DN
5139 (let ((continued 't))
5140 (if (eq 0 (forward-line -1))
5141 (progn
5142 (end-of-line)
5143 (verilog-backward-ws&directives)
5144 (if (bobp)
5145 (setq continued nil)
5146 (while (and continued
5147 (save-excursion
5148 (skip-chars-backward " \t")
5149 (not (bolp))))
60618039 5150 (setq continued (verilog-backward-token)))))
6341f357
DN
5151 (setq continued nil))
5152 continued))
5153
5154(defun verilog-backward-token ()
14862301 5155 "Step backward token, returing true if this is a continued line."
6341f357
DN
5156 (interactive)
5157 (verilog-backward-syntactic-ws)
5158 (cond
5159 ((bolp)
5160 nil)
5161 (;-- Anything ending in a ; is complete
5162 (= (preceding-char) ?\;)
5163 nil)
5164 (; If a "}" is prefixed by a ";", then this is a complete statement
5165 ; i.e.: constraint foo { a = b; }
5166 (= (preceding-char) ?\})
5167 (progn
5168 (backward-char)
a3a8b002 5169 (not(verilog-at-close-constraint-p))))
6341f357
DN
5170 (;-- constraint foo { a = b }
5171 ; is a complete statement. *sigh*
5172 (= (preceding-char) ?\{)
5173 (progn
5174 (backward-char)
60618039 5175 (not (verilog-at-constraint-p))))
a3a8b002
DN
5176 (;" string "
5177 (= (preceding-char) ?\")
5178 (backward-char)
5179 (verilog-skip-backward-comment-or-string)
5180 nil)
5181
5182 (; [3:4]
5183 (= (preceding-char) ?\])
5184 (backward-char)
5185 (verilog-backward-open-bracket)
5186 t)
5187
6341f357
DN
5188 (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
5189 ; also could be simply '@(foo)'
5190 ; or foo u1 #(a=8)
5191 ; (b, ... which ISN'T complete
5192 ;;;; Do we need this???
5193 (= (preceding-char) ?\))
5194 (progn
5195 (backward-char)
a03c2342 5196 (verilog-backward-up-list 1)
6341f357
DN
5197 (verilog-backward-syntactic-ws)
5198 (let ((back (point)))
5199 (forward-word -1)
5200 (cond
a3a8b002 5201 ;;XX
6341f357
DN
5202 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
5203 (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
a3a8b002
DN
5204 ((looking-at verilog-ovm-statement-re)
5205 nil)
5206 ((looking-at verilog-ovm-begin-re)
5207 t)
5208 ((looking-at verilog-ovm-end-re)
5209 t)
86a4c7ac
DN
5210 ;; JBA find VMM macros
5211 ((looking-at verilog-vmm-statement-re)
5212 nil )
5213 ((looking-at verilog-vmm-begin-re)
5214 t)
5215 ((looking-at verilog-vmm-end-re)
5216 nil)
5217 ;; JBA trying to catch macro lines with no ; at end
5218 ((looking-at "\\<`")
5219 nil)
6341f357
DN
5220 (t
5221 (goto-char back)
5222 (cond
5223 ((= (preceding-char) ?\@)
5224 (backward-char)
5225 (save-excursion
5226 (verilog-backward-token)
5227 (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
5228 ((= (preceding-char) ?\#)
60618039
DN
5229 (backward-char))
5230 (t t)))))))
6341f357
DN
5231
5232 (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
5233 t
5234 (forward-word -1)
0e5c8aed
DN
5235 (while (= (preceding-char) ?\_)
5236 (forward-word -1))
6341f357
DN
5237 (cond
5238 ((looking-at "\\<else\\>")
5239 t)
2a9eb3f5
DN
5240 ((looking-at verilog-behavioral-block-beg-re)
5241 t)
6341f357
DN
5242 ((looking-at verilog-indent-re)
5243 nil)
5244 (t
5245 (let
5246 ((back (point)))
5247 (verilog-backward-syntactic-ws)
5248 (cond
5249 ((= (preceding-char) ?\:)
5250 (backward-char)
5251 (verilog-backward-syntactic-ws)
5252 (backward-sexp)
5253 (if (looking-at verilog-nameable-item-re )
5254 nil
60618039 5255 t))
6341f357
DN
5256 ((= (preceding-char) ?\#)
5257 (backward-char)
5258 t)
5259 ((= (preceding-char) ?\`)
5260 (backward-char)
5261 t)
5262
5263 (t
5264 (goto-char back)
60618039 5265 t))))))))
6341f357 5266
a03c2342
WS
5267(defun verilog-backward-syntactic-ws ()
5268 (verilog-skip-backward-comments)
5269 (forward-comment (- (buffer-size))))
6341f357 5270
a03c2342
WS
5271(defun verilog-forward-syntactic-ws ()
5272 (verilog-skip-forward-comment-p)
5273 (forward-comment (buffer-size)))
6341f357
DN
5274
5275(defun verilog-backward-ws&directives (&optional bound)
5276 "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
5277Optional BOUND limits search."
5278 (save-restriction
5279 (let* ((bound (or bound (point-min)))
5280 (here bound)
5281 (p nil) )
5282 (if (< bound (point))
5283 (progn
d63b01e1 5284 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5285 (cond
5286 ((nth 7 state) ;; in // comment
5287 (verilog-re-search-backward "//" nil 'move)
5288 (skip-chars-backward "/"))
5289 ((nth 4 state) ;; in /* */ comment
5290 (verilog-re-search-backward "/\*" nil 'move))))
5291 (narrow-to-region bound (point))
5292 (while (/= here (point))
5293 (setq here (point))
5294 (verilog-skip-backward-comments)
5295 (setq p
5296 (save-excursion
5297 (beginning-of-line)
5298 (cond
a3a8b002
DN
5299 ((and verilog-highlight-translate-off
5300 (verilog-within-translate-off))
6341f357
DN
5301 (verilog-back-to-start-translate-off (point-min)))
5302 ((looking-at verilog-directive-re-1)
5303 (point))
5304 (t
5305 nil))))
60618039 5306 (if p (goto-char p))))))))
6341f357
DN
5307
5308(defun verilog-forward-ws&directives (&optional bound)
5309 "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
5310Optional BOUND limits search."
5311 (save-restriction
5312 (let* ((bound (or bound (point-max)))
5313 (here bound)
60618039 5314 jump)
6341f357
DN
5315 (if (> bound (point))
5316 (progn
d63b01e1 5317 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5318 (cond
5319 ((nth 7 state) ;; in // comment
a03c2342
WS
5320 (end-of-line)
5321 (forward-char 1)
5322 (skip-chars-forward " \t\n\f")
5323 )
6341f357 5324 ((nth 4 state) ;; in /* */ comment
a03c2342 5325 (verilog-re-search-forward "\*\/\\s-*" nil 'move))))
6341f357
DN
5326 (narrow-to-region (point) bound)
5327 (while (/= here (point))
5328 (setq here (point)
5329 jump nil)
5330 (forward-comment (buffer-size))
a03c2342
WS
5331 (and (looking-at "\\s-*(\\*.*\\*)\\s-*") ;; Attribute
5332 (goto-char (match-end 0)))
6341f357
DN
5333 (save-excursion
5334 (beginning-of-line)
5335 (if (looking-at verilog-directive-re-1)
5336 (setq jump t)))
5337 (if jump
60618039 5338 (beginning-of-line 2))))))))
6341f357
DN
5339
5340(defun verilog-in-comment-p ()
5341 "Return true if in a star or // comment."
d63b01e1 5342 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5343 (or (nth 4 state) (nth 7 state))))
5344
5345(defun verilog-in-star-comment-p ()
5346 "Return true if in a star comment."
d63b01e1 5347 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5348 (and
5349 (nth 4 state) ; t if in a comment of style a // or b /**/
5350 (not
5351 (nth 7 state) ; t if in a comment of style b /**/
5352 ))))
5353
5354(defun verilog-in-slash-comment-p ()
5355 "Return true if in a slash comment."
d63b01e1 5356 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5357 (nth 7 state)))
5358
5359(defun verilog-in-comment-or-string-p ()
5360 "Return true if in a string or comment."
d63b01e1 5361 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5362 (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
5363
a03c2342
WS
5364(defun verilog-in-attribute-p ()
5365 "Return true if point is in an attribute (* [] attribute *)."
5366 (save-excursion
5367 (verilog-re-search-backward "\\((\\*\\)\\|\\(\\*)\\)" nil 'move)
5368 (numberp (match-beginning 1))))
5369
6341f357
DN
5370(defun verilog-in-escaped-name-p ()
5371 "Return true if in an escaped name."
5372 (save-excursion
5373 (backward-char)
5374 (skip-chars-backward "^ \t\n\f")
5375 (if (equal (char-after (point) ) ?\\ )
5376 t
5377 nil)))
a3a8b002 5378(defun verilog-in-directive-p ()
a03c2342 5379 "Return true if in a directive."
a3a8b002
DN
5380 (save-excursion
5381 (beginning-of-line)
5382 (looking-at verilog-directive-re-1)))
6341f357
DN
5383
5384(defun verilog-in-paren ()
5385 "Return true if in a parenthetical expression."
d63b01e1 5386 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5387 (> (nth 0 state) 0 )))
5388
a3a8b002
DN
5389(defun verilog-in-struct-p ()
5390 "Return true if in a struct declaration."
5391 (interactive)
5392 (save-excursion
5393 (if (verilog-in-paren)
5394 (progn
a03c2342 5395 (verilog-backward-up-list 1)
a3a8b002
DN
5396 (verilog-at-struct-p)
5397 )
5398 nil)))
5399
5400(defun verilog-in-coverage-p ()
6341f357
DN
5401 "Return true if in a constraint or coverpoint expression."
5402 (interactive)
5403 (save-excursion
5404 (if (verilog-in-paren)
5405 (progn
a03c2342 5406 (verilog-backward-up-list 1)
6341f357
DN
5407 (verilog-at-constraint-p)
5408 )
5409 nil)))
5410(defun verilog-at-close-constraint-p ()
5411 "If at the } that closes a constraint or covergroup, return true."
5412 (if (and
5413 (equal (char-after) ?\})
5414 (verilog-in-paren))
5415
5416 (save-excursion
5417 (verilog-backward-ws&directives)
5418 (if (equal (char-before) ?\;)
5419 (point)
5420 nil))))
5421
5422(defun verilog-at-constraint-p ()
5423 "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
5424 (if (save-excursion
5425 (and
5426 (equal (char-after) ?\{)
5427 (forward-list)
5428 (progn (backward-char 1)
5429 (verilog-backward-ws&directives)
60618039 5430 (equal (char-before) ?\;))))
6341f357
DN
5431 ;; maybe
5432 (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
5433 ;; not
60618039 5434 nil))
6341f357 5435
a3a8b002
DN
5436(defun verilog-at-struct-p ()
5437 "If at the { of a struct, return true, moving point to struct."
5438 (save-excursion
5439 (if (and (equal (char-after) ?\{)
5440 (verilog-backward-token))
0e5c8aed 5441 (looking-at "\\<struct\\|union\\|packed\\|\\(un\\)?signed\\>")
a3a8b002
DN
5442 nil)))
5443
6341f357
DN
5444(defun verilog-parenthesis-depth ()
5445 "Return non zero if in parenthetical-expression."
d63b01e1 5446 (save-excursion (nth 1 (verilog-syntax-ppss))))
6341f357
DN
5447
5448
5449(defun verilog-skip-forward-comment-or-string ()
5450 "Return true if in a string or comment."
d63b01e1 5451 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5452 (cond
5453 ((nth 3 state) ;Inside string
495ab0d5 5454 (search-forward "\"")
6341f357
DN
5455 t)
5456 ((nth 7 state) ;Inside // comment
5457 (forward-line 1)
5458 t)
5459 ((nth 4 state) ;Inside any comment (hence /**/)
5460 (search-forward "*/"))
5461 (t
5462 nil))))
5463
5464(defun verilog-skip-backward-comment-or-string ()
5465 "Return true if in a string or comment."
d63b01e1 5466 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5467 (cond
5468 ((nth 3 state) ;Inside string
5469 (search-backward "\"")
5470 t)
5471 ((nth 7 state) ;Inside // comment
5472 (search-backward "//")
5473 (skip-chars-backward "/")
5474 t)
5475 ((nth 4 state) ;Inside /* */ comment
5476 (search-backward "/*")
5477 t)
5478 (t
5479 nil))))
5480
5481(defun verilog-skip-backward-comments ()
5482 "Return true if a comment was skipped."
5483 (let ((more t))
5484 (while more
5485 (setq more
d63b01e1 5486 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
5487 (cond
5488 ((nth 7 state) ;Inside // comment
5489 (search-backward "//")
5490 (skip-chars-backward "/")
5491 (skip-chars-backward " \t\n\f")
5492 t)
5493 ((nth 4 state) ;Inside /* */ comment
5494 (search-backward "/*")
5495 (skip-chars-backward " \t\n\f")
5496 t)
5497 ((and (not (bobp))
5498 (= (char-before) ?\/)
60618039 5499 (= (char-before (1- (point))) ?\*))
6341f357 5500 (goto-char (- (point) 2))
a03c2342
WS
5501 t) ;; Let nth 4 state handle the rest
5502 ((and (not (bobp))
5503 (= (char-before) ?\))
5504 (= (char-before (1- (point))) ?\*))
5505 (goto-char (- (point) 2))
5506 (if (search-backward "(*" nil t)
5507 (progn
5508 (skip-chars-backward " \t\n\f")
5509 t)
5510 (progn
5511 (goto-char (+ (point) 2))
5512 nil)))
6341f357 5513 (t
a03c2342 5514 (/= (skip-chars-backward " \t\n\f") 0))))))))
6341f357
DN
5515
5516(defun verilog-skip-forward-comment-p ()
5517 "If in comment, move to end and return true."
a03c2342
WS
5518 (let* (h
5519 (state (save-excursion (verilog-syntax-ppss)))
5520 (skip (cond
5521 ((nth 3 state) ;Inside string
5522 t)
5523 ((nth 7 state) ;Inside // comment
5524 (end-of-line)
5525 (forward-char 1)
5526 t)
5527 ((nth 4 state) ;Inside /* comment
5528 (search-forward "*/")
5529 t)
5530 ((verilog-in-attribute-p) ;Inside (* attribute
5531 (search-forward "*)" nil t)
5532 t)
5533 (t nil))))
5534 (skip-chars-forward " \t\n\f")
5535 (while
5536 (cond
5537 ((looking-at "\\/\\*")
5538 (progn
5539 (setq h (point))
5540 (goto-char (match-end 0))
5541 (if (search-forward "*/" nil t)
5542 (progn
5543 (skip-chars-forward " \t\n\f")
5544 (setq skip 't))
5545 (progn
5546 (goto-char h)
5547 nil))))
5548 ((looking-at "(\\*")
5549 (progn
5550 (setq h (point))
5551 (goto-char (match-end 0))
5552 (if (search-forward "*)" nil t)
5553 (progn
5554 (skip-chars-forward " \t\n\f")
5555 (setq skip 't))
5556 (progn
5557 (goto-char h)
5558 nil))))
5559 (t nil)))
5560 skip))
6341f357
DN
5561
5562(defun verilog-indent-line-relative ()
5563 "Cheap version of indent line.
5564Only look at a few lines to determine indent level."
5565 (interactive)
5566 (let ((indent-str)
5567 (sp (point)))
5568 (if (looking-at "^[ \t]*$")
5569 (cond ;- A blank line; No need to be too smart.
5570 ((bobp)
5571 (setq indent-str (list 'cpp 0)))
5572 ((verilog-continued-line)
5573 (let ((sp1 (point)))
5574 (if (verilog-continued-line)
7ea26faf
DN
5575 (progn
5576 (goto-char sp)
60618039
DN
5577 (setq indent-str
5578 (list 'statement (verilog-current-indent-level))))
6341f357
DN
5579 (goto-char sp1)
5580 (setq indent-str (list 'block (verilog-current-indent-level)))))
5581 (goto-char sp))
5582 ((goto-char sp)
5583 (setq indent-str (verilog-calculate-indent))))
5584 (progn (skip-chars-forward " \t")
5585 (setq indent-str (verilog-calculate-indent))))
5586 (verilog-do-indent indent-str)))
5587
5588(defun verilog-indent-line ()
5589 "Indent for special part of code."
5590 (verilog-do-indent (verilog-calculate-indent)))
5591
5592(defun verilog-do-indent (indent-str)
5593 (let ((type (car indent-str))
5594 (ind (car (cdr indent-str))))
5595 (cond
5596 (; handle continued exp
5597 (eq type 'cexp)
5598 (let ((here (point)))
5599 (verilog-backward-syntactic-ws)
5600 (cond
5601 ((or
5602 (= (preceding-char) ?\,)
5603 (= (preceding-char) ?\])
5604 (save-excursion
5605 (verilog-beg-of-statement-1)
5606 (looking-at verilog-declaration-re)))
5607 (let* ( fst
5608 (val
5609 (save-excursion
5610 (backward-char 1)
5611 (verilog-beg-of-statement-1)
5612 (setq fst (point))
5613 (if (looking-at verilog-declaration-re)
5614 (progn ;; we have multiple words
5615 (goto-char (match-end 0))
5616 (skip-chars-forward " \t")
5617 (cond
5618 ((and verilog-indent-declaration-macros
5619 (= (following-char) ?\`))
5620 (progn
5621 (forward-char 1)
5622 (forward-word 1)
5623 (skip-chars-forward " \t")))
5624 ((= (following-char) ?\[)
5625 (progn
5626 (forward-char 1)
a03c2342 5627 (verilog-backward-up-list -1)
60618039 5628 (skip-chars-forward " \t"))))
6341f357
DN
5629 (current-column))
5630 (progn
5631 (goto-char fst)
60618039 5632 (+ (current-column) verilog-cexp-indent))))))
6341f357 5633 (goto-char here)
60618039 5634 (indent-line-to val)))
6341f357
DN
5635 ((= (preceding-char) ?\) )
5636 (goto-char here)
5637 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5638 (indent-line-to val)))
5639 (t
5640 (goto-char here)
5641 (let ((val))
5642 (verilog-beg-of-statement-1)
5643 (if (and (< (point) here)
5644 (verilog-re-search-forward "=[ \\t]*" here 'move))
5645 (setq val (current-column))
5646 (setq val (eval (cdr (assoc type verilog-indent-alist)))))
5647 (goto-char here)
60618039 5648 (indent-line-to val))))))
6341f357
DN
5649
5650 (; handle inside parenthetical expressions
5651 (eq type 'cparenexp)
a03c2342
WS
5652 (let* ( here
5653 (val (save-excursion
5654 (verilog-backward-up-list 1)
5655 (forward-char 1)
5656 (if verilog-indent-lists
5657 (skip-chars-forward " \t")
5658 (verilog-forward-syntactic-ws))
5659 (setq here (point))
5660 (current-column)))
5661
5662 (decl (save-excursion
5663 (goto-char here)
5664 (verilog-forward-syntactic-ws)
5665 (setq here (point))
5666 (looking-at verilog-declaration-re))))
5667 (indent-line-to val)
5668 (if decl
5669 (verilog-pretty-declarations))))
a3a8b002 5670
6341f357
DN
5671 (;-- Handle the ends
5672 (or
5673 (looking-at verilog-end-block-re )
5674 (verilog-at-close-constraint-p))
5675 (let ((val (if (eq type 'statement)
5676 (- ind verilog-indent-level)
5677 ind)))
5678 (indent-line-to val)))
5679
5680 (;-- Case -- maybe line 'em up
5681 (and (eq type 'case) (not (looking-at "^[ \t]*$")))
5682 (progn
5683 (cond
5684 ((looking-at "\\<endcase\\>")
5685 (indent-line-to ind))
5686 (t
5687 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5688 (indent-line-to val))))))
5689
5690 (;-- defun
5691 (and (eq type 'defun)
5692 (looking-at verilog-zero-indent-re))
5693 (indent-line-to 0))
5694
5695 (;-- declaration
5696 (and (or
5697 (eq type 'defun)
5698 (eq type 'block))
5699 (looking-at verilog-declaration-re))
5700 (verilog-indent-declaration ind))
5701
5702 (;-- Everything else
5703 t
5704 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
60618039
DN
5705 (indent-line-to val))))
5706
6341f357
DN
5707 (if (looking-at "[ \t]+$")
5708 (skip-chars-forward " \t"))
5709 indent-str ; Return indent data
5710 ))
5711
5712(defun verilog-current-indent-level ()
37ea4b9b 5713 "Return the indent-level of the current statement."
6341f357
DN
5714 (save-excursion
5715 (let (par-pos)
5716 (beginning-of-line)
5717 (setq par-pos (verilog-parenthesis-depth))
5718 (while par-pos
5719 (goto-char par-pos)
5720 (beginning-of-line)
5721 (setq par-pos (verilog-parenthesis-depth)))
5722 (skip-chars-forward " \t")
5723 (current-column))))
5724
5725(defun verilog-case-indent-level ()
37ea4b9b 5726 "Return the indent-level of the current statement.
6341f357
DN
5727Do not count named blocks or case-statements."
5728 (save-excursion
5729 (skip-chars-forward " \t")
5730 (cond
5731 ((looking-at verilog-named-block-re)
5732 (current-column))
a3a8b002 5733 ((and (not (looking-at verilog-extended-case-re))
6341f357
DN
5734 (looking-at "^[^:;]+[ \t]*:"))
5735 (verilog-re-search-forward ":" nil t)
5736 (skip-chars-forward " \t")
5737 (current-column))
5738 (t
5739 (current-column)))))
5740
5741(defun verilog-indent-comment ()
5742 "Indent current line as comment."
5743 (let* ((stcol
5744 (cond
5745 ((verilog-in-star-comment-p)
5746 (save-excursion
5747 (re-search-backward "/\\*" nil t)
5748 (1+(current-column))))
5749 (comment-column
5750 comment-column )
5751 (t
5752 (save-excursion
5753 (re-search-backward "//" nil t)
60618039 5754 (current-column))))))
6341f357
DN
5755 (indent-line-to stcol)
5756 stcol))
5757
5758(defun verilog-more-comment ()
5759 "Make more comment lines like the previous."
5760 (let* ((star 0)
5761 (stcol
5762 (cond
5763 ((verilog-in-star-comment-p)
5764 (save-excursion
5765 (setq star 1)
5766 (re-search-backward "/\\*" nil t)
5767 (1+(current-column))))
5768 (comment-column
5769 comment-column )
5770 (t
5771 (save-excursion
5772 (re-search-backward "//" nil t)
60618039 5773 (current-column))))))
6341f357
DN
5774 (progn
5775 (indent-to stcol)
5776 (if (and star
5777 (save-excursion
5778 (forward-line -1)
5779 (skip-chars-forward " \t")
5780 (looking-at "\*")))
5781 (insert "* ")))))
5782
5783(defun verilog-comment-indent (&optional arg)
5784 "Return the column number the line should be indented to.
5785ARG is ignored, for `comment-indent-function' compatibility."
5786 (cond
5787 ((verilog-in-star-comment-p)
5788 (save-excursion
5789 (re-search-backward "/\\*" nil t)
5790 (1+(current-column))))
5791 ( comment-column
5792 comment-column )
5793 (t
5794 (save-excursion
5795 (re-search-backward "//" nil t)
5796 (current-column)))))
5797
5798;;
5799
7e2a6000 5800(defun verilog-pretty-declarations (&optional quiet)
a3a8b002
DN
5801 "Line up declarations around point.
5802Be verbose about progress unless optional QUIET set."
6341f357 5803 (interactive)
a03c2342
WS
5804 (let* ((m1 (make-marker))
5805 (e (point))
5806 el
5807 r
5808 (here (point))
5809 ind
5810 start
5811 startpos
5812 end
5813 endpos
5814 base-ind
5815 )
5816 (save-excursion
5817 (if (progn
5818; (verilog-beg-of-statement-1)
5819 (beginning-of-line)
5820 (verilog-forward-syntactic-ws)
5821 (and (not (verilog-in-directive-p)) ;; could have `define input foo
a3a8b002 5822 (looking-at verilog-declaration-re)))
a03c2342
WS
5823 (progn
5824 (if (verilog-parenthesis-depth)
5825 ;; in an argument list or parameter block
5826 (setq el (verilog-backward-up-list -1)
5827 start (progn
5828 (goto-char e)
5829 (verilog-backward-up-list 1)
5830 (forward-line) ;; ignore ( input foo,
5831 (verilog-re-search-forward verilog-declaration-re el 'move)
5832 (goto-char (match-beginning 0))
5833 (skip-chars-backward " \t")
5834 (point))
5835 startpos (set-marker (make-marker) start)
5836 end (progn
5837 (goto-char start)
5838 (verilog-backward-up-list -1)
5839 (forward-char -1)
5840 (verilog-backward-syntactic-ws)
5841 (point))
5842 endpos (set-marker (make-marker) end)
5843 base-ind (progn
5844 (goto-char start)
5845 (forward-char 1)
5846 (skip-chars-forward " \t")
5847 (current-column))
5848 )
5849 ;; in a declaration block (not in argument list)
5850 (setq
5851 start (progn
5852 (verilog-beg-of-statement-1)
5853 (while (and (looking-at verilog-declaration-re)
5854 (not (bobp)))
5855 (skip-chars-backward " \t")
5856 (setq e (point))
5857 (beginning-of-line)
5858 (verilog-backward-syntactic-ws)
5859 (backward-char)
5860 (verilog-beg-of-statement-1))
5861 e)
5862 startpos (set-marker (make-marker) start)
5863 end (progn
5864 (goto-char here)
5865 (verilog-end-of-statement)
5866 (setq e (point)) ;Might be on last line
5867 (verilog-forward-syntactic-ws)
5868 (while (looking-at verilog-declaration-re)
5869 (verilog-end-of-statement)
5870 (setq e (point))
5871 (verilog-forward-syntactic-ws))
5872 e)
5873 endpos (set-marker (make-marker) end)
5874 base-ind (progn
5875 (goto-char start)
5876 (verilog-do-indent (verilog-calculate-indent))
5877 (verilog-forward-ws&directives)
5878 (current-column))))
5879 ;; OK, start and end are set
5880 (goto-char (marker-position startpos))
5881 (if (and (not quiet)
5882 (> (- end start) 100))
5883 (message "Lining up declarations..(please stand by)"))
5884 ;; Get the beginning of line indent first
5885 (while (progn (setq e (marker-position endpos))
5886 (< (point) e))
5887 (cond
5888 ((save-excursion (skip-chars-backward " \t")
5889 (bolp))
5890 (verilog-forward-ws&directives)
5891 (indent-line-to base-ind)
5892 (verilog-forward-ws&directives)
5893 (if (< (point) e)
5894 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5895 (t
5896 (just-one-space)
5897 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5898 ;;(forward-line)
5899 )
5900 ;; Now find biggest prefix
5901 (setq ind (verilog-get-lineup-indent (marker-position startpos) endpos))
5902 ;; Now indent each line.
5903 (goto-char (marker-position startpos))
5904 (while (progn (setq e (marker-position endpos))
5905 (setq r (- e (point)))
5906 (> r 0))
5907 (setq e (point))
5908 (unless quiet (message "%d" r))
5909 ;;(verilog-do-indent (verilog-calculate-indent)))
5910 (verilog-forward-ws&directives)
5911 (cond
5912 ((or (and verilog-indent-declaration-macros
5913 (looking-at verilog-declaration-re-2-macro))
5914 (looking-at verilog-declaration-re-2-no-macro))
5915 (let ((p (match-end 0)))
5916 (set-marker m1 p)
5917 (if (verilog-re-search-forward "[[#`]" p 'move)
5918 (progn
5919 (forward-char -1)
5920 (just-one-space)
5921 (goto-char (marker-position m1))
5922 (just-one-space)
5923 (indent-to ind))
5924 (progn
5925 (just-one-space)
5926 (indent-to ind)))))
5927 ((verilog-continued-line-1 (marker-position startpos))
5928 (goto-char e)
5929 (indent-line-to ind))
5930 ((verilog-in-struct-p)
5931 ;; could have a declaration of a user defined item
5932 (goto-char e)
5933 (verilog-end-of-statement))
5934 (t ; Must be comment or white space
5935 (goto-char e)
5936 (verilog-forward-ws&directives)
5937 (forward-line -1)))
5938 (forward-line 1))
5939 (unless quiet (message "")))))))
6341f357 5940
7e2a6000 5941(defun verilog-pretty-expr (&optional quiet myre)
0e5c8aed 5942 "Line up expressions around point, optionally QUIET with regexp MYRE."
a03c2342 5943 (interactive "i\nsRegular Expression: ((<|:)?=) ")
6341f357
DN
5944 (save-excursion
5945 (if (or (eq myre nil)
5946 (string-equal myre ""))
5947 (setq myre "\\(<\\|:\\)?="))
a03c2342
WS
5948 ;; want to match the first <= | := | =
5949 (setq myre (concat "\\(^.*?\\)\\(" myre "\\)"))
7e2a6000
DN
5950 (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
5951 (beginning-of-line)
5952 (if (and (not (looking-at rexp ))
a3a8b002
DN
5953 (looking-at myre)
5954 (save-excursion
5955 (goto-char (match-beginning 2))
5956 (not (verilog-in-comment-or-string-p))))
5957 (let* ((here (point))
5958 (e) (r)
5959 (start
5960 (progn
5961 (beginning-of-line)
5962 (setq e (point))
5963 (verilog-backward-syntactic-ws)
5964 (beginning-of-line)
5965 (while (and (not (looking-at rexp ))
5966 (looking-at myre)
5967 (not (bobp))
5968 )
5969 (setq e (point))
5970 (verilog-backward-syntactic-ws)
5971 (beginning-of-line)
5972 ) ;Ack, need to grok `define
5973 e))
5974 (end
5975 (progn
5976 (goto-char here)
5977 (end-of-line)
5978 (setq e (point)) ;Might be on last line
5979 (verilog-forward-syntactic-ws)
5980 (beginning-of-line)
5981 (while (and
5982 (not (looking-at rexp ))
5983 (looking-at myre)
5984 (progn
5985 (end-of-line)
5986 (not (eq e (point)))))
5987 (setq e (point))
5988 (verilog-forward-syntactic-ws)
5989 (beginning-of-line)
5990 )
5991 e))
a03c2342 5992 (endpos (set-marker (make-marker) end))
a3a8b002
DN
5993 (ind)
5994 )
5995 (goto-char start)
5996 (verilog-do-indent (verilog-calculate-indent))
5997 (if (and (not quiet)
5998 (> (- end start) 100))
5999 (message "Lining up expressions..(please stand by)"))
6000
6001 ;; Set indent to minimum throughout region
a03c2342 6002 (while (< (point) (marker-position endpos))
a3a8b002
DN
6003 (beginning-of-line)
6004 (verilog-just-one-space myre)
6005 (end-of-line)
6006 (verilog-forward-syntactic-ws)
6007 )
6008
6009 ;; Now find biggest prefix
a03c2342 6010 (setq ind (verilog-get-lineup-indent-2 myre start endpos))
a3a8b002
DN
6011
6012 ;; Now indent each line.
6013 (goto-char start)
a03c2342 6014 (while (progn (setq e (marker-position endpos))
a3a8b002
DN
6015 (setq r (- e (point)))
6016 (> r 0))
6017 (setq e (point))
6018 (if (not quiet) (message "%d" r))
6019 (cond
6020 ((looking-at myre)
6021 (goto-char (match-beginning 2))
86a4c7ac 6022 (if (not (verilog-parenthesis-depth)) ;; ignore parenthesized exprs
a3a8b002
DN
6023 (if (eq (char-after) ?=)
6024 (indent-to (1+ ind)) ; line up the = of the <= with surrounding =
6025 (indent-to ind)
6026 )))
6027 ((verilog-continued-line-1 start)
6028 (goto-char e)
6029 (indent-line-to ind))
6030 (t ; Must be comment or white space
6031 (goto-char e)
6032 (verilog-forward-ws&directives)
6033 (forward-line -1))
6034 )
6035 (forward-line 1))
6036 (unless quiet (message ""))
6037 )))))
6341f357
DN
6038
6039(defun verilog-just-one-space (myre)
6040 "Remove extra spaces around regular expression MYRE."
6041 (interactive)
6042 (if (and (not(looking-at verilog-complete-reg))
6043 (looking-at myre))
6044 (let ((p1 (match-end 1))
6045 (p2 (match-end 2)))
6046 (progn
6047 (goto-char p2)
60618039 6048 (if (looking-at "\\s-") (just-one-space))
6341f357
DN
6049 (goto-char p1)
6050 (forward-char -1)
7e2a6000
DN
6051 (if (looking-at "\\s-") (just-one-space))
6052 ))))
6341f357
DN
6053
6054(defun verilog-indent-declaration (baseind)
6055 "Indent current lines as declaration.
6056Line up the variable names based on previous declaration's indentation.
6057BASEIND is the base indent to offset everything."
6058 (interactive)
6059 (let ((pos (point-marker))
6060 (lim (save-excursion
6061 ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
6062 (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
6063 (point)))
6064 (ind)
6065 (val)
60618039 6066 (m1 (make-marker)))
7ea26faf
DN
6067 (setq val
6068 (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6341f357
DN
6069 (indent-line-to val)
6070
6071 ;; Use previous declaration (in this module) as template.
a3a8b002
DN
6072 (if (or (eq 'all verilog-auto-lineup)
6073 (eq 'declarations verilog-auto-lineup))
6edb5716 6074 (if (verilog-re-search-backward
6341f357
DN
6075 (or (and verilog-indent-declaration-macros
6076 verilog-declaration-re-1-macro)
6077 verilog-declaration-re-1-no-macro) lim t)
6078 (progn
6079 (goto-char (match-end 0))
6080 (skip-chars-forward " \t")
6081 (setq ind (current-column))
6082 (goto-char pos)
7ea26faf
DN
6083 (setq val
6084 (+ baseind
6085 (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6341f357
DN
6086 (indent-line-to val)
6087 (if (and verilog-indent-declaration-macros
6088 (looking-at verilog-declaration-re-2-macro))
6089 (let ((p (match-end 0)))
6090 (set-marker m1 p)
6091 (if (verilog-re-search-forward "[[#`]" p 'move)
6092 (progn
6093 (forward-char -1)
6094 (just-one-space)
6095 (goto-char (marker-position m1))
6096 (just-one-space)
60618039 6097 (indent-to ind))
6341f357
DN
6098 (if (/= (current-column) ind)
6099 (progn
6100 (just-one-space)
60618039 6101 (indent-to ind)))))
6341f357
DN
6102 (if (looking-at verilog-declaration-re-2-no-macro)
6103 (let ((p (match-end 0)))
6104 (set-marker m1 p)
6105 (if (verilog-re-search-forward "[[`#]" p 'move)
6106 (progn
6107 (forward-char -1)
6108 (just-one-space)
6109 (goto-char (marker-position m1))
6110 (just-one-space)
6111 (indent-to ind))
6112 (if (/= (current-column) ind)
6113 (progn
6114 (just-one-space)
7ea26faf
DN
6115 (indent-to ind))))))))))
6116 (goto-char pos)))
6341f357
DN
6117
6118(defun verilog-get-lineup-indent (b edpos)
6119 "Return the indent level that will line up several lines within the region.
6120Region is defined by B and EDPOS."
6121 (save-excursion
6122 (let ((ind 0) e)
6123 (goto-char b)
6124 ;; Get rightmost position
6125 (while (progn (setq e (marker-position edpos))
6126 (< (point) e))
6edb5716 6127 (if (verilog-re-search-forward
6341f357
DN
6128 (or (and verilog-indent-declaration-macros
6129 verilog-declaration-re-1-macro)
6130 verilog-declaration-re-1-no-macro) e 'move)
6131 (progn
6132 (goto-char (match-end 0))
6133 (verilog-backward-syntactic-ws)
6134 (if (> (current-column) ind)
6135 (setq ind (current-column)))
6136 (goto-char (match-end 0)))))
6137 (if (> ind 0)
6138 (1+ ind)
6139 ;; No lineup-string found
6140 (goto-char b)
6141 (end-of-line)
a03c2342
WS
6142 (verilog-backward-syntactic-ws)
6143 ;;(skip-chars-backward " \t")
6341f357
DN
6144 (1+ (current-column))))))
6145
6146(defun verilog-get-lineup-indent-2 (myre b edpos)
6147 "Return the indent level that will line up several lines within the region."
6148 (save-excursion
6149 (let ((ind 0) e)
6150 (goto-char b)
6151 ;; Get rightmost position
6152 (while (progn (setq e (marker-position edpos))
6153 (< (point) e))
7e2a6000 6154 (if (and (verilog-re-search-forward myre e 'move)
86a4c7ac 6155 (not (verilog-parenthesis-depth))) ;; skip parenthesized exprs
6341f357 6156 (progn
7e2a6000 6157 (goto-char (match-beginning 2))
6341f357
DN
6158 (verilog-backward-syntactic-ws)
6159 (if (> (current-column) ind)
6160 (setq ind (current-column)))
7e2a6000
DN
6161 (goto-char (match-end 0)))
6162 ))
6341f357
DN
6163 (if (> ind 0)
6164 (1+ ind)
6165 ;; No lineup-string found
6166 (goto-char b)
6167 (end-of-line)
6168 (skip-chars-backward " \t")
6169 (1+ (current-column))))))
6170
6171(defun verilog-comment-depth (type val)
6172 "A useful mode debugging aide. TYPE and VAL are comments for insertion."
6173 (save-excursion
6174 (let
6175 ((b (prog2
6176 (beginning-of-line)
6177 (point-marker)
6178 (end-of-line)))
6179 (e (point-marker)))
6180 (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
6181 (progn
6182 (replace-match " /* -# ## */")
6183 (end-of-line))
6184 (progn
6185 (end-of-line)
6186 (insert " /* ## ## */"))))
6187 (backward-char 6)
6188 (insert
6189 (format "%s %d" type val))))
6190
6191;; \f
6192;;
6193;; Completion
6194;;
6195(defvar verilog-str nil)
6196(defvar verilog-all nil)
6197(defvar verilog-pred nil)
6198(defvar verilog-buffer-to-use nil)
6199(defvar verilog-flag nil)
6200(defvar verilog-toggle-completions nil
6201 "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
6202Repeated use of \\[verilog-complete-word] will show you all of them.
6203Normally, when there is more than one possible completion,
6204it displays a list of all possible completions.")
6205
6206
6207(defvar verilog-type-keywords
6208 '(
6209 "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
6210 "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
a03c2342 6211 "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
6341f357
DN
6212 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
6213 "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
6214 "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
6215 )
6216 "*Keywords for types used when completing a word in a declaration or parmlist.
0e5c8aed 6217\(integer, real, reg...)")
6341f357
DN
6218
6219(defvar verilog-cpp-keywords
6220 '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
6221 "endif")
6222 "*Keywords to complete when at first word of a line in declarative scope.
0e5c8aed 6223\(initial, always, begin, assign...)
6341f357 6224The procedures and variables defined within the Verilog program
37ea4b9b 6225will be completed at runtime and should not be added to this list.")
6341f357
DN
6226
6227(defvar verilog-defun-keywords
6228 (append
6229 '(
6230 "always" "always_comb" "always_ff" "always_latch" "assign"
6231 "begin" "end" "generate" "endgenerate" "module" "endmodule"
6232 "specify" "endspecify" "function" "endfunction" "initial" "final"
6233 "task" "endtask" "primitive" "endprimitive"
6234 )
6235 verilog-type-keywords)
6236 "*Keywords to complete when at first word of a line in declarative scope.
0e5c8aed 6237\(initial, always, begin, assign...)
6341f357 6238The procedures and variables defined within the Verilog program
37ea4b9b 6239will be completed at runtime and should not be added to this list.")
6341f357
DN
6240
6241(defvar verilog-block-keywords
6242 '(
6243 "begin" "break" "case" "continue" "else" "end" "endfunction"
6244 "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
6245 "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
6246 "while")
6247 "*Keywords to complete when at first word of a line in behavioral scope.
0e5c8aed 6248\(begin, if, then, else, for, fork...)
6341f357 6249The procedures and variables defined within the Verilog program
37ea4b9b 6250will be completed at runtime and should not be added to this list.")
6341f357
DN
6251
6252(defvar verilog-tf-keywords
6253 '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
6254 "*Keywords to complete when at first word of a line in a task or function.
0e5c8aed 6255\(begin, if, then, else, for, fork.)
6341f357 6256The procedures and variables defined within the Verilog program
37ea4b9b 6257will be completed at runtime and should not be added to this list.")
6341f357
DN
6258
6259(defvar verilog-case-keywords
6260 '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
6261 "*Keywords to complete when at first word of a line in case scope.
0e5c8aed 6262\(begin, if, then, else, for, fork...)
6341f357 6263The procedures and variables defined within the Verilog program
37ea4b9b 6264will be completed at runtime and should not be added to this list.")
6341f357
DN
6265
6266(defvar verilog-separator-keywords
6267 '("else" "then" "begin")
6268 "*Keywords to complete when NOT standing at the first word of a statement.
0e5c8aed 6269\(else, then, begin...)
37ea4b9b
JB
6270Variables and function names defined within the Verilog program
6271will be completed at runtime and should not be added to this list.")
6341f357 6272
a03c2342
WS
6273(defvar verilog-gate-ios
6274 ;; All these have an implied {"input"...} at the end
6275 '(("and" "output")
6276 ("buf" "output")
6277 ("bufif0" "output")
6278 ("bufif1" "output")
6279 ("cmos" "output")
6280 ("nand" "output")
6281 ("nmos" "output")
6282 ("nor" "output")
6283 ("not" "output")
6284 ("notif0" "output")
6285 ("notif1" "output")
6286 ("or" "output")
6287 ("pmos" "output")
6288 ("pulldown" "output")
6289 ("pullup" "output")
6290 ("rcmos" "output")
6291 ("rnmos" "output")
6292 ("rpmos" "output")
6293 ("rtran" "inout" "inout")
6294 ("rtranif0" "inout" "inout")
6295 ("rtranif1" "inout" "inout")
6296 ("tran" "inout" "inout")
6297 ("tranif0" "inout" "inout")
6298 ("tranif1" "inout" "inout")
6299 ("xnor" "output")
6300 ("xor" "output"))
6301 "*Map of direction for each positional argument to each gate primitive.")
6302
6303(defvar verilog-gate-keywords (mapcar `car verilog-gate-ios)
6304 "*Keywords for gate primitives.")
6305
6341f357
DN
6306(defun verilog-string-diff (str1 str2)
6307 "Return index of first letter where STR1 and STR2 differs."
6308 (catch 'done
6309 (let ((diff 0))
6310 (while t
6311 (if (or (> (1+ diff) (length str1))
6312 (> (1+ diff) (length str2)))
6313 (throw 'done diff))
6314 (or (equal (aref str1 diff) (aref str2 diff))
6315 (throw 'done diff))
6316 (setq diff (1+ diff))))))
6317
6318;; Calculate all possible completions for functions if argument is `function',
6319;; completions for procedures if argument is `procedure' or both functions and
6320;; procedures otherwise.
6321
6322(defun verilog-func-completion (type)
6323 "Build regular expression for module/task/function names.
6324TYPE is 'module, 'tf for task or function, or t if unknown."
6325 (if (string= verilog-str "")
6326 (setq verilog-str "[a-zA-Z_]"))
6327 (let ((verilog-str (concat (cond
6328 ((eq type 'module) "\\<\\(module\\)\\s +")
6329 ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
6330 (t "\\<\\(task\\|function\\|module\\)\\s +"))
6331 "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
6332 match)
6333
6334 (if (not (looking-at verilog-defun-re))
6335 (verilog-re-search-backward verilog-defun-re nil t))
6336 (forward-char 1)
6337
6338 ;; Search through all reachable functions
6339 (goto-char (point-min))
6340 (while (verilog-re-search-forward verilog-str (point-max) t)
6341 (progn (setq match (buffer-substring (match-beginning 2)
6342 (match-end 2)))
6343 (if (or (null verilog-pred)
6344 (funcall verilog-pred match))
6345 (setq verilog-all (cons match verilog-all)))))
6346 (if (match-beginning 0)
6347 (goto-char (match-beginning 0)))))
6348
6349(defun verilog-get-completion-decl (end)
6350 "Macro for searching through current declaration (var, type or const)
6351for matches of `str' and adding the occurrence tp `all' through point END."
6352 (let ((re (or (and verilog-indent-declaration-macros
6353 verilog-declaration-re-2-macro)
6354 verilog-declaration-re-2-no-macro))
6355 decl-end match)
6356 ;; Traverse lines
6357 (while (and (< (point) end)
6358 (verilog-re-search-forward re end t))
6359 ;; Traverse current line
6360 (setq decl-end (save-excursion (verilog-declaration-end)))
6361 (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
6362 (not (match-end 1)))
6363 (setq match (buffer-substring (match-beginning 0) (match-end 0)))
6364 (if (string-match (concat "\\<" verilog-str) match)
6365 (if (or (null verilog-pred)
6366 (funcall verilog-pred match))
6367 (setq verilog-all (cons match verilog-all)))))
60618039
DN
6368 (forward-line 1)))
6369 verilog-all)
6341f357
DN
6370
6371(defun verilog-type-completion ()
6372 "Calculate all possible completions for types."
6373 (let ((start (point))
6374 goon)
6375 ;; Search for all reachable type declarations
6376 (while (or (verilog-beg-of-defun)
6377 (setq goon (not goon)))
6378 (save-excursion
6379 (if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
6380 (point))
6381 (forward-char 1)))
6382 (verilog-re-search-forward
6383 "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
6384 start t)
6385 (not (match-end 1)))
6386 ;; Check current type declaration
6387 (verilog-get-completion-decl start))))))
6388
6389(defun verilog-var-completion ()
6390 "Calculate all possible completions for variables (or constants)."
6391 (let ((start (point)))
6392 ;; Search for all reachable var declarations
6393 (verilog-beg-of-defun)
6394 (save-excursion
6395 ;; Check var declarations
6396 (verilog-get-completion-decl start))))
6397
6398(defun verilog-keyword-completion (keyword-list)
6399 "Give list of all possible completions of keywords in KEYWORD-LIST."
6400 (mapcar '(lambda (s)
6401 (if (string-match (concat "\\<" verilog-str) s)
6402 (if (or (null verilog-pred)
6403 (funcall verilog-pred s))
6404 (setq verilog-all (cons s verilog-all)))))
6405 keyword-list))
6406
6407
6408(defun verilog-completion (verilog-str verilog-pred verilog-flag)
6409 "Function passed to `completing-read', `try-completion' or `all-completions'.
6410Called to get completion on VERILOG-STR. If VERILOG-PRED is non-nil, it
6411must be a function to be called for every match to check if this should
37ea4b9b
JB
6412really be a match. If VERILOG-FLAG is t, the function returns a list of
6413all possible completions. If VERILOG-FLAG is nil it returns a string,
6414the longest possible completion, or t if VERILOG-STR is an exact match.
6415If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
6416exact match, nil otherwise."
6341f357
DN
6417 (save-excursion
6418 (let ((verilog-all nil))
6419 ;; Set buffer to use for searching labels. This should be set
6420 ;; within functions which use verilog-completions
6421 (set-buffer verilog-buffer-to-use)
6422
6423 ;; Determine what should be completed
6424 (let ((state (car (verilog-calculate-indent))))
6425 (cond ((eq state 'defun)
6426 (save-excursion (verilog-var-completion))
6427 (verilog-func-completion 'module)
6428 (verilog-keyword-completion verilog-defun-keywords))
6429
6430 ((eq state 'behavioral)
6431 (save-excursion (verilog-var-completion))
6432 (verilog-func-completion 'module)
6433 (verilog-keyword-completion verilog-defun-keywords))
6434
6435 ((eq state 'block)
6436 (save-excursion (verilog-var-completion))
6437 (verilog-func-completion 'tf)
6438 (verilog-keyword-completion verilog-block-keywords))
6439
6440 ((eq state 'case)
6441 (save-excursion (verilog-var-completion))
6442 (verilog-func-completion 'tf)
6443 (verilog-keyword-completion verilog-case-keywords))
6444
6445 ((eq state 'tf)
6446 (save-excursion (verilog-var-completion))
6447 (verilog-func-completion 'tf)
6448 (verilog-keyword-completion verilog-tf-keywords))
6449
6450 ((eq state 'cpp)
6451 (save-excursion (verilog-var-completion))
6452 (verilog-keyword-completion verilog-cpp-keywords))
6453
6454 ((eq state 'cparenexp)
6455 (save-excursion (verilog-var-completion)))
6456
6457 (t;--Anywhere else
6458 (save-excursion (verilog-var-completion))
6459 (verilog-func-completion 'both)
6460 (verilog-keyword-completion verilog-separator-keywords))))
6461
6462 ;; Now we have built a list of all matches. Give response to caller
6463 (verilog-completion-response))))
6464
6465(defun verilog-completion-response ()
6466 (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
6467 ;; This was not called by all-completions
6468 (if (null verilog-all)
6469 ;; Return nil if there was no matching label
6470 nil
6471 ;; Get longest string common in the labels
6472 (let* ((elm (cdr verilog-all))
6473 (match (car verilog-all))
6474 (min (length match))
6475 tmp)
6476 (if (string= match verilog-str)
6477 ;; Return t if first match was an exact match
6478 (setq match t)
6479 (while (not (null elm))
6480 ;; Find longest common string
6481 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
6482 (progn
6483 (setq min tmp)
6484 (setq match (substring match 0 min))))
6485 ;; Terminate with match=t if this is an exact match
6486 (if (string= (car elm) verilog-str)
6487 (progn
6488 (setq match t)
6489 (setq elm nil))
6490 (setq elm (cdr elm)))))
6491 ;; If this is a test just for exact match, return nil ot t
6492 (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
6493 nil
6494 match))))
6495 ;; If flag is t, this was called by all-completions. Return
6496 ;; list of all possible completions
6497 (verilog-flag
6498 verilog-all)))
6499
6500(defvar verilog-last-word-numb 0)
6501(defvar verilog-last-word-shown nil)
6502(defvar verilog-last-completions nil)
6503
6504(defun verilog-complete-word ()
6505 "Complete word at current point.
6506\(See also `verilog-toggle-completions', `verilog-type-keywords',
6507and `verilog-separator-keywords'.)"
6508 (interactive)
6509 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
6510 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
6511 (verilog-str (buffer-substring b e))
6512 ;; The following variable is used in verilog-completion
6513 (verilog-buffer-to-use (current-buffer))
6514 (allcomp (if (and verilog-toggle-completions
6515 (string= verilog-last-word-shown verilog-str))
6516 verilog-last-completions
6517 (all-completions verilog-str 'verilog-completion)))
6518 (match (if verilog-toggle-completions
6519 "" (try-completion
6520 verilog-str (mapcar '(lambda (elm)
6521 (cons elm 0)) allcomp)))))
6522 ;; Delete old string
6523 (delete-region b e)
6524
6525 ;; Toggle-completions inserts whole labels
6526 (if verilog-toggle-completions
6527 (progn
6528 ;; Update entry number in list
6529 (setq verilog-last-completions allcomp
6530 verilog-last-word-numb
6531 (if (>= verilog-last-word-numb (1- (length allcomp)))
6532 0
6533 (1+ verilog-last-word-numb)))
6534 (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
6535 ;; Display next match or same string if no match was found
6536 (if (not (null allcomp))
6537 (insert "" verilog-last-word-shown)
6538 (insert "" verilog-str)
6539 (message "(No match)")))
6540 ;; The other form of completion does not necessarily do that.
6541
6542 ;; Insert match if found, or the original string if no match
6543 (if (or (null match) (equal match 't))
6544 (progn (insert "" verilog-str)
6545 (message "(No match)"))
6546 (insert "" match))
6547 ;; Give message about current status of completion
6548 (cond ((equal match 't)
6549 (if (not (null (cdr allcomp)))
6550 (message "(Complete but not unique)")
6551 (message "(Sole completion)")))
6552 ;; Display buffer if the current completion didn't help
6553 ;; on completing the label.
6554 ((and (not (null (cdr allcomp))) (= (length verilog-str)
6555 (length match)))
6556 (with-output-to-temp-buffer "*Completions*"
6557 (display-completion-list allcomp))
6558 ;; Wait for a key press. Then delete *Completion* window
6559 (momentary-string-display "" (point))
6560 (delete-window (get-buffer-window (get-buffer "*Completions*")))
6561 )))))
6562
6563(defun verilog-show-completions ()
6564 "Show all possible completions at current point."
6565 (interactive)
6566 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
6567 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
6568 (verilog-str (buffer-substring b e))
6569 ;; The following variable is used in verilog-completion
6570 (verilog-buffer-to-use (current-buffer))
6571 (allcomp (if (and verilog-toggle-completions
6572 (string= verilog-last-word-shown verilog-str))
6573 verilog-last-completions
6574 (all-completions verilog-str 'verilog-completion))))
6575 ;; Show possible completions in a temporary buffer.
6576 (with-output-to-temp-buffer "*Completions*"
6577 (display-completion-list allcomp))
6578 ;; Wait for a key press. Then delete *Completion* window
6579 (momentary-string-display "" (point))
6580 (delete-window (get-buffer-window (get-buffer "*Completions*")))))
6581
6582
6583(defun verilog-get-default-symbol ()
6584 "Return symbol around current point as a string."
6585 (save-excursion
6586 (buffer-substring (progn
6587 (skip-chars-backward " \t")
6588 (skip-chars-backward "a-zA-Z0-9_")
6589 (point))
6590 (progn
6591 (skip-chars-forward "a-zA-Z0-9_")
6592 (point)))))
6593
6594(defun verilog-build-defun-re (str &optional arg)
6595 "Return function/task/module starting with STR as regular expression.
6596With optional second ARG non-nil, STR is the complete name of the instruction."
6597 (if arg
6598 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
6599 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
6600
6601(defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
6602 "Function passed to `completing-read', `try-completion' or `all-completions'.
6603Returns a completion on any function name based on VERILOG-STR prefix. If
6604VERILOG-PRED is non-nil, it must be a function to be called for every match
6605to check if this should really be a match. If VERILOG-FLAG is t, the
6606function returns a list of all possible completions. If it is nil it
6607returns a string, the longest possible completion, or t if VERILOG-STR is
6608an exact match. If VERILOG-FLAG is 'lambda, the function returns t if
6609VERILOG-STR is an exact match, nil otherwise."
6610 (save-excursion
6611 (let ((verilog-all nil)
6612 match)
6613
6614 ;; Set buffer to use for searching labels. This should be set
6615 ;; within functions which use verilog-completions
6616 (set-buffer verilog-buffer-to-use)
6617
6618 (let ((verilog-str verilog-str))
6619 ;; Build regular expression for functions
6620 (if (string= verilog-str "")
6621 (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
6622 (setq verilog-str (verilog-build-defun-re verilog-str)))
6623 (goto-char (point-min))
6624
6625 ;; Build a list of all possible completions
6626 (while (verilog-re-search-forward verilog-str nil t)
6627 (setq match (buffer-substring (match-beginning 2) (match-end 2)))
6628 (if (or (null verilog-pred)
6629 (funcall verilog-pred match))
6630 (setq verilog-all (cons match verilog-all)))))
6631
6632 ;; Now we have built a list of all matches. Give response to caller
6633 (verilog-completion-response))))
6634
6635(defun verilog-goto-defun ()
a03c2342 6636 "Move to specified Verilog module/interface/task/function.
6341f357
DN
6637The default is a name found in the buffer around point.
6638If search fails, other files are checked based on
6639`verilog-library-flags'."
6640 (interactive)
6641 (let* ((default (verilog-get-default-symbol))
6642 ;; The following variable is used in verilog-comp-function
6643 (verilog-buffer-to-use (current-buffer))
6644 (label (if (not (string= default ""))
6645 ;; Do completion with default
a3a8b002
DN
6646 (completing-read (concat "Goto-Label: (default "
6647 default ") ")
6341f357
DN
6648 'verilog-comp-defun nil nil "")
6649 ;; There is no default value. Complete without it
a3a8b002 6650 (completing-read "Goto-Label: "
6341f357
DN
6651 'verilog-comp-defun nil nil "")))
6652 pt)
a3a8b002
DN
6653 ;; Make sure library paths are correct, in case need to resolve module
6654 (verilog-auto-reeval-locals)
6655 (verilog-getopt-flags)
6341f357
DN
6656 ;; If there was no response on prompt, use default value
6657 (if (string= label "")
6658 (setq label default))
6659 ;; Goto right place in buffer if label is not an empty string
6660 (or (string= label "")
6661 (progn
6662 (save-excursion
6663 (goto-char (point-min))
7ea26faf
DN
6664 (setq pt
6665 (re-search-forward (verilog-build-defun-re label t) nil t)))
6341f357
DN
6666 (when pt
6667 (goto-char pt)
6668 (beginning-of-line))
6669 pt)
60618039 6670 (verilog-goto-defun-file label))))
6341f357
DN
6671
6672;; Eliminate compile warning
7d55bf04 6673(defvar occur-pos-list)
6341f357
DN
6674
6675(defun verilog-showscopes ()
6676 "List all scopes in this module."
6677 (interactive)
6678 (let ((buffer (current-buffer))
6679 (linenum 1)
6680 (nlines 0)
6681 (first 1)
6682 (prevpos (point-min))
6683 (final-context-start (make-marker))
60618039 6684 (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
6341f357
DN
6685 (with-output-to-temp-buffer "*Occur*"
6686 (save-excursion
6687 (message (format "Searching for %s ..." regexp))
6688 ;; Find next match, but give up if prev match was at end of buffer.
6689 (while (and (not (= prevpos (point-max)))
6690 (verilog-re-search-forward regexp nil t))
6691 (goto-char (match-beginning 0))
6692 (beginning-of-line)
6693 (save-match-data
6694 (setq linenum (+ linenum (count-lines prevpos (point)))))
6695 (setq prevpos (point))
6696 (goto-char (match-end 0))
6697 (let* ((start (save-excursion
6698 (goto-char (match-beginning 0))
6699 (forward-line (if (< nlines 0) nlines (- nlines)))
6700 (point)))
6701 (end (save-excursion
6702 (goto-char (match-end 0))
6703 (if (> nlines 0)
6704 (forward-line (1+ nlines))
6705 (forward-line 1))
6706 (point)))
6707 (tag (format "%3d" linenum))
6708 (empty (make-string (length tag) ?\ ))
6709 tem)
6710 (save-excursion
6711 (setq tem (make-marker))
6712 (set-marker tem (point))
6713 (set-buffer standard-output)
6714 (setq occur-pos-list (cons tem occur-pos-list))
6715 (or first (zerop nlines)
6716 (insert "--------\n"))
6717 (setq first nil)
6718 (insert-buffer-substring buffer start end)
6719 (backward-char (- end start))
6720 (setq tem (if (< nlines 0) (- nlines) nlines))
6721 (while (> tem 0)
6722 (insert empty ?:)
6723 (forward-line 1)
6724 (setq tem (1- tem)))
6725 (let ((this-linenum linenum))
6726 (set-marker final-context-start
6727 (+ (point) (- (match-end 0) (match-beginning 0))))
6728 (while (< (point) final-context-start)
6729 (if (null tag)
6730 (setq tag (format "%3d" this-linenum)))
6731 (insert tag ?:)))))))
6732 (set-buffer-modified-p nil))))
6733
6734
6735;; Highlight helper functions
6736(defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
6737(defun verilog-within-translate-off ()
6738 "Return point if within translate-off region, else nil."
6739 (and (save-excursion
6740 (re-search-backward
6741 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
6742 nil t))
6743 (equal "off" (match-string 2))
6744 (point)))
6745
6746(defun verilog-start-translate-off (limit)
6747 "Return point before translate-off directive if before LIMIT, else nil."
6748 (when (re-search-forward
6749 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6750 limit t)
6751 (match-beginning 0)))
6752
6753(defun verilog-back-to-start-translate-off (limit)
6754 "Return point before translate-off directive if before LIMIT, else nil."
6755 (when (re-search-backward
6756 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6757 limit t)
6758 (match-beginning 0)))
6759
6760(defun verilog-end-translate-off (limit)
6761 "Return point after translate-on directive if before LIMIT, else nil."
6762
6763 (re-search-forward (concat
6764 "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
6765
6766(defun verilog-match-translate-off (limit)
6767 "Match a translate-off block, setting `match-data' and returning t, else nil.
6768Bound search by LIMIT."
6769 (when (< (point) limit)
6770 (let ((start (or (verilog-within-translate-off)
6771 (verilog-start-translate-off limit)))
6772 (case-fold-search t))
6773 (when start
6774 (let ((end (or (verilog-end-translate-off limit) limit)))
6775 (set-match-data (list start end))
6776 (goto-char end))))))
6777
6778(defun verilog-font-lock-match-item (limit)
6779 "Match, and move over, any declaration item after point.
6780Bound search by LIMIT. Adapted from
6781`font-lock-match-c-style-declaration-item-and-skip-to-next'."
6782 (condition-case nil
6783 (save-restriction
6784 (narrow-to-region (point-min) limit)
6785 ;; match item
6786 (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
6787 (save-match-data
6788 (goto-char (match-end 1))
6789 ;; move to next item
6790 (if (looking-at "\\(\\s-*,\\)")
6791 (goto-char (match-end 1))
6792 (end-of-line) t))))
6793 (error nil)))
6794
6795
6796;; Added by Subbu Meiyappan for Header
6797
6798(defun verilog-header ()
a3a8b002
DN
6799 "Insert a standard Verilog file header.
6800See also `verilog-sk-header' for an alternative format."
6341f357
DN
6801 (interactive)
6802 (let ((start (point)))
6803 (insert "\
6804//-----------------------------------------------------------------------------
6805// Title : <title>
6806// Project : <project>
6807//-----------------------------------------------------------------------------
6808// File : <filename>
6809// Author : <author>
6810// Created : <credate>
6811// Last modified : <moddate>
6812//-----------------------------------------------------------------------------
6813// Description :
6814// <description>
6815//-----------------------------------------------------------------------------
6816// Copyright (c) <copydate> by <company> This model is the confidential and
6817// proprietary property of <company> and the possession or use of this
6818// file requires a written license from <company>.
6819//------------------------------------------------------------------------------
6820// Modification history :
6821// <modhist>
6822//-----------------------------------------------------------------------------
6823
6824")
6825 (goto-char start)
6826 (search-forward "<filename>")
6827 (replace-match (buffer-name) t t)
6828 (search-forward "<author>") (replace-match "" t t)
6829 (insert (user-full-name))
6830 (insert " <" (user-login-name) "@" (system-name) ">")
6831 (search-forward "<credate>") (replace-match "" t t)
6ca0ff73 6832 (verilog-insert-date)
6341f357 6833 (search-forward "<moddate>") (replace-match "" t t)
6ca0ff73 6834 (verilog-insert-date)
6341f357 6835 (search-forward "<copydate>") (replace-match "" t t)
6ca0ff73 6836 (verilog-insert-year)
6341f357 6837 (search-forward "<modhist>") (replace-match "" t t)
6ca0ff73 6838 (verilog-insert-date)
6341f357
DN
6839 (insert " : created")
6840 (goto-char start)
6841 (let (string)
6842 (setq string (read-string "title: "))
6843 (search-forward "<title>")
6844 (replace-match string t t)
6845 (setq string (read-string "project: " verilog-project))
6341f357
DN
6846 (setq verilog-project string)
6847 (search-forward "<project>")
6848 (replace-match string t t)
6849 (setq string (read-string "Company: " verilog-company))
6341f357
DN
6850 (setq verilog-company string)
6851 (search-forward "<company>")
6852 (replace-match string t t)
6853 (search-forward "<company>")
6854 (replace-match string t t)
6855 (search-forward "<company>")
6856 (replace-match string t t)
6857 (search-backward "<description>")
60618039 6858 (replace-match "" t t))))
6341f357 6859
6ca0ff73 6860;; verilog-header Uses the verilog-insert-date function
6341f357 6861
6ca0ff73 6862(defun verilog-insert-date ()
6341f357
DN
6863 "Insert date from the system."
6864 (interactive)
a3a8b002
DN
6865 (if verilog-date-scientific-format
6866 (insert (format-time-string "%Y/%m/%d"))
6867 (insert (format-time-string "%d.%m.%Y"))))
6341f357 6868
6ca0ff73 6869(defun verilog-insert-year ()
6341f357
DN
6870 "Insert year from the system."
6871 (interactive)
a3a8b002 6872 (insert (format-time-string "%Y")))
6341f357
DN
6873
6874\f
6875;;
6876;; Signal list parsing
6877;;
6878
6879;; Elements of a signal list
a03c2342
WS
6880(defsubst verilog-sig-new (name bits comment mem enum signed type multidim modport)
6881 (list name bits comment mem enum signed type multidim modport))
6341f357
DN
6882(defsubst verilog-sig-name (sig)
6883 (car sig))
6884(defsubst verilog-sig-bits (sig)
6885 (nth 1 sig))
6886(defsubst verilog-sig-comment (sig)
6887 (nth 2 sig))
6888(defsubst verilog-sig-memory (sig)
6889 (nth 3 sig))
6890(defsubst verilog-sig-enum (sig)
6891 (nth 4 sig))
6892(defsubst verilog-sig-signed (sig)
6893 (nth 5 sig))
6894(defsubst verilog-sig-type (sig)
6895 (nth 6 sig))
6896(defsubst verilog-sig-multidim (sig)
6897 (nth 7 sig))
6898(defsubst verilog-sig-multidim-string (sig)
6899 (if (verilog-sig-multidim sig)
6900 (let ((str "") (args (verilog-sig-multidim sig)))
6901 (while args
6902 (setq str (concat str (car args)))
6903 (setq args (cdr args)))
6904 str)))
a3a8b002
DN
6905(defsubst verilog-sig-modport (sig)
6906 (nth 8 sig))
6341f357
DN
6907(defsubst verilog-sig-width (sig)
6908 (verilog-make-width-expression (verilog-sig-bits sig)))
6909
a03c2342
WS
6910(defsubst verilog-alw-new (outputs temps inputs delayed)
6911 (list outputs temps inputs delayed))
6341f357
DN
6912(defsubst verilog-alw-get-outputs (sigs)
6913 (nth 0 sigs))
a03c2342
WS
6914(defsubst verilog-alw-get-temps (sigs)
6915 (nth 1 sigs))
6916(defsubst verilog-alw-get-inputs (sigs)
6917 (nth 2 sigs))
6341f357
DN
6918(defsubst verilog-alw-get-uses-delayed (sigs)
6919 (nth 3 sigs))
6920
a03c2342
WS
6921(defsubst verilog-modi-new (name fob pt type)
6922 (vector name fob pt type))
6923(defsubst verilog-modi-name (modi)
6924 (aref modi 0))
6925(defsubst verilog-modi-file-or-buffer (modi)
6926 (aref modi 1))
6927(defsubst verilog-modi-get-point (modi)
6928 (aref modi 2))
6929(defsubst verilog-modi-get-type (modi) ;; "module" or "interface"
6930 (aref modi 3))
6931(defsubst verilog-modi-get-decls (modi)
6932 (verilog-modi-cache-results modi 'verilog-read-decls))
6933(defsubst verilog-modi-get-sub-decls (modi)
6934 (verilog-modi-cache-results modi 'verilog-read-sub-decls))
6935
6936;; Signal reading for given module
6937;; Note these all take modi's - as returned from verilog-modi-current
6938(defsubst verilog-decls-new (out inout in wires regs assigns consts gparams interfaces)
6939 (vector out inout in wires regs assigns consts gparams interfaces))
6940(defsubst verilog-decls-get-outputs (decls)
6941 (aref decls 0))
6942(defsubst verilog-decls-get-inouts (decls)
6943 (aref decls 1))
6944(defsubst verilog-decls-get-inputs (decls)
6945 (aref decls 2))
6946(defsubst verilog-decls-get-wires (decls)
6947 (aref decls 3))
6948(defsubst verilog-decls-get-regs (decls)
6949 (aref decls 4))
6950(defsubst verilog-decls-get-assigns (decls)
6951 (aref decls 5))
6952(defsubst verilog-decls-get-consts (decls)
6953 (aref decls 6))
6954(defsubst verilog-decls-get-gparams (decls)
6955 (aref decls 7))
6956(defsubst verilog-decls-get-interfaces (decls)
6957 (aref decls 8))
6958
6959(defsubst verilog-subdecls-new (out inout in intf intfd)
6960 (vector out inout in intf intfd))
6961(defsubst verilog-subdecls-get-outputs (subdecls)
6962 (aref subdecls 0))
6963(defsubst verilog-subdecls-get-inouts (subdecls)
6964 (aref subdecls 1))
6965(defsubst verilog-subdecls-get-inputs (subdecls)
6966 (aref subdecls 2))
6967(defsubst verilog-subdecls-get-interfaces (subdecls)
6968 (aref subdecls 3))
6969(defsubst verilog-subdecls-get-interfaced (subdecls)
6970 (aref subdecls 4))
6971
6341f357 6972(defun verilog-signals-not-in (in-list not-list)
37ea4b9b
JB
6973 "Return list of signals in IN-LIST that aren't also in NOT-LIST.
6974Also remove any duplicates in IN-LIST.
6341f357 6975Signals must be in standard (base vector) form."
a03c2342
WS
6976 ;; This function is hot, so implemented as O(1)
6977 (cond ((eval-when-compile (fboundp 'make-hash-table))
6978 (let ((ht (make-hash-table :test 'equal :rehash-size 4.0))
6979 out-list)
6980 (while not-list
6981 (puthash (car (car not-list)) t ht)
6982 (setq not-list (cdr not-list)))
6983 (while in-list
6984 (when (not (gethash (car (car in-list)) ht))
6985 (setq out-list (cons (car in-list) out-list))
6986 (puthash (car (car in-list)) t ht))
6987 (setq in-list (cdr in-list)))
6988 (nreverse out-list)))
6989 ;; Slower Fallback if no hash tables (pre Emacs 21.1/XEmacs 21.4)
6990 (t
6991 (let (out-list)
6992 (while in-list
6993 (if (not (or (assoc (car (car in-list)) not-list)
6994 (assoc (car (car in-list)) out-list)))
6995 (setq out-list (cons (car in-list) out-list)))
6996 (setq in-list (cdr in-list)))
6997 (nreverse out-list)))))
6341f357
DN
6998;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
6999
6341f357
DN
7000(defun verilog-signals-memory (in-list)
7001 "Return list of signals in IN-LIST that are memoried (multidimensional)."
7002 (let (out-list)
7003 (while in-list
7004 (if (nth 3 (car in-list))
7005 (setq out-list (cons (car in-list) out-list)))
7006 (setq in-list (cdr in-list)))
7007 out-list))
7008;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
7009
7010(defun verilog-signals-sort-compare (a b)
7011 "Compare signal A and B for sorting."
7012 (string< (car a) (car b)))
7013
7014(defun verilog-signals-not-params (in-list)
7015 "Return list of signals in IN-LIST that aren't parameters or numeric constants."
7016 (let (out-list)
7017 (while in-list
7018 (unless (boundp (intern (concat "vh-" (car (car in-list)))))
7019 (setq out-list (cons (car in-list) out-list)))
7020 (setq in-list (cdr in-list)))
7021 (nreverse out-list)))
7022
7023(defun verilog-signals-combine-bus (in-list)
7024 "Return a list of signals in IN-LIST, with busses combined.
7025Duplicate signals are also removed. For example A[2] and A[1] become A[2:1]."
7026 (let (combo buswarn
7027 out-list
7028 sig highbit lowbit ; Temp information about current signal
7029 sv-name sv-highbit sv-lowbit ; Details about signal we are forming
7030 sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
a3a8b002 7031 sv-modport
6341f357
DN
7032 bus)
7033 ;; Shove signals so duplicated signals will be adjacent
7034 (setq in-list (sort in-list `verilog-signals-sort-compare))
7035 (while in-list
7036 (setq sig (car in-list))
7037 ;; No current signal; form from existing details
7038 (unless sv-name
7039 (setq sv-name (verilog-sig-name sig)
7040 sv-highbit nil
7041 sv-busstring nil
7042 sv-comment (verilog-sig-comment sig)
7043 sv-memory (verilog-sig-memory sig)
7044 sv-enum (verilog-sig-enum sig)
7045 sv-signed (verilog-sig-signed sig)
7046 sv-type (verilog-sig-type sig)
7047 sv-multidim (verilog-sig-multidim sig)
a3a8b002 7048 sv-modport (verilog-sig-modport sig)
6341f357 7049 combo ""
60618039 7050 buswarn ""))
6341f357
DN
7051 ;; Extract bus details
7052 (setq bus (verilog-sig-bits sig))
7053 (cond ((and bus
7054 (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
7ea26faf
DN
7055 (setq highbit (string-to-number (match-string 1 bus))
7056 lowbit (string-to-number
7057 (match-string 2 bus))))
6341f357 7058 (and (string-match "\\[\\([0-9]+\\)\\]" bus)
7ea26faf 7059 (setq highbit (string-to-number (match-string 1 bus))
6341f357
DN
7060 lowbit highbit))))
7061 ;; Combine bits in bus
7062 (if sv-highbit
7063 (setq sv-highbit (max highbit sv-highbit)
7064 sv-lowbit (min lowbit sv-lowbit))
7065 (setq sv-highbit highbit
7066 sv-lowbit lowbit)))
7067 (bus
7068 ;; String, probably something like `preproc:0
7069 (setq sv-busstring bus)))
7070 ;; Peek ahead to next signal
7071 (setq in-list (cdr in-list))
7072 (setq sig (car in-list))
7073 (cond ((and sig (equal sv-name (verilog-sig-name sig)))
7074 ;; Combine with this signal
7ea26faf
DN
7075 (when (and sv-busstring
7076 (not (equal sv-busstring (verilog-sig-bits sig))))
6341f357
DN
7077 (when nil ;; Debugging
7078 (message (concat "Warning, can't merge into single bus "
7079 sv-name bus
7080 ", the AUTOs may be wrong")))
7081 (setq buswarn ", Couldn't Merge"))
7082 (if (verilog-sig-comment sig) (setq combo ", ..."))
7083 (setq sv-memory (or sv-memory (verilog-sig-memory sig))
7084 sv-enum (or sv-enum (verilog-sig-enum sig))
7085 sv-signed (or sv-signed (verilog-sig-signed sig))
7086 sv-type (or sv-type (verilog-sig-type sig))
a3a8b002
DN
7087 sv-multidim (or sv-multidim (verilog-sig-multidim sig))
7088 sv-modport (or sv-modport (verilog-sig-modport sig))))
6341f357
DN
7089 ;; Doesn't match next signal, add to queue, zero in prep for next
7090 ;; Note sig may also be nil for the last signal in the list
7091 (t
7092 (setq out-list
a03c2342
WS
7093 (cons (verilog-sig-new
7094 sv-name
7ea26faf
DN
7095 (or sv-busstring
7096 (if sv-highbit
7097 (concat "[" (int-to-string sv-highbit) ":"
7098 (int-to-string sv-lowbit) "]")))
60618039 7099 (concat sv-comment combo buswarn)
a3a8b002 7100 sv-memory sv-enum sv-signed sv-type sv-multidim sv-modport)
a03c2342 7101 out-list)
60618039 7102 sv-name nil))))
6341f357
DN
7103 ;;
7104 out-list))
7105
7106(defun verilog-sig-tieoff (sig &optional no-width)
60618039 7107 "Return tieoff expression for given SIG, with appropriate width.
6341f357
DN
7108Ignore width if optional NO-WIDTH is set."
7109 (let* ((width (if no-width nil (verilog-sig-width sig))))
7110 (concat
7111 (if (and verilog-active-low-regexp
7112 (string-match verilog-active-low-regexp (verilog-sig-name sig)))
7113 "~" "")
7114 (cond ((not width)
7115 "0")
7116 ((string-match "^[0-9]+$" width)
7117 (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
7118 (t
7119 (concat "{" width "{1'b0}}"))))))
7120
7121;;
7122;; Port/Wire/Etc Reading
7123;;
7124
7125(defun verilog-read-inst-backward-name ()
7126 "Internal. Move point back to beginning of inst-name."
7127 (verilog-backward-open-paren)
7128 (let (done)
7129 (while (not done)
7130 (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil) ; ] isn't word boundary
7131 (cond ((looking-at ")")
7132 (verilog-backward-open-paren))
7133 (t (setq done t)))))
7134 (while (looking-at "\\]")
7135 (verilog-backward-open-bracket)
7136 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
7137 (skip-chars-backward "a-zA-Z0-9`_$"))
7138
a03c2342
WS
7139(defun verilog-read-inst-module-matcher ()
7140 "Set match data 0 with module_name when point is inside instantiation."
7141 (verilog-read-inst-backward-name)
7142 ;; Skip over instantiation name
7143 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
7144 ;; Check for parameterized instantiations
7145 (when (looking-at ")")
7146 (verilog-backward-open-paren)
7147 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
7148 (skip-chars-backward "a-zA-Z0-9'_$")
7149 (looking-at "[a-zA-Z0-9`_\$]+")
7150 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7151 (buffer-substring-no-properties (match-beginning 0) (match-end 0))
7152 ;; Caller assumes match-beginning/match-end is still set
7153 )
7154
6341f357
DN
7155(defun verilog-read-inst-module ()
7156 "Return module_name when point is inside instantiation."
7157 (save-excursion
a03c2342 7158 (verilog-read-inst-module-matcher)))
6341f357
DN
7159
7160(defun verilog-read-inst-name ()
7161 "Return instance_name when point is inside instantiation."
7162 (save-excursion
7163 (verilog-read-inst-backward-name)
7164 (looking-at "[a-zA-Z0-9`_\$]+")
d63b01e1 7165 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6341f357
DN
7166 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
7167
7168(defun verilog-read-module-name ()
7169 "Return module name when after its ( or ;."
7170 (save-excursion
7171 (re-search-backward "[(;]")
7172 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
7173 (skip-chars-backward "a-zA-Z0-9`_$")
7174 (looking-at "[a-zA-Z0-9`_\$]+")
d63b01e1 7175 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
a3a8b002
DN
7176 (verilog-symbol-detick
7177 (buffer-substring-no-properties (match-beginning 0) (match-end 0)) t)))
6341f357 7178
4c5e69c6
DN
7179(defun verilog-read-inst-param-value ()
7180 "Return list of parameters and values when point is inside instantiation."
7181 (save-excursion
7182 (verilog-read-inst-backward-name)
7183 ;; Skip over instantiation name
7184 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
7185 ;; If there are parameterized instantiations
7186 (when (looking-at ")")
7187 (let ((end-pt (point))
7188 params
7189 param-name paren-beg-pt param-value)
7190 (verilog-backward-open-paren)
7191 (while (verilog-re-search-forward-quick "\\." end-pt t)
7192 (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
7193 (skip-chars-backward "a-zA-Z0-9'_$")
7194 (looking-at "[a-zA-Z0-9`_\$]+")
7195 (setq param-name (buffer-substring-no-properties
7196 (match-beginning 0) (match-end 0)))
7197 (verilog-re-search-forward-quick "(" nil nil)
7198 (setq paren-beg-pt (point))
7199 (verilog-forward-close-paren)
7200 (setq param-value (verilog-string-remove-spaces
7201 (buffer-substring-no-properties
7202 paren-beg-pt (1- (point)))))
7203 (setq params (cons (list param-name param-value) params)))
7204 params))))
7205
6341f357
DN
7206(defun verilog-read-auto-params (num-param &optional max-param)
7207 "Return parameter list inside auto.
7208Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
7209 (let ((olist))
7210 (save-excursion
7211 ;; /*AUTOPUNT("parameter", "parameter")*/
7212 (search-backward "(")
7213 (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
7214 (setq olist (cons (match-string 1) olist))
7215 (goto-char (match-end 0))))
7216 (or (eq nil num-param)
7217 (<= num-param (length olist))
7218 (error "%s: Expected %d parameters" (verilog-point-text) num-param))
7219 (if (eq max-param nil) (setq max-param num-param))
7220 (or (eq nil max-param)
7221 (>= max-param (length olist))
7222 (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
7223 (nreverse olist)))
7224
7225(defun verilog-read-decls ()
7226 "Compute signal declaration information for the current module at point.
7227Return a array of [outputs inouts inputs wire reg assign const]."
7228 (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
a3a8b002 7229 (functask 0) (paren 0) (sig-paren 0) (v2kargs-ok t)
a03c2342 7230 in-modport
a3a8b002
DN
7231 sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const
7232 sigs-gparam sigs-intf
7233 vec expect-signal keywd newsig rvalue enum io signed typedefed multidim
7234 modport)
6341f357
DN
7235 (save-excursion
7236 (verilog-beg-of-defun)
7237 (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
7238 (while (< (point) end-mod-point)
a03c2342 7239 ;;(if dbg (setq dbg (concat dbg (format "Pt %s Vec %s C%c Kwd'%s'\n" (point) vec (following-char) keywd))))
6341f357
DN
7240 (cond
7241 ((looking-at "//")
7242 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
7243 (setq enum (match-string 1)))
7244 (search-forward "\n"))
7245 ((looking-at "/\\*")
7246 (forward-char 2)
a03c2342 7247 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6341f357
DN
7248 (setq enum (match-string 1)))
7249 (or (search-forward "*/")
7250 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7251 ((looking-at "(\\*")
7252 (forward-char 2)
a3a8b002 7253 (or (looking-at "\\s-*)") ; It's an "always @ (*)"
6341f357
DN
7254 (search-forward "*)")
7255 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7256 ((eq ?\" (following-char))
7257 (or (re-search-forward "[^\\]\"" nil t) ;; don't forward-char first, since we look for a non backslash first
7258 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
7259 ((eq ?\; (following-char))
a3a8b002 7260 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil
a03c2342 7261 v2kargs-ok nil in-modport nil)
6341f357
DN
7262 (forward-char 1))
7263 ((eq ?= (following-char))
7264 (setq rvalue t newsig nil)
7265 (forward-char 1))
14862301
SM
7266 ((and (eq ?, (following-char))
7267 (eq paren sig-paren))
7268 (setq rvalue nil)
7269 (forward-char 1))
7270 ;; ,'s can occur inside {} & funcs
7271 ((looking-at "[{(]")
7272 (setq paren (1+ paren))
7273 (forward-char 1))
7274 ((looking-at "[})]")
7275 (setq paren (1- paren))
7276 (forward-char 1)
7277 (when (< paren sig-paren)
7278 (setq expect-signal nil))) ; ) that ends variables inside v2k arg list
6341f357
DN
7279 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
7280 (goto-char (match-end 0))
7281 (cond (newsig ; Memory, not just width. Patch last signal added's memory (nth 3)
8468f78b
WS
7282 (setcar (cdr (cdr (cdr newsig)))
7283 (if (verilog-sig-memory newsig)
7284 (concat (verilog-sig-memory newsig) (match-string 1))
7285 (match-string 1))))
6341f357
DN
7286 (vec ;; Multidimensional
7287 (setq multidim (cons vec multidim))
7288 (setq vec (verilog-string-replace-matches
7289 "\\s-+" "" nil nil (match-string 1))))
7290 (t ;; Bit width
7291 (setq vec (verilog-string-replace-matches
7292 "\\s-+" "" nil nil (match-string 1))))))
7293 ;; Normal or escaped identifier -- note we remember the \ if escaped
7294 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
7295 (goto-char (match-end 0))
7296 (setq keywd (match-string 1))
86a4c7ac 7297 (when (string-match "^\\\\" (match-string 1))
6341f357 7298 (setq keywd (concat keywd " "))) ;; Escaped ID needs space at end
86a4c7ac
DN
7299 ;; Add any :: package names to same identifier
7300 (while (looking-at "\\s-*::\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
7301 (goto-char (match-end 0))
7302 (setq keywd (concat keywd "::" (match-string 1)))
7303 (when (string-match "^\\\\" (match-string 1))
7304 (setq keywd (concat keywd " ")))) ;; Escaped ID needs space at end
6341f357
DN
7305 (cond ((equal keywd "input")
7306 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002 7307 expect-signal 'sigs-in io t modport nil))
6341f357
DN
7308 ((equal keywd "output")
7309 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002 7310 expect-signal 'sigs-out io t modport nil))
6341f357
DN
7311 ((equal keywd "inout")
7312 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002
DN
7313 expect-signal 'sigs-inout io t modport nil))
7314 ((equal keywd "parameter")
7315 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7316 expect-signal 'sigs-gparam io t modport nil))
7317 ((member keywd '("wire" "tri" "tri0" "tri1" "triand" "trior" "wand" "wor"))
6341f357 7318 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002
DN
7319 expect-signal 'sigs-wire modport nil)))
7320 ((member keywd '("reg" "trireg"
7321 "byte" "shortint" "int" "longint" "integer" "time"
a03c2342
WS
7322 "bit" "logic"
7323 "shortreal" "real" "realtime"
7324 "string" "event" "chandle"))
6341f357 7325 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002 7326 expect-signal 'sigs-reg modport nil)))
6341f357
DN
7327 ((equal keywd "assign")
7328 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002
DN
7329 expect-signal 'sigs-assign modport nil))
7330 ((member keywd '("supply0" "supply1" "supply"
7331 "localparam" "genvar"))
6341f357 7332 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002 7333 expect-signal 'sigs-const modport nil)))
6341f357
DN
7334 ((equal keywd "signed")
7335 (setq signed "signed"))
a3a8b002
DN
7336 ((member keywd '("class" "clocking" "covergroup" "function"
7337 "property" "randsequence" "sequence" "task"))
6341f357 7338 (setq functask (1+ functask)))
a3a8b002
DN
7339 ((member keywd '("endclass" "endclocking" "endgroup" "endfunction"
7340 "endproperty" "endsequence" "endtask"))
6341f357 7341 (setq functask (1- functask)))
a03c2342
WS
7342 ((equal keywd "modport")
7343 (setq in-modport t))
a3a8b002 7344 ;; Ifdef? Ignore name of define
a03c2342 7345 ((member keywd '("`ifdef" "`ifndef" "`elsif"))
6341f357 7346 (setq rvalue t))
a3a8b002 7347 ;; Type?
6341f357
DN
7348 ((verilog-typedef-name-p keywd)
7349 (setq typedefed keywd))
a3a8b002
DN
7350 ;; Interface with optional modport in v2k arglist?
7351 ;; Skip over parsing modport, and take the interface name as the type
7352 ((and v2kargs-ok
7353 (eq paren 1)
a03c2342
WS
7354 (not rvalue)
7355 (looking-at "\\s-*\\(\\.\\(\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*\\)\\|\\)\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*"))
a3a8b002
DN
7356 (when (match-end 2) (goto-char (match-end 2)))
7357 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed keywd multidim nil sig-paren paren
7358 expect-signal 'sigs-intf io t modport (match-string 2)))
a03c2342
WS
7359 ;; Ignore dotted LHS assignments: "assign foo.bar = z;"
7360 ((looking-at "\\s-*\\.")
7361 (goto-char (match-end 0))
7362 (when (not rvalue)
7363 (setq expect-signal nil)))
a3a8b002 7364 ;; New signal, maybe?
6341f357 7365 ((and expect-signal
6341f357 7366 (not rvalue)
a03c2342
WS
7367 (eq functask 0)
7368 (not in-modport)
6341f357
DN
7369 (not (member keywd verilog-keywords)))
7370 ;; Add new signal to expect-signal's variable
a03c2342 7371 (setq newsig (verilog-sig-new keywd vec nil nil enum signed typedefed multidim modport))
6341f357
DN
7372 (set expect-signal (cons newsig
7373 (symbol-value expect-signal))))))
7374 (t
7375 (forward-char 1)))
7376 (skip-syntax-forward " "))
7377 ;; Return arguments
a03c2342
WS
7378 (verilog-decls-new (nreverse sigs-out)
7379 (nreverse sigs-inout)
7380 (nreverse sigs-in)
7381 (nreverse sigs-wire)
7382 (nreverse sigs-reg)
7383 (nreverse sigs-assign)
7384 (nreverse sigs-const)
7385 (nreverse sigs-gparam)
7386 (nreverse sigs-intf)))))
7387
7388(defvar verilog-read-sub-decls-in-interfaced nil
7389 "For `verilog-read-sub-decls', process next signal as under interfaced block.")
7390
7391(defvar verilog-read-sub-decls-gate-ios nil
7392 "For `verilog-read-sub-decls', gate IO pins remaining, nil if non-primitive.")
6341f357 7393
60618039
DN
7394(eval-when-compile
7395 ;; Prevent compile warnings; these are let's, not globals
7396 ;; Do not remove the eval-when-compile
7397 ;; - we want a error when we are debugging this code if they are refed.
7398 (defvar sigs-in)
7399 (defvar sigs-inout)
a3a8b002 7400 (defvar sigs-out)
a03c2342
WS
7401 (defvar sigs-intf)
7402 (defvar sigs-intfd))
5509c6ad
DN
7403
7404(defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
37ea4b9b 7405 "For `verilog-read-sub-decls-line', add a signal."
a03c2342
WS
7406 ;; sig eq t to indicate .name syntax
7407 ;;(message "vrsds: %s(%S)" port sig)
7408 (let ((dotname (eq sig t))
7409 portdata)
6341f357
DN
7410 (when sig
7411 (setq port (verilog-symbol-detick-denumber port))
a03c2342 7412 (setq sig (if dotname port (verilog-symbol-detick-denumber sig)))
6341f357
DN
7413 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
7414 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
7415 (unless (or (not sig)
7416 (equal sig "")) ;; Ignore .foo(1'b1) assignments
a03c2342
WS
7417 (cond ((or (setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
7418 (equal "inout" verilog-read-sub-decls-gate-ios))
7419 (setq sigs-inout
7420 (cons (verilog-sig-new
7421 sig
7422 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
7423 (concat "To/From " comment)
7424 (verilog-sig-memory portdata)
7425 nil
a03c2342
WS
7426 (verilog-sig-signed portdata)
7427 (verilog-sig-type portdata)
7428 multidim nil)
7429 sigs-inout)))
7430 ((or (setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
7431 (equal "output" verilog-read-sub-decls-gate-ios))
7432 (setq sigs-out
7433 (cons (verilog-sig-new
7434 sig
7435 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
7436 (concat "From " comment)
7437 (verilog-sig-memory portdata)
7438 nil
a03c2342
WS
7439 (verilog-sig-signed portdata)
7440 (verilog-sig-type portdata)
7441 multidim nil)
7442 sigs-out)))
7443 ((or (setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
7444 (equal "input" verilog-read-sub-decls-gate-ios))
7445 (setq sigs-in
7446 (cons (verilog-sig-new
7447 sig
7448 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
7449 (concat "To " comment)
7450 (verilog-sig-memory portdata)
7451 nil
a03c2342
WS
7452 (verilog-sig-signed portdata)
7453 (verilog-sig-type portdata)
7454 multidim nil)
7455 sigs-in)))
a3a8b002 7456 ((setq portdata (assoc port (verilog-decls-get-interfaces submoddecls)))
a03c2342
WS
7457 (setq sigs-intf
7458 (cons (verilog-sig-new
7459 sig
7460 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
7461 (concat "To/From " comment)
7462 (verilog-sig-memory portdata)
7463 nil
a03c2342
WS
7464 (verilog-sig-signed portdata)
7465 (verilog-sig-type portdata)
7466 multidim nil)
7467 sigs-intf)))
7468 ((setq portdata (and verilog-read-sub-decls-in-interfaced
7469 (or (assoc port (verilog-decls-get-regs submoddecls))
7470 (assoc port (verilog-decls-get-wires submoddecls)))))
7471 (setq sigs-intfd
7472 (cons (verilog-sig-new
7473 sig
7474 (if dotname (verilog-sig-bits portdata) vec)
8468f78b
WS
7475 (concat "To/From " comment)
7476 (verilog-sig-memory portdata)
7477 nil
a03c2342
WS
7478 (verilog-sig-signed portdata)
7479 (verilog-sig-type portdata)
7480 multidim nil)
7481 sigs-intf)))
6341f357
DN
7482 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
7483 )))))
7484
a3a8b002
DN
7485(defun verilog-read-sub-decls-expr (submoddecls comment port expr)
7486 "For `verilog-read-sub-decls-line', parse a subexpression and add signals."
7487 ;;(message "vrsde: '%s'" expr)
7488 ;; Replace special /*[....]*/ comments inserted by verilog-auto-inst-port
7489 (setq expr (verilog-string-replace-matches "/\\*\\(\\[[^*]+\\]\\)\\*/" "\\1" nil nil expr))
7490 ;; Remove front operators
7491 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
7492 ;;
7493 (cond
7494 ;; {..., a, b} requires us to recurse on a,b
a03c2342
WS
7495 ;; To support {#{},{#{a,b}} we'll just split everything on [{},]
7496 ((string-match "^\\s-*{\\(.*\\)}\\s-*$" expr)
14862301 7497 (unless verilog-auto-ignore-concat
a03c2342 7498 (let ((mlst (split-string (match-string 1 expr) "[{},]"))
14862301
SM
7499 mstr)
7500 (while (setq mstr (pop mlst))
7501 (verilog-read-sub-decls-expr submoddecls comment port mstr)))))
a3a8b002
DN
7502 (t
7503 (let (sig vec multidim)
a03c2342
WS
7504 ;; Remove leading reduction operators, etc
7505 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
7506 ;;(message "vrsde-ptop: '%s'" expr)
a3a8b002
DN
7507 (cond ;; Find \signal. Final space is part of escaped signal name
7508 ((string-match "^\\s-*\\(\\\\[^ \t\n\f]+\\s-\\)" expr)
7509 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
7510 (setq sig (match-string 1 expr)
7511 expr (substring expr (match-end 0))))
7512 ;; Find signal
a03c2342 7513 ((string-match "^\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" expr)
a3a8b002
DN
7514 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
7515 (setq sig (verilog-string-remove-spaces (match-string 1 expr))
7516 expr (substring expr (match-end 0)))))
7517 ;; Find [vector] or [multi][multi][multi][vector]
7518 (while (string-match "^\\s-*\\(\\[[^]]+\\]\\)" expr)
7519 ;;(message "vrsde-v: '%s'" (match-string 1 expr))
7520 (when vec (setq multidim (cons vec multidim)))
7521 (setq vec (match-string 1 expr)
7522 expr (substring expr (match-end 0))))
7523 ;; If found signal, and nothing unrecognized, add the signal
7524 ;;(message "vrsde-rem: '%s'" expr)
7525 (when (and sig (string-match "^\\s-*$" expr))
7526 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))))
7527
5509c6ad 7528(defun verilog-read-sub-decls-line (submoddecls comment)
a03c2342
WS
7529 "For `verilog-read-sub-decls', read lines of port defs until none match.
7530Inserts the list of signals found, using submodi to look up each port."
a3a8b002 7531 (let (done port)
6341f357
DN
7532 (save-excursion
7533 (forward-line 1)
7534 (while (not done)
7535 ;; Get port name
7536 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
7537 (setq port (match-string 1))
7538 (goto-char (match-end 0)))
a03c2342 7539 ;; .\escaped (
6341f357
DN
7540 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
7541 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
7542 (goto-char (match-end 0)))
a03c2342
WS
7543 ;; .name
7544 ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*[,)/]")
7545 (verilog-read-sub-decls-sig
7546 submoddecls comment (match-string 1) t ; sig==t for .name
7547 nil nil) ; vec multidim
7548 (setq port nil))
7549 ;; .\escaped_name
7550 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*[,)/]")
7551 (verilog-read-sub-decls-sig
7552 submoddecls comment (concat (match-string 1) " ") t ; sig==t for .name
7553 nil nil) ; vec multidim
7554 (setq port nil))
7555 ;; random
6341f357
DN
7556 ((looking-at "\\s-*\\.[^(]*(")
7557 (setq port nil) ;; skip this line
7558 (goto-char (match-end 0)))
7559 (t
7560 (setq port nil done t))) ;; Unknown, ignore rest of line
a3a8b002
DN
7561 ;; Get signal name. Point is at the first-non-space after (
7562 ;; We intentionally ignore (non-escaped) signals with .s in them
7563 ;; this prevents AUTOWIRE etc from noticing hierarchical sigs.
6341f357 7564 (when port
a03c2342 7565 (cond ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*)")
a3a8b002
DN
7566 (verilog-read-sub-decls-sig
7567 submoddecls comment port
7568 (verilog-string-remove-spaces (match-string 1)) ; sig
7569 nil nil)) ; vec multidim
7570 ;;
a03c2342 7571 ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
a3a8b002
DN
7572 (verilog-read-sub-decls-sig
7573 submoddecls comment port
7574 (verilog-string-remove-spaces (match-string 1)) ; sig
7575 (match-string 2) nil)) ; vec multidim
7576 ;; Fastpath was above looking-at's.
7577 ;; For something more complicated invoke a parser
7578 ((looking-at "[^)]+")
7579 (verilog-read-sub-decls-expr
7580 submoddecls comment port
7581 (buffer-substring
a03c2342 7582 (point) (1- (progn (search-backward "(") ; start at (
a3a8b002 7583 (forward-sexp 1) (point)))))))) ; expr
6341f357
DN
7584 ;;
7585 (forward-line 1)))))
7586
a03c2342
WS
7587(defun verilog-read-sub-decls-gate (submoddecls comment submod end-inst-point)
7588 "For `verilog-read-sub-decls', read lines of UDP gate decl until none match.
7589Inserts the list of signals found."
7590 (save-excursion
7591 (let ((iolist (cdr (assoc submod verilog-gate-ios))))
7592 (while (< (point) end-inst-point)
7593 ;; Get primitive's signal name, as will never have port, and no trailing )
7594 (cond ((looking-at "//")
7595 (search-forward "\n"))
7596 ((looking-at "/\\*")
7597 (or (search-forward "*/")
7598 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7599 ((looking-at "(\\*")
7600 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7601 (search-forward "*)")
7602 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7603 ;; On pins, parse and advance to next pin
7604 ;; Looking at pin, but *not* an // Output comment, or ) to end the inst
7605 ((looking-at "\\s-*[a-zA-Z0-9`_$({}\\\\][^,]*")
7606 (goto-char (match-end 0))
7607 (setq verilog-read-sub-decls-gate-ios (or (car iolist) "input")
7608 iolist (cdr iolist))
7609 (verilog-read-sub-decls-expr
7610 submoddecls comment "primitive_port"
7611 (match-string 0)))
7612 (t
7613 (forward-char 1)
7614 (skip-syntax-forward " ")))))))
7615
6341f357
DN
7616(defun verilog-read-sub-decls ()
7617 "Internally parse signals going to modules under this module.
7618Return a array of [ outputs inouts inputs ] signals for modules that are
7619instantiated in this module. For example if declare A A (.B(SIG)) and SIG
7620is a output, then SIG will be included in the list.
7621
7622This only works on instantiations created with /*AUTOINST*/ converted by
7623\\[verilog-auto-inst]. Otherwise, it would have to read in the whole
7624component library to determine connectivity of the design.
7625
7626One work around for this problem is to manually create // Inputs and //
7627Outputs comments above subcell signals, for example:
7628
1dd4b004 7629 module ModuleName (
6341f357
DN
7630 // Outputs
7631 .out (out),
7632 // Inputs
7633 .in (in));"
7634 (save-excursion
7635 (let ((end-mod-point (verilog-get-end-of-defun t))
7636 st-point end-inst-point
7637 ;; below 3 modified by verilog-read-sub-decls-line
a03c2342 7638 sigs-out sigs-inout sigs-in sigs-intf sigs-intfd)
6341f357 7639 (verilog-beg-of-defun)
495ab0d5 7640 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
6341f357
DN
7641 (save-excursion
7642 (goto-char (match-beginning 0))
7643 (unless (verilog-inside-comment-p)
7644 ;; Attempt to snarf a comment
7645 (let* ((submod (verilog-read-inst-module))
7646 (inst (verilog-read-inst-name))
a03c2342 7647 (subprim (member submod verilog-gate-keywords))
5509c6ad
DN
7648 (comment (concat inst " of " submod ".v"))
7649 submodi submoddecls)
a03c2342
WS
7650 (cond
7651 (subprim
7652 (setq submodi `primitive
7653 submoddecls (verilog-decls-new nil nil nil nil nil nil nil nil nil)
7654 comment (concat inst " of " submod))
6341f357
DN
7655 (verilog-backward-open-paren)
7656 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
7657 st-point (point))
a03c2342
WS
7658 (forward-char 1)
7659 (verilog-read-sub-decls-gate submoddecls comment submod end-inst-point))
7660 ;; Non-primitive
7661 (t
7662 (when (setq submodi (verilog-modi-lookup submod t))
7663 (setq submoddecls (verilog-modi-get-decls submodi)
7664 verilog-read-sub-decls-gate-ios nil)
7665 (verilog-backward-open-paren)
7666 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
7667 st-point (point))
7668 ;; This could have used a list created by verilog-auto-inst
7669 ;; However I want it to be runnable even on user's manually added signals
7670 (let ((verilog-read-sub-decls-in-interfaced t))
7671 (while (re-search-forward "\\s *(?\\s *// Interfaced" end-inst-point t)
7672 (verilog-read-sub-decls-line submoddecls comment))) ;; Modifies sigs-ifd
7673 (goto-char st-point)
7674 (while (re-search-forward "\\s *(?\\s *// Interfaces" end-inst-point t)
7675 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
7676 (goto-char st-point)
7677 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
7678 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
7679 (goto-char st-point)
7680 (while (re-search-forward "\\s *(?\\s *// Inouts" end-inst-point t)
7681 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
7682 (goto-char st-point)
7683 (while (re-search-forward "\\s *(?\\s *// Inputs" end-inst-point t)
7684 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
7685 )))))))
6341f357
DN
7686 ;; Combine duplicate bits
7687 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
a03c2342
WS
7688 (verilog-subdecls-new
7689 (verilog-signals-combine-bus (nreverse sigs-out))
7690 (verilog-signals-combine-bus (nreverse sigs-inout))
7691 (verilog-signals-combine-bus (nreverse sigs-in))
7692 (verilog-signals-combine-bus (nreverse sigs-intf))
7693 (verilog-signals-combine-bus (nreverse sigs-intfd))))))
6341f357
DN
7694
7695(defun verilog-read-inst-pins ()
37ea4b9b 7696 "Return an array of [ pins ] for the current instantiation at point.
6341f357
DN
7697For example if declare A A (.B(SIG)) then B will be included in the list."
7698 (save-excursion
7699 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
7700 pins pin)
7701 (verilog-backward-open-paren)
7702 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
7703 (setq pin (match-string 1))
7704 (unless (verilog-inside-comment-p)
7705 (setq pins (cons (list pin) pins))
7706 (when (looking-at "(")
7707 (forward-sexp 1))))
7708 (vector pins))))
7709
7710(defun verilog-read-arg-pins ()
37ea4b9b 7711 "Return an array of [ pins ] for the current argument declaration at point."
6341f357
DN
7712 (save-excursion
7713 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
7714 pins pin)
7715 (verilog-backward-open-paren)
7716 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
7717 (setq pin (match-string 1))
7718 (unless (verilog-inside-comment-p)
7719 (setq pins (cons (list pin) pins))))
7720 (vector pins))))
7721
7722(defun verilog-read-auto-constants (beg end-mod-point)
7723 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
7724 ;; Insert new
7725 (save-excursion
7726 (let (sig-list tpl-end-pt)
7727 (goto-char beg)
7728 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
7729 (if (not (looking-at "\\s *("))
7730 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
7731 (search-forward "(" end-mod-point)
7732 (setq tpl-end-pt (save-excursion
7733 (backward-char 1)
7734 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7735 (backward-char 1)
7736 (point)))
7737 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
7738 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
7739 sig-list)))
7740
a03c2342
WS
7741(defvar verilog-cache-has-lisp nil "True if any AUTO_LISP in buffer.")
7742(make-variable-buffer-local 'verilog-cache-has-lisp)
7743
7744(defun verilog-read-auto-lisp-present ()
7745 "Set `verilog-cache-has-lisp' if any AUTO_LISP in this buffer."
6341f357 7746 (save-excursion
a03c2342
WS
7747 (setq verilog-cache-has-lisp (re-search-forward "\\<AUTO_LISP(" nil t))))
7748
7749(defun verilog-read-auto-lisp (start end)
7750 "Look for and evaluate a AUTO_LISP between START and END.
7751Must call `verilog-read-auto-lisp-present' before this function."
7752 ;; This function is expensive for large buffers, so we cache if any AUTO_LISP exists
7753 (when verilog-cache-has-lisp
7754 (save-excursion
7755 (goto-char start)
7756 (while (re-search-forward "\\<AUTO_LISP(" end t)
7757 (backward-char)
7758 (let* ((beg-pt (prog1 (point)
7759 (forward-sexp 1))) ;; Closing paren
7760 (end-pt (point)))
7761 (eval-region beg-pt end-pt nil))))))
6341f357 7762
60618039
DN
7763(eval-when-compile
7764 ;; Prevent compile warnings; these are let's, not globals
7765 ;; Do not remove the eval-when-compile
7766 ;; - we want a error when we are debugging this code if they are refed.
7767 (defvar sigs-in)
7768 (defvar sigs-out)
a03c2342 7769 (defvar sigs-temp)
60618039
DN
7770 (defvar uses-delayed)
7771 (defvar vector-skip-list))
6341f357
DN
7772
7773(defun verilog-read-always-signals-recurse
a03c2342 7774 (exit-keywd rvalue temp-next)
6341f357
DN
7775 "Recursive routine for parentheses/bracket matching.
7776EXIT-KEYWD is expression to stop at, nil if top level.
7777RVALUE is true if at right hand side of equal.
7778IGNORE-NEXT is true to ignore next token, fake from inside case statement."
7779 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
a03c2342
WS
7780 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-list end-else-check
7781 ignore-next)
7782 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue temp-next))))
6341f357
DN
7783 (while (not (or (eobp) gotend))
7784 (cond
7785 ((looking-at "//")
7786 (search-forward "\n"))
7787 ((looking-at "/\\*")
7788 (or (search-forward "*/")
7789 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7790 ((looking-at "(\\*")
7791 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7792 (search-forward "*)")
7793 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7794 (t (setq keywd (buffer-substring-no-properties
7795 (point)
7796 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7797 (forward-char 1))
7798 (point)))
7799 sig-last-tolk sig-tolk
7800 sig-tolk nil)
14862301 7801 ;;(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
7802 (cond
7803 ((equal keywd "\"")
7804 (or (re-search-forward "[^\\]\"" nil t)
7805 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
7806 ;; else at top level loop, keep parsing
7807 ((and end-else-check (equal keywd "else"))
7808 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
7809 ;; no forward movement, want to see else in lower loop
7810 (setq end-else-check nil))
7811 ;; End at top level loop
7812 ((and end-else-check (looking-at "[^ \t\n\f]"))
7813 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
7814 (setq gotend t))
7815 ;; Final statement?
7816 ((and exit-keywd (equal keywd exit-keywd))
7817 (setq gotend t)
7818 (forward-char (length keywd)))
7819 ;; Standard tokens...
7820 ((equal keywd ";")
7821 (setq ignore-next nil rvalue semi-rvalue)
7822 ;; Final statement at top level loop?
7823 (when (not exit-keywd)
7824 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
7825 (setq end-else-check t))
7826 (forward-char 1))
7827 ((equal keywd "'")
14862301 7828 (if (looking-at "'[sS]?[hdxboHDXBO]?[ \t]*[0-9a-fA-F_xzXZ?]+")
6341f357
DN
7829 (goto-char (match-end 0))
7830 (forward-char 1)))
7831 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
7832 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
7833 (setq ignore-next nil rvalue nil))
7834 ((equal "?" exit-keywd) ;; x?y:z rvalue
7835 ) ;; NOP
a3a8b002
DN
7836 ((equal "]" exit-keywd) ;; [x:y] rvalue
7837 ) ;; NOP
6341f357
DN
7838 (got-sig ;; label: statement
7839 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
7840 ((not rvalue) ;; begin label
7841 (setq ignore-next t rvalue nil)))
7842 (forward-char 1))
7843 ((equal keywd "=")
a3a8b002
DN
7844 (if (and (eq (char-before) ?< )
7845 (not rvalue))
6341f357
DN
7846 (setq uses-delayed 1))
7847 (setq ignore-next nil rvalue t)
7848 (forward-char 1))
7849 ((equal keywd "?")
7850 (forward-char 1)
7851 (verilog-read-always-signals-recurse ":" rvalue nil))
7852 ((equal keywd "[")
7853 (forward-char 1)
7854 (verilog-read-always-signals-recurse "]" t nil))
7855 ((equal keywd "(")
7856 (forward-char 1)
7857 (cond (sig-last-tolk ;; Function call; zap last signal
7858 (setq got-sig nil)))
7859 (cond ((equal last-keywd "for")
a03c2342
WS
7860 ;; temp-next: Variables on LHS are lvalues, but generally we want
7861 ;; to ignore them, assuming they are loop increments
7862 (verilog-read-always-signals-recurse ";" nil t)
6341f357
DN
7863 (verilog-read-always-signals-recurse ";" t nil)
7864 (verilog-read-always-signals-recurse ")" nil nil))
7865 (t (verilog-read-always-signals-recurse ")" t nil))))
7866 ((equal keywd "begin")
7867 (skip-syntax-forward "w_")
7868 (verilog-read-always-signals-recurse "end" nil nil)
7869 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
7870 (setq ignore-next nil rvalue semi-rvalue)
7871 (if (not exit-keywd) (setq end-else-check t)))
a03c2342 7872 ((member keywd '("case" "casex" "casez"))
6341f357
DN
7873 (skip-syntax-forward "w_")
7874 (verilog-read-always-signals-recurse "endcase" t nil)
7875 (setq ignore-next nil rvalue semi-rvalue)
7876 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
7877 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
a03c2342 7878 (cond ((member keywd '("`ifdef" "`ifndef" "`elsif"))
6341f357
DN
7879 (setq ignore-next t))
7880 ((or ignore-next
7881 (member keywd verilog-keywords)
7882 (string-match "^\\$" keywd)) ;; PLI task
7883 (setq ignore-next nil))
7884 (t
7885 (setq keywd (verilog-symbol-detick-denumber keywd))
7886 (when got-sig
a03c2342
WS
7887 (set got-list (cons got-sig (symbol-value got-list)))
7888 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S got-list=%S\n" got-sig got-list))))
6341f357 7889 )
a03c2342
WS
7890 (setq got-list (cond (temp-next 'sigs-temp)
7891 (rvalue 'sigs-in)
7892 (t 'sigs-out))
6341f357 7893 got-sig (if (or (not keywd)
a03c2342 7894 (assoc keywd (symbol-value got-list)))
6341f357 7895 nil (list keywd nil nil))
a03c2342 7896 temp-next nil
6341f357
DN
7897 sig-tolk t)))
7898 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7899 (t
7900 (forward-char 1)))
7901 ;; End of non-comment token
60618039 7902 (setq last-keywd keywd)))
6341f357
DN
7903 (skip-syntax-forward " "))
7904 ;; Append the final pending signal
7905 (when got-sig
a03c2342
WS
7906 ;;(if dbg (setq dbg (concat dbg (format "\t\tfinal got-sig=%S got-list=%s\n" got-sig got-list))))
7907 (set got-list (cons got-sig (symbol-value got-list)))
6341f357
DN
7908 (setq got-sig nil))
7909 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
7910 ))
7911
7912(defun verilog-read-always-signals ()
7913 "Parse always block at point and return list of (outputs inout inputs)."
6341f357
DN
7914 (save-excursion
7915 (let* (;;(dbg "")
a03c2342 7916 sigs-out sigs-temp sigs-in
6341f357
DN
7917 uses-delayed) ;; Found signal/rvalue; push if not function
7918 (search-forward ")")
7919 (verilog-read-always-signals-recurse nil nil nil)
14862301 7920 ;;(if dbg (with-current-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg ""))
6341f357 7921 ;; Return what was found
a03c2342 7922 (verilog-alw-new sigs-out sigs-temp sigs-in uses-delayed))))
6341f357
DN
7923
7924(defun verilog-read-instants ()
7925 "Parse module at point and return list of ( ( file instance ) ... )."
7926 (verilog-beg-of-defun)
7927 (let* ((end-mod-point (verilog-get-end-of-defun t))
7928 (state nil)
7929 (instants-list nil))
7930 (save-excursion
7931 (while (< (point) end-mod-point)
7932 ;; Stay at level 0, no comments
7933 (while (progn
7934 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
7935 (or (> (car state) 0) ; in parens
7936 (nth 5 state) ; comment
7937 ))
7938 (forward-line 1))
7939 (beginning-of-line)
7940 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
7941 ;;(if (looking-at "^\\(.+\\)$")
7942 (let ((module (match-string 1))
7943 (instant (match-string 2)))
7944 (if (not (member module verilog-keywords))
7945 (setq instants-list (cons (list module instant) instants-list)))))
60618039 7946 (forward-line 1)))
6341f357
DN
7947 instants-list))
7948
7949
7950(defun verilog-read-auto-template (module)
7951 "Look for a auto_template for the instantiation of the given MODULE.
7952If found returns the signal name connections. Return REGEXP and
37ea4b9b 7953list of ( (signal_name connection_name)... )."
6341f357
DN
7954 (save-excursion
7955 ;; Find beginning
7956 (let ((tpl-regexp "\\([0-9]+\\)")
7957 (lineno 0)
7958 (templateno 0)
a03c2342 7959 (pt (point))
6341f357 7960 tpl-sig-list tpl-wild-list tpl-end-pt rep)
a03c2342
WS
7961 ;; Note this search is expensive, as we hunt from mod-begin to point
7962 ;; for every instantiation. Likewise in verilog-read-auto-lisp.
7963 ;; So, we look first for an exact string rather than a slow regexp.
7964 ;; Someday we may keep a cache of every template, but this would also
7965 ;; need to record the relative position of each AUTOINST, as multiple
7966 ;; templates exist for each module, and we're inserting lines.
6341f357 7967 (cond ((or
a03c2342
WS
7968 (verilog-re-search-backward-substr
7969 "AUTO_TEMPLATE"
7970 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
7971 ;; Also try forward of this AUTOINST
7972 ;; This is for historical support; this isn't speced as working
7973 (progn
7974 (goto-char pt)
7975 (verilog-re-search-forward-substr
7976 "AUTO_TEMPLATE"
7977 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
6341f357
DN
7978 (goto-char (match-end 0))
7979 ;; Parse "REGEXP"
a03c2342
WS
7980 ;; We reserve @"..." for future lisp expressions that evaluate
7981 ;; once-per-AUTOINST
14862301 7982 (when (looking-at "\\s-*\"\\([^\"]*\\)\"")
6341f357
DN
7983 (setq tpl-regexp (match-string 1))
7984 (goto-char (match-end 0)))
7985 (search-forward "(")
7986 ;; Parse lines in the template
7987 (when verilog-auto-inst-template-numbers
7988 (save-excursion
7989 (goto-char (point-min))
7990 (while (search-forward "AUTO_TEMPLATE" nil t)
7991 (setq templateno (1+ templateno)))))
7992 (setq tpl-end-pt (save-excursion
7993 (backward-char 1)
7994 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7995 (backward-char 1)
7996 (point)))
7997 ;;
7998 (while (< (point) tpl-end-pt)
7999 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
8000 (setq tpl-sig-list (cons (list
8001 (match-string-no-properties 1)
8002 (match-string-no-properties 2)
8003 templateno lineno)
8004 tpl-sig-list))
8005 (goto-char (match-end 0)))
8006 ;; Regexp form??
8007 ((looking-at
d63b01e1 8008 ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
6341f357
DN
8009 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
8010 (setq rep (match-string-no-properties 3))
8011 (goto-char (match-end 0))
8012 (setq tpl-wild-list
8013 (cons (list
8014 (concat "^"
8015 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
8016 (match-string 1))
8017 "$")
8018 rep
8019 templateno lineno)
8020 tpl-wild-list)))
8021 ((looking-at "[ \t\f]+")
8022 (goto-char (match-end 0)))
8023 ((looking-at "\n")
8024 (setq lineno (1+ lineno))
8025 (goto-char (match-end 0)))
8026 ((looking-at "//")
8027 (search-forward "\n"))
8028 ((looking-at "/\\*")
8029 (forward-char 2)
8030 (or (search-forward "*/")
8031 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8032 (t
8033 (error "%s: AUTO_TEMPLATE parsing error: %s"
8034 (verilog-point-text)
60618039 8035 (progn (looking-at ".*$") (match-string 0))))))
6341f357
DN
8036 ;; Return
8037 (vector tpl-regexp
8038 (list tpl-sig-list tpl-wild-list)))
8039 ;; If no template found
8040 (t (vector tpl-regexp nil))))))
8041;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
8042
8043(defun verilog-set-define (defname defvalue &optional buffer enumname)
8044 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
8045Optionally associate it with the specified enumeration ENUMNAME."
9a529312 8046 (with-current-buffer (or buffer (current-buffer))
6341f357
DN
8047 (let ((mac (intern (concat "vh-" defname))))
8048 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
8049 ;; Need to define to a constant if no value given
14862301 8050 (set (make-local-variable mac)
6341f357
DN
8051 (if (equal defvalue "") "1" defvalue)))
8052 (if enumname
8053 (let ((enumvar (intern (concat "venum-" enumname))))
8054 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
a3a8b002 8055 (unless (boundp enumvar) (set enumvar nil))
14862301 8056 (make-local-variable enumvar)
60618039 8057 (add-to-list enumvar defname)))))
6341f357
DN
8058
8059(defun verilog-read-defines (&optional filename recurse subcall)
8060 "Read `defines and parameters for the current file, or optional FILENAME.
8061If the filename is provided, `verilog-library-flags' will be used to
8062resolve it. If optional RECURSE is non-nil, recurse through `includes.
8063
8064Parameters must be simple assignments to constants, or have their own
8065\"parameter\" label rather than a list of parameters. Thus:
8066
8067 parameter X = 5, Y = 10; // Ok
8068 parameter X = {1'b1, 2'h2}; // Ok
8069 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
8070
8071Defines must be simple text substitutions, one on a line, starting
8072at the beginning of the line. Any ifdefs or multiline comments around the
8073define are ignored.
8074
8075Defines are stored inside Emacs variables using the name vh-{definename}.
8076
8077This function is useful for setting vh-* variables. The file variables
8078feature can be used to set defines that `verilog-mode' can see; put at the
8079*END* of your file something like:
8080
8081 // Local Variables:
8082 // vh-macro:\"macro_definition\"
8083 // End:
8084
8085If macros are defined earlier in the same file and you want their values,
8086you can read them automatically (provided `enable-local-eval' is on):
8087
8088 // Local Variables:
8089 // eval:(verilog-read-defines)
8090 // eval:(verilog-read-defines \"group_standard_includes.v\")
8091 // End:
8092
8093Note these are only read when the file is first visited, you must use
8094\\[find-alternate-file] RET to have these take effect after editing them!
8095
8096If you want to disable the \"Process `eval' or hook local variables\"
8097warning message, you need to add to your .emacs file:
8098
8099 (setq enable-local-eval t)"
8100 (let ((origbuf (current-buffer)))
8101 (save-excursion
8102 (unless subcall (verilog-getopt-flags))
8103 (when filename
8104 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
8105 (if fns
8106 (set-buffer (find-file-noselect (car fns)))
8107 (error (concat (verilog-point-text)
8108 ": Can't find verilog-read-defines file: " filename)))))
8109 (when recurse
8110 (goto-char (point-min))
8111 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
a03c2342
WS
8112 (let ((inc (verilog-string-replace-matches
8113 "\"" "" nil nil (match-string-no-properties 1))))
6341f357
DN
8114 (unless (verilog-inside-comment-p)
8115 (verilog-read-defines inc recurse t)))))
8116 ;; Read `defines
8117 ;; note we don't use verilog-re... it's faster this way, and that
8118 ;; function has problems when comments are at the end of the define
8119 (goto-char (point-min))
8120 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
8121 (let ((defname (match-string-no-properties 1))
8122 (defvalue (match-string-no-properties 2)))
8123 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
8124 (verilog-set-define defname defvalue origbuf)))
8125 ;; Hack: Read parameters
8126 (goto-char (point-min))
8127 (while (re-search-forward
a3a8b002
DN
8128 "^\\s-*\\(parameter\\|localparam\\)\\(\\s-*\\[[^]]*\\]\\)?\\s-+" nil t)
8129 (let (enumname)
6341f357
DN
8130 ;; The primary way of getting defines is verilog-read-decls
8131 ;; However, that isn't called yet for included files, so we'll add another scheme
8132 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
8133 (setq enumname (match-string-no-properties 1)))
6341f357
DN
8134 (forward-comment 999)
8135 (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
a03c2342
WS
8136 (verilog-set-define (match-string-no-properties 1)
8137 (match-string-no-properties 2) origbuf enumname)
6341f357 8138 (goto-char (match-end 0))
60618039 8139 (forward-comment 999)))))))
6341f357
DN
8140
8141(defun verilog-read-includes ()
8142 "Read `includes for the current file.
8143This will find all of the `includes which are at the beginning of lines,
8144ignoring any ifdefs or multiline comments around them.
8145`verilog-read-defines' is then performed on the current and each included
8146file.
8147
8148It is often useful put at the *END* of your file something like:
8149
8150 // Local Variables:
8151 // eval:(verilog-read-defines)
8152 // eval:(verilog-read-includes)
8153 // End:
8154
8155Note includes are only read when the file is first visited, you must use
8156\\[find-alternate-file] RET to have these take effect after editing them!
8157
8158It is good to get in the habit of including all needed files in each .v
8159file that needs it, rather than waiting for compile time. This will aid
8160this process, Verilint, and readability. To prevent defining the same
8161variable over and over when many modules are compiled together, put a test
8162around the inside each include file:
8163
8164foo.v (a include):
8165 `ifdef _FOO_V // include if not already included
8166 `else
8167 `define _FOO_V
8168 ... contents of file
8169 `endif // _FOO_V"
8170;;slow: (verilog-read-defines nil t))
8171 (save-excursion
8172 (verilog-getopt-flags)
8173 (goto-char (point-min))
8174 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
8175 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
8176 (verilog-read-defines inc nil t)))))
8177
8178(defun verilog-read-signals (&optional start end)
8179 "Return a simple list of all possible signals in the file.
8180Bounded by optional region from START to END. Overly aggressive but fast.
37ea4b9b 8181Some macros and such are also found and included. For dinotrace.el."
6341f357
DN
8182 (let (sigs-all keywd)
8183 (progn;save-excursion
8184 (goto-char (or start (point-min)))
8185 (setq end (or end (point-max)))
8186 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
8187 (forward-char -1)
8188 (cond
8189 ((looking-at "//")
8190 (search-forward "\n"))
8191 ((looking-at "/\\*")
8192 (search-forward "*/"))
8193 ((looking-at "(\\*")
8194 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
8195 (search-forward "*)")))
8196 ((eq ?\" (following-char))
8197 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
8198 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
8199 (goto-char (match-end 0))
8200 (setq keywd (match-string-no-properties 1))
8201 (or (member keywd verilog-keywords)
8202 (member keywd sigs-all)
8203 (setq sigs-all (cons keywd sigs-all))))
60618039 8204 (t (forward-char 1))))
6341f357
DN
8205 ;; Return list
8206 sigs-all)))
8207
8208;;
8209;; Argument file parsing
8210;;
8211
8212(defun verilog-getopt (arglist)
8213 "Parse -f, -v etc arguments in ARGLIST list or string."
8214 (unless (listp arglist) (setq arglist (list arglist)))
8215 (let ((space-args '())
8216 arg next-param)
8217 ;; Split on spaces, so users can pass whole command lines
8218 (while arglist
8219 (setq arg (car arglist)
8220 arglist (cdr arglist))
8221 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
8222 (setq space-args (append space-args
8223 (list (match-string-no-properties 1 arg))))
8224 (setq arg (match-string 2 arg))))
8225 ;; Parse arguments
8226 (while space-args
8227 (setq arg (car space-args)
8228 space-args (cdr space-args))
8229 (cond
8230 ;; Need another arg
8231 ((equal arg "-f")
8232 (setq next-param arg))
8233 ((equal arg "-v")
8234 (setq next-param arg))
8235 ((equal arg "-y")
8236 (setq next-param arg))
8237 ;; +libext+(ext1)+(ext2)...
8238 ((string-match "^\\+libext\\+\\(.*\\)" arg)
8239 (setq arg (match-string 1 arg))
8240 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
8241 (verilog-add-list-unique `verilog-library-extensions
8242 (match-string 1 arg))
8243 (setq arg (match-string 2 arg))))
8244 ;;
8245 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
8246 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
8247 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
8248 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
8249 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
8250 ;;
8251 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
8252 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
8253 (verilog-add-list-unique `verilog-library-directories
a3a8b002 8254 (match-string 1 (substitute-in-file-name arg))))
6341f357
DN
8255 ;; Ignore
8256 ((equal "+librescan" arg))
8257 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
8258 ;; Second parameters
8259 ((equal next-param "-f")
8260 (setq next-param nil)
a3a8b002 8261 (verilog-getopt-file (substitute-in-file-name arg)))
6341f357
DN
8262 ((equal next-param "-v")
8263 (setq next-param nil)
a3a8b002
DN
8264 (verilog-add-list-unique `verilog-library-files
8265 (substitute-in-file-name arg)))
6341f357
DN
8266 ((equal next-param "-y")
8267 (setq next-param nil)
a3a8b002
DN
8268 (verilog-add-list-unique `verilog-library-directories
8269 (substitute-in-file-name arg)))
6341f357
DN
8270 ;; Filename
8271 ((string-match "^[^-+]" arg)
a3a8b002
DN
8272 (verilog-add-list-unique `verilog-library-files
8273 (substitute-in-file-name arg)))
6341f357 8274 ;; Default - ignore; no warning
60618039 8275 ))))
6341f357
DN
8276;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
8277
8278(defun verilog-getopt-file (filename)
37ea4b9b 8279 "Read Verilog options from the specified FILENAME."
6341f357
DN
8280 (save-excursion
8281 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
8282 (orig-buffer (current-buffer))
8283 line)
8284 (if fns
8285 (set-buffer (find-file-noselect (car fns)))
8286 (error (concat (verilog-point-text)
5509c6ad 8287 ": Can't find verilog-getopt-file -f file: " filename)))
6341f357
DN
8288 (goto-char (point-min))
8289 (while (not (eobp))
8290 (setq line (buffer-substring (point)
8291 (save-excursion (end-of-line) (point))))
8292 (forward-line 1)
8293 (when (string-match "//" line)
8294 (setq line (substring line 0 (match-beginning 0))))
14862301 8295 (with-current-buffer orig-buffer ; Variables are buffer-local, so need right context.
6341f357
DN
8296 (verilog-getopt line))))))
8297
8298(defun verilog-getopt-flags ()
8299 "Convert `verilog-library-flags' into standard library variables."
8300 ;; If the flags are local, then all the outputs should be local also
8301 (when (local-variable-p `verilog-library-flags (current-buffer))
7ea26faf
DN
8302 (mapc 'make-local-variable '(verilog-library-extensions
8303 verilog-library-directories
8304 verilog-library-files
8305 verilog-library-flags)))
6341f357
DN
8306 ;; Allow user to customize
8307 (run-hooks 'verilog-before-getopt-flags-hook)
8308 ;; Process arguments
8309 (verilog-getopt verilog-library-flags)
8310 ;; Allow user to customize
8311 (run-hooks 'verilog-getopt-flags-hook))
8312
8313(defun verilog-add-list-unique (varref object)
8314 "Append to VARREF list the given OBJECT,
37ea4b9b 8315unless it is already a member of the variable's list."
6341f357
DN
8316 (unless (member object (symbol-value varref))
8317 (set varref (append (symbol-value varref) (list object))))
8318 varref)
8319;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
8320
a03c2342
WS
8321(defun verilog-current-flags ()
8322 "Convert `verilog-library-flags' and similar variables to command line.
8323Used for __FLAGS__ in `verilog-expand-command'."
8324 (let ((cmd (mapconcat `concat verilog-library-flags " ")))
8325 (when (equal cmd "")
8326 (setq cmd (concat
8327 "+libext+" (mapconcat `concat verilog-library-extensions "+")
8328 (mapconcat (lambda (i) (concat " -y " i " +incdir+" i))
8329 verilog-library-directories "")
8330 (mapconcat (lambda (i) (concat " -v " i))
8331 verilog-library-files ""))))
8332 cmd))
8333;;(verilog-current-flags)
8334
6341f357 8335\f
5509c6ad
DN
8336;;
8337;; Cached directory support
8338;;
8339
8340(defvar verilog-dir-cache-preserving nil
8341 "If set, the directory cache is enabled, and file system changes are ignored.
8342See `verilog-dir-exists-p' and `verilog-dir-files'.")
8343
8344;; If adding new cached variable, add also to verilog-preserve-dir-cache
8345(defvar verilog-dir-cache-list nil
8346 "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
8347(defvar verilog-dir-cache-lib-filenames nil
8348 "Cached data for `verilog-library-filenames'.")
8349
8350(defmacro verilog-preserve-dir-cache (&rest body)
8351 "Execute the BODY forms, allowing directory cache preservation within BODY.
8352This means that changes inside BODY made to the file system will not be
8353seen by the `verilog-dir-files' and related functions."
a03c2342 8354 `(let ((verilog-dir-cache-preserving (current-buffer))
5509c6ad
DN
8355 verilog-dir-cache-list
8356 verilog-dir-cache-lib-filenames)
8357 (progn ,@body)))
8358
8359(defun verilog-dir-files (dirname)
8360 "Return all filenames in the DIRNAME directory.
8361Relative paths depend on the `default-directory'.
8362Results are cached if inside `verilog-preserve-dir-cache'."
8363 (unless verilog-dir-cache-preserving
8364 (setq verilog-dir-cache-list nil)) ;; Cache disabled
8365 ;; We don't use expand-file-name on the dirname to make key, as it's slow
8366 (let* ((cache-key (list dirname default-directory))
8367 (fass (assoc cache-key verilog-dir-cache-list))
8368 exp-dirname data)
8369 (cond (fass ;; Return data from cache hit
8370 (nth 1 fass))
8371 (t
8372 (setq exp-dirname (expand-file-name dirname)
8373 data (and (file-directory-p exp-dirname)
8374 (directory-files exp-dirname nil nil nil)))
8375 ;; Note we also encache nil for non-existing dirs.
8376 (setq verilog-dir-cache-list (cons (list cache-key data)
8377 verilog-dir-cache-list))
8378 data))))
8379;; Miss-and-hit test:
8380;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
8381;; (prin1 (verilog-dir-files ".")) nil)
8382
8383(defun verilog-dir-file-exists-p (filename)
8384 "Return true if FILENAME exists.
8385Like `file-exists-p' but results are cached if inside
8386`verilog-preserve-dir-cache'."
8387 (let* ((dirname (file-name-directory filename))
8388 ;; Correct for file-name-nondirectory returning same if no slash.
8389 (dirnamed (if (or (not dirname) (equal dirname filename))
8390 default-directory dirname))
8391 (flist (verilog-dir-files dirnamed)))
8392 (and flist
8393 (member (file-name-nondirectory filename) flist)
8394 t)))
8395;;(verilog-dir-file-exists-p "verilog-mode.el")
8396;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
8397
8398\f
6341f357
DN
8399;;
8400;; Module name lookup
8401;;
8402
8403(defun verilog-module-inside-filename-p (module filename)
a03c2342 8404 "Return modi if MODULE is specified inside FILENAME, else nil.
6341f357
DN
8405Allows version control to check out the file if need be."
8406 (and (or (file-exists-p filename)
7ea26faf
DN
8407 (and (fboundp 'vc-backend)
8408 (vc-backend filename)))
a03c2342 8409 (let (modi type)
9a529312 8410 (with-current-buffer (find-file-noselect filename)
14862301
SM
8411 (save-excursion
8412 (goto-char (point-min))
8413 (while (and
8414 ;; It may be tempting to look for verilog-defun-re,
8415 ;; don't, it slows things down a lot!
a03c2342
WS
8416 (verilog-re-search-forward-quick "\\<\\(module\\|interface\\)\\>" nil t)
8417 (setq type (match-string-no-properties 0))
14862301
SM
8418 (verilog-re-search-forward-quick "[(;]" nil t))
8419 (if (equal module (verilog-read-module-name))
a03c2342
WS
8420 (setq modi (verilog-modi-new module filename (point) type))))
8421 modi)))))
6341f357
DN
8422
8423(defun verilog-is-number (symbol)
8424 "Return true if SYMBOL is number-like."
8425 (or (string-match "^[0-9 \t:]+$" symbol)
8426 (string-match "^[---]*[0-9]+$" symbol)
60618039 8427 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
6341f357
DN
8428
8429(defun verilog-symbol-detick (symbol wing-it)
37ea4b9b 8430 "Return an expanded SYMBOL name without any defines.
6341f357
DN
8431If the variable vh-{symbol} is defined, return that value.
8432If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
8433 (while (and symbol (string-match "^`" symbol))
8434 (setq symbol (substring symbol 1))
8435 (setq symbol
8436 (if (boundp (intern (concat "vh-" symbol)))
8437 ;; Emacs has a bug where boundp on a buffer-local
8438 ;; variable in only one buffer returns t in another.
8439 ;; This can confuse, so check for nil.
8440 (let ((val (eval (intern (concat "vh-" symbol)))))
8441 (if (eq val nil)
8442 (if wing-it symbol nil)
8443 val))
8444 (if wing-it symbol nil))))
8445 symbol)
8446;;(verilog-symbol-detick "`mod" nil)
8447
8448(defun verilog-symbol-detick-denumber (symbol)
8449 "Return SYMBOL with defines converted and any numbers dropped to nil."
8450 (when (string-match "^`" symbol)
8451 ;; This only will work if the define is a simple signal, not
8452 ;; something like a[b]. Sorry, it should be substituted into the parser
8453 (setq symbol
8454 (verilog-string-replace-matches
8455 "\[[^0-9: \t]+\]" "" nil nil
8456 (or (verilog-symbol-detick symbol nil)
8457 (if verilog-auto-sense-defines-constant
8458 "0"
8459 symbol)))))
8460 (if (verilog-is-number symbol)
8461 nil
8462 symbol))
8463
8464(defun verilog-symbol-detick-text (text)
37ea4b9b 8465 "Return TEXT without any known defines.
6341f357
DN
8466If the variable vh-{symbol} is defined, substitute that value."
8467 (let ((ok t) symbol val)
8468 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
8469 (setq symbol (match-string 1 text))
a3a8b002 8470 ;;(message symbol)
6341f357
DN
8471 (cond ((and
8472 (boundp (intern (concat "vh-" symbol)))
8473 ;; Emacs has a bug where boundp on a buffer-local
8474 ;; variable in only one buffer returns t in another.
8475 ;; This can confuse, so check for nil.
8476 (setq val (eval (intern (concat "vh-" symbol)))))
8477 (setq text (replace-match val nil nil text)))
8478 (t (setq ok nil)))))
8479 text)
8480;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
8481
8482(defun verilog-expand-dirnames (&optional dirnames)
8483 "Return a list of existing directories given a list of wildcarded DIRNAMES.
8484Or, just the existing dirnames themselves if there are no wildcards."
5509c6ad
DN
8485 ;; Note this function is performance critical.
8486 ;; Do not call anything that requires disk access that cannot be cached.
6341f357
DN
8487 (interactive)
8488 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
8489 (setq dirnames (reverse dirnames)) ; not nreverse
8490 (let ((dirlist nil)
5509c6ad 8491 pattern dirfile dirfiles dirname root filename rest basefile)
6341f357
DN
8492 (while dirnames
8493 (setq dirname (substitute-in-file-name (car dirnames))
8494 dirnames (cdr dirnames))
8495 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
8496 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
8497 "\\(.*\\)") ;; rest
8498 dirname)
8499 (setq root (match-string 1 dirname)
8500 filename (match-string 2 dirname)
8501 rest (match-string 3 dirname)
8502 pattern filename)
8503 ;; now replace those * and ? with .+ and .
8504 ;; use ^ and /> to get only whole file names
6341f357
DN
8505 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
8506 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
5509c6ad
DN
8507 pattern (concat "^" pattern "$")
8508 dirfiles (verilog-dir-files root))
6341f357 8509 (while dirfiles
5509c6ad
DN
8510 (setq basefile (car dirfiles)
8511 dirfile (expand-file-name (concat root basefile rest))
6341f357 8512 dirfiles (cdr dirfiles))
5509c6ad
DN
8513 (if (and (string-match pattern basefile)
8514 ;; Don't allow abc/*/rtl to match abc/rtl via ..
8515 (not (equal basefile "."))
8516 (not (equal basefile ".."))
8517 (file-directory-p dirfile))
60618039 8518 (setq dirlist (cons dirfile dirlist)))))
6341f357
DN
8519 ;; Defaults
8520 (t
8521 (if (file-directory-p dirname)
60618039 8522 (setq dirlist (cons dirname dirlist))))))
6341f357
DN
8523 dirlist))
8524;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
8525
0e5c8aed 8526(defun verilog-library-filenames (filename &optional current check-ext)
5509c6ad 8527 "Return a search path to find the given FILENAME or module name.
0e5c8aed
DN
8528Uses the optional CURRENT filename or buffer-file-name, plus
8529`verilog-library-directories' and `verilog-library-extensions'
8530variables to build the path. With optional CHECK-EXT also check
8531`verilog-library-extensions'."
8532 (unless current (setq current (buffer-file-name)))
5509c6ad
DN
8533 (unless verilog-dir-cache-preserving
8534 (setq verilog-dir-cache-lib-filenames nil))
8535 (let* ((cache-key (list filename current check-ext))
8536 (fass (assoc cache-key verilog-dir-cache-lib-filenames))
8537 chkdirs chkdir chkexts fn outlist)
8538 (cond (fass ;; Return data from cache hit
8539 (nth 1 fass))
8540 (t
8541 ;; Note this expand can't be easily cached, as we need to
8542 ;; pick up buffer-local variables for newly read sub-module files
8543 (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
8544 (while chkdirs
8545 (setq chkdir (expand-file-name (car chkdirs)
8546 (file-name-directory current))
8547 chkexts (if check-ext verilog-library-extensions `("")))
8548 (while chkexts
8549 (setq fn (expand-file-name (concat filename (car chkexts))
8550 chkdir))
8551 ;;(message "Check for %s" fn)
8552 (if (verilog-dir-file-exists-p fn)
8553 (setq outlist (cons (expand-file-name
8554 fn (file-name-directory current))
8555 outlist)))
8556 (setq chkexts (cdr chkexts)))
8557 (setq chkdirs (cdr chkdirs)))
8558 (setq outlist (nreverse outlist))
8559 (setq verilog-dir-cache-lib-filenames
8560 (cons (list cache-key outlist)
8561 verilog-dir-cache-lib-filenames))
8562 outlist))))
6341f357
DN
8563
8564(defun verilog-module-filenames (module current)
8565 "Return a search path to find the given MODULE name.
8566Uses the CURRENT filename, `verilog-library-extensions',
8567`verilog-library-directories' and `verilog-library-files'
8568variables to build the path."
8569 ;; Return search locations for it
8570 (append (list current) ; first, current buffer
8571 (verilog-library-filenames module current t)
8572 verilog-library-files)) ; finally, any libraries
8573
8574;;
8575;; Module Information
8576;;
8577;; Many of these functions work on "modi" a module information structure
8578;; A modi is: [module-name-string file-name begin-point]
8579
8580(defvar verilog-cache-enabled t
8581 "If true, enable caching of signals, etc. Set to nil for debugging to make things SLOW!")
8582
8583(defvar verilog-modi-cache-list nil
8584 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
8585For speeding up verilog-modi-get-* commands.
8586Buffer-local.")
7ea26faf
DN
8587(make-variable-buffer-local 'verilog-modi-cache-list)
8588
6341f357
DN
8589(defvar verilog-modi-cache-preserve-tick nil
8590 "Modification tick after which the cache is still considered valid.
5509c6ad 8591Use `verilog-preserve-modi-cache' to set it.")
6341f357
DN
8592(defvar verilog-modi-cache-preserve-buffer nil
8593 "Modification tick after which the cache is still considered valid.
5509c6ad 8594Use `verilog-preserve-modi-cache' to set it.")
a03c2342
WS
8595(defvar verilog-modi-cache-current-enable nil
8596 "If true, allow caching `verilog-modi-current', set by let().")
8597(defvar verilog-modi-cache-current nil
8598 "Currently active `verilog-modi-current', if any, set by let().")
8599(defvar verilog-modi-cache-current-max nil
8600 "Current endmodule point for `verilog-modi-cache-current', if any.")
6341f357
DN
8601
8602(defun verilog-modi-current ()
a03c2342
WS
8603 "Return the modi structure for the module currently at point, possibly cached."
8604 (cond ((and verilog-modi-cache-current
8605 (>= (point) (verilog-modi-get-point verilog-modi-cache-current))
8606 (<= (point) verilog-modi-cache-current-max))
8607 ;; Slow assertion, for debugging the cache:
8608 ;;(or (equal verilog-modi-cache-current (verilog-modi-current-get)) (debug))
8609 verilog-modi-cache-current)
8610 (verilog-modi-cache-current-enable
8611 (setq verilog-modi-cache-current (verilog-modi-current-get)
8612 verilog-modi-cache-current-max
8613 ;; The cache expires when we pass "endmodule" as then the
8614 ;; current modi may change to the next module
8615 ;; This relies on the AUTOs generally inserting, not deleting text
8616 (save-excursion
8617 (verilog-re-search-forward-quick verilog-end-defun-re nil nil)))
8618 verilog-modi-cache-current)
8619 (t
8620 (verilog-modi-current-get))))
8621
8622(defun verilog-modi-current-get ()
6341f357 8623 "Return the modi structure for the module currently at point."
a03c2342 8624 (let* (name type pt)
6341f357
DN
8625 ;; read current module's name
8626 (save-excursion
8627 (verilog-re-search-backward-quick verilog-defun-re nil nil)
a03c2342 8628 (setq type (match-string-no-properties 0))
6341f357
DN
8629 (verilog-re-search-forward-quick "(" nil nil)
8630 (setq name (verilog-read-module-name))
8631 (setq pt (point)))
a03c2342
WS
8632 ;; return modi - note this vector built two places
8633 (verilog-modi-new name (or (buffer-file-name) (current-buffer)) pt type)))
6341f357 8634
a03c2342
WS
8635(defvar verilog-modi-lookup-cache nil "Hash of (modulename modi).")
8636(make-variable-buffer-local 'verilog-modi-lookup-cache)
8637(defvar verilog-modi-lookup-last-current nil "Cache of `current-buffer' at last lookup.")
8638(defvar verilog-modi-lookup-last-tick nil "Cache of `buffer-chars-modified-tick' at last lookup.")
6341f357
DN
8639
8640(defun verilog-modi-lookup (module allow-cache &optional ignore-error)
8641 "Find the file and point at which MODULE is defined.
8642If ALLOW-CACHE is set, check and remember cache of previous lookups.
8643Return modi if successful, else print message unless IGNORE-ERROR is true."
a03c2342
WS
8644 (let* ((current (or (buffer-file-name) (current-buffer)))
8645 modi)
8646 ;; Check cache
8647 ;;(message "verilog-modi-lookup: %s" module)
8648 (cond ((and verilog-modi-lookup-cache
6341f357
DN
8649 verilog-cache-enabled
8650 allow-cache
a03c2342 8651 (setq modi (gethash module verilog-modi-lookup-cache))
6341f357 8652 (equal verilog-modi-lookup-last-current current)
a03c2342
WS
8653 ;; Iff hit is in current buffer, then tick must match
8654 (or (equal verilog-modi-lookup-last-tick (buffer-chars-modified-tick))
8655 (not (equal current (verilog-modi-file-or-buffer modi)))))
8656 ;;(message "verilog-modi-lookup: HIT %S" modi)
8657 modi)
8658 ;; Miss
6341f357
DN
8659 (t (let* ((realmod (verilog-symbol-detick module t))
8660 (orig-filenames (verilog-module-filenames realmod current))
8661 (filenames orig-filenames)
a03c2342
WS
8662 mif)
8663 (while (and filenames (not mif))
8664 (if (not (setq mif (verilog-module-inside-filename-p realmod (car filenames))))
6341f357 8665 (setq filenames (cdr filenames))))
a03c2342
WS
8666 ;; mif has correct form to become later elements of modi
8667 (cond (mif (setq modi mif))
8668 (t (setq modi nil)
6341f357
DN
8669 (or ignore-error
8670 (error (concat (verilog-point-text)
8671 ": Can't locate " module " module definition"
8672 (if (not (equal module realmod))
8673 (concat " (Expanded macro to " realmod ")")
8674 "")
8675 "\n Check the verilog-library-directories variable."
8676 "\n I looked in (if not listed, doesn't exist):\n\t"
60618039 8677 (mapconcat 'concat orig-filenames "\n\t"))))))
a03c2342
WS
8678 (when (eval-when-compile (fboundp 'make-hash-table))
8679 (unless verilog-modi-lookup-cache
8680 (setq verilog-modi-lookup-cache
8681 (make-hash-table :test 'equal :rehash-size 4.0)))
8682 (puthash module modi verilog-modi-lookup-cache))
8683 (setq verilog-modi-lookup-last-current current
8684 verilog-modi-lookup-last-tick (buffer-chars-modified-tick)))))
8685 modi))
6341f357
DN
8686
8687(defun verilog-modi-filename (modi)
37ea4b9b 8688 "Filename of MODI, or name of buffer if it's never been saved."
6341f357
DN
8689 (if (bufferp (verilog-modi-file-or-buffer modi))
8690 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
8691 (buffer-name (verilog-modi-file-or-buffer modi)))
8692 (verilog-modi-file-or-buffer modi)))
8693
8694(defun verilog-modi-goto (modi)
8695 "Move point/buffer to specified MODI."
8696 (or modi (error "Passed unfound modi to goto, check earlier"))
8697 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
8698 (verilog-modi-file-or-buffer modi)
8699 (find-file-noselect (verilog-modi-file-or-buffer modi))))
37ea4b9b 8700 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
6341f357 8701 (verilog-mode))
a03c2342 8702 (goto-char (verilog-modi-get-point modi)))
6341f357
DN
8703
8704(defun verilog-goto-defun-file (module)
8705 "Move point to the file at which a given MODULE is defined."
8706 (interactive "sGoto File for Module: ")
8707 (let* ((modi (verilog-modi-lookup module nil)))
8708 (when modi
8709 (verilog-modi-goto modi)
8710 (switch-to-buffer (current-buffer)))))
8711
8712(defun verilog-modi-cache-results (modi function)
8713 "Run on MODI the given FUNCTION. Locate the module in a file.
8714Cache the output of function so next call may have faster access."
5509c6ad
DN
8715 (let (fass)
8716 (save-excursion ;; Cache is buffer-local so can't avoid this.
6341f357 8717 (verilog-modi-goto modi)
5509c6ad 8718 (if (and (setq fass (assoc (list modi function)
6341f357
DN
8719 verilog-modi-cache-list))
8720 ;; Destroy caching when incorrect; Modified or file changed
8721 (not (and verilog-cache-enabled
a03c2342 8722 (or (equal (buffer-chars-modified-tick) (nth 1 fass))
6341f357
DN
8723 (and verilog-modi-cache-preserve-tick
8724 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
8725 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
8726 (equal (visited-file-modtime) (nth 2 fass)))))
8727 (setq verilog-modi-cache-list nil
8728 fass nil))
8729 (cond (fass
5509c6ad
DN
8730 ;; Return data from cache hit
8731 (nth 3 fass))
6341f357
DN
8732 (t
8733 ;; Read from file
86a4c7ac 8734 ;; Clear then restore any highlighting to make emacs19 happy
6341f357
DN
8735 (let ((fontlocked (when (and (boundp 'font-lock-mode)
8736 font-lock-mode)
7cb1c4d7 8737 (font-lock-mode 0)
5509c6ad
DN
8738 t))
8739 func-returns)
6341f357 8740 (setq func-returns (funcall function))
5509c6ad 8741 (when fontlocked (font-lock-mode t))
9c059794
DN
8742 ;; Cache for next time
8743 (setq verilog-modi-cache-list
5509c6ad 8744 (cons (list (list modi function)
a03c2342 8745 (buffer-chars-modified-tick)
9c059794
DN
8746 (visited-file-modtime)
8747 func-returns)
5509c6ad
DN
8748 verilog-modi-cache-list))
8749 func-returns))))))
6341f357
DN
8750
8751(defun verilog-modi-cache-add (modi function element sig-list)
8752 "Add function return results to the module cache.
8753Update MODI's cache for given FUNCTION so that the return ELEMENT of that
8754function now contains the additional SIG-LIST parameters."
8755 (let (fass)
8756 (save-excursion
8757 (verilog-modi-goto modi)
5509c6ad 8758 (if (setq fass (assoc (list modi function)
6341f357
DN
8759 verilog-modi-cache-list))
8760 (let ((func-returns (nth 3 fass)))
8761 (aset func-returns element
8762 (append sig-list (aref func-returns element))))))))
8763
5509c6ad 8764(defmacro verilog-preserve-modi-cache (&rest body)
6341f357
DN
8765 "Execute the BODY forms, allowing cache preservation within BODY.
8766This means that changes to the buffer will not result in the cache being
8767flushed. If the changes affect the modsig state, they must call the
8768modsig-cache-add-* function, else the results of later calls may be
8769incorrect. Without this, changes are assumed to be adding/removing signals
8770and invalidating the cache."
a03c2342 8771 `(let ((verilog-modi-cache-preserve-tick (buffer-chars-modified-tick))
6341f357
DN
8772 (verilog-modi-cache-preserve-buffer (current-buffer)))
8773 (progn ,@body)))
8774
6341f357
DN
8775
8776(defun verilog-signals-matching-enum (in-list enum)
8777 "Return all signals in IN-LIST matching the given ENUM."
8778 (let (out-list)
8779 (while in-list
8780 (if (equal (verilog-sig-enum (car in-list)) enum)
8781 (setq out-list (cons (car in-list) out-list)))
8782 (setq in-list (cdr in-list)))
8783 ;; New scheme
8784 (let* ((enumvar (intern (concat "venum-" enum)))
8785 (enumlist (and (boundp enumvar) (eval enumvar))))
8786 (while enumlist
8787 (add-to-list 'out-list (list (car enumlist)))
8788 (setq enumlist (cdr enumlist))))
8789 (nreverse out-list)))
8790
e2076c2c
DN
8791(defun verilog-signals-matching-regexp (in-list regexp)
8792 "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
a3a8b002 8793 (if (or (not regexp) (equal regexp ""))
e2076c2c
DN
8794 in-list
8795 (let (out-list)
8796 (while in-list
8797 (if (string-match regexp (verilog-sig-name (car in-list)))
8798 (setq out-list (cons (car in-list) out-list)))
8799 (setq in-list (cdr in-list)))
8800 (nreverse out-list))))
8801
6341f357
DN
8802(defun verilog-signals-not-matching-regexp (in-list regexp)
8803 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
a3a8b002 8804 (if (or (not regexp) (equal regexp ""))
6341f357
DN
8805 in-list
8806 (let (out-list)
8807 (while in-list
8808 (if (not (string-match regexp (verilog-sig-name (car in-list))))
8809 (setq out-list (cons (car in-list) out-list)))
8810 (setq in-list (cdr in-list)))
8811 (nreverse out-list))))
8812
a3a8b002 8813(defun verilog-signals-matching-dir-re (in-list decl-type regexp)
0e5c8aed 8814 "Return all signals in IN-LIST matching the given DECL-TYPE and REGEXP,
a3a8b002
DN
8815if non-nil."
8816 (if (or (not regexp) (equal regexp ""))
8817 in-list
8818 (let (out-list to-match)
8819 (while in-list
8820 ;; Note verilog-insert-one-definition matches on this order
8821 (setq to-match (concat
8822 decl-type
8823 " " (verilog-sig-signed (car in-list))
8824 " " (verilog-sig-multidim (car in-list))
8825 (verilog-sig-bits (car in-list))))
8826 (if (string-match regexp to-match)
8827 (setq out-list (cons (car in-list) out-list)))
8828 (setq in-list (cdr in-list)))
8829 (nreverse out-list))))
8830
6341f357 8831;; Combined
5509c6ad 8832(defun verilog-decls-get-signals (decls)
6341f357 8833 (append
5509c6ad
DN
8834 (verilog-decls-get-outputs decls)
8835 (verilog-decls-get-inouts decls)
8836 (verilog-decls-get-inputs decls)
8837 (verilog-decls-get-wires decls)
8838 (verilog-decls-get-regs decls)
8839 (verilog-decls-get-assigns decls)
8840 (verilog-decls-get-consts decls)
8841 (verilog-decls-get-gparams decls)))
8842
8843(defun verilog-decls-get-ports (decls)
6341f357 8844 (append
5509c6ad
DN
8845 (verilog-decls-get-outputs decls)
8846 (verilog-decls-get-inouts decls)
8847 (verilog-decls-get-inputs decls)))
6341f357
DN
8848
8849(defsubst verilog-modi-cache-add-outputs (modi sig-list)
8850 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
8851(defsubst verilog-modi-cache-add-inouts (modi sig-list)
8852 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
8853(defsubst verilog-modi-cache-add-inputs (modi sig-list)
8854 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
8855(defsubst verilog-modi-cache-add-wires (modi sig-list)
8856 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
8857(defsubst verilog-modi-cache-add-regs (modi sig-list)
8858 (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
8859
8860(defun verilog-signals-from-signame (signame-list)
8861 "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
8862 (mapcar (function (lambda (name) (list name nil nil)))
8863 signame-list))
8864\f
8865;;
8866;; Auto creation utilities
8867;;
8868
495ab0d5
DN
8869(defun verilog-auto-re-search-do (search-for func)
8870 "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
6341f357 8871 (goto-char (point-min))
495ab0d5
DN
8872 (while (verilog-re-search-forward search-for nil t)
8873 (funcall func)))
6341f357 8874
6341f357 8875(defun verilog-insert-one-definition (sig type indent-pt)
60618039 8876 "Print out a definition for SIG of the given TYPE,
6341f357
DN
8877with appropriate INDENT-PT indentation."
8878 (indent-to indent-pt)
a3a8b002 8879 ;; Note verilog-signals-matching-dir-re matches on this order
6341f357 8880 (insert type)
a3a8b002
DN
8881 (when (verilog-sig-modport sig)
8882 (insert "." (verilog-sig-modport sig)))
6341f357
DN
8883 (when (verilog-sig-signed sig)
8884 (insert " " (verilog-sig-signed sig)))
8885 (when (verilog-sig-multidim sig)
8886 (insert " " (verilog-sig-multidim-string sig)))
8887 (when (verilog-sig-bits sig)
8888 (insert " " (verilog-sig-bits sig)))
8889 (indent-to (max 24 (+ indent-pt 16)))
8890 (unless (= (char-syntax (preceding-char)) ?\ )
8891 (insert " ")) ; Need space between "]name" if indent-to did nothing
8468f78b
WS
8892 (insert (verilog-sig-name sig))
8893 (when (verilog-sig-memory sig)
8894 (insert " " (verilog-sig-memory sig))))
6341f357
DN
8895
8896(defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
8897 "Print out a definition for a list of SIGS of the given DIRECTION,
8898with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
8899format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output."
8900 (or dont-sort
8901 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
8902 (while sigs
8903 (let ((sig (car sigs)))
8904 (verilog-insert-one-definition
8905 sig
8906 ;; Want "type x" or "output type x", not "wire type x"
8907 (cond ((verilog-sig-type sig)
8908 (concat
a3a8b002 8909 (if (not (member direction '("wire" "interface")))
6341f357
DN
8910 (concat direction " "))
8911 (verilog-sig-type sig)))
8912 (t direction))
8913 indent-pt)
8914 (insert (if v2k "," ";"))
8915 (if (or (not (verilog-sig-comment sig))
8916 (equal "" (verilog-sig-comment sig)))
8917 (insert "\n")
8918 (indent-to (max 48 (+ indent-pt 40)))
a03c2342 8919 (verilog-insert "// " (verilog-sig-comment sig) "\n"))
6341f357
DN
8920 (setq sigs (cdr sigs)))))
8921
8922(eval-when-compile
8923 (if (not (boundp 'indent-pt))
8924 (defvar indent-pt nil "Local used by insert-indent")))
8925
8926(defun verilog-insert-indent (&rest stuff)
8927 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
8928Presumes that any newlines end a list element."
8929 (let ((need-indent t))
8930 (while stuff
8931 (if need-indent (indent-to indent-pt))
8932 (setq need-indent nil)
a03c2342 8933 (verilog-insert (car stuff))
6341f357
DN
8934 (setq need-indent (string-match "\n$" (car stuff))
8935 stuff (cdr stuff)))))
8936;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
8937
8938(defun verilog-repair-open-comma ()
a3a8b002
DN
8939 "Insert comma if previous argument is other than a open parenthesis or endif."
8940 ;; We can't just search backward for ) as it might be inside another expression.
8941 ;; Also want "`ifdef X input foo `endif" to just leave things to the human to deal with
6341f357
DN
8942 (save-excursion
8943 (verilog-backward-syntactic-ws)
a3a8b002
DN
8944 (when (and (not (save-excursion ;; Not beginning (, or existing ,
8945 (backward-char 1)
8946 (looking-at "[(,]")))
8947 (not (save-excursion ;; Not `endif, or user define
8948 (backward-char 1)
8949 (skip-chars-backward "[a-zA-Z0-9_`]")
8950 (looking-at "`"))))
8951 (insert ","))))
6341f357
DN
8952
8953(defun verilog-repair-close-comma ()
8954 "If point is at a comma followed by a close parenthesis, fix it.
8955This repairs those mis-inserted by a AUTOARG."
8956 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
8957 (save-excursion
8958 (verilog-forward-close-paren)
8959 (backward-char 1)
8960 (verilog-backward-syntactic-ws)
8961 (backward-char 1)
8962 (when (looking-at ",")
8963 (delete-char 1))))
8964
8965(defun verilog-get-list (start end)
8966 "Return the elements of a comma separated list between START and END."
8967 (interactive)
8968 (let ((my-list (list))
8969 my-string)
8970 (save-excursion
8971 (while (< (point) end)
8972 (when (re-search-forward "\\([^,{]+\\)" end t)
8973 (setq my-string (verilog-string-remove-spaces (match-string 1)))
8974 (setq my-list (nconc my-list (list my-string) ))
8975 (goto-char (match-end 0))))
8976 my-list)))
8977
8978(defun verilog-make-width-expression (range-exp)
8979 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
8980 ;; strip off the []
8981 (cond ((not range-exp)
8982 "1")
8983 (t
8984 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
8985 (setq range-exp (match-string 1 range-exp)))
8986 (cond ((not range-exp)
8987 "1")
a3a8b002 8988 ;; [#:#] We can compute a numeric result
7ea26faf
DN
8989 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
8990 range-exp)
8991 (int-to-string
8992 (1+ (abs (- (string-to-number (match-string 1 range-exp))
8993 (string-to-number (match-string 2 range-exp)))))))
a3a8b002
DN
8994 ;; [PARAM-1:0] can just return PARAM
8995 ((string-match "^\\s *\\([a-zA-Z_][a-zA-Z0-9_]*\\)\\s *-\\s *1\\s *:\\s *0\\s *$" range-exp)
8996 (match-string 1 range-exp))
8997 ;; [arbitrary] need math
6341f357 8998 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
7ea26faf 8999 (concat "(1+(" (match-string 1 range-exp) ")"
60618039
DN
9000 (if (equal "0" (match-string 2 range-exp))
9001 "" ;; Don't bother with -(0)
6341f357
DN
9002 (concat "-(" (match-string 2 range-exp) ")"))
9003 ")"))
9004 (t nil)))))
9005;;(verilog-make-width-expression "`A:`B")
9006
4c5e69c6
DN
9007(defun verilog-simplify-range-expression (range-exp)
9008 "Return a simplified range expression with constants eliminated from RANGE-EXP."
9009 (let ((out range-exp)
9010 (last-pass ""))
9011 (while (not (equal last-pass out))
9012 (setq last-pass out)
7cb1c4d7 9013 (while (string-match "(\\<\\([0-9A-Z-az_]+\\)\\>)" out)
4c5e69c6
DN
9014 (setq out (replace-match "\\1" nil nil out)))
9015 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\+\\s *\\<\\([0-9]+\\)\\>" out)
a3a8b002 9016 (setq out (replace-match
4c5e69c6
DN
9017 (int-to-string (+ (string-to-number (match-string 1 out))
9018 (string-to-number (match-string 2 out))))
9019 nil nil out)))
9020 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\-\\s *\\<\\([0-9]+\\)\\>" out)
a3a8b002 9021 (setq out (replace-match
4c5e69c6
DN
9022 (int-to-string (- (string-to-number (match-string 1 out))
9023 (string-to-number (match-string 2 out))))
9024 nil nil out))))
9025 out))
9026;;(verilog-simplify-range-expression "1")
9027;;(verilog-simplify-range-expression "(((16)+1)-3)")
9028
6341f357
DN
9029(defun verilog-typedef-name-p (variable-name)
9030 "Return true if the VARIABLE-NAME is a type definition."
9031 (when verilog-typedef-regexp
9032 (string-match verilog-typedef-regexp variable-name)))
9033\f
9034;;
9035;; Auto deletion
9036;;
9037
9038(defun verilog-delete-autos-lined ()
9039 "Delete autos that occupy multiple lines, between begin and end comments."
9040 (let ((pt (point)))
9041 (forward-line 1)
9042 (when (and
9043 (looking-at "\\s-*// Beginning")
9044 (search-forward "// End of automatic" nil t))
9045 ;; End exists
9046 (end-of-line)
9047 (delete-region pt (point))
60618039 9048 (forward-line 1))))
6341f357 9049
0e5c8aed
DN
9050(defun verilog-delete-empty-auto-pair ()
9051 "Delete begin/end auto pair at point, if empty."
9052 (forward-line 0)
9053 (when (looking-at (concat "\\s-*// Beginning of automatic.*\n"
9054 "\\s-*// End of automatics\n"))
9055 (delete-region (point) (save-excursion (forward-line 2) (point)))))
9056
6341f357 9057(defun verilog-forward-close-paren ()
37ea4b9b
JB
9058 "Find the close parenthesis that match the current point.
9059Ignore other close parenthesis with matching open parens."
6341f357
DN
9060 (let ((parens 1))
9061 (while (> parens 0)
9062 (unless (verilog-re-search-forward-quick "[()]" nil t)
9063 (error "%s: Mismatching ()" (verilog-point-text)))
9064 (cond ((= (preceding-char) ?\( )
9065 (setq parens (1+ parens)))
9066 ((= (preceding-char) ?\) )
9067 (setq parens (1- parens)))))))
9068
9069(defun verilog-backward-open-paren ()
37ea4b9b
JB
9070 "Find the open parenthesis that match the current point.
9071Ignore other open parenthesis with matching close parens."
6341f357
DN
9072 (let ((parens 1))
9073 (while (> parens 0)
9074 (unless (verilog-re-search-backward-quick "[()]" nil t)
9075 (error "%s: Mismatching ()" (verilog-point-text)))
9076 (cond ((= (following-char) ?\) )
9077 (setq parens (1+ parens)))
9078 ((= (following-char) ?\( )
9079 (setq parens (1- parens)))))))
9080
9081(defun verilog-backward-open-bracket ()
37ea4b9b
JB
9082 "Find the open bracket that match the current point.
9083Ignore other open bracket with matching close bracket."
6341f357
DN
9084 (let ((parens 1))
9085 (while (> parens 0)
9086 (unless (verilog-re-search-backward-quick "[][]" nil t)
9087 (error "%s: Mismatching []" (verilog-point-text)))
9088 (cond ((= (following-char) ?\] )
9089 (setq parens (1+ parens)))
9090 ((= (following-char) ?\[ )
9091 (setq parens (1- parens)))))))
9092
9093(defun verilog-delete-to-paren ()
9094 "Delete the automatic inst/sense/arg created by autos.
9095Deletion stops at the matching end parenthesis."
9096 (delete-region (point)
9097 (save-excursion
9098 (verilog-backward-open-paren)
9099 (forward-sexp 1) ;; Moves to paren that closes argdecl's
9100 (backward-char 1)
9101 (point))))
9102
9103(defun verilog-auto-star-safe ()
9104 "Return if a .* AUTOINST is safe to delete or expand.
9105It was created by the AUTOS themselves, or by the user."
9106 (and verilog-auto-star-expand
0e5c8aed 9107 (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\|Interfaces\\)\\)")))
6341f357
DN
9108
9109(defun verilog-delete-auto-star-all ()
9110 "Delete a .* AUTOINST, if it is safe."
9111 (when (verilog-auto-star-safe)
9112 (verilog-delete-to-paren)))
9113
9114(defun verilog-delete-auto-star-implicit ()
9115 "Delete all .* implicit connections created by `verilog-auto-star'.
9116This function will be called automatically at save unless
9117`verilog-auto-star-save' is set, any non-templated expanded pins will be
9118removed."
9119 (interactive)
9120 (let (paren-pt indent have-close-paren)
9121 (save-excursion
9122 (goto-char (point-min))
9123 ;; We need to match these even outside of comments.
9124 ;; For reasonable performance, we don't check if inside comments, sorry.
9125 (while (re-search-forward "// Implicit \\.\\*" nil t)
9126 (setq paren-pt (point))
9127 (beginning-of-line)
9128 (setq have-close-paren
9129 (save-excursion
9130 (when (search-forward ");" paren-pt t)
9131 (setq indent (current-indentation))
9132 t)))
9133 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
9134 (when have-close-paren
9135 ;; Delete extra commentary
9136 (save-excursion
9137 (while (progn
9138 (forward-line -1)
0e5c8aed 9139 (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\|Interfaces\\)\n"))
6341f357
DN
9140 (delete-region (match-beginning 0) (match-end 0))))
9141 ;; If it is simple, we can put the ); on the same line as the last text
9142 (let ((rtn-pt (point)))
9143 (save-excursion
9144 (while (progn (backward-char 1)
9145 (looking-at "[ \t\n\f]")))
9146 (when (looking-at ",")
9147 (delete-region (+ 1 (point)) rtn-pt))))
9148 (when (bolp)
9149 (indent-to indent))
9150 (insert ");\n")
9151 ;; Still need to kill final comma - always is one as we put one after the .*
9152 (re-search-backward ",")
9153 (delete-char 1))))))
9154
9155(defun verilog-delete-auto ()
9156 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
9157Use \\[verilog-auto] to re-insert the updated AUTOs.
9158
9159The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
9160called before and after this function, respectively."
9161 (interactive)
9162 (save-excursion
9163 (if (buffer-file-name)
9164 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
a03c2342
WS
9165 (verilog-save-no-change-functions
9166 (verilog-save-scan-cache
9167 ;; Allow user to customize
9168 (run-hooks 'verilog-before-delete-auto-hook)
9169
9170 ;; Remove those that have multi-line insertions, possibly with parameters
9171 (verilog-auto-re-search-do
9172 (concat "/\\*"
9173 (eval-when-compile
9174 (verilog-regexp-words
9175 `("AUTOASCIIENUM" "AUTOCONCATCOMMENT" "AUTODEFINEVALUE"
9176 "AUTOINOUT" "AUTOINOUTCOMP" "AUTOINOUTMODULE"
9177 "AUTOINPUT" "AUTOINSERTLISP" "AUTOOUTPUT" "AUTOOUTPUTEVERY"
9178 "AUTOREG" "AUTOREGINPUT" "AUTORESET" "AUTOTIEOFF"
9179 "AUTOUNUSED" "AUTOWIRE")))
9180 ;; Optional parens or quoted parameter or .* for (((...)))
9181 "\\(\\|([^)]*)\\|(\"[^\"]*\")\\).*?"
9182 "\\*/")
9183 'verilog-delete-autos-lined)
9184 ;; Remove those that are in parenthesis
9185 (verilog-auto-re-search-do
9186 (concat "/\\*"
9187 (eval-when-compile
9188 (verilog-regexp-words
9189 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
9190 "AUTOSENSE")))
9191 "\\*/")
9192 'verilog-delete-to-paren)
9193 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
9194 (verilog-auto-re-search-do "\\.\\*"
9195 'verilog-delete-auto-star-all)
9196 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
9197 (goto-char (point-min))
9198 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
9199 (replace-match ""))
6341f357 9200
a03c2342
WS
9201 ;; Final customize
9202 (run-hooks 'verilog-delete-auto-hook)))))
6341f357
DN
9203\f
9204;;
9205;; Auto inject
9206;;
9207
9208(defun verilog-inject-auto ()
9209 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
9210
9211Any always @ blocks with sensitivity lists that match computed lists will
9212be replaced with /*AS*/ comments.
9213
37ea4b9b
JB
9214Any cells will get /*AUTOINST*/ added to the end of the pin list.
9215Pins with have identical names will be deleted.
6341f357
DN
9216
9217Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
9218support adding new ports. You may wish to delete older ports yourself.
9219
9220For example:
9221
1dd4b004 9222 module ExampInject (i, o);
6341f357
DN
9223 input i;
9224 input j;
9225 output o;
9226 always @ (i or j)
9227 o = i | j;
1dd4b004
DN
9228 InstModule instName
9229 (.foobar(baz),
9230 j(j));
6341f357
DN
9231 endmodule
9232
9233Typing \\[verilog-inject-auto] will make this into:
9234
1dd4b004 9235 module ExampInject (i, o/*AUTOARG*/
6341f357
DN
9236 // Inputs
9237 j);
9238 input i;
9239 output o;
9240 always @ (/*AS*/i or j)
9241 o = i | j;
1dd4b004
DN
9242 InstModule instName
9243 (.foobar(baz),
9244 /*AUTOINST*/
9245 // Outputs
9246 j(j));
6341f357
DN
9247 endmodule"
9248 (interactive)
9249 (verilog-auto t))
9250
9251(defun verilog-inject-arg ()
9252 "Inject AUTOARG into new code. See `verilog-inject-auto'."
9253 ;; Presume one module per file.
9254 (save-excursion
9255 (goto-char (point-min))
9256 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
9257 (let ((endmodp (save-excursion
9258 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
9259 (point))))
9260 ;; See if there's already a comment .. inside a comment so not verilog-re-search
9261 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
9262 (verilog-re-search-forward-quick ";" nil t)
9263 (backward-char 1)
9264 (verilog-backward-syntactic-ws)
9265 (backward-char 1) ; Moves to paren that closes argdecl's
9266 (when (looking-at ")")
a03c2342 9267 (verilog-insert "/*AUTOARG*/")))))))
6341f357
DN
9268
9269(defun verilog-inject-sense ()
9270 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
9271 (save-excursion
9272 (goto-char (point-min))
9273 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
5509c6ad 9274 (let* ((start-pt (point))
9c059794 9275 (modi (verilog-modi-current))
5509c6ad 9276 (moddecls (verilog-modi-get-decls modi))
9c059794
DN
9277 pre-sigs
9278 got-sigs)
6341f357
DN
9279 (backward-char 1)
9280 (forward-sexp 1)
9281 (backward-char 1) ;; End )
9282 (when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
9283 (setq pre-sigs (verilog-signals-from-signame
9284 (verilog-read-signals start-pt (point)))
5509c6ad 9285 got-sigs (verilog-auto-sense-sigs moddecls nil))
6341f357
DN
9286 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
9287 (verilog-signals-not-in got-sigs pre-sigs)))
9288 (delete-region start-pt (point))
a03c2342 9289 (verilog-insert "/*AS*/")))))))
6341f357
DN
9290
9291(defun verilog-inject-inst ()
9292 "Inject AUTOINST into new code. See `verilog-inject-auto'."
9293 (save-excursion
9294 (goto-char (point-min))
9295 ;; It's hard to distinguish modules; we'll instead search for pins.
9296 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
9297 (verilog-backward-open-paren) ;; Inst start
9298 (cond
9299 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
9300 (forward-char 1)
9301 (verilog-forward-close-paren)) ;; Parameters done
9302 (t
9303 (forward-char 1)
9304 (let ((indent-pt (+ (current-column)))
9305 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
9306 (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
9307 (goto-char end-pt)) ;; Already there, continue search with next instance
9308 (t
9309 ;; Delete identical interconnect
9310 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
9311 (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
9312 (delete-region (match-beginning 0) (match-end 0))
9313 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
9314 (while (or (looking-at "[ \t\n\f,]+")
9315 (looking-at "//[^\n]*"))
9316 (delete-region (match-beginning 0) (match-end 0))
9317 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
9318 (verilog-forward-close-paren)
9319 (backward-char 1)
9320 ;; Not verilog-re-search, as we don't want to strip comments
9321 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
9322 (delete-region (match-beginning 0) (match-end 0)))
a03c2342
WS
9323 (verilog-insert "\n")
9324 (verilog-insert-indent "/*AUTOINST*/")))))))))
6341f357
DN
9325\f
9326;;
9327;; Auto save
9328;;
9329
9330(defun verilog-auto-save-check ()
9331 "On saving see if we need auto update."
9332 (cond ((not verilog-auto-save-policy)) ; disabled
9333 ((not (save-excursion
9334 (save-match-data
9335 (let ((case-fold-search nil))
9336 (goto-char (point-min))
9337 (re-search-forward "AUTO" nil t))))))
9338 ((eq verilog-auto-save-policy 'force)
9339 (verilog-auto))
9340 ((not (buffer-modified-p)))
a03c2342 9341 ((eq verilog-auto-update-tick (buffer-chars-modified-tick))) ; up-to-date
6341f357
DN
9342 ((eq verilog-auto-save-policy 'detect)
9343 (verilog-auto))
9344 (t
9345 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
9346 (verilog-auto))
9347 ;; Don't ask again if didn't update
a03c2342 9348 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))))
6341f357
DN
9349 (when (not verilog-auto-star-save)
9350 (verilog-delete-auto-star-implicit))
9351 nil) ;; Always return nil -- we don't write the file ourselves
9352
9353(defun verilog-auto-read-locals ()
9354 "Return file local variable segment at bottom of file."
9355 (save-excursion
9356 (goto-char (point-max))
9357 (if (re-search-backward "Local Variables:" nil t)
9358 (buffer-substring-no-properties (point) (point-max))
9359 "")))
9360
9361(defun verilog-auto-reeval-locals (&optional force)
9362 "Read file local variable segment at bottom of file if it has changed.
9363If FORCE, always reread it."
7ea26faf 9364 (make-local-variable 'verilog-auto-last-file-locals)
6341f357
DN
9365 (let ((curlocal (verilog-auto-read-locals)))
9366 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
9367 (setq verilog-auto-last-file-locals curlocal)
a3a8b002
DN
9368 ;; Note this may cause this function to be recursively invoked,
9369 ;; because hack-local-variables may call (verilog-mode)
6341f357
DN
9370 ;; The above when statement will prevent it from recursing forever.
9371 (hack-local-variables)
9372 t)))
9373\f
9374;;
9375;; Auto creation
9376;;
9377
9378(defun verilog-auto-arg-ports (sigs message indent-pt)
9379 "Print a list of ports for a AUTOINST.
9380Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
9381 (when sigs
a3a8b002
DN
9382 (when verilog-auto-arg-sort
9383 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
6341f357
DN
9384 (insert "\n")
9385 (indent-to indent-pt)
9386 (insert message)
9387 (insert "\n")
9388 (let ((space ""))
9389 (indent-to indent-pt)
9390 (while sigs
9391 (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
9392 (insert "\n")
9393 (indent-to indent-pt))
9394 (t (insert space)))
9395 (insert (verilog-sig-name (car sigs)) ",")
9396 (setq sigs (cdr sigs)
9397 space " ")))))
9398
9399(defun verilog-auto-arg ()
9400 "Expand AUTOARG statements.
9401Replace the argument declarations at the beginning of the
9402module with ones automatically derived from input and output
9403statements. This can be dangerous if the module is instantiated
9404using position-based connections, so use only name-based when
9405instantiating the resulting module. Long lines are split based
9406on the `fill-column', see \\[set-fill-column].
9407
9408Limitations:
9409 Concatenation and outputting partial busses is not supported.
9410
9411 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9412
9413For example:
9414
1dd4b004 9415 module ExampArg (/*AUTOARG*/);
6341f357
DN
9416 input i;
9417 output o;
9418 endmodule
9419
9420Typing \\[verilog-auto] will make this into:
9421
1dd4b004 9422 module ExampArg (/*AUTOARG*/
6341f357
DN
9423 // Outputs
9424 o,
9425 // Inputs
9426 i
9427 );
9428 input i;
9429 output o;
9430 endmodule
9431
a3a8b002
DN
9432The argument declarations may be printed in declaration order to best suit
9433order based instantiations, or alphabetically, based on the
9434`verilog-auto-arg-sort' variable.
9435
6341f357
DN
9436Any ports declared between the ( and /*AUTOARG*/ are presumed to be
9437predeclared and are not redeclared by AUTOARG. AUTOARG will make a
37ea4b9b
JB
9438conservative guess on adding a comma for the first signal, if you have
9439any ifdefs or complicated expressions before the AUTOARG you will need
9440to choose the comma yourself.
6341f357
DN
9441
9442Avoid declaring ports manually, as it makes code harder to maintain."
9443 (save-excursion
5509c6ad
DN
9444 (let* ((modi (verilog-modi-current))
9445 (moddecls (verilog-modi-get-decls modi))
9c059794 9446 (skip-pins (aref (verilog-read-arg-pins) 0)))
6341f357
DN
9447 (verilog-repair-open-comma)
9448 (verilog-auto-arg-ports (verilog-signals-not-in
5509c6ad 9449 (verilog-decls-get-outputs moddecls)
6341f357
DN
9450 skip-pins)
9451 "// Outputs"
9452 verilog-indent-level-declaration)
9453 (verilog-auto-arg-ports (verilog-signals-not-in
5509c6ad 9454 (verilog-decls-get-inouts moddecls)
6341f357
DN
9455 skip-pins)
9456 "// Inouts"
9457 verilog-indent-level-declaration)
9458 (verilog-auto-arg-ports (verilog-signals-not-in
5509c6ad 9459 (verilog-decls-get-inputs moddecls)
6341f357
DN
9460 skip-pins)
9461 "// Inputs"
9462 verilog-indent-level-declaration)
9463 (verilog-repair-close-comma)
9464 (unless (eq (char-before) ?/ )
9465 (insert "\n"))
60618039 9466 (indent-to verilog-indent-level-declaration))))
6341f357
DN
9467
9468(defun verilog-auto-inst-port-map (port-st)
9469 nil)
9470
6341f357
DN
9471(defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
9472(defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
a3a8b002 9473(defvar vl-modport nil "See `verilog-auto-inst'.") ; Prevent compile warning
6341f357
DN
9474(defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
9475(defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
9476(defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
a03c2342
WS
9477(defvar vl-bits nil "See `verilog-auto-inst'.") ; Prevent compile warning
9478(defvar vl-mbits nil "See `verilog-auto-inst'.") ; Prevent compile warning
6341f357 9479
4c5e69c6 9480(defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
6341f357
DN
9481 "Print out a instantiation connection for this PORT-ST.
9482Insert to INDENT-PT, use template TPL-LIST.
9483@ are instantiation numbers, replaced with TPL-NUM.
60618039 9484@\"(expression @)\" are evaluated, with @ as a variable.
4c5e69c6
DN
9485If FOR-STAR add comment it is a .* expansion.
9486If PAR-VALUES replace final strings with these parameter values."
6341f357
DN
9487 (let* ((port (verilog-sig-name port-st))
9488 (tpl-ass (or (assoc port (car tpl-list))
9489 (verilog-auto-inst-port-map port-st)))
9490 ;; vl-* are documented for user use
9491 (vl-name (verilog-sig-name port-st))
9492 (vl-width (verilog-sig-width port-st))
a3a8b002 9493 (vl-modport (verilog-sig-modport port-st))
a03c2342
WS
9494 (vl-mbits (if (verilog-sig-multidim port-st)
9495 (verilog-sig-multidim-string port-st) ""))
6341f357
DN
9496 (vl-bits (if (or verilog-auto-inst-vector
9497 (not (assoc port vector-skip-list))
9498 (not (equal (verilog-sig-bits port-st)
9499 (verilog-sig-bits (assoc port vector-skip-list)))))
9500 (or (verilog-sig-bits port-st) "")
9501 ""))
4c5e69c6 9502 (case-fold-search nil)
7cb1c4d7
DN
9503 (check-values par-values)
9504 tpl-net)
4c5e69c6
DN
9505 ;; Replace parameters in bit-width
9506 (when (and check-values
9507 (not (equal vl-bits "")))
9508 (while check-values
9509 (setq vl-bits (verilog-string-replace-matches
9510 (concat "\\<" (nth 0 (car check-values)) "\\>")
9511 (concat "(" (nth 1 (car check-values)) ")")
9512 t t vl-bits)
9513 check-values (cdr check-values)))
9514 (setq vl-bits (verilog-simplify-range-expression vl-bits))) ; Not in the loop for speed
7cb1c4d7 9515 ;; Default net value if not found
a3a8b002
DN
9516 (setq tpl-net (concat port
9517 (if vl-modport (concat "." vl-modport) "")
9518 (if (verilog-sig-multidim port-st)
9519 (concat "/*" (verilog-sig-multidim-string port-st)
9520 vl-bits "*/")
9521 (concat vl-bits))))
6341f357
DN
9522 ;; Find template
9523 (cond (tpl-ass ; Template of exact port name
9524 (setq tpl-net (nth 1 tpl-ass)))
9525 ((nth 1 tpl-list) ; Wildcards in template, search them
9526 (let ((wildcards (nth 1 tpl-list)))
9527 (while wildcards
9528 (when (string-match (nth 0 (car wildcards)) port)
9529 (setq tpl-ass (car wildcards) ; so allow @ parsing
9530 tpl-net (replace-match (nth 1 (car wildcards))
9531 t nil port)))
9532 (setq wildcards (cdr wildcards))))))
9533 ;; Parse Templated variable
9534 (when tpl-ass
9535 ;; Evaluate @"(lispcode)"
9536 (when (string-match "@\".*[^\\]\"" tpl-net)
9537 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
9538 (setq tpl-net
9539 (concat
9540 (substring tpl-net 0 (match-beginning 0))
9541 (save-match-data
9542 (let* ((expr (match-string 1 tpl-net))
9543 (value
9544 (progn
9545 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
9546 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
9547 (prin1 (eval (car (read-from-string expr)))
9548 (lambda (ch) ())))))
9549 (if (numberp value) (setq value (number-to-string value)))
60618039 9550 value))
6341f357
DN
9551 (substring tpl-net (match-end 0))))))
9552 ;; Replace @ and [] magic variables in final output
9553 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
60618039 9554 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
4c5e69c6 9555 ;; Insert it
6341f357
DN
9556 (indent-to indent-pt)
9557 (insert "." port)
a03c2342
WS
9558 (unless (and verilog-auto-inst-dot-name
9559 (equal port tpl-net))
9560 (indent-to verilog-auto-inst-column)
9561 (insert "(" tpl-net ")"))
9562 (insert ",")
6341f357
DN
9563 (cond (tpl-ass
9564 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
9565 verilog-auto-inst-column))
a03c2342
WS
9566 (if verilog-auto-inst-template-numbers
9567 (verilog-insert " // Templated"
9568 " T" (int-to-string (nth 2 tpl-ass))
9569 " L" (int-to-string (nth 3 tpl-ass)))
9570 (verilog-insert " // Templated")))
6341f357
DN
9571 (for-star
9572 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
9573 verilog-auto-inst-column))
a03c2342 9574 (verilog-insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
6341f357
DN
9575 (insert "\n")))
9576;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
9577;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
9578;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
9579
9580(defun verilog-auto-inst-first ()
9581 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
9582 ;; Do we need a trailing comma?
9583 ;; There maybe a ifdef or something similar before us. What a mess. Thus
86a4c7ac 9584 ;; to avoid trouble we only insert on preceding ) or *.
6341f357
DN
9585 ;; Insert first port on new line
9586 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
9587 (save-excursion
9588 (verilog-re-search-backward "[^ \t\n\f]" nil nil)
9589 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
9590 (forward-char 1)
9591 (insert ","))))
9592
9593(defun verilog-auto-star ()
9594 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
9595
9596If `verilog-auto-star-expand' is set, .* pins are treated if they were
37ea4b9b 9597AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
6341f357
DN
9598will also ignore any .* that are not last in your pin list (this prevents
9599it from deleting pins following the .* when it expands the AUTOINST.)
9600
9601On writing your file, unless `verilog-auto-star-save' is set, any
9602non-templated expanded pins will be removed. You may do this at any time
9603with \\[verilog-delete-auto-star-implicit].
9604
9605If you are converting a module to use .* for the first time, you may wish
9606to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
9607
9608See `verilog-auto-inst' for examples, templates, and more information."
9609 (when (verilog-auto-star-safe)
9610 (verilog-auto-inst)))
9611
9612(defun verilog-auto-inst ()
9613 "Expand AUTOINST statements, as part of \\[verilog-auto].
a03c2342
WS
9614Replace the pin connections to an instantiation or interface
9615declaration with ones automatically derived from the module or
9616interface header of the instantiated item.
6341f357
DN
9617
9618If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
9619and delete them before saving unless `verilog-auto-star-save' is set.
9620See `verilog-auto-star' for more information.
9621
9622Limitations:
9623 Module names must be resolvable to filenames by adding a
9624 `verilog-library-extensions', and being found in the same directory, or
9625 by changing the variable `verilog-library-flags' or
9626 `verilog-library-directories'. Macros `modname are translated through the
9627 vh-{name} Emacs variable, if that is not found, it just ignores the `.
9628
9629 In templates you must have one signal per line, ending in a ), or ));,
9630 and have proper () nesting, including a final ); to end the template.
9631
9632 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9633
37ea4b9b 9634 SystemVerilog multidimensional input/output has only experimental support.
6341f357 9635
a03c2342
WS
9636 SystemVerilog .name syntax is used if `verilog-auto-inst-dot-name' is set.
9637
4c5e69c6
DN
9638 Parameters referenced by the instantiation will remain symbolic, unless
9639 `verilog-auto-inst-param-value' is set.
9640
a03c2342
WS
9641 Gate primitives (and/or) may have AUTOINST for the purpose of
9642 AUTOWIRE declarations, etc. Gates are the only case when
9643 position based connections are passed.
9644
1dd4b004 9645For example, first take the submodule InstModule.v:
6341f357 9646
a03c2342 9647 module InstModule (o,i);
6341f357
DN
9648 output [31:0] o;
9649 input i;
9650 wire [31:0] o = {32{i}};
9651 endmodule
9652
9653This is then used in a upper level module:
9654
a03c2342 9655 module ExampInst (o,i);
6341f357
DN
9656 output o;
9657 input i;
1dd4b004
DN
9658 InstModule instName
9659 (/*AUTOINST*/);
6341f357
DN
9660 endmodule
9661
9662Typing \\[verilog-auto] will make this into:
9663
a03c2342 9664 module ExampInst (o,i);
6341f357
DN
9665 output o;
9666 input i;
1dd4b004
DN
9667 InstModule instName
9668 (/*AUTOINST*/
9669 // Outputs
9670 .ov (ov[31:0]),
9671 // Inputs
9672 .i (i));
6341f357
DN
9673 endmodule
9674
9675Where the list of inputs and outputs came from the inst module.
9676\f
9677Exceptions:
9678
9679 Unless you are instantiating a module multiple times, or the module is
37ea4b9b 9680 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
6341f357 9681 It just makes for unmaintainable code. To sanitize signal names, try
855b42a2 9682 vrename from URL `http://www.veripool.org'.
6341f357
DN
9683
9684 When you need to violate this suggestion there are two ways to list
9685 exceptions, placing them before the AUTOINST, or using templates.
9686
9687 Any ports defined before the /*AUTOINST*/ are not included in the list of
9688 automatics. This is similar to making a template as described below, but
9689 is restricted to simple connections just like you normally make. Also note
9690 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
9691 you have the appropriate // Input or // Output comment, and exactly the
9692 same line formatting as AUTOINST itself uses.
9693
1dd4b004
DN
9694 InstModule instName
9695 (// Inputs
9696 .i (my_i_dont_mess_with_it),
9697 /*AUTOINST*/
9698 // Outputs
9699 .ov (ov[31:0]));
6341f357
DN
9700
9701\f
9702Templates:
9703
9704 For multiple instantiations based upon a single template, create a
9705 commented out template:
9706
1dd4b004 9707 /* InstModule AUTO_TEMPLATE (
6341f357
DN
9708 .sig3 (sigz[]),
9709 );
9710 */
9711
37ea4b9b 9712 Templates go ABOVE the instantiation(s). When an instantiation is
6341f357
DN
9713 expanded `verilog-mode' simply searches up for the closest template.
9714 Thus you can have multiple templates for the same module, just alternate
37ea4b9b 9715 between the template for an instantiation and the instantiation itself.
6341f357
DN
9716
9717 The module name must be the same as the name of the module in the
9718 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
9719 words and capitalized. Only signals that must be different for each
9720 instantiation need to be listed.
9721
9722 Inside a template, a [] in a connection name (with nothing else inside
9723 the brackets) will be replaced by the same bus subscript as it is being
9724 connected to, or the [] will be removed if it is a single bit signal.
9725 Generally it is a good idea to do this for all connections in a template,
9726 as then they will work for any width signal, and with AUTOWIRE. See
9727 PTL_BUS becoming PTL_BUSNEW below.
9728
9729 If you have a complicated template, set `verilog-auto-inst-template-numbers'
9730 to see which regexps are matching. Don't leave that mode set after
9731 debugging is completed though, it will result in lots of extra differences
9732 and merge conflicts.
9733
9734 For example:
9735
1dd4b004 9736 /* InstModule AUTO_TEMPLATE (
6341f357
DN
9737 .ptl_bus (ptl_busnew[]),
9738 );
9739 */
1dd4b004 9740 InstModule ms2m (/*AUTOINST*/);
6341f357
DN
9741
9742 Typing \\[verilog-auto] will make this into:
9743
1dd4b004 9744 InstModule ms2m (/*AUTOINST*/
6341f357
DN
9745 // Outputs
9746 .NotInTemplate (NotInTemplate),
9747 .ptl_bus (ptl_busnew[3:0]), // Templated
9748 ....
9749\f
9750@ Templates:
9751
9752 It is common to instantiate a cell multiple times, so templates make it
9753 trivial to substitute part of the cell name into the connection name.
9754
1dd4b004 9755 /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
6341f357
DN
9756 .sig1 (sigx[@]),
9757 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
9758 );
9759 */
9760
9761 If no regular expression is provided immediately after the AUTO_TEMPLATE
9762 keyword, then the @ character in any connection names will be replaced
9763 with the instantiation number; the first digits found in the cell's
9764 instantiation name.
9765
9766 If a regular expression is provided, the @ character will be replaced
9767 with the first \(\) grouping that matches against the cell name. Using a
9768 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
9769 regexp is provided. If you use multiple layers of parenthesis,
9770 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
9771 characters after test and before _, whereas
9772 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
9773 match.
9774
9775 For example:
9776
1dd4b004 9777 /* InstModule AUTO_TEMPLATE (
6341f357
DN
9778 .ptl_mapvalidx (ptl_mapvalid[@]),
9779 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
9780 );
9781 */
1dd4b004 9782 InstModule ms2m (/*AUTOINST*/);
6341f357
DN
9783
9784 Typing \\[verilog-auto] will make this into:
9785
1dd4b004 9786 InstModule ms2m (/*AUTOINST*/
6341f357
DN
9787 // Outputs
9788 .ptl_mapvalidx (ptl_mapvalid[2]),
9789 .ptl_mapvalidp1x (ptl_mapvalid[3]));
9790
9791 Note the @ character was replaced with the 2 from \"ms2m\".
9792
9793 Alternatively, using a regular expression for @:
9794
1dd4b004 9795 /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
6341f357
DN
9796 .ptl_mapvalidx (@_ptl_mapvalid),
9797 .ptl_mapvalidp1x (ptl_mapvalid_@),
9798 );
9799 */
1dd4b004
DN
9800 InstModule ms2_FOO (/*AUTOINST*/);
9801 InstModule ms2_BAR (/*AUTOINST*/);
6341f357
DN
9802
9803 Typing \\[verilog-auto] will make this into:
9804
1dd4b004 9805 InstModule ms2_FOO (/*AUTOINST*/
6341f357
DN
9806 // Outputs
9807 .ptl_mapvalidx (FOO_ptl_mapvalid),
9808 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
1dd4b004 9809 InstModule ms2_BAR (/*AUTOINST*/
6341f357
DN
9810 // Outputs
9811 .ptl_mapvalidx (BAR_ptl_mapvalid),
9812 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
9813
9814\f
9815Regexp Templates:
9816
9817 A template entry of the form
9818
9819 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
9820
37ea4b9b 9821 will apply an Emacs style regular expression search for any port beginning
6341f357
DN
9822 in pci_req followed by numbers and ending in _l and connecting that to
9823 the pci_req_jtag_[] net, with the bus subscript coming from what matches
9824 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
9825
9826 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
0e5c8aed 9827 does the same thing. (Note a @ in the connection/replacement text is
6341f357
DN
9828 completely different -- still use \\1 there!) Thus this is the same as
9829 the above template:
9830
9831 .pci_req@_l (pci_req_jtag_[\\1]),
9832
9833 Here's another example to remove the _l, useful when naming conventions
9834 specify _ alone to mean active low. Note the use of [] to keep the bus
9835 subscript:
9836
9837 .\\(.*\\)_l (\\1_[]),
9838\f
9839Lisp Templates:
9840
9841 First any regular expression template is expanded.
9842
9843 If the syntax @\"( ... )\" is found in a connection, the expression in
9844 quotes will be evaluated as a Lisp expression, with @ replaced by the
9845 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
9846 4 into the brackets. Quote all double-quotes inside the expression with
0e5c8aed
DN
9847 a leading backslash (\\\"...\\\"); or if the Lisp template is also a
9848 regexp template backslash the backslash quote (\\\\\"...\\\\\").
9849
9850 There are special variables defined that are useful in these
9851 Lisp functions:
6341f357 9852
37ea4b9b
JB
9853 vl-name Name portion of the input/output port.
9854 vl-bits Bus bits portion of the input/output port ('[2:0]').
a03c2342 9855 vl-mbits Multidimensional array bits for port ('[2:0][3:0]').
37ea4b9b 9856 vl-width Width of the input/output port ('3' for [2:0]).
6341f357 9857 May be a (...) expression if bits isn't a constant.
a3a8b002
DN
9858 vl-dir Direction of the pin input/output/inout/interface.
9859 vl-modport The modport, if an interface with a modport.
1dd4b004
DN
9860 vl-cell-type Module name/type of the cell ('InstModule').
9861 vl-cell-name Instance name of the cell ('instName').
6341f357
DN
9862
9863 Normal Lisp variables may be used in expressions. See
9864 `verilog-read-defines' which can set vh-{definename} variables for use
9865 here. Also, any comments of the form:
9866
9867 /*AUTO_LISP(setq foo 1)*/
9868
9869 will evaluate any Lisp expression inside the parenthesis between the
9870 beginning of the buffer and the point of the AUTOINST. This allows
9871 functions to be defined or variables to be changed between instantiations.
a3a8b002
DN
9872 (See also `verilog-auto-insert-lisp' if you want the output from your
9873 lisp function to be inserted.)
6341f357
DN
9874
9875 Note that when using lisp expressions errors may occur when @ is not a
37ea4b9b 9876 number; you may need to use the standard Emacs Lisp functions
6341f357
DN
9877 `number-to-string' and `string-to-number'.
9878
9879 After the evaluation is completed, @ substitution and [] substitution
0e5c8aed
DN
9880 occur.
9881
9882For more information see the \\[verilog-faq] and forums at URL
9883`http://www.veripool.org'."
6341f357
DN
9884 (save-excursion
9885 ;; Find beginning
9886 (let* ((pt (point))
9887 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
9888 (indent-pt (save-excursion (verilog-backward-open-paren)
9889 (1+ (current-column))))
9890 (verilog-auto-inst-column (max verilog-auto-inst-column
9891 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
9892 (modi (verilog-modi-current))
5509c6ad 9893 (moddecls (verilog-modi-get-decls modi))
6341f357 9894 (vector-skip-list (unless verilog-auto-inst-vector
5509c6ad
DN
9895 (verilog-decls-get-signals moddecls)))
9896 submod submodi submoddecls
4c5e69c6
DN
9897 inst skip-pins tpl-list tpl-num did-first par-values)
9898
6341f357
DN
9899 ;; Find module name that is instantiated
9900 (setq submod (verilog-read-inst-module)
9901 inst (verilog-read-inst-name)
9902 vl-cell-type submod
9903 vl-cell-name inst
9904 skip-pins (aref (verilog-read-inst-pins) 0))
9905
9906 ;; Parse any AUTO_LISP() before here
9907 (verilog-read-auto-lisp (point-min) pt)
9908
4c5e69c6
DN
9909 ;; Read parameters (after AUTO_LISP)
9910 (setq par-values (and verilog-auto-inst-param-value
9911 (verilog-read-inst-param-value)))
9912
6341f357
DN
9913 ;; Lookup position, etc of submodule
9914 ;; Note this may raise an error
a03c2342
WS
9915 (when (and (not (member submod verilog-gate-keywords))
9916 (setq submodi (verilog-modi-lookup submod t)))
5509c6ad 9917 (setq submoddecls (verilog-modi-get-decls submodi))
6341f357
DN
9918 ;; If there's a number in the instantiation, it may be a argument to the
9919 ;; automatic variable instantiation program.
9920 (let* ((tpl-info (verilog-read-auto-template submod))
9921 (tpl-regexp (aref tpl-info 0)))
9922 (setq tpl-num (if (string-match tpl-regexp inst)
9923 (match-string 1 inst)
9924 "")
9925 tpl-list (aref tpl-info 1)))
9926 ;; Find submodule's signals and dump
a03c2342
WS
9927 (let ((sig-list (and (equal (verilog-modi-get-type submodi) "interface")
9928 (verilog-signals-not-in
9929 (append (verilog-decls-get-wires submoddecls)
9930 (verilog-decls-get-regs submoddecls))
9931 skip-pins)))
9932 (vl-dir "interfaced"))
9933 (when sig-list
9934 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9935 ;; Note these are searched for in verilog-read-sub-decls.
9936 (verilog-insert-indent "// Interfaced\n")
9937 (mapc (lambda (port)
9938 (verilog-auto-inst-port port indent-pt
9939 tpl-list tpl-num for-star par-values))
9940 sig-list)))
a3a8b002
DN
9941 (let ((sig-list (verilog-signals-not-in
9942 (verilog-decls-get-interfaces submoddecls)
9943 skip-pins))
9944 (vl-dir "interface"))
9945 (when sig-list
9946 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
a3a8b002 9947 ;; Note these are searched for in verilog-read-sub-decls.
a03c2342 9948 (verilog-insert-indent "// Interfaces\n")
a3a8b002
DN
9949 (mapc (lambda (port)
9950 (verilog-auto-inst-port port indent-pt
9951 tpl-list tpl-num for-star par-values))
9952 sig-list)))
6341f357 9953 (let ((sig-list (verilog-signals-not-in
5509c6ad 9954 (verilog-decls-get-outputs submoddecls)
6341f357
DN
9955 skip-pins))
9956 (vl-dir "output"))
9957 (when sig-list
9958 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
a03c2342 9959 (verilog-insert-indent "// Outputs\n")
7ea26faf
DN
9960 (mapc (lambda (port)
9961 (verilog-auto-inst-port port indent-pt
4c5e69c6 9962 tpl-list tpl-num for-star par-values))
7ea26faf 9963 sig-list)))
6341f357 9964 (let ((sig-list (verilog-signals-not-in
5509c6ad 9965 (verilog-decls-get-inouts submoddecls)
6341f357
DN
9966 skip-pins))
9967 (vl-dir "inout"))
9968 (when sig-list
9969 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
a03c2342 9970 (verilog-insert-indent "// Inouts\n")
7ea26faf
DN
9971 (mapc (lambda (port)
9972 (verilog-auto-inst-port port indent-pt
4c5e69c6 9973 tpl-list tpl-num for-star par-values))
7ea26faf 9974 sig-list)))
6341f357 9975 (let ((sig-list (verilog-signals-not-in
5509c6ad 9976 (verilog-decls-get-inputs submoddecls)
6341f357
DN
9977 skip-pins))
9978 (vl-dir "input"))
9979 (when sig-list
9980 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
a03c2342 9981 (verilog-insert-indent "// Inputs\n")
7ea26faf
DN
9982 (mapc (lambda (port)
9983 (verilog-auto-inst-port port indent-pt
4c5e69c6 9984 tpl-list tpl-num for-star par-values))
7ea26faf 9985 sig-list)))
6341f357
DN
9986 ;; Kill extra semi
9987 (save-excursion
9988 (cond (did-first
9989 (re-search-backward "," pt t)
9990 (delete-char 1)
9991 (insert ");")
9992 (search-forward "\n") ;; Added by inst-port
a03c2342 9993 (delete-char -1)
6341f357 9994 (if (search-forward ")" nil t) ;; From user, moved up a line
a03c2342 9995 (delete-char -1))
6341f357 9996 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
a03c2342 9997 (delete-char -1)))))))))
6341f357
DN
9998
9999(defun verilog-auto-inst-param ()
10000 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
10001Replace the parameter connections to an instantiation with ones
10002automatically derived from the module header of the instantiated netlist.
10003
10004See \\[verilog-auto-inst] for limitations, and templates to customize the
10005output.
10006
1dd4b004 10007For example, first take the submodule InstModule.v:
6341f357 10008
a03c2342 10009 module InstModule (o,i);
6341f357
DN
10010 parameter PAR;
10011 endmodule
10012
10013This is then used in a upper level module:
10014
a03c2342 10015 module ExampInst (o,i);
6341f357 10016 parameter PAR;
1dd4b004
DN
10017 InstModule #(/*AUTOINSTPARAM*/)
10018 instName (/*AUTOINST*/);
6341f357
DN
10019 endmodule
10020
10021Typing \\[verilog-auto] will make this into:
10022
a03c2342 10023 module ExampInst (o,i);
6341f357
DN
10024 output o;
10025 input i;
1dd4b004
DN
10026 InstModule #(/*AUTOINSTPARAM*/
10027 // Parameters
10028 .PAR (PAR));
10029 instName (/*AUTOINST*/);
6341f357
DN
10030 endmodule
10031
10032Where the list of parameter connections come from the inst module.
10033\f
10034Templates:
10035
10036 You can customize the parameter connections using AUTO_TEMPLATEs,
10037 just as you would with \\[verilog-auto-inst]."
10038 (save-excursion
10039 ;; Find beginning
10040 (let* ((pt (point))
10041 (indent-pt (save-excursion (verilog-backward-open-paren)
10042 (1+ (current-column))))
10043 (verilog-auto-inst-column (max verilog-auto-inst-column
10044 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
10045 (modi (verilog-modi-current))
5509c6ad 10046 (moddecls (verilog-modi-get-decls modi))
6341f357 10047 (vector-skip-list (unless verilog-auto-inst-vector
5509c6ad
DN
10048 (verilog-decls-get-signals moddecls)))
10049 submod submodi submoddecls
10050 inst skip-pins tpl-list tpl-num did-first)
6341f357
DN
10051 ;; Find module name that is instantiated
10052 (setq submod (save-excursion
10053 ;; Get to the point where AUTOINST normally is to read the module
10054 (verilog-re-search-forward-quick "[(;]" nil nil)
10055 (verilog-read-inst-module))
10056 inst (save-excursion
10057 ;; Get to the point where AUTOINST normally is to read the module
10058 (verilog-re-search-forward-quick "[(;]" nil nil)
10059 (verilog-read-inst-name))
10060 vl-cell-type submod
10061 vl-cell-name inst
10062 skip-pins (aref (verilog-read-inst-pins) 0))
10063
10064 ;; Parse any AUTO_LISP() before here
10065 (verilog-read-auto-lisp (point-min) pt)
10066
10067 ;; Lookup position, etc of submodule
10068 ;; Note this may raise an error
10069 (when (setq submodi (verilog-modi-lookup submod t))
5509c6ad 10070 (setq submoddecls (verilog-modi-get-decls submodi))
6341f357
DN
10071 ;; If there's a number in the instantiation, it may be a argument to the
10072 ;; automatic variable instantiation program.
10073 (let* ((tpl-info (verilog-read-auto-template submod))
10074 (tpl-regexp (aref tpl-info 0)))
10075 (setq tpl-num (if (string-match tpl-regexp inst)
10076 (match-string 1 inst)
10077 "")
10078 tpl-list (aref tpl-info 1)))
10079 ;; Find submodule's signals and dump
10080 (let ((sig-list (verilog-signals-not-in
5509c6ad 10081 (verilog-decls-get-gparams submoddecls)
6341f357
DN
10082 skip-pins))
10083 (vl-dir "parameter"))
10084 (when sig-list
10085 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
7ea26faf 10086 ;; Note these are searched for in verilog-read-sub-decls.
a03c2342 10087 (verilog-insert-indent "// Parameters\n")
7ea26faf
DN
10088 (mapc (lambda (port)
10089 (verilog-auto-inst-port port indent-pt
4c5e69c6 10090 tpl-list tpl-num nil nil))
7ea26faf 10091 sig-list)))
6341f357
DN
10092 ;; Kill extra semi
10093 (save-excursion
10094 (cond (did-first
10095 (re-search-backward "," pt t)
10096 (delete-char 1)
10097 (insert ")")
10098 (search-forward "\n") ;; Added by inst-port
a03c2342 10099 (delete-char -1)
6341f357 10100 (if (search-forward ")" nil t) ;; From user, moved up a line
a03c2342 10101 (delete-char -1)))))))))
6341f357
DN
10102
10103(defun verilog-auto-reg ()
10104 "Expand AUTOREG statements, as part of \\[verilog-auto].
10105Make reg statements for any output that isn't already declared,
10106and isn't a wire output from a block.
10107
10108Limitations:
10109 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10110
10111 This does NOT work on memories, declare those yourself.
10112
10113An example:
10114
a03c2342 10115 module ExampReg (o,i);
6341f357
DN
10116 output o;
10117 input i;
10118 /*AUTOREG*/
10119 always o = i;
10120 endmodule
10121
10122Typing \\[verilog-auto] will make this into:
10123
a03c2342 10124 module ExampReg (o,i);
6341f357
DN
10125 output o;
10126 input i;
10127 /*AUTOREG*/
10128 // Beginning of automatic regs (for this module's undeclared outputs)
1dd4b004 10129 reg o;
6341f357
DN
10130 // End of automatics
10131 always o = i;
10132 endmodule"
10133 (save-excursion
10134 ;; Point must be at insertion point.
10135 (let* ((indent-pt (current-indentation))
10136 (modi (verilog-modi-current))
5509c6ad
DN
10137 (moddecls (verilog-modi-get-decls modi))
10138 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 10139 (sig-list (verilog-signals-not-in
5509c6ad
DN
10140 (verilog-decls-get-outputs moddecls)
10141 (append (verilog-decls-get-wires moddecls)
10142 (verilog-decls-get-regs moddecls)
10143 (verilog-decls-get-assigns moddecls)
10144 (verilog-decls-get-consts moddecls)
10145 (verilog-decls-get-gparams moddecls)
a03c2342 10146 (verilog-subdecls-get-interfaced modsubdecls)
5509c6ad
DN
10147 (verilog-subdecls-get-outputs modsubdecls)
10148 (verilog-subdecls-get-inouts modsubdecls)))))
6341f357
DN
10149 (forward-line 1)
10150 (when sig-list
10151 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
10152 (verilog-insert-definition sig-list "reg" indent-pt nil)
10153 (verilog-modi-cache-add-regs modi sig-list)
60618039 10154 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
10155
10156(defun verilog-auto-reg-input ()
10157 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
10158Make reg statements instantiation inputs that aren't already declared.
10159This is useful for making a top level shell for testing the module that is
10160to be instantiated.
10161
10162Limitations:
10163 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
10164
10165 This does NOT work on memories, declare those yourself.
10166
10167An example (see `verilog-auto-inst' for what else is going on here):
10168
a03c2342 10169 module ExampRegInput (o,i);
6341f357
DN
10170 output o;
10171 input i;
10172 /*AUTOREGINPUT*/
1dd4b004
DN
10173 InstModule instName
10174 (/*AUTOINST*/);
6341f357
DN
10175 endmodule
10176
10177Typing \\[verilog-auto] will make this into:
10178
a03c2342 10179 module ExampRegInput (o,i);
6341f357
DN
10180 output o;
10181 input i;
10182 /*AUTOREGINPUT*/
10183 // Beginning of automatic reg inputs (for undeclared ...
1dd4b004 10184 reg [31:0] iv; // From inst of inst.v
6341f357 10185 // End of automatics
1dd4b004
DN
10186 InstModule instName
10187 (/*AUTOINST*/
10188 // Outputs
10189 .o (o[31:0]),
10190 // Inputs
10191 .iv (iv));
6341f357
DN
10192 endmodule"
10193 (save-excursion
10194 ;; Point must be at insertion point.
10195 (let* ((indent-pt (current-indentation))
10196 (modi (verilog-modi-current))
5509c6ad
DN
10197 (moddecls (verilog-modi-get-decls modi))
10198 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357
DN
10199 (sig-list (verilog-signals-combine-bus
10200 (verilog-signals-not-in
5509c6ad
DN
10201 (append (verilog-subdecls-get-inputs modsubdecls)
10202 (verilog-subdecls-get-inouts modsubdecls))
10203 (verilog-decls-get-signals moddecls)))))
6341f357
DN
10204 (forward-line 1)
10205 (when sig-list
10206 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
10207 (verilog-insert-definition sig-list "reg" indent-pt nil)
10208 (verilog-modi-cache-add-regs modi sig-list)
60618039 10209 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
10210
10211(defun verilog-auto-wire ()
10212 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
10213Make wire statements for instantiations outputs that aren't
10214already declared.
10215
10216Limitations:
10217 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
10218 and all busses must have widths, such as those from AUTOINST, or using []
10219 in AUTO_TEMPLATEs.
10220
10221 This does NOT work on memories or SystemVerilog .name connections,
10222 declare those yourself.
10223
37ea4b9b
JB
10224 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
10225 determine how to bus together. This occurs when you have ports with
10226 non-numeric or non-sequential bus subscripts. If Verilog mode
6341f357
DN
10227 mis-guessed, you'll have to declare them yourself.
10228
10229An example (see `verilog-auto-inst' for what else is going on here):
10230
a03c2342 10231 module ExampWire (o,i);
6341f357
DN
10232 output o;
10233 input i;
10234 /*AUTOWIRE*/
1dd4b004
DN
10235 InstModule instName
10236 (/*AUTOINST*/);
6341f357
DN
10237 endmodule
10238
10239Typing \\[verilog-auto] will make this into:
10240
a03c2342 10241 module ExampWire (o,i);
6341f357
DN
10242 output o;
10243 input i;
10244 /*AUTOWIRE*/
10245 // Beginning of automatic wires
10246 wire [31:0] ov; // From inst of inst.v
10247 // End of automatics
1dd4b004
DN
10248 InstModule instName
10249 (/*AUTOINST*/
10250 // Outputs
10251 .ov (ov[31:0]),
10252 // Inputs
10253 .i (i));
6341f357
DN
10254 wire o = | ov;
10255 endmodule"
10256 (save-excursion
10257 ;; Point must be at insertion point.
10258 (let* ((indent-pt (current-indentation))
10259 (modi (verilog-modi-current))
5509c6ad
DN
10260 (moddecls (verilog-modi-get-decls modi))
10261 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357
DN
10262 (sig-list (verilog-signals-combine-bus
10263 (verilog-signals-not-in
5509c6ad
DN
10264 (append (verilog-subdecls-get-outputs modsubdecls)
10265 (verilog-subdecls-get-inouts modsubdecls))
10266 (verilog-decls-get-signals moddecls)))))
6341f357
DN
10267 (forward-line 1)
10268 (when sig-list
10269 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
10270 (verilog-insert-definition sig-list "wire" indent-pt nil)
10271 (verilog-modi-cache-add-wires modi sig-list)
10272 (verilog-insert-indent "// End of automatics\n")
10273 (when nil ;; Too slow on huge modules, plus makes everyone's module change
10274 (beginning-of-line)
10275 (setq pnt (point))
7e2a6000 10276 (verilog-pretty-declarations quiet)
6341f357 10277 (goto-char pnt)
a3a8b002 10278 (verilog-pretty-expr t "//"))))))
6341f357 10279
e2076c2c 10280(defun verilog-auto-output (&optional with-params)
6341f357
DN
10281 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
10282Make output statements for any output signal from an /*AUTOINST*/ that
10283isn't a input to another AUTOINST. This is useful for modules which
10284only instantiate other modules.
10285
10286Limitations:
10287 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10288
10289 If placed inside the parenthesis of a module declaration, it creates
10290 Verilog 2001 style, else uses Verilog 1995 style.
10291
10292 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10293 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10294
10295 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10296
10297 Signals matching `verilog-auto-output-ignore-regexp' are not included.
10298
10299An example (see `verilog-auto-inst' for what else is going on here):
10300
a03c2342 10301 module ExampOutput (ov,i);
6341f357
DN
10302 input i;
10303 /*AUTOOUTPUT*/
1dd4b004
DN
10304 InstModule instName
10305 (/*AUTOINST*/);
6341f357
DN
10306 endmodule
10307
10308Typing \\[verilog-auto] will make this into:
10309
a03c2342 10310 module ExampOutput (ov,i);
6341f357
DN
10311 input i;
10312 /*AUTOOUTPUT*/
10313 // Beginning of automatic outputs (from unused autoinst outputs)
1dd4b004 10314 output [31:0] ov; // From inst of inst.v
6341f357 10315 // End of automatics
1dd4b004
DN
10316 InstModule instName
10317 (/*AUTOINST*/
10318 // Outputs
10319 .ov (ov[31:0]),
10320 // Inputs
10321 .i (i));
e2076c2c
DN
10322 endmodule
10323
10324You may also provide an optional regular expression, in which case only
10325signals matching the regular expression will be included. For example the
10326same expansion will result from only extracting outputs starting with ov:
10327
10328 /*AUTOOUTPUT(\"^ov\")*/"
6341f357
DN
10329 (save-excursion
10330 ;; Point must be at insertion point.
10331 (let* ((indent-pt (current-indentation))
e2076c2c
DN
10332 (regexp (and with-params
10333 (nth 0 (verilog-read-auto-params 1))))
6341f357
DN
10334 (v2k (verilog-in-paren))
10335 (modi (verilog-modi-current))
5509c6ad
DN
10336 (moddecls (verilog-modi-get-decls modi))
10337 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 10338 (sig-list (verilog-signals-not-in
5509c6ad
DN
10339 (verilog-subdecls-get-outputs modsubdecls)
10340 (append (verilog-decls-get-outputs moddecls)
10341 (verilog-decls-get-inouts moddecls)
10342 (verilog-subdecls-get-inputs modsubdecls)
10343 (verilog-subdecls-get-inouts modsubdecls)))))
e2076c2c
DN
10344 (when regexp
10345 (setq sig-list (verilog-signals-matching-regexp
10346 sig-list regexp)))
6341f357
DN
10347 (setq sig-list (verilog-signals-not-matching-regexp
10348 sig-list verilog-auto-output-ignore-regexp))
10349 (forward-line 1)
10350 (when v2k (verilog-repair-open-comma))
10351 (when sig-list
10352 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
10353 (verilog-insert-definition sig-list "output" indent-pt v2k)
10354 (verilog-modi-cache-add-outputs modi sig-list)
10355 (verilog-insert-indent "// End of automatics\n"))
60618039 10356 (when v2k (verilog-repair-close-comma)))))
6341f357
DN
10357
10358(defun verilog-auto-output-every ()
10359 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
10360Make output statements for any signals that aren't primary inputs or
10361outputs already. This makes every signal in the design a output. This is
10362useful to get Synopsys to preserve every signal in the design, since it
10363won't optimize away the outputs.
10364
10365An example:
10366
a03c2342 10367 module ExampOutputEvery (o,i,tempa,tempb);
6341f357
DN
10368 output o;
10369 input i;
10370 /*AUTOOUTPUTEVERY*/
10371 wire tempa = i;
10372 wire tempb = tempa;
10373 wire o = tempb;
10374 endmodule
10375
10376Typing \\[verilog-auto] will make this into:
10377
a03c2342 10378 module ExampOutputEvery (o,i,tempa,tempb);
6341f357
DN
10379 output o;
10380 input i;
10381 /*AUTOOUTPUTEVERY*/
10382 // Beginning of automatic outputs (every signal)
1dd4b004
DN
10383 output tempb;
10384 output tempa;
6341f357
DN
10385 // End of automatics
10386 wire tempa = i;
10387 wire tempb = tempa;
10388 wire o = tempb;
10389 endmodule"
10390 (save-excursion
10391 ;;Point must be at insertion point
10392 (let* ((indent-pt (current-indentation))
10393 (v2k (verilog-in-paren))
10394 (modi (verilog-modi-current))
5509c6ad 10395 (moddecls (verilog-modi-get-decls modi))
6341f357
DN
10396 (sig-list (verilog-signals-combine-bus
10397 (verilog-signals-not-in
5509c6ad
DN
10398 (verilog-decls-get-signals moddecls)
10399 (verilog-decls-get-ports moddecls)))))
6341f357
DN
10400 (forward-line 1)
10401 (when v2k (verilog-repair-open-comma))
10402 (when sig-list
10403 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
10404 (verilog-insert-definition sig-list "output" indent-pt v2k)
10405 (verilog-modi-cache-add-outputs modi sig-list)
10406 (verilog-insert-indent "// End of automatics\n"))
60618039 10407 (when v2k (verilog-repair-close-comma)))))
6341f357 10408
e2076c2c 10409(defun verilog-auto-input (&optional with-params)
6341f357
DN
10410 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
10411Make input statements for any input signal into an /*AUTOINST*/ that
10412isn't declared elsewhere inside the module. This is useful for modules which
10413only instantiate other modules.
10414
10415Limitations:
10416 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10417
10418 If placed inside the parenthesis of a module declaration, it creates
10419 Verilog 2001 style, else uses Verilog 1995 style.
10420
10421 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10422 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10423
10424 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10425
10426 Signals matching `verilog-auto-input-ignore-regexp' are not included.
10427
10428An example (see `verilog-auto-inst' for what else is going on here):
10429
a03c2342 10430 module ExampInput (ov,i);
6341f357
DN
10431 output [31:0] ov;
10432 /*AUTOINPUT*/
1dd4b004
DN
10433 InstModule instName
10434 (/*AUTOINST*/);
6341f357
DN
10435 endmodule
10436
10437Typing \\[verilog-auto] will make this into:
10438
a03c2342 10439 module ExampInput (ov,i);
6341f357
DN
10440 output [31:0] ov;
10441 /*AUTOINPUT*/
10442 // Beginning of automatic inputs (from unused autoinst inputs)
1dd4b004 10443 input i; // From inst of inst.v
6341f357 10444 // End of automatics
1dd4b004
DN
10445 InstModule instName
10446 (/*AUTOINST*/
10447 // Outputs
10448 .ov (ov[31:0]),
10449 // Inputs
10450 .i (i));
e2076c2c
DN
10451 endmodule
10452
10453You may also provide an optional regular expression, in which case only
10454signals matching the regular expression will be included. For example the
10455same expansion will result from only extracting inputs starting with i:
10456
10457 /*AUTOINPUT(\"^i\")*/"
6341f357
DN
10458 (save-excursion
10459 (let* ((indent-pt (current-indentation))
e2076c2c
DN
10460 (regexp (and with-params
10461 (nth 0 (verilog-read-auto-params 1))))
6341f357
DN
10462 (v2k (verilog-in-paren))
10463 (modi (verilog-modi-current))
5509c6ad
DN
10464 (moddecls (verilog-modi-get-decls modi))
10465 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 10466 (sig-list (verilog-signals-not-in
5509c6ad
DN
10467 (verilog-subdecls-get-inputs modsubdecls)
10468 (append (verilog-decls-get-inputs moddecls)
10469 (verilog-decls-get-inouts moddecls)
10470 (verilog-decls-get-wires moddecls)
10471 (verilog-decls-get-regs moddecls)
10472 (verilog-decls-get-consts moddecls)
10473 (verilog-decls-get-gparams moddecls)
a03c2342 10474 (verilog-subdecls-get-interfaced modsubdecls)
5509c6ad
DN
10475 (verilog-subdecls-get-outputs modsubdecls)
10476 (verilog-subdecls-get-inouts modsubdecls)))))
e2076c2c
DN
10477 (when regexp
10478 (setq sig-list (verilog-signals-matching-regexp
10479 sig-list regexp)))
6341f357
DN
10480 (setq sig-list (verilog-signals-not-matching-regexp
10481 sig-list verilog-auto-input-ignore-regexp))
10482 (forward-line 1)
10483 (when v2k (verilog-repair-open-comma))
10484 (when sig-list
10485 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
10486 (verilog-insert-definition sig-list "input" indent-pt v2k)
10487 (verilog-modi-cache-add-inputs modi sig-list)
10488 (verilog-insert-indent "// End of automatics\n"))
60618039 10489 (when v2k (verilog-repair-close-comma)))))
6341f357 10490
e2076c2c 10491(defun verilog-auto-inout (&optional with-params)
6341f357
DN
10492 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
10493Make inout statements for any inout signal in an /*AUTOINST*/ that
10494isn't declared elsewhere inside the module.
10495
10496Limitations:
10497 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10498
10499 If placed inside the parenthesis of a module declaration, it creates
10500 Verilog 2001 style, else uses Verilog 1995 style.
10501
10502 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10503 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10504
10505 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10506
10507 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
10508
10509An example (see `verilog-auto-inst' for what else is going on here):
10510
a03c2342 10511 module ExampInout (ov,i);
6341f357
DN
10512 input i;
10513 /*AUTOINOUT*/
1dd4b004
DN
10514 InstModule instName
10515 (/*AUTOINST*/);
6341f357
DN
10516 endmodule
10517
10518Typing \\[verilog-auto] will make this into:
10519
a03c2342 10520 module ExampInout (ov,i);
6341f357
DN
10521 input i;
10522 /*AUTOINOUT*/
10523 // Beginning of automatic inouts (from unused autoinst inouts)
1dd4b004 10524 inout [31:0] ov; // From inst of inst.v
6341f357 10525 // End of automatics
1dd4b004
DN
10526 InstModule instName
10527 (/*AUTOINST*/
10528 // Inouts
10529 .ov (ov[31:0]),
10530 // Inputs
10531 .i (i));
e2076c2c
DN
10532 endmodule
10533
10534You may also provide an optional regular expression, in which case only
10535signals matching the regular expression will be included. For example the
10536same expansion will result from only extracting inouts starting with i:
10537
10538 /*AUTOINOUT(\"^i\")*/"
6341f357
DN
10539 (save-excursion
10540 ;; Point must be at insertion point.
10541 (let* ((indent-pt (current-indentation))
e2076c2c
DN
10542 (regexp (and with-params
10543 (nth 0 (verilog-read-auto-params 1))))
6341f357
DN
10544 (v2k (verilog-in-paren))
10545 (modi (verilog-modi-current))
5509c6ad
DN
10546 (moddecls (verilog-modi-get-decls modi))
10547 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 10548 (sig-list (verilog-signals-not-in
5509c6ad
DN
10549 (verilog-subdecls-get-inouts modsubdecls)
10550 (append (verilog-decls-get-outputs moddecls)
10551 (verilog-decls-get-inouts moddecls)
10552 (verilog-decls-get-inputs moddecls)
10553 (verilog-subdecls-get-inputs modsubdecls)
10554 (verilog-subdecls-get-outputs modsubdecls)))))
e2076c2c
DN
10555 (when regexp
10556 (setq sig-list (verilog-signals-matching-regexp
10557 sig-list regexp)))
6341f357
DN
10558 (setq sig-list (verilog-signals-not-matching-regexp
10559 sig-list verilog-auto-inout-ignore-regexp))
10560 (forward-line 1)
10561 (when v2k (verilog-repair-open-comma))
10562 (when sig-list
10563 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
10564 (verilog-insert-definition sig-list "inout" indent-pt v2k)
10565 (verilog-modi-cache-add-inouts modi sig-list)
10566 (verilog-insert-indent "// End of automatics\n"))
60618039 10567 (when v2k (verilog-repair-close-comma)))))
6341f357 10568
7cb1c4d7 10569(defun verilog-auto-inout-module (&optional complement)
6341f357
DN
10570 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
10571Take input/output/inout statements from the specified module and insert
10572into the current module. This is useful for making null templates and
37ea4b9b
JB
10573shell modules which need to have identical I/O with another module.
10574Any I/O which are already defined in this module will not be redefined.
a03c2342 10575For the complement of this function, see `verilog-auto-inout-comp'.
6341f357
DN
10576
10577Limitations:
10578 If placed inside the parenthesis of a module declaration, it creates
10579 Verilog 2001 style, else uses Verilog 1995 style.
10580
10581 Concatenation and outputting partial busses is not supported.
10582
10583 Module names must be resolvable to filenames. See `verilog-auto-inst'.
10584
10585 Signals are not inserted in the same order as in the original module,
10586 though they will appear to be in the same order to a AUTOINST
10587 instantiating either module.
10588
10589An example:
10590
a03c2342 10591 module ExampShell (/*AUTOARG*/);
1dd4b004 10592 /*AUTOINOUTMODULE(\"ExampMain\")*/
6341f357
DN
10593 endmodule
10594
a03c2342 10595 module ExampMain (i,o,io);
6341f357
DN
10596 input i;
10597 output o;
10598 inout io;
10599 endmodule
10600
10601Typing \\[verilog-auto] will make this into:
10602
a03c2342 10603 module ExampShell (/*AUTOARG*/i,o,io);
1dd4b004 10604 /*AUTOINOUTMODULE(\"ExampMain\")*/
6341f357 10605 // Beginning of automatic in/out/inouts (from specific module)
6341f357
DN
10606 output o;
10607 inout io;
7cb1c4d7 10608 input i;
6341f357 10609 // End of automatics
1dd4b004
DN
10610 endmodule
10611
10612You may also provide an optional regular expression, in which case only
10613signals matching the regular expression will be included. For example the
10614same expansion will result from only extracting signals starting with i:
10615
a3a8b002
DN
10616 /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/
10617
14862301 10618You may also provide an optional second regular expression, in
a3a8b002
DN
10619which case only signals which have that pin direction and data
10620type will be included. This matches against everything before
10621the signal name in the declaration, for example against
10622\"input\" (single bit), \"output logic\" (direction and type) or
10623\"output [1:0]\" (direction and implicit type). You also
10624probably want to skip spaces in your regexp.
10625
10626For example, the below will result in matching the output \"o\"
10627against the previous example's module:
10628
10629 /*AUTOINOUTMODULE(\"ExampMain\",\"\",\"^output.*\")*/"
6341f357 10630 (save-excursion
a3a8b002 10631 (let* ((params (verilog-read-auto-params 1 3))
1dd4b004
DN
10632 (submod (nth 0 params))
10633 (regexp (nth 1 params))
a3a8b002 10634 (direction-re (nth 2 params))
1dd4b004 10635 submodi)
6341f357
DN
10636 ;; Lookup position, etc of co-module
10637 ;; Note this may raise an error
10638 (when (setq submodi (verilog-modi-lookup submod t))
10639 (let* ((indent-pt (current-indentation))
10640 (v2k (verilog-in-paren))
10641 (modi (verilog-modi-current))
5509c6ad
DN
10642 (moddecls (verilog-modi-get-decls modi))
10643 (submoddecls (verilog-modi-get-decls submodi))
6341f357 10644 (sig-list-i (verilog-signals-not-in
7cb1c4d7
DN
10645 (if complement
10646 (verilog-decls-get-outputs submoddecls)
10647 (verilog-decls-get-inputs submoddecls))
5509c6ad 10648 (append (verilog-decls-get-inputs moddecls))))
6341f357 10649 (sig-list-o (verilog-signals-not-in
7cb1c4d7
DN
10650 (if complement
10651 (verilog-decls-get-inputs submoddecls)
10652 (verilog-decls-get-outputs submoddecls))
5509c6ad 10653 (append (verilog-decls-get-outputs moddecls))))
6341f357 10654 (sig-list-io (verilog-signals-not-in
5509c6ad 10655 (verilog-decls-get-inouts submoddecls)
a3a8b002
DN
10656 (append (verilog-decls-get-inouts moddecls))))
10657 (sig-list-if (verilog-signals-not-in
10658 (verilog-decls-get-interfaces submoddecls)
10659 (append (verilog-decls-get-interfaces moddecls)))))
6341f357 10660 (forward-line 1)
a3a8b002
DN
10661 (setq sig-list-i (verilog-signals-matching-dir-re
10662 (verilog-signals-matching-regexp sig-list-i regexp)
10663 "input" direction-re)
10664 sig-list-o (verilog-signals-matching-dir-re
10665 (verilog-signals-matching-regexp sig-list-o regexp)
10666 "output" direction-re)
10667 sig-list-io (verilog-signals-matching-dir-re
10668 (verilog-signals-matching-regexp sig-list-io regexp)
10669 "inout" direction-re)
10670 sig-list-if (verilog-signals-matching-dir-re
10671 (verilog-signals-matching-regexp sig-list-if regexp)
10672 "interface" direction-re))
6341f357
DN
10673 (when v2k (verilog-repair-open-comma))
10674 (when (or sig-list-i sig-list-o sig-list-io)
10675 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
10676 ;; Don't sort them so a upper AUTOINST will match the main module
10677 (verilog-insert-definition sig-list-o "output" indent-pt v2k t)
10678 (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
10679 (verilog-insert-definition sig-list-i "input" indent-pt v2k t)
a3a8b002 10680 (verilog-insert-definition sig-list-if "interface" indent-pt v2k t)
6341f357
DN
10681 (verilog-modi-cache-add-inputs modi sig-list-i)
10682 (verilog-modi-cache-add-outputs modi sig-list-o)
10683 (verilog-modi-cache-add-inouts modi sig-list-io)
10684 (verilog-insert-indent "// End of automatics\n"))
60618039 10685 (when v2k (verilog-repair-close-comma)))))))
6341f357 10686
7cb1c4d7
DN
10687(defun verilog-auto-inout-comp ()
10688 "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
10689Take input/output/inout statements from the specified module and
10690insert the inverse into the current module (inputs become outputs
10691and vice-versa.) This is useful for making test and stimulus
10692modules which need to have complementing I/O with another module.
10693Any I/O which are already defined in this module will not be
a03c2342
WS
10694redefined. For the complement of this function, see
10695`verilog-auto-inout-module'.
7cb1c4d7
DN
10696
10697Limitations:
10698 If placed inside the parenthesis of a module declaration, it creates
10699 Verilog 2001 style, else uses Verilog 1995 style.
10700
10701 Concatenation and outputting partial busses is not supported.
10702
10703 Module names must be resolvable to filenames. See `verilog-auto-inst'.
10704
10705 Signals are not inserted in the same order as in the original module,
10706 though they will appear to be in the same order to a AUTOINST
10707 instantiating either module.
10708
10709An example:
10710
a03c2342 10711 module ExampShell (/*AUTOARG*/);
7cb1c4d7
DN
10712 /*AUTOINOUTCOMP(\"ExampMain\")*/
10713 endmodule
10714
a03c2342 10715 module ExampMain (i,o,io);
7cb1c4d7
DN
10716 input i;
10717 output o;
10718 inout io;
10719 endmodule
10720
10721Typing \\[verilog-auto] will make this into:
10722
a03c2342 10723 module ExampShell (/*AUTOARG*/i,o,io);
7cb1c4d7
DN
10724 /*AUTOINOUTCOMP(\"ExampMain\")*/
10725 // Beginning of automatic in/out/inouts (from specific module)
10726 output i;
10727 inout io;
10728 input o;
10729 // End of automatics
10730 endmodule
10731
10732You may also provide an optional regular expression, in which case only
10733signals matching the regular expression will be included. For example the
10734same expansion will result from only extracting signals starting with i:
10735
10736 /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/"
10737 (verilog-auto-inout-module t))
10738
a3a8b002
DN
10739(defun verilog-auto-insert-lisp ()
10740 "Expand AUTOINSERTLISP statements, as part of \\[verilog-auto].
10741The Lisp code provided is called, and the Lisp code calls
10742`insert` to insert text into the current file beginning on the
10743line after the AUTOINSERTLISP.
10744
10745See also AUTO_LISP, which takes a Lisp expression and evaluates
10746it during `verilog-auto-inst' but does not insert any text.
10747
10748An example:
10749
10750 module ExampInsertLisp;
10751 /*AUTOINSERTLISP(my-verilog-insert-hello \"world\")*/
10752 endmodule
10753
10754 // For this example we declare the function in the
10755 // module's file itself. Often you'd define it instead
10756 // in a site-start.el or .emacs file.
10757 /*
10758 Local Variables:
10759 eval:
10760 (defun my-verilog-insert-hello (who)
10761 (insert (concat \"initial $write(\\\"hello \" who \"\\\");\\n\")))
10762 End:
10763 */
10764
10765Typing \\[verilog-auto] will call my-verilog-insert-hello and
10766expand the above into:
10767
10768 // Beginning of automatic insert lisp
10769 initial $write(\"hello world\");
10770 // End of automatics
10771
10772You can also call an external program and insert the returned
10773text:
10774
10775 /*AUTOINSERTLISP(insert (shell-command-to-string \"echo //hello\"))*/
10776 // Beginning of automatic insert lisp
10777 //hello
10778 // End of automatics"
10779 (save-excursion
10780 ;; Point is at end of /*AUTO...*/
10781 (let* ((indent-pt (current-indentation))
10782 (cmd-end-pt (save-excursion (search-backward ")")
10783 (forward-char)
10784 (point))) ;; Closing paren
10785 (cmd-beg-pt (save-excursion (goto-char cmd-end-pt)
10786 (backward-sexp 1)
10787 (point))) ;; Beginning paren
10788 (cmd (buffer-substring-no-properties cmd-beg-pt cmd-end-pt)))
10789 (forward-line 1)
0e5c8aed
DN
10790 ;; Some commands don't move point (like insert-file) so we always
10791 ;; add the begin/end comments, then delete it if not needed
10792 (verilog-insert-indent "// Beginning of automatic insert lisp\n")
10793 (verilog-insert-indent "// End of automatics\n")
10794 (forward-line -1)
10795 (eval (read cmd))
10796 (forward-line -1)
a03c2342 10797 (setq verilog-scan-cache-tick nil) ;; Clear cache; inserted unknown text
0e5c8aed 10798 (verilog-delete-empty-auto-pair))))
a3a8b002 10799
5509c6ad 10800(defun verilog-auto-sense-sigs (moddecls presense-sigs)
6341f357
DN
10801 "Return list of signals for current AUTOSENSE block."
10802 (let* ((sigss (verilog-read-always-signals))
10803 (sig-list (verilog-signals-not-params
10804 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
10805 (append (and (not verilog-auto-sense-include-inputs)
10806 (verilog-alw-get-outputs sigss))
a03c2342 10807 (verilog-alw-get-temps sigss)
5509c6ad
DN
10808 (verilog-decls-get-consts moddecls)
10809 (verilog-decls-get-gparams moddecls)
6341f357
DN
10810 presense-sigs)))))
10811 sig-list))
10812
10813(defun verilog-auto-sense ()
10814 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
10815Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
10816with one automatically derived from all inputs declared in the always
10817statement. Signals that are generated within the same always block are NOT
10818placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
10819Long lines are split based on the `fill-column', see \\[set-fill-column].
10820
10821Limitations:
10822 Verilog does not allow memories (multidimensional arrays) in sensitivity
10823 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
10824
10825Constant signals:
10826 AUTOSENSE cannot always determine if a `define is a constant or a signal
10827 (it could be in a include file for example). If a `define or other signal
10828 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
10829 declaration anywhere in the module (parenthesis are required):
10830
10831 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
10832
10833 Better yet, use a parameter, which will be understood to be constant
10834 automatically.
10835
10836OOps!
10837 If AUTOSENSE makes a mistake, please report it. (First try putting
10838 a begin/end after your always!) As a workaround, if a signal that
10839 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
10840 If a signal should be in the sensitivity list wasn't, placing it before
10841 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
10842 autos are updated (or added if it occurs there already).
10843
10844An example:
10845
1dd4b004 10846 always @ (/*AS*/) begin
6341f357
DN
10847 /* AUTO_CONSTANT (`constant) */
10848 outin = ina | inb | `constant;
10849 out = outin;
10850 end
10851
10852Typing \\[verilog-auto] will make this into:
10853
1dd4b004 10854 always @ (/*AS*/ina or inb) begin
6341f357
DN
10855 /* AUTO_CONSTANT (`constant) */
10856 outin = ina | inb | `constant;
10857 out = outin;
1dd4b004
DN
10858 end
10859
10860Note in Verilog 2001, you can often get the same result from the new @*
10861operator. (This was added to the language in part due to AUTOSENSE!)
10862
10863 always @* begin
10864 outin = ina | inb | `constant;
10865 out = outin;
6341f357
DN
10866 end"
10867 (save-excursion
10868 ;; Find beginning
10869 (let* ((start-pt (save-excursion
10870 (verilog-re-search-backward "(" nil t)
10871 (point)))
10872 (indent-pt (save-excursion
10873 (or (and (goto-char start-pt) (1+ (current-column)))
10874 (current-indentation))))
10875 (modi (verilog-modi-current))
5509c6ad 10876 (moddecls (verilog-modi-get-decls modi))
6341f357
DN
10877 (sig-memories (verilog-signals-memory
10878 (append
5509c6ad
DN
10879 (verilog-decls-get-regs moddecls)
10880 (verilog-decls-get-wires moddecls))))
6341f357
DN
10881 sig-list not-first presense-sigs)
10882 ;; Read signals in always, eliminate outputs from sense list
10883 (setq presense-sigs (verilog-signals-from-signame
10884 (save-excursion
10885 (verilog-read-signals start-pt (point)))))
5509c6ad 10886 (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
6341f357
DN
10887 (when sig-memories
10888 (let ((tlen (length sig-list)))
10889 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
a03c2342 10890 (if (not (eq tlen (length sig-list))) (verilog-insert " /*memory or*/ "))))
6341f357
DN
10891 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
10892 (save-excursion (goto-char (point))
10893 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10894 (verilog-re-search-backward "\\s-" start-pt t)
10895 (while (looking-at "\\s-`endif")
10896 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10897 (verilog-re-search-backward "\\s-" start-pt t))
10898 (not (looking-at "\\s-or\\b"))))
10899 (setq not-first t))
10900 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10901 (while sig-list
10902 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
10903 (insert "\n")
10904 (indent-to indent-pt)
10905 (if not-first (insert "or ")))
10906 (not-first (insert " or ")))
10907 (insert (verilog-sig-name (car sig-list)))
10908 (setq sig-list (cdr sig-list)
60618039 10909 not-first t)))))
6341f357
DN
10910
10911(defun verilog-auto-reset ()
10912 "Expand AUTORESET statements, as part of \\[verilog-auto].
10913Replace the /*AUTORESET*/ comment with code to initialize all
10914registers set elsewhere in the always block.
10915
10916Limitations:
10917 AUTORESET will not clear memories.
10918
86a4c7ac 10919 AUTORESET uses <= if there are any <= assignments in the block,
a3a8b002 10920 else it uses =.
6341f357
DN
10921
10922/*AUTORESET*/ presumes that any signals mentioned between the previous
10923begin/case/if statement and the AUTORESET comment are being reset manually
10924and should not be automatically reset. This includes omitting any signals
10925used on the right hand side of assignments.
10926
10927By default, AUTORESET will include the width of the signal in the autos,
10928this is a recent change. To control this behavior, see
10929`verilog-auto-reset-widths'.
10930
10931AUTORESET ties signals to deasserted, which is presumed to be zero.
10932Signals that match `verilog-active-low-regexp' will be deasserted by tieing
10933them to a one.
10934
10935An example:
10936
10937 always @(posedge clk or negedge reset_l) begin
10938 if (!reset_l) begin
10939 c <= 1;
10940 /*AUTORESET*/
10941 end
10942 else begin
10943 a <= in_a;
10944 b <= in_b;
10945 c <= in_c;
10946 end
10947 end
10948
10949Typing \\[verilog-auto] will make this into:
10950
10951 always @(posedge core_clk or negedge reset_l) begin
10952 if (!reset_l) begin
10953 c <= 1;
10954 /*AUTORESET*/
10955 // Beginning of autoreset for uninitialized flops
10956 a <= 0;
10957 b <= 0;
10958 // End of automatics
10959 end
10960 else begin
10961 a <= in_a;
10962 b <= in_b;
10963 c <= in_c;
10964 end
10965 end"
10966
10967 (interactive)
10968 (save-excursion
10969 ;; Find beginning
10970 (let* ((indent-pt (current-indentation))
10971 (modi (verilog-modi-current))
5509c6ad
DN
10972 (moddecls (verilog-modi-get-decls modi))
10973 (all-list (verilog-decls-get-signals moddecls))
6341f357
DN
10974 sigss sig-list prereset-sigs assignment-str)
10975 ;; Read signals in always, eliminate outputs from reset list
10976 (setq prereset-sigs (verilog-signals-from-signame
10977 (save-excursion
10978 (verilog-read-signals
10979 (save-excursion
10980 (verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
10981 (point))
10982 (point)))))
10983 (save-excursion
10984 (verilog-re-search-backward "@" nil t)
10985 (setq sigss (verilog-read-always-signals)))
10986 (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
10987 (concat " <= " verilog-assignment-delay)
10988 " = "))
10989 (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
a03c2342
WS
10990 (append
10991 (verilog-alw-get-temps sigss)
10992 prereset-sigs)))
6341f357
DN
10993 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10994 (when sig-list
10995 (insert "\n");
a03c2342 10996 (verilog-insert-indent "// Beginning of autoreset for uninitialized flops\n");
6341f357
DN
10997 (indent-to indent-pt)
10998 (while sig-list
10999 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
11000 (car sig-list))))
11001 (insert (verilog-sig-name sig)
11002 assignment-str
11003 (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
11004 ";\n")
11005 (indent-to indent-pt)
11006 (setq sig-list (cdr sig-list))))
a03c2342 11007 (verilog-insert "// End of automatics")))))
6341f357
DN
11008
11009(defun verilog-auto-tieoff ()
11010 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
11011Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
11012signals to deasserted.
11013
11014/*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
11015input/output list as another module, but no internals. Specifically, it
11016finds all outputs in the module, and if that input is not otherwise declared
11017as a register or wire, creates a tieoff.
11018
11019AUTORESET ties signals to deasserted, which is presumed to be zero.
11020Signals that match `verilog-active-low-regexp' will be deasserted by tieing
11021them to a one.
11022
a03c2342
WS
11023You can add signals you do not want included in AUTOTIEOFF with
11024`verilog-auto-tieoff-ignore-regexp'.
11025
6341f357
DN
11026An example of making a stub for another module:
11027
1dd4b004 11028 module ExampStub (/*AUTOINST*/);
6341f357
DN
11029 /*AUTOINOUTMODULE(\"Foo\")*/
11030 /*AUTOTIEOFF*/
11031 // verilator lint_off UNUSED
11032 wire _unused_ok = &{1'b0,
11033 /*AUTOUNUSED*/
11034 1'b0};
11035 // verilator lint_on UNUSED
11036 endmodule
11037
11038Typing \\[verilog-auto] will make this into:
11039
1dd4b004 11040 module ExampStub (/*AUTOINST*/...);
6341f357
DN
11041 /*AUTOINOUTMODULE(\"Foo\")*/
11042 // Beginning of autotieoff
11043 output [2:0] foo;
11044 // End of automatics
11045
11046 /*AUTOTIEOFF*/
11047 // Beginning of autotieoff
11048 wire [2:0] foo = 3'b0;
11049 // End of automatics
11050 ...
11051 endmodule"
11052 (interactive)
11053 (save-excursion
11054 ;; Find beginning
11055 (let* ((indent-pt (current-indentation))
11056 (modi (verilog-modi-current))
5509c6ad
DN
11057 (moddecls (verilog-modi-get-decls modi))
11058 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 11059 (sig-list (verilog-signals-not-in
5509c6ad
DN
11060 (verilog-decls-get-outputs moddecls)
11061 (append (verilog-decls-get-wires moddecls)
11062 (verilog-decls-get-regs moddecls)
11063 (verilog-decls-get-assigns moddecls)
11064 (verilog-decls-get-consts moddecls)
11065 (verilog-decls-get-gparams moddecls)
a03c2342 11066 (verilog-subdecls-get-interfaced modsubdecls)
5509c6ad
DN
11067 (verilog-subdecls-get-outputs modsubdecls)
11068 (verilog-subdecls-get-inouts modsubdecls)))))
a03c2342
WS
11069 (setq sig-list (verilog-signals-not-matching-regexp
11070 sig-list verilog-auto-tieoff-ignore-regexp))
6341f357
DN
11071 (when sig-list
11072 (forward-line 1)
11073 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
11074 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
11075 (verilog-modi-cache-add-wires modi sig-list) ; Before we trash list
11076 (while sig-list
11077 (let ((sig (car sig-list)))
11078 (verilog-insert-one-definition sig "wire" indent-pt)
11079 (indent-to (max 48 (+ indent-pt 40)))
11080 (insert "= " (verilog-sig-tieoff sig)
11081 ";\n")
11082 (setq sig-list (cdr sig-list))))
60618039 11083 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
11084
11085(defun verilog-auto-unused ()
11086 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
11087Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
11088input and inout signals.
11089
11090/*AUTOUNUSED*/ is used to make stub modules; modules that have the same
11091input/output list as another module, but no internals. Specifically, it
11092finds all inputs and inouts in the module, and if that input is not otherwise
11093used, adds it to a comma separated list.
11094
11095The comma separated list is intended to be used to create a _unused_ok
11096signal. Using the exact name \"_unused_ok\" for name of the temporary
11097signal is recommended as it will insure maximum forward compatibility, it
11098also makes lint warnings easy to understand; ignore any unused warnings
11099with \"unused\" in the signal name.
11100
11101To reduce simulation time, the _unused_ok signal should be forced to a
11102constant to prevent wiggling. The easiest thing to do is use a
11103reduction-and with 1'b0 as shown.
11104
11105This way all unused signals are in one place, making it convenient to add
11106your tool's specific pragmas around the assignment to disable any unused
11107warnings.
11108
11109You can add signals you do not want included in AUTOUNUSED with
11110`verilog-auto-unused-ignore-regexp'.
11111
11112An example of making a stub for another module:
11113
1dd4b004
DN
11114 module ExampStub (/*AUTOINST*/);
11115 /*AUTOINOUTMODULE(\"Examp\")*/
6341f357
DN
11116 /*AUTOTIEOFF*/
11117 // verilator lint_off UNUSED
11118 wire _unused_ok = &{1'b0,
11119 /*AUTOUNUSED*/
11120 1'b0};
11121 // verilator lint_on UNUSED
11122 endmodule
11123
11124Typing \\[verilog-auto] will make this into:
11125
11126 ...
11127 // verilator lint_off UNUSED
11128 wire _unused_ok = &{1'b0,
11129 /*AUTOUNUSED*/
11130 // Beginning of automatics
11131 unused_input_a,
11132 unused_input_b,
11133 unused_input_c,
11134 // End of automatics
11135 1'b0};
11136 // verilator lint_on UNUSED
11137 endmodule"
11138 (interactive)
11139 (save-excursion
11140 ;; Find beginning
11141 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
11142 (modi (verilog-modi-current))
5509c6ad
DN
11143 (moddecls (verilog-modi-get-decls modi))
11144 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 11145 (sig-list (verilog-signals-not-in
5509c6ad
DN
11146 (append (verilog-decls-get-inputs moddecls)
11147 (verilog-decls-get-inouts moddecls))
11148 (append (verilog-subdecls-get-inputs modsubdecls)
11149 (verilog-subdecls-get-inouts modsubdecls)))))
6341f357
DN
11150 (setq sig-list (verilog-signals-not-matching-regexp
11151 sig-list verilog-auto-unused-ignore-regexp))
11152 (when sig-list
11153 (forward-line 1)
11154 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
11155 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
11156 (while sig-list
11157 (let ((sig (car sig-list)))
11158 (indent-to indent-pt)
11159 (insert (verilog-sig-name sig) ",\n")
11160 (setq sig-list (cdr sig-list))))
60618039 11161 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
11162
11163(defun verilog-enum-ascii (signm elim-regexp)
37ea4b9b 11164 "Convert an enum name SIGNM to an ascii string for insertion.
6341f357
DN
11165Remove user provided prefix ELIM-REGEXP."
11166 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
11167 (let ((case-fold-search t))
11168 ;; All upper becomes all lower for readability
11169 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
11170
11171(defun verilog-auto-ascii-enum ()
11172 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
11173Create a register to contain the ASCII decode of a enumerated signal type.
11174This will allow trace viewers to show the ASCII name of states.
11175
11176First, parameters are built into a enumeration using the synopsys enum
11177comment. The comment must be between the keyword and the symbol.
6edb5716 11178\(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
6341f357
DN
11179
11180Next, registers which that enum applies to are also tagged with the same
11181enum. Synopsys also suggests labeling state vectors, but `verilog-mode'
11182doesn't care.
11183
11184Finally, a AUTOASCIIENUM command is used.
11185
11186 The first parameter is the name of the signal to be decoded.
a3a8b002
DN
11187 If and only if the first parameter width is 2^(number of states
11188 in enum) and does NOT match the width of the enum, the signal
11189 is assumed to be a one hot decode. Otherwise, it's a normal
11190 encoded state vector.
6341f357
DN
11191
11192 The second parameter is the name to store the ASCII code into. For the
11193 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
11194 a signal that is just for simulation, and the magic characters _ascii
11195 tell viewers like Dinotrace to display in ASCII format.
11196
11197 The final optional parameter is a string which will be removed from the
11198 state names.
11199
11200An example:
11201
11202 //== State enumeration
11203 parameter [2:0] // synopsys enum state_info
11204 SM_IDLE = 3'b000,
11205 SM_SEND = 3'b001,
11206 SM_WAIT1 = 3'b010;
11207 //== State variables
a3a8b002
DN
11208 reg [2:0] /* synopsys enum state_info */
11209 state_r; /* synopsys state_vector state_r */
11210 reg [2:0] /* synopsys enum state_info */
11211 state_e1;
6341f357
DN
11212
11213 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
11214
11215Typing \\[verilog-auto] will make this into:
11216
11217 ... same front matter ...
11218
11219 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
11220 // Beginning of automatic ASCII enum decoding
11221 reg [39:0] state_ascii_r; // Decode of state_r
11222 always @(state_r) begin
11223 case ({state_r})
11224 SM_IDLE: state_ascii_r = \"idle \";
11225 SM_SEND: state_ascii_r = \"send \";
11226 SM_WAIT1: state_ascii_r = \"wait1\";
11227 default: state_ascii_r = \"%Erro\";
11228 endcase
11229 end
11230 // End of automatics"
11231 (save-excursion
11232 (let* ((params (verilog-read-auto-params 2 3))
11233 (undecode-name (nth 0 params))
11234 (ascii-name (nth 1 params))
11235 (elim-regexp (nth 2 params))
11236 ;;
11237 (indent-pt (current-indentation))
11238 (modi (verilog-modi-current))
5509c6ad 11239 (moddecls (verilog-modi-get-decls modi))
6341f357 11240 ;;
5509c6ad
DN
11241 (sig-list-consts (append (verilog-decls-get-consts moddecls)
11242 (verilog-decls-get-gparams moddecls)))
11243 (sig-list-all (append (verilog-decls-get-regs moddecls)
11244 (verilog-decls-get-outputs moddecls)
11245 (verilog-decls-get-inouts moddecls)
11246 (verilog-decls-get-inputs moddecls)
11247 (verilog-decls-get-wires moddecls)))
6341f357
DN
11248 ;;
11249 (undecode-sig (or (assoc undecode-name sig-list-all)
11250 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
11251 (undecode-enum (or (verilog-sig-enum undecode-sig)
11252 (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
11253 ;;
a3a8b002
DN
11254 (enum-sigs (verilog-signals-not-in
11255 (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
11256 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum))
11257 nil))
6341f357 11258 ;;
a3a8b002
DN
11259 (one-hot (and ;; width(enum) != width(sig)
11260 (or (not (verilog-sig-bits (car enum-sigs)))
11261 (not (equal (verilog-sig-width (car enum-sigs))
11262 (verilog-sig-width undecode-sig))))
11263 ;; count(enums) == width(sig)
11264 (equal (number-to-string (length enum-sigs))
11265 (verilog-sig-width undecode-sig))))
11266 (enum-chars 0)
6341f357
DN
11267 (ascii-chars 0))
11268 ;;
11269 ;; Find number of ascii chars needed
11270 (let ((tmp-sigs enum-sigs))
11271 (while tmp-sigs
11272 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
11273 ascii-chars (max ascii-chars (length (verilog-enum-ascii
11274 (verilog-sig-name (car tmp-sigs))
11275 elim-regexp)))
11276 tmp-sigs (cdr tmp-sigs))))
11277 ;;
11278 (forward-line 1)
11279 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
11280 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
11281 (concat "Decode of " undecode-name) nil nil))))
11282 (verilog-insert-definition decode-sig-list "reg" indent-pt nil)
11283 (verilog-modi-cache-add-regs modi decode-sig-list))
11284 ;;
11285 (verilog-insert-indent "always @(" undecode-name ") begin\n")
11286 (setq indent-pt (+ indent-pt verilog-indent-level))
11287 (indent-to indent-pt)
11288 (insert "case ({" undecode-name "})\n")
11289 (setq indent-pt (+ indent-pt verilog-case-indent))
11290 ;;
11291 (let ((tmp-sigs enum-sigs)
a3a8b002
DN
11292 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n"
11293 (+ (if one-hot 9 1) (max 8 enum-chars))
6341f357
DN
11294 ascii-name ascii-chars))
11295 (errname (substring "%Error" 0 (min 6 ascii-chars))))
11296 (while tmp-sigs
11297 (verilog-insert-indent
a3a8b002
DN
11298 (concat
11299 (format chrfmt
11300 (concat (if one-hot "(")
11301 (if one-hot (verilog-sig-width undecode-sig))
11302 ;; We use a shift instead of var[index]
11303 ;; so that a non-one hot value will show as error.
11304 (if one-hot "'b1<<")
11305 (verilog-sig-name (car tmp-sigs))
11306 (if one-hot ")") ":")
11307 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
11308 elim-regexp))))
6341f357
DN
11309 (setq tmp-sigs (cdr tmp-sigs)))
11310 (verilog-insert-indent (format chrfmt "default:" errname)))
11311 ;;
11312 (setq indent-pt (- indent-pt verilog-case-indent))
11313 (verilog-insert-indent "endcase\n")
11314 (setq indent-pt (- indent-pt verilog-indent-level))
11315 (verilog-insert-indent "end\n"
60618039 11316 "// End of automatics\n"))))
6341f357
DN
11317
11318(defun verilog-auto-templated-rel ()
11319 "Replace Templated relative line numbers with absolute line numbers.
11320Internal use only. This hacks around the line numbers in AUTOINST Templates
11321being different from the final output's line numbering."
a03c2342 11322 (let ((templateno 0) (template-line (list 0)) (buf-line 1))
6341f357 11323 ;; Find line number each template is on
a03c2342 11324 ;; Count lines as we go, as otherwise it's O(n^2) to use count-lines
6341f357 11325 (goto-char (point-min))
a03c2342
WS
11326 (while (not (eobp))
11327 (when (looking-at ".*AUTO_TEMPLATE")
11328 (setq templateno (1+ templateno))
11329 (setq template-line (cons buf-line template-line)))
11330 (setq buf-line (1+ buf-line))
11331 (forward-line 1))
6341f357
DN
11332 (setq template-line (nreverse template-line))
11333 ;; Replace T# L# with absolute line number
11334 (goto-char (point-min))
11335 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
7ea26faf
DN
11336 (replace-match
11337 (concat " Templated "
11338 (int-to-string (+ (nth (string-to-number (match-string 1))
11339 template-line)
11340 (string-to-number (match-string 2)))))
11341 t t))))
6341f357
DN
11342
11343\f
11344;;
11345;; Auto top level
11346;;
11347
11348(defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing a arg
11349 "Expand AUTO statements.
11350Look for any /*AUTO...*/ commands in the code, as used in
11351instantiations or argument headers. Update the list of signals
11352following the /*AUTO...*/ command.
11353
11354Use \\[verilog-delete-auto] to remove the AUTOs.
11355
11356Use \\[verilog-inject-auto] to insert AUTOs for the first time.
11357
11358Use \\[verilog-faq] for a pointer to frequently asked questions.
11359
11360The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
11361called before and after this function, respectively.
11362
11363For example:
a03c2342 11364 module ModuleName (/*AUTOARG*/);
6341f357
DN
11365 /*AUTOINPUT*/
11366 /*AUTOOUTPUT*/
11367 /*AUTOWIRE*/
11368 /*AUTOREG*/
1dd4b004 11369 InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
6341f357
DN
11370
11371You can also update the AUTOs from the shell using:
11372 emacs --batch <filenames.v> -f verilog-batch-auto
11373Or fix indentation with:
11374 emacs --batch <filenames.v> -f verilog-batch-indent
11375Likewise, you can delete or inject AUTOs with:
11376 emacs --batch <filenames.v> -f verilog-batch-delete-auto
11377 emacs --batch <filenames.v> -f verilog-batch-inject-auto
11378
11379Using \\[describe-function], see also:
11380 `verilog-auto-arg' for AUTOARG module instantiations
11381 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
7cb1c4d7 11382 `verilog-auto-inout-comp' for AUTOINOUTCOMP copy complemented i/o
6341f357
DN
11383 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
11384 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
11385 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
a3a8b002 11386 `verilog-auto-insert-lisp' for AUTOINSERTLISP insert code from lisp function
6341f357
DN
11387 `verilog-auto-inst' for AUTOINST instantiation pins
11388 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
11389 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
11390 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
11391 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
11392 `verilog-auto-reg' for AUTOREG registers
11393 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
11394 `verilog-auto-reset' for AUTORESET flop resets
11395 `verilog-auto-sense' for AUTOSENSE always sensitivity lists
11396 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
11397 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
11398 `verilog-auto-wire' for AUTOWIRE instantiation wires
11399
11400 `verilog-read-defines' for reading `define values
11401 `verilog-read-includes' for reading `includes
11402
a3a8b002 11403If you have bugs with these autos, please file an issue at
855b42a2 11404URL `http://www.veripool.org/verilog-mode' or contact the AUTOAUTHOR
a3a8b002 11405Wilson Snyder (wsnyder@wsnyder.org)."
6341f357
DN
11406 (interactive)
11407 (unless noninteractive (message "Updating AUTOs..."))
7ea26faf 11408 (if (fboundp 'dinotrace-unannotate-all)
6341f357
DN
11409 (dinotrace-unannotate-all))
11410 (let ((oldbuf (if (not (buffer-modified-p))
11411 (buffer-string)))
11412 ;; Before version 20, match-string with font-lock returns a
11413 ;; vector that is not equal to the string. IE if on "input"
11414 ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
11415 (fontlocked (when (and (boundp 'font-lock-mode)
11416 font-lock-mode)
7cb1c4d7 11417 (font-lock-mode 0)
5509c6ad
DN
11418 t))
11419 ;; Cache directories; we don't write new files, so can't change
a03c2342
WS
11420 (verilog-dir-cache-preserving t)
11421 ;; Cache current module
11422 (verilog-modi-cache-current-enable t)
11423 (verilog-modi-cache-current-max (point-min)) ; IE it's invalid
11424 verilog-modi-cache-current)
11425 (unwind-protect
11426 ;; Disable change hooks for speed
11427 ;; This let can't be part of above let; must restore
11428 ;; after-change-functions before font-lock resumes
11429 (verilog-save-no-change-functions
11430 (verilog-save-scan-cache
11431 (save-excursion
11432 ;; If we're not in verilog-mode, change syntax table so parsing works right
11433 (unless (eq major-mode `verilog-mode) (verilog-mode))
11434 ;; Allow user to customize
11435 (run-hooks 'verilog-before-auto-hook)
11436 ;; Try to save the user from needing to revert-file to reread file local-variables
11437 (verilog-auto-reeval-locals)
11438 (verilog-read-auto-lisp-present)
11439 (verilog-read-auto-lisp (point-min) (point-max))
11440 (verilog-getopt-flags)
11441 ;; From here on out, we can cache anything we read from disk
11442 (verilog-preserve-dir-cache
11443 ;; These two may seem obvious to do always, but on large includes it can be way too slow
11444 (when verilog-auto-read-includes
11445 (verilog-read-includes)
11446 (verilog-read-defines nil nil t))
11447 ;; This particular ordering is important
11448 ;; INST: Lower modules correct, no internal dependencies, FIRST
11449 (verilog-preserve-modi-cache
11450 ;; Clear existing autos else we'll be screwed by existing ones
11451 (verilog-delete-auto)
11452 ;; Injection if appropriate
11453 (when inject
11454 (verilog-inject-inst)
11455 (verilog-inject-sense)
11456 (verilog-inject-arg))
11457 ;;
11458 ;; Do user inserts first, so their code can insert AUTOs
11459 ;; We may provide a AUTOINSERTLISPLAST if another cleanup pass is needed
11460 (verilog-auto-re-search-do "/\\*AUTOINSERTLISP(.*?)\\*/"
11461 'verilog-auto-insert-lisp)
11462 ;; Expand instances before need the signals the instances input/output
11463 (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
11464 (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
11465 (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
11466 ;; Doesn't matter when done, but combine it with a common changer
11467 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
11468 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
11469 ;; Must be done before autoin/out as creates a reg
11470 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
11471 ;;
11472 ;; first in/outs from other files
11473 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
11474 (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP([^)]*)\\*/" 'verilog-auto-inout-comp)
11475 ;; next in/outs which need previous sucked inputs first
11476 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((\"[^\"]*\")\\)\\*/"
11477 '(lambda () (verilog-auto-output t)))
11478 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\*/" 'verilog-auto-output)
11479 (verilog-auto-re-search-do "/\\*AUTOINPUT\\((\"[^\"]*\")\\)\\*/"
11480 '(lambda () (verilog-auto-input t)))
11481 (verilog-auto-re-search-do "/\\*AUTOINPUT\\*/" 'verilog-auto-input)
11482 (verilog-auto-re-search-do "/\\*AUTOINOUT\\((\"[^\"]*\")\\)\\*/"
11483 '(lambda () (verilog-auto-inout t)))
11484 (verilog-auto-re-search-do "/\\*AUTOINOUT\\*/" 'verilog-auto-inout)
11485 ;; Then tie off those in/outs
11486 (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
11487 ;; Wires/regs must be after inputs/outputs
11488 (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
11489 (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
11490 (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
11491 ;; outputevery needs AUTOOUTPUTs done first
11492 (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\*/" 'verilog-auto-output-every)
11493 ;; After we've created all new variables
11494 (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
11495 ;; Must be after all inputs outputs are generated
11496 (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
11497 ;; Fix line numbers (comments only)
11498 (when verilog-auto-inst-template-numbers
11499 (verilog-auto-templated-rel))))
11500 ;;
11501 (run-hooks 'verilog-auto-hook)
11502 ;;
11503 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))
11504 ;;
11505 ;; If end result is same as when started, clear modified flag
11506 (cond ((and oldbuf (equal oldbuf (buffer-string)))
11507 (set-buffer-modified-p nil)
11508 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
11509 (t (unless noninteractive (message "Updating AUTOs...done"))))
11510 ;; End of after-change protection
11511 )))
11512 ;; Unwind forms
11513 (progn
11514 ;; Restore font-lock
11515 (when fontlocked (font-lock-mode t))))))
6341f357
DN
11516\f
11517
11518;;
11519;; Skeleton based code insertion
11520;;
60618039 11521(defvar verilog-template-map
6edb5716
DN
11522 (let ((map (make-sparse-keymap)))
11523 (define-key map "a" 'verilog-sk-always)
11524 (define-key map "b" 'verilog-sk-begin)
11525 (define-key map "c" 'verilog-sk-case)
11526 (define-key map "f" 'verilog-sk-for)
11527 (define-key map "g" 'verilog-sk-generate)
11528 (define-key map "h" 'verilog-sk-header)
11529 (define-key map "i" 'verilog-sk-initial)
11530 (define-key map "j" 'verilog-sk-fork)
11531 (define-key map "m" 'verilog-sk-module)
11532 (define-key map "p" 'verilog-sk-primitive)
11533 (define-key map "r" 'verilog-sk-repeat)
11534 (define-key map "s" 'verilog-sk-specify)
11535 (define-key map "t" 'verilog-sk-task)
11536 (define-key map "w" 'verilog-sk-while)
11537 (define-key map "x" 'verilog-sk-casex)
11538 (define-key map "z" 'verilog-sk-casez)
11539 (define-key map "?" 'verilog-sk-if)
11540 (define-key map ":" 'verilog-sk-else-if)
11541 (define-key map "/" 'verilog-sk-comment)
11542 (define-key map "A" 'verilog-sk-assign)
11543 (define-key map "F" 'verilog-sk-function)
11544 (define-key map "I" 'verilog-sk-input)
11545 (define-key map "O" 'verilog-sk-output)
11546 (define-key map "S" 'verilog-sk-state-machine)
11547 (define-key map "=" 'verilog-sk-inout)
11548 (define-key map "W" 'verilog-sk-wire)
11549 (define-key map "R" 'verilog-sk-reg)
30d48f20
DN
11550 (define-key map "D" 'verilog-sk-define-signal)
11551 map)
6341f357
DN
11552 "Keymap used in Verilog mode for smart template operations.")
11553
6341f357
DN
11554
11555;;
11556;; Place the templates into Verilog Mode. They may be inserted under any key.
11557;; C-c C-t will be the default. If you use templates a lot, you
11558;; may want to consider moving the binding to another key in your .emacs
11559;; file.
11560;;
11561;(define-key verilog-mode-map "\C-ct" verilog-template-map)
11562(define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
11563
11564;;; ---- statement skeletons ------------------------------------------
11565
11566(define-skeleton verilog-sk-prompt-condition
11567 "Prompt for the loop condition."
11568 "[condition]: " str )
11569
11570(define-skeleton verilog-sk-prompt-init
11571 "Prompt for the loop init statement."
11572 "[initial statement]: " str )
11573
11574(define-skeleton verilog-sk-prompt-inc
11575 "Prompt for the loop increment statement."
11576 "[increment statement]: " str )
11577
11578(define-skeleton verilog-sk-prompt-name
11579 "Prompt for the name of something."
11580 "[name]: " str)
11581
11582(define-skeleton verilog-sk-prompt-clock
11583 "Prompt for the name of something."
11584 "name and edge of clock(s): " str)
11585
11586(defvar verilog-sk-reset nil)
11587(defun verilog-sk-prompt-reset ()
11588 "Prompt for the name of a state machine reset."
7ea26faf 11589 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
6341f357
DN
11590
11591
11592(define-skeleton verilog-sk-prompt-state-selector
11593 "Prompt for the name of a state machine selector."
11594 "name of selector (eg {a,b,c,d}): " str )
11595
11596(define-skeleton verilog-sk-prompt-output
11597 "Prompt for the name of something."
11598 "output: " str)
11599
11600(define-skeleton verilog-sk-prompt-msb
11601 "Prompt for least significant bit specification."
f07fe184 11602 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
6341f357
DN
11603
11604(define-skeleton verilog-sk-prompt-lsb
11605 "Prompt for least significant bit specification."
11606 "lsb:" str )
11607
11608(defvar verilog-sk-p nil)
11609(define-skeleton verilog-sk-prompt-width
11610 "Prompt for a width specification."
11611 ()
11612 (progn
11613 (setq verilog-sk-p (point))
11614 (verilog-sk-prompt-msb)
11615 (if (> (point) verilog-sk-p) "] " " ")))
11616
11617(defun verilog-sk-header ()
a3a8b002
DN
11618 "Insert a descriptive header at the top of the file.
11619See also `verilog-header' for an alternative format."
6341f357
DN
11620 (interactive "*")
11621 (save-excursion
11622 (goto-char (point-min))
11623 (verilog-sk-header-tmpl)))
11624
11625(define-skeleton verilog-sk-header-tmpl
11626 "Insert a comment block containing the module title, author, etc."
11627 "[Description]: "
11628 "// -*- Mode: Verilog -*-"
11629 "\n// Filename : " (buffer-name)
11630 "\n// Description : " str
11631 "\n// Author : " (user-full-name)
11632 "\n// Created On : " (current-time-string)
a3a8b002
DN
11633 "\n// Last Modified By: " (user-full-name)
11634 "\n// Last Modified On: " (current-time-string)
6341f357
DN
11635 "\n// Update Count : 0"
11636 "\n// Status : Unknown, Use with caution!"
11637 "\n")
11638
11639(define-skeleton verilog-sk-module
11640 "Insert a module definition."
11641 ()
f07fe184 11642 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
6341f357
DN
11643 > _ \n
11644 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
11645
11646(define-skeleton verilog-sk-primitive
11647 "Insert a task definition."
11648 ()
f07fe184 11649 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
6341f357
DN
11650 > _ \n
11651 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
11652
11653(define-skeleton verilog-sk-task
11654 "Insert a task definition."
11655 ()
f07fe184 11656 > "task " '(verilog-sk-prompt-name) & ?; \n
6341f357
DN
11657 > _ \n
11658 > "begin" \n
11659 > \n
11660 > (- verilog-indent-level-behavioral) "end" \n
11661 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
11662
11663(define-skeleton verilog-sk-function
11664 "Insert a function definition."
11665 ()
f07fe184 11666 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
6341f357
DN
11667 > _ \n
11668 > "begin" \n
11669 > \n
11670 > (- verilog-indent-level-behavioral) "end" \n
11671 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
11672
11673(define-skeleton verilog-sk-always
11674 "Insert always block. Uses the minibuffer to prompt
11675for sensitivity list."
11676 ()
11677 > "always @ ( /*AUTOSENSE*/ ) begin\n"
11678 > _ \n
11679 > (- verilog-indent-level-behavioral) "end" \n >
11680 )
11681
11682(define-skeleton verilog-sk-initial
11683 "Insert an initial block."
11684 ()
11685 > "initial begin\n"
11686 > _ \n
11687 > (- verilog-indent-level-behavioral) "end" \n > )
11688
11689(define-skeleton verilog-sk-specify
11690 "Insert specify block. "
11691 ()
11692 > "specify\n"
11693 > _ \n
11694 > (- verilog-indent-level-behavioral) "endspecify" \n > )
11695
11696(define-skeleton verilog-sk-generate
11697 "Insert generate block. "
11698 ()
11699 > "generate\n"
11700 > _ \n
11701 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
11702
11703(define-skeleton verilog-sk-begin
37ea4b9b 11704 "Insert begin end block. Uses the minibuffer to prompt for name."
6341f357 11705 ()
f07fe184 11706 > "begin" '(verilog-sk-prompt-name) \n
6341f357
DN
11707 > _ \n
11708 > (- verilog-indent-level-behavioral) "end"
11709)
11710
11711(define-skeleton verilog-sk-fork
37ea4b9b 11712 "Insert a fork join block."
6341f357
DN
11713 ()
11714 > "fork\n"
11715 > "begin" \n
11716 > _ \n
11717 > (- verilog-indent-level-behavioral) "end" \n
11718 > "begin" \n
11719 > \n
11720 > (- verilog-indent-level-behavioral) "end" \n
11721 > (- verilog-indent-level-behavioral) "join" \n
11722 > )
11723
11724
11725(define-skeleton verilog-sk-case
11726 "Build skeleton case statement, prompting for the selector expression,
11727and the case items."
11728 "[selector expression]: "
11729 > "case (" str ") " \n
a3a8b002 11730 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
6341f357
DN
11731 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11732
11733(define-skeleton verilog-sk-casex
11734 "Build skeleton casex statement, prompting for the selector expression,
11735and the case items."
11736 "[selector expression]: "
11737 > "casex (" str ") " \n
a3a8b002 11738 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
6341f357
DN
11739 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11740
11741(define-skeleton verilog-sk-casez
11742 "Build skeleton casez statement, prompting for the selector expression,
11743and the case items."
11744 "[selector expression]: "
11745 > "casez (" str ") " \n
a3a8b002 11746 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
6341f357
DN
11747 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11748
11749(define-skeleton verilog-sk-if
11750 "Insert a skeleton if statement."
f07fe184 11751 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
6341f357
DN
11752 > _ \n
11753 > (- verilog-indent-level-behavioral) "end " \n )
11754
11755(define-skeleton verilog-sk-else-if
11756 "Insert a skeleton else if statement."
11757 > (verilog-indent-line) "else if ("
f07fe184 11758 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
6341f357
DN
11759 > _ \n
11760 > "end" (progn (electric-verilog-terminate-line) nil))
11761
11762(define-skeleton verilog-sk-datadef
37ea4b9b 11763 "Common routine to get data definition."
6341f357 11764 ()
f07fe184 11765 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
6341f357
DN
11766
11767(define-skeleton verilog-sk-input
11768 "Insert an input definition."
11769 ()
f07fe184 11770 > "input [" '(verilog-sk-datadef))
6341f357
DN
11771
11772(define-skeleton verilog-sk-output
11773 "Insert an output definition."
11774 ()
f07fe184 11775 > "output [" '(verilog-sk-datadef))
6341f357
DN
11776
11777(define-skeleton verilog-sk-inout
11778 "Insert an inout definition."
11779 ()
f07fe184 11780 > "inout [" '(verilog-sk-datadef))
6341f357
DN
11781
11782(defvar verilog-sk-signal nil)
11783(define-skeleton verilog-sk-def-reg
11784 "Insert a reg definition."
11785 ()
f07fe184 11786 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
6341f357
DN
11787
11788(defun verilog-sk-define-signal ()
11789 "Insert a definition of signal under point at top of module."
11790 (interactive "*")
60618039 11791 (let* ((sig-re "[a-zA-Z0-9_]*")
6341f357
DN
11792 (v1 (buffer-substring
11793 (save-excursion
11794 (skip-chars-backward sig-re)
11795 (point))
11796 (save-excursion
11797 (skip-chars-forward sig-re)
60618039 11798 (point)))))
6341f357
DN
11799 (if (not (member v1 verilog-keywords))
11800 (save-excursion
11801 (setq verilog-sk-signal v1)
11802 (verilog-beg-of-defun)
11803 (verilog-end-of-statement)
11804 (verilog-forward-syntactic-ws)
11805 (verilog-sk-def-reg)
11806 (message "signal at point is %s" v1))
60618039 11807 (message "object at point (%s) is a keyword" v1))))
6341f357
DN
11808
11809(define-skeleton verilog-sk-wire
11810 "Insert a wire definition."
11811 ()
f07fe184 11812 > "wire [" '(verilog-sk-datadef))
6341f357
DN
11813
11814(define-skeleton verilog-sk-reg
11815 "Insert a reg definition."
11816 ()
f07fe184 11817 > "reg [" '(verilog-sk-datadef))
6341f357
DN
11818
11819(define-skeleton verilog-sk-assign
11820 "Insert a skeleton assign statement."
11821 ()
f07fe184 11822 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
6341f357
DN
11823
11824(define-skeleton verilog-sk-while
11825 "Insert a skeleton while loop statement."
11826 ()
f07fe184 11827 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
6341f357
DN
11828 > _ \n
11829 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11830
11831(define-skeleton verilog-sk-repeat
11832 "Insert a skeleton repeat loop statement."
11833 ()
f07fe184 11834 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
6341f357
DN
11835 > _ \n
11836 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11837
11838(define-skeleton verilog-sk-for
11839 "Insert a skeleton while loop statement."
11840 ()
11841 > "for ("
f07fe184
DN
11842 '(verilog-sk-prompt-init) "; "
11843 '(verilog-sk-prompt-condition) "; "
11844 '(verilog-sk-prompt-inc)
6341f357
DN
11845 ") begin" \n
11846 > _ \n
11847 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11848
11849(define-skeleton verilog-sk-comment
11850 "Inserts three comment lines, making a display comment."
11851 ()
11852 > "/*\n"
11853 > "* " _ \n
11854 > "*/")
11855
11856(define-skeleton verilog-sk-state-machine
11857 "Insert a state machine definition."
11858 "Name of state variable: "
11859 '(setq input "state")
11860 > "// State registers for " str | -23 \n
11861 '(setq verilog-sk-state str)
f07fe184 11862 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
6341f357
DN
11863 '(setq input nil)
11864 > \n
11865 > "// State FF for " verilog-sk-state \n
11866 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
11867 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
11868 > verilog-sk-state " = next_" verilog-sk-state ?; \n
11869 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
11870 > \n
11871 > "// Next State Logic for " verilog-sk-state \n
11872 > "always @ ( /*AUTOSENSE*/ ) begin\n"
f07fe184 11873 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
6341f357
DN
11874 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
11875 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
11876 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
6341f357
DN
11877\f
11878
11879;;
11880;; Include file loading with mouse/return event
11881;;
11882;; idea & first impl.: M. Rouat (eldo-mode.el)
11883;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
11884
11885(if (featurep 'xemacs)
af62aa88 11886 (require 'overlay))
6341f357
DN
11887
11888(defconst verilog-include-file-regexp
11889 "^`include\\s-+\"\\([^\n\"]*\\)\""
11890 "Regexp that matches the include file.")
11891
60618039 11892(defvar verilog-mode-mouse-map
6341f357
DN
11893 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
11894 (set-keymap-parent map verilog-mode-map)
11895 ;; mouse button bindings
11896 (define-key map "\r" 'verilog-load-file-at-point)
11897 (if (featurep 'xemacs)
11898 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
11899 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
11900 (if (featurep 'xemacs)
11901 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
30d48f20
DN
11902 (define-key map [S-mouse-2] 'mouse-yank-at-click))
11903 map)
6edb5716
DN
11904 "Map containing mouse bindings for `verilog-mode'.")
11905
6341f357 11906
a03c2342
WS
11907(defun verilog-highlight-region (beg end old-len)
11908 "Colorize included files and modules in the (changed?) region.
6341f357 11909Clicking on the middle-mouse button loads them in a buffer (as in dired)."
a03c2342
WS
11910 (when (or verilog-highlight-includes
11911 verilog-highlight-modules)
11912 (save-excursion
11913 (save-match-data ;; A query-replace may call this function - do not disturb
11914 (verilog-save-buffer-state
11915 (verilog-save-scan-cache
11916 (let (end-point)
11917 (goto-char end)
11918 (setq end-point (verilog-get-end-of-line))
11919 (goto-char beg)
11920 (beginning-of-line) ; scan entire line
11921 ;; delete overlays existing on this line
11922 (let ((overlays (overlays-in (point) end-point)))
11923 (while overlays
11924 (if (and
11925 (overlay-get (car overlays) 'detachable)
11926 (or (overlay-get (car overlays) 'verilog-include-file)
11927 (overlay-get (car overlays) 'verilog-inst-module)))
11928 (delete-overlay (car overlays)))
11929 (setq overlays (cdr overlays))))
11930 ;;
11931 ;; make new include overlays
11932 (when verilog-highlight-includes
11933 (while (search-forward-regexp verilog-include-file-regexp end-point t)
11934 (goto-char (match-beginning 1))
11935 (let ((ov (make-overlay (match-beginning 1) (match-end 1))))
11936 (overlay-put ov 'start-closed 't)
11937 (overlay-put ov 'end-closed 't)
11938 (overlay-put ov 'evaporate 't)
11939 (overlay-put ov 'verilog-include-file 't)
11940 (overlay-put ov 'mouse-face 'highlight)
11941 (overlay-put ov 'local-map verilog-mode-mouse-map))))
11942 ;;
11943 ;; make new module overlays
11944 (goto-char beg)
11945 ;; This scanner is syntax-fragile, so don't get bent
11946 (when verilog-highlight-modules
11947 (condition-case nil
11948 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-point t)
11949 (save-excursion
11950 (goto-char (match-beginning 0))
11951 (unless (verilog-inside-comment-p)
11952 (verilog-read-inst-module-matcher) ;; sets match 0
11953 (let* ((ov (make-overlay (match-beginning 0) (match-end 0))))
11954 (overlay-put ov 'start-closed 't)
11955 (overlay-put ov 'end-closed 't)
11956 (overlay-put ov 'evaporate 't)
11957 (overlay-put ov 'verilog-inst-module 't)
11958 (overlay-put ov 'mouse-face 'highlight)
11959 (overlay-put ov 'local-map verilog-mode-mouse-map)))))
11960 (error nil)))
11961 ;;
11962 ;; Future highlights:
11963 ;; variables - make an Occur buffer of where referenced
11964 ;; pins - make an Occur buffer of the sig in the declaration module
11965 )))))))
11966
11967(defun verilog-highlight-buffer ()
11968 "Colorize included files and modules across the whole buffer."
11969 ;; Invoked via verilog-mode calling font-lock then `font-lock-mode-hook'
6341f357 11970 (interactive)
a03c2342
WS
11971 ;; delete and remake overlays
11972 (verilog-highlight-region (point-min) (point-max) nil))
11973
11974;; Deprecated, but was interactive, so we'll keep it around
11975(defalias 'verilog-colorize-include-files-buffer 'verilog-highlight-buffer)
6341f357 11976
37ea4b9b 11977;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
6341f357
DN
11978;; so define this function to do more or less the same as ffap-at-mouse
11979;; but first resolve filename...
11980(defun verilog-load-file-at-mouse (event)
11981 "Load file under button 2 click's EVENT.
a03c2342 11982Files are checked based on `verilog-library-flags'."
6341f357 11983 (interactive "@e")
37ea4b9b 11984 (save-excursion ;; implement a Verilog specific ffap-at-mouse
6341f357 11985 (mouse-set-point event)
a03c2342 11986 (verilog-load-file-at-point t)))
6341f357 11987
37ea4b9b 11988;; ffap isn't useable for Verilog mode. It uses library paths.
6341f357
DN
11989;; so define this function to do more or less the same as ffap
11990;; but first resolve filename...
a03c2342 11991(defun verilog-load-file-at-point (&optional warn)
6341f357 11992 "Load file under point.
a03c2342
WS
11993If WARN, throw warning if not found.
11994Files are checked based on `verilog-library-flags'."
6341f357 11995 (interactive)
37ea4b9b 11996 (save-excursion ;; implement a Verilog specific ffap
a03c2342
WS
11997 (let ((overlays (overlays-in (point) (point)))
11998 hit)
11999 (while (and overlays (not hit))
12000 (when (overlay-get (car overlays) 'verilog-inst-module)
12001 (verilog-goto-defun-file (buffer-substring
12002 (overlay-start (car overlays))
12003 (overlay-end (car overlays))))
12004 (setq hit t))
12005 (setq overlays (cdr overlays)))
12006 ;; Include?
12007 (beginning-of-line)
12008 (when (and (not hit)
12009 (looking-at verilog-include-file-regexp))
12010 (if (and (car (verilog-library-filenames
12011 (match-string 1) (buffer-file-name)))
12012 (file-readable-p (car (verilog-library-filenames
12013 (match-string 1) (buffer-file-name)))))
6341f357 12014 (find-file (car (verilog-library-filenames
a03c2342
WS
12015 (match-string 1) (buffer-file-name))))
12016 (when warn
12017 (message
12018 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
12019 (match-string 1))))))))
6341f357
DN
12020
12021;;
12022;; Bug reporting
12023;;
12024
12025(defun verilog-faq ()
12026 "Tell the user their current version, and where to get the FAQ etc."
12027 (interactive)
12028 (with-output-to-temp-buffer "*verilog-mode help*"
12029 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
12030 (princ "\n")
12031 (princ "For new releases, see http://www.verilog.com\n")
12032 (princ "\n")
7cb1c4d7 12033 (princ "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
6341f357
DN
12034 (princ "\n")
12035 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
12036 (princ "\n")))
12037
7ea26faf 12038(autoload 'reporter-submit-bug-report "reporter")
60618039 12039(defvar reporter-prompt-for-summary-p)
7ea26faf 12040
6341f357
DN
12041(defun verilog-submit-bug-report ()
12042 "Submit via mail a bug report on verilog-mode.el."
12043 (interactive)
12044 (let ((reporter-prompt-for-summary-p t))
12045 (reporter-submit-bug-report
86a4c7ac 12046 "mac@verilog.com, wsnyder@wsnyder.org"
6341f357
DN
12047 (concat "verilog-mode v" verilog-mode-version)
12048 '(
a03c2342 12049 verilog-active-low-regexp
6341f357 12050 verilog-align-ifelse
a03c2342
WS
12051 verilog-assignment-delay
12052 verilog-auto-arg-sort
6341f357
DN
12053 verilog-auto-endcomments
12054 verilog-auto-hook
a03c2342 12055 verilog-auto-ignore-concat
6341f357 12056 verilog-auto-indent-on-newline
a03c2342
WS
12057 verilog-auto-inout-ignore-regexp
12058 verilog-auto-input-ignore-regexp
12059 verilog-auto-inst-column
12060 verilog-auto-inst-dot-name
12061 verilog-auto-inst-param-value
6341f357 12062 verilog-auto-inst-template-numbers
a03c2342 12063 verilog-auto-inst-vector
6341f357
DN
12064 verilog-auto-lineup
12065 verilog-auto-newline
a03c2342
WS
12066 verilog-auto-output-ignore-regexp
12067 verilog-auto-read-includes
12068 verilog-auto-reset-widths
6341f357
DN
12069 verilog-auto-save-policy
12070 verilog-auto-sense-defines-constant
12071 verilog-auto-sense-include-inputs
a03c2342
WS
12072 verilog-auto-star-expand
12073 verilog-auto-star-save
12074 verilog-auto-unused-ignore-regexp
6341f357 12075 verilog-before-auto-hook
a03c2342
WS
12076 verilog-before-delete-auto-hook
12077 verilog-before-getopt-flags-hook
6341f357
DN
12078 verilog-case-indent
12079 verilog-cexp-indent
12080 verilog-compiler
12081 verilog-coverage
a03c2342
WS
12082 verilog-delete-auto-hook
12083 verilog-getopt-flags-hook
12084 verilog-highlight-grouping-keywords
12085 verilog-highlight-p1800-keywords
6341f357
DN
12086 verilog-highlight-translate-off
12087 verilog-indent-begin-after-if
12088 verilog-indent-declaration-macros
12089 verilog-indent-level
12090 verilog-indent-level-behavioral
12091 verilog-indent-level-declaration
12092 verilog-indent-level-directive
12093 verilog-indent-level-module
12094 verilog-indent-lists
6341f357
DN
12095 verilog-library-directories
12096 verilog-library-extensions
12097 verilog-library-files
a03c2342 12098 verilog-library-flags
6341f357
DN
12099 verilog-linter
12100 verilog-minimum-comment-distance
12101 verilog-mode-hook
a03c2342 12102 verilog-preprocessor
6341f357
DN
12103 verilog-simulator
12104 verilog-tab-always-indent
12105 verilog-tab-to-comment
a03c2342 12106 verilog-typedef-regexp
6341f357
DN
12107 )
12108 nil nil
12109 (concat "Hi Mac,
12110
86a4c7ac 12111I want to report a bug.
6341f357
DN
12112
12113Before I go further, I want to say that Verilog mode has changed my life.
12114I save so much time, my files are colored nicely, my co workers respect
12115my coding ability... until now. I'd really appreciate anything you
12116could do to help me out with this minor deficiency in the product.
12117
86a4c7ac 12118I've taken a look at the Verilog-Mode FAQ at
7cb1c4d7 12119http://www.veripool.org/verilog-mode-faq.html.
6341f357 12120
86a4c7ac
DN
12121And, I've considered filing the bug on the issue tracker at
12122http://www.veripool.org/verilog-mode-bugs
12123since I realize that public bugs are easier for you to track,
12124and for others to search, but would prefer to email.
12125
12126So, to reproduce the bug, start a fresh Emacs via " invocation-name "
37ea4b9b 12127-no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
6341f357
DN
12128the code included below.
12129
12130Given those lines, I expected [[Fill in here]] to happen;
12131but instead, [[Fill in here]] happens!.
12132
12133== The code: =="))))
12134
6edb5716
DN
12135(provide 'verilog-mode)
12136
6341f357
DN
12137;; Local Variables:
12138;; checkdoc-permit-comma-termination-flag:t
12139;; checkdoc-force-docstrings-flag:nil
12140;; End:
12141
819ee2f4 12142;; arch-tag: 87923725-57b3-41b5-9494-be21118c6a6f
6341f357 12143;;; verilog-mode.el ends here