(jdb): Add gud-pstar to dump object information.
[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,
ae940284 4;; 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
6341f357
DN
5
6;; Author: Michael McNamara (mac@verilog.com)
7;; http://www.verilog.com
8;;
9;; AUTO features, signal, modsig; by: Wilson Snyder
10;; (wsnyder@wsnyder.org)
7cb1c4d7 11;; http://www.veripool.org
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 )
7cb1c4d7 82; (add-to-list 'auto-mode-alist '("\\.[ds]?v\\'" . verilog-mode))
6341f357
DN
83
84;; If you want to customize Verilog mode to fit your needs better,
85;; you may add these lines (the values of the variables presented
60618039 86;; here are the defaults). Note also that if you use an Emacs that
6341f357
DN
87;; supports custom, it's probably better to use the custom menu to
88;; edit these.
89;;
90;; Be sure to examine at the help for verilog-auto, and the other
91;; verilog-auto-* functions for some major coding time savers.
92;;
93; ;; User customization for Verilog mode
94; (setq verilog-indent-level 3
95; verilog-indent-level-module 3
96; verilog-indent-level-declaration 3
97; verilog-indent-level-behavioral 3
98; verilog-indent-level-directive 1
99; verilog-case-indent 2
100; verilog-auto-newline t
101; verilog-auto-indent-on-newline t
102; verilog-tab-always-indent t
103; verilog-auto-endcomments t
104; verilog-minimum-comment-distance 40
105; verilog-indent-begin-after-if t
a3a8b002 106; verilog-auto-lineup 'declarations
6341f357
DN
107; verilog-highlight-p1800-keywords nil
108; verilog-linter "my_lint_shell_command"
109; )
110
111;; \f
112
113;;; History:
37ea4b9b 114;;
7cb1c4d7 115;; See commit history at http://www.veripool.org/verilog-mode.html
60618039
DN
116;; (This section is required to appease checkdoc.)
117
6341f357
DN
118;;; Code:
119
6341f357 120;; This variable will always hold the version number of the mode
d88782c3 121(defconst verilog-mode-version "525"
1418c701 122 "Version of this Verilog mode.")
d88782c3 123(defconst verilog-mode-release-date "2009-07-02-GNU"
1418c701 124 "Release date of this Verilog mode.")
60618039 125(defconst verilog-mode-release-emacs t
1418c701 126 "If non-nil, this version of Verilog mode was released with Emacs itself.")
6341f357
DN
127
128(defun verilog-version ()
129 "Inform caller of the version of this file."
130 (interactive)
7ea26faf 131 (message "Using verilog-mode version %s" verilog-mode-version))
6341f357
DN
132
133;; Insure we have certain packages, and deal with it if we don't
60618039 134;; Be sure to note which Emacs flavor and version added each feature.
6edb5716 135(eval-when-compile
7cb1c4d7 136 ;; Provide stuff if we are XEmacs
7ea26faf
DN
137 (when (featurep 'xemacs)
138 (condition-case nil
139 (require 'easymenu)
140 (error nil))
141 (condition-case nil
142 (require 'regexp-opt)
143 (error nil))
144 ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
145 (condition-case nil
146 (load "skeleton")
147 (error nil))
148 (condition-case nil
149 (if (fboundp 'when)
150 nil ;; fab
151 (defmacro when (cond &rest body)
152 (list 'if cond (cons 'progn body))))
153 (error nil))
154 (condition-case nil
155 (if (fboundp 'unless)
156 nil ;; fab
157 (defmacro unless (cond &rest body)
158 (cons 'if (cons cond (cons nil body)))))
159 (error nil))
160 (condition-case nil
161 (if (fboundp 'store-match-data)
162 nil ;; fab
163 (defmacro store-match-data (&rest args) nil))
164 (error nil))
7ea26faf
DN
165 (condition-case nil
166 (if (fboundp 'char-before)
167 nil ;; great
168 (defmacro char-before (&rest body)
169 (char-after (1- (point)))))
170 (error nil))
171 (condition-case nil
172 (require 'custom)
173 (error nil))
174 (condition-case nil
175 (if (fboundp 'match-string-no-properties)
176 nil ;; great
177 (defsubst match-string-no-properties (num &optional string)
178 "Return string of text matched by last search, without text properties.
6341f357
DN
179NUM specifies which parenthesized expression in the last regexp.
180 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
181Zero means the entire text matched by the whole regexp or whole string.
182STRING should be given if the last search was by `string-match' on STRING."
7ea26faf
DN
183 (if (match-beginning num)
184 (if string
185 (let ((result
186 (substring string
187 (match-beginning num) (match-end num))))
188 (set-text-properties 0 (length result) nil result)
189 result)
190 (buffer-substring-no-properties (match-beginning num)
191 (match-end num)
60618039
DN
192 (current-buffer)))))
193 )
7ea26faf
DN
194 (error nil))
195 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
196 nil ;; We've got what we needed
197 ;; We have the old custom-library, hack around it!
198 (defmacro defgroup (&rest args) nil)
199 (defmacro customize (&rest args)
200 (message
37ea4b9b 201 "Sorry, Customize is not available with this version of Emacs"))
7ea26faf
DN
202 (defmacro defcustom (var value doc &rest args)
203 `(defvar ,var ,value ,doc))
204 )
205 (if (fboundp 'defface)
206 nil ; great!
207 (defmacro defface (var values doc &rest args)
208 `(make-face ,var))
209 )
6341f357 210
7ea26faf
DN
211 (if (and (featurep 'custom) (fboundp 'customize-group))
212 nil ;; We've got what we needed
213 ;; We have an intermediate custom-library, hack around it!
214 (defmacro customize-group (var &rest args)
215 `(customize ,var))
7cb1c4d7
DN
216 ))
217 ;; OK, do this stuff if we are NOT XEmacs:
218 (unless (featurep 'xemacs)
219 (unless (fboundp 'region-active-p)
220 (defmacro region-active-p ()
221 `(and transient-mark-mode mark-active))))
222 )
6341f357 223
6341f357
DN
224;; Provide a regular expression optimization routine, using regexp-opt
225;; if provided by the user's elisp libraries
226(eval-and-compile
60618039
DN
227 ;; The below were disabled when GNU Emacs 22 was released;
228 ;; perhaps some still need to be there to support Emacs 21.
7ea26faf
DN
229 (if (featurep 'xemacs)
230 (if (fboundp 'regexp-opt)
231 ;; regexp-opt is defined, does it take 3 or 2 arguments?
232 (if (fboundp 'function-max-args)
233 (let ((args (function-max-args `regexp-opt)))
234 (cond
235 ((eq args 3) ;; It takes 3
236 (condition-case nil ; Hide this defun from emacses
6341f357 237 ;with just a two input regexp
7ea26faf
DN
238 (defun verilog-regexp-opt (a b)
239 "Deal with differing number of required arguments for `regexp-opt'.
6341f357 240 Call 'regexp-opt' on A and B."
60618039 241 (regexp-opt a b 't))
7ea26faf
DN
242 (error nil))
243 )
244 ((eq args 2) ;; It takes 2
245 (defun verilog-regexp-opt (a b)
246 "Call 'regexp-opt' on A and B."
247 (regexp-opt a b))
248 )
249 (t nil)))
250 ;; We can't tell; assume it takes 2
251 (defun verilog-regexp-opt (a b)
252 "Call 'regexp-opt' on A and B."
253 (regexp-opt a b))
254 )
255 ;; There is no regexp-opt, provide our own
256 (defun verilog-regexp-opt (strings &optional paren shy)
257 (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
258 (concat open (mapconcat 'regexp-quote strings "\\|") close)))
259 )
260 ;; Emacs.
261 (defalias 'verilog-regexp-opt 'regexp-opt)))
6341f357 262
38f584e9
DN
263(eval-when-compile
264 (defun verilog-regexp-words (a)
265 "Call 'regexp-opt' with word delimiters for the words A."
266 (concat "\\<" (verilog-regexp-opt a t) "\\>")))
6341f357 267
495ab0d5 268(defun verilog-easy-menu-filter (menu)
a3a8b002 269 "Filter `easy-menu-define' MENU to support new features."
495ab0d5
DN
270 (cond ((not (featurep 'xemacs))
271 menu) ;; GNU Emacs - passthru
272 ;; Xemacs doesn't support :help. Strip it.
273 ;; Recursively filter the a submenu
274 ((listp menu)
275 (mapcar 'verilog-easy-menu-filter menu))
276 ;; Look for [:help "blah"] and remove
277 ((vectorp menu)
278 (let ((i 0) (out []))
279 (while (< i (length menu))
280 (if (equal `:help (aref menu i))
281 (setq i (+ 2 i))
282 (setq out (vconcat out (vector (aref menu i)))
283 i (1+ i))))
284 out))
285 (t menu))) ;; Default - ok
286;;(verilog-easy-menu-filter
287;; `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
288;; "----" ["MB" nil :help "Help MB"]))
289
6341f357 290(defun verilog-customize ()
495ab0d5 291 "Customize variables and other settings used by Verilog-Mode."
6341f357
DN
292 (interactive)
293 (customize-group 'verilog-mode))
294
295(defun verilog-font-customize ()
495ab0d5 296 "Customize fonts used by Verilog-Mode."
6341f357 297 (interactive)
7ea26faf
DN
298 (if (fboundp 'customize-apropos)
299 (customize-apropos "font-lock-*" 'faces)))
6341f357 300
eaf7efe9
DN
301(defun verilog-booleanp (value)
302 "Return t if VALUE is boolean.
a3a8b002
DN
303This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
304This function may be removed when Emacs 21 is no longer supported."
eaf7efe9
DN
305 (or (equal value t) (equal value nil)))
306
a3a8b002
DN
307(defun verilog-insert-last-command-event ()
308 "Insert the `last-command-event'."
309 (insert (if (featurep 'xemacs)
310 ;; XEmacs 21.5 doesn't like last-command-event
311 last-command-char
312 ;; And GNU Emacs 22 has obsoleted last-command-char
313 last-command-event)))
314
d63b01e1
SM
315(defalias 'verilog-syntax-ppss
316 (if (fboundp 'syntax-ppss) 'syntax-ppss
317 (lambda (&optional pos) (parse-partial-sexp (point-min) (or pos (point))))))
318
6341f357 319(defgroup verilog-mode nil
37ea4b9b 320 "Facilitates easy editing of Verilog source text."
8e788369 321 :version "22.2"
6341f357
DN
322 :group 'languages)
323
324; (defgroup verilog-mode-fonts nil
325; "Facilitates easy customization fonts used in Verilog source text"
326; :link '(customize-apropos "font-lock-*" 'faces)
327; :group 'verilog-mode)
328
329(defgroup verilog-mode-indent nil
37ea4b9b 330 "Customize indentation and highlighting of Verilog source text."
6341f357
DN
331 :group 'verilog-mode)
332
333(defgroup verilog-mode-actions nil
37ea4b9b 334 "Customize actions on Verilog source text."
6341f357
DN
335 :group 'verilog-mode)
336
337(defgroup verilog-mode-auto nil
37ea4b9b 338 "Customize AUTO actions when expanding Verilog source text."
6341f357
DN
339 :group 'verilog-mode)
340
341(defcustom verilog-linter
342 "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
37ea4b9b 343 "*Unix program and arguments to call to run a lint checker on Verilog source.
6341f357
DN
344Depending on the `verilog-set-compile-command', this may be invoked when
345you type \\[compile]. When the compile completes, \\[next-error] will take
346you to the next lint error."
347 :type 'string
348 :group 'verilog-mode-actions)
60618039 349;; We don't mark it safe, as it's used as a shell command
6341f357
DN
350
351(defcustom verilog-coverage
352 "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
37ea4b9b 353 "*Program and arguments to use to annotate for coverage Verilog source.
6341f357
DN
354Depending on the `verilog-set-compile-command', this may be invoked when
355you type \\[compile]. When the compile completes, \\[next-error] will take
356you to the next lint error."
357 :type 'string
358 :group 'verilog-mode-actions)
60618039 359;; We don't mark it safe, as it's used as a shell command
6341f357
DN
360
361(defcustom verilog-simulator
362 "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
37ea4b9b 363 "*Program and arguments to use to interpret Verilog source.
6341f357
DN
364Depending on the `verilog-set-compile-command', this may be invoked when
365you type \\[compile]. When the compile completes, \\[next-error] will take
366you to the next lint error."
367 :type 'string
368 :group 'verilog-mode-actions)
60618039 369;; We don't mark it safe, as it's used as a shell command
6341f357
DN
370
371(defcustom verilog-compiler
372 "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
37ea4b9b 373 "*Program and arguments to use to compile Verilog source.
6341f357
DN
374Depending on the `verilog-set-compile-command', this may be invoked when
375you type \\[compile]. When the compile completes, \\[next-error] will take
376you to the next lint error."
377 :type 'string
378 :group 'verilog-mode-actions)
60618039 379;; We don't mark it safe, as it's used as a shell command
6341f357
DN
380
381(defvar verilog-tool 'verilog-linter
382 "Which tool to use for building compiler-command.
383Either nil, `verilog-linter, `verilog-coverage, `verilog-simulator, or
384`verilog-compiler. Alternatively use the \"Choose Compilation Action\"
385menu. See `verilog-set-compile-command' for more information.")
386
387(defcustom verilog-highlight-translate-off nil
388 "*Non-nil means background-highlight code excluded from translation.
389That is, all code between \"// synopsys translate_off\" and
390\"// synopsys translate_on\" is highlighted using a different background color
391\(face `verilog-font-lock-translate-off-face').
392
393Note: This will slow down on-the-fly fontification (and thus editing).
394
395Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
396entry \"Fontify Buffer\"). XEmacs: turn off and on font locking."
397 :type 'boolean
398 :group 'verilog-mode-indent)
60618039 399;; Note we don't use :safe, as that would break on Emacsen before 22.0.
eaf7efe9 400(put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
6341f357 401
a3a8b002
DN
402(defcustom verilog-auto-lineup 'declarations
403 "*Type of statements to lineup across multiple lines.
404If 'all' is selected, then all line ups described below are done.
405
406If 'declaration', then just declarations are lined up with any
407preceding declarations, taking into account widths and the like,
408so or example the code:
409 reg [31:0] a;
410 reg b;
411would become
412 reg [31:0] a;
413 reg b;
414
415If 'assignment', then assignments are lined up with any preceding
416assignments, so for example the code
417 a_long_variable <= b + c;
418 d = e + f;
419would become
420 a_long_variable <= b + c;
421 d = e + f;
422
423In order to speed up editing, large blocks of statements are lined up
424only when a \\[verilog-pretty-expr] is typed; and large blocks of declarations
425are lineup only when \\[verilog-pretty-declarations] is typed."
426
427 :type '(radio (const :tag "Line up Assignments and Declarations" all)
428 (const :tag "Line up Assignment statements" assignments )
429 (const :tag "Line up Declarartions" declarations)
430 (function :tag "Other"))
431 :group 'verilog-mode-indent )
432
6341f357
DN
433(defcustom verilog-indent-level 3
434 "*Indentation of Verilog statements with respect to containing block."
435 :group 'verilog-mode-indent
436 :type 'integer)
60618039 437(put 'verilog-indent-level 'safe-local-variable 'integerp)
6341f357
DN
438
439(defcustom verilog-indent-level-module 3
37ea4b9b 440 "*Indentation of Module level Verilog statements (eg always, initial).
6341f357
DN
441Set to 0 to get initial and always statements lined up on the left side of
442your screen."
443 :group 'verilog-mode-indent
444 :type 'integer)
60618039 445(put 'verilog-indent-level-module 'safe-local-variable 'integerp)
6341f357
DN
446
447(defcustom verilog-indent-level-declaration 3
448 "*Indentation of declarations with respect to containing block.
449Set to 0 to get them list right under containing block."
450 :group 'verilog-mode-indent
451 :type 'integer)
60618039 452(put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
6341f357
DN
453
454(defcustom verilog-indent-declaration-macros nil
455 "*How to treat macro expansions in a declaration.
456If nil, indent as:
457 input [31:0] a;
458 input `CP;
459 output c;
460If non nil, treat as:
461 input [31:0] a;
462 input `CP ;
463 output c;"
464 :group 'verilog-mode-indent
465 :type 'boolean)
eaf7efe9 466(put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
6341f357
DN
467
468(defcustom verilog-indent-lists t
469 "*How to treat indenting items in a list.
470If t (the default), indent as:
471 always @( posedge a or
472 reset ) begin
473
474If nil, treat as:
475 always @( posedge a or
476 reset ) begin"
477 :group 'verilog-mode-indent
478 :type 'boolean)
eaf7efe9 479(put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
6341f357
DN
480
481(defcustom verilog-indent-level-behavioral 3
482 "*Absolute indentation of first begin in a task or function block.
483Set to 0 to get such code to start at the left side of the screen."
484 :group 'verilog-mode-indent
485 :type 'integer)
60618039 486(put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
6341f357
DN
487
488(defcustom verilog-indent-level-directive 1
489 "*Indentation to add to each level of `ifdef declarations.
490Set to 0 to have all directives start at the left side of the screen."
491 :group 'verilog-mode-indent
492 :type 'integer)
60618039 493(put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
6341f357
DN
494
495(defcustom verilog-cexp-indent 2
496 "*Indentation of Verilog statements split across lines."
497 :group 'verilog-mode-indent
498 :type 'integer)
60618039 499(put 'verilog-cexp-indent 'safe-local-variable 'integerp)
6341f357
DN
500
501(defcustom verilog-case-indent 2
502 "*Indentation for case statements."
503 :group 'verilog-mode-indent
504 :type 'integer)
60618039 505(put 'verilog-case-indent 'safe-local-variable 'integerp)
6341f357
DN
506
507(defcustom verilog-auto-newline t
508 "*True means automatically newline after semicolons."
509 :group 'verilog-mode-indent
510 :type 'boolean)
eaf7efe9 511(put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
6341f357
DN
512
513(defcustom verilog-auto-indent-on-newline t
514 "*True means automatically indent line after newline."
515 :group 'verilog-mode-indent
516 :type 'boolean)
eaf7efe9 517(put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
6341f357
DN
518
519(defcustom verilog-tab-always-indent t
520 "*True means TAB should always re-indent the current line.
37ea4b9b 521A nil value means TAB will only reindent when at the beginning of the line."
6341f357
DN
522 :group 'verilog-mode-indent
523 :type 'boolean)
eaf7efe9 524(put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
6341f357
DN
525
526(defcustom verilog-tab-to-comment nil
527 "*True means TAB moves to the right hand column in preparation for a comment."
528 :group 'verilog-mode-actions
529 :type 'boolean)
eaf7efe9 530(put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
6341f357
DN
531
532(defcustom verilog-indent-begin-after-if t
533 "*If true, indent begin statements following if, else, while, for and repeat.
534Otherwise, line them up."
535 :group 'verilog-mode-indent
60618039 536 :type 'boolean)
eaf7efe9 537(put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
6341f357
DN
538
539
540(defcustom verilog-align-ifelse nil
541 "*If true, align `else' under matching `if'.
542Otherwise else is lined up with first character on line holding matching if."
543 :group 'verilog-mode-indent
60618039 544 :type 'boolean)
eaf7efe9 545(put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
6341f357
DN
546
547(defcustom verilog-minimum-comment-distance 10
548 "*Minimum distance (in lines) between begin and end required before a comment.
549Setting this variable to zero results in every end acquiring a comment; the
37ea4b9b 550default avoids too many redundant comments in tight quarters."
6341f357
DN
551 :group 'verilog-mode-indent
552 :type 'integer)
60618039 553(put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
6341f357 554
6341f357 555(defcustom verilog-highlight-p1800-keywords nil
60618039
DN
556 "*True means highlight words newly reserved by IEEE-1800.
557These will appear in `verilog-font-lock-p1800-face' in order to gently
558suggest changing where these words are used as variables to something else.
37ea4b9b 559A nil value means highlight these words as appropriate for the SystemVerilog
60618039 560IEEE-1800 standard. Note that changing this will require restarting Emacs
37ea4b9b 561to see the effect as font color choices are cached by Emacs."
6341f357
DN
562 :group 'verilog-mode-indent
563 :type 'boolean)
eaf7efe9 564(put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
6341f357 565
a1ebd734
DN
566(defcustom verilog-highlight-grouping-keywords nil
567 "*True means highlight grouping keywords 'begin' and 'end' more dramatically.
a3a8b002
DN
568If false, these words are in the `font-lock-type-face'; if True then they are in
569`verilog-font-lock-ams-face'. Some find that special highlighting on these
a1ebd734
DN
570grouping constructs allow the structure of the code to be understood at a glance."
571 :group 'verilog-mode-indent
572 :type 'boolean)
b1d0fc86 573(put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
a1ebd734 574
6341f357
DN
575(defcustom verilog-auto-endcomments t
576 "*True means insert a comment /* ... */ after 'end's.
577The name of the function or case will be set between the braces."
578 :group 'verilog-mode-actions
60618039 579 :type 'boolean)
eaf7efe9 580(put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
6341f357
DN
581
582(defcustom verilog-auto-read-includes nil
583 "*True means to automatically read includes before AUTOs.
584This will do a `verilog-read-defines' and `verilog-read-includes' before
585each AUTO expansion. This makes it easier to embed defines and includes,
586but can result in very slow reading times if there are many or large
587include files."
588 :group 'verilog-mode-actions
60618039 589 :type 'boolean)
eaf7efe9 590(put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
6341f357
DN
591
592(defcustom verilog-auto-save-policy nil
593 "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
594A value of `force' will always do a \\[verilog-auto] automatically if
595needed on every save. A value of `detect' will do \\[verilog-auto]
596automatically when it thinks necessary. A value of `ask' will query the
597user when it thinks updating is needed.
598
599You should not rely on the 'ask or 'detect policies, they are safeguards
600only. They do not detect when AUTOINSTs need to be updated because a
601sub-module's port list has changed."
602 :group 'verilog-mode-actions
603 :type '(choice (const nil) (const ask) (const detect) (const force)))
604
605(defcustom verilog-auto-star-expand t
606 "*Non-nil indicates to expand a SystemVerilog .* instance ports.
607They will be expanded in the same way as if there was a AUTOINST in the
608instantiation. See also `verilog-auto-star' and `verilog-auto-star-save'."
609 :group 'verilog-mode-actions
610 :type 'boolean)
eaf7efe9 611(put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
6341f357
DN
612
613(defcustom verilog-auto-star-save nil
614 "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
37ea4b9b
JB
615A nil value indicates direct connections will be removed before saving.
616Only meaningful to those created due to `verilog-auto-star-expand' being set.
6341f357
DN
617
618Instead of setting this, you may want to use /*AUTOINST*/, which will
619always be saved."
620 :group 'verilog-mode-actions
621 :type 'boolean)
eaf7efe9 622(put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
6341f357
DN
623
624(defvar verilog-auto-update-tick nil
625 "Modification tick at which autos were last performed.")
626
627(defvar verilog-auto-last-file-locals nil
628 "Text from file-local-variables during last evaluation.")
629
a3a8b002
DN
630;;; Compile support
631(require 'compile)
d88782c3 632(defvar verilog-error-regexp-added nil)
a3a8b002
DN
633; List of regexps for Verilog compilers, like verilint. See compilation-error-regexp-alist
634; for the formatting.
d88782c3
DN
635; Here is the version for Emacs 22:
636(defvar verilog-error-regexp-emacs-alist
637 '(
638 (verilog-xl-1
639 "\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
640 (verilog-xl-2
641 "([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 3)
642 (verilog-IES
643 ".*\\*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)" 1 2)
644 (verilog-surefire-1
645 "[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
646 (verilog-surefire-2
647 "\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\),\\s-+\\(line \\)?\\([0-9]+\\):" 2 4 )
648 (verilog-verbose
649 "\
650\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
651:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
652 (verilog-xsim
653 "\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
654 (verilog-vcs-1
655 "\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
656 (verilog-vcs-2
657 "Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
658 (verilog-vcs-3
659 "\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
660 (verilog-vcs-4
661 "syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
662 (verilog-verilator
663 "%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
664 (verilog-leda
665 "In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):
666.*
667.*
668.*
669\\(Warning\\|Error\\|Failure\\)" 1 2)
670 ))
671;; And the version for XEmacs:
672(defvar verilog-error-regexp-xemacs-alist
673 '(verilog
674 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
675 ("\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\),\\s-+\\(line \\)?\\([0-9]+\\):" 2 4 )
676 ("\
6341f357
DN
677\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
678:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
a3a8b002
DN
679; xsim
680; Error! in file /homes/mac/Axis/Xsim/test.v at line 13 [OBJ_NOT_DECLARED]
d88782c3 681 ("\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
a3a8b002 682; vcs
d88782c3
DN
683 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
684 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
685 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
686 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
a3a8b002 687; Verilator
d88782c3 688 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
a3a8b002 689; verilog-xl
d88782c3
DN
690 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
691 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 2) ; vxl
692 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 2)
a3a8b002 693; nc-verilog
d88782c3 694 (".*\\*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 2)
a3a8b002 695; Leda
d88782c3
DN
696 ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 2)
697 )
698 )
6341f357
DN
699
700(defvar verilog-error-font-lock-keywords
701 '(
702 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
703 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
d88782c3 704
6341f357
DN
705 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
706 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
707
708 ("\
709\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
710:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
711 ("\
712\\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
713:\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
714
715 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
716 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
717
718 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
719 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
720
721 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
722 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
723
724 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
725 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
726
727 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
728 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
729 ; vxl
730 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
731 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
732
733 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 bold t)
734 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 2 bold t)
735
736 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 bold t)
737 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 2 bold t)
738 ; nc-verilog
739 (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 bold t)
740 (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
741 ; Leda
742 ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 bold t)
743 ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 2 bold t)
744 )
60618039 745 "*Keywords to also highlight in Verilog *compilation* buffers.")
6341f357
DN
746
747(defcustom verilog-library-flags '("")
748 "*List of standard Verilog arguments to use for /*AUTOINST*/.
749These arguments are used to find files for `verilog-auto', and match
750the flags accepted by a standard Verilog-XL simulator.
751
752 -f filename Reads more `verilog-library-flags' from the filename.
753 +incdir+dir Adds the directory to `verilog-library-directories'.
754 -Idir Adds the directory to `verilog-library-directories'.
755 -y dir Adds the directory to `verilog-library-directories'.
756 +libext+.v Adds the extensions to `verilog-library-extensions'.
757 -v filename Adds the filename to `verilog-library-files'.
758
759 filename Adds the filename to `verilog-library-files'.
760 This is not recommended, -v is a better choice.
761
762You might want these defined in each file; put at the *END* of your file
763something like:
764
765 // Local Variables:
766 // verilog-library-flags:(\"-y dir -y otherdir\")
767 // End:
768
769Verilog-mode attempts to detect changes to this local variable, but they
37ea4b9b 770are only insured to be correct when the file is first visited. Thus if you
6341f357
DN
771have problems, use \\[find-alternate-file] RET to have these take effect.
772
773See also the variables mentioned above."
774 :group 'verilog-mode-auto
775 :type '(repeat string))
60618039 776(put 'verilog-library-flags 'safe-local-variable 'listp)
6341f357
DN
777
778(defcustom verilog-library-directories '(".")
779 "*List of directories when looking for files for /*AUTOINST*/.
780The directory may be relative to the current file, or absolute.
781Environment variables are also expanded in the directory names.
782Having at least the current directory is a good idea.
783
784You might want these defined in each file; put at the *END* of your file
785something like:
786
787 // Local Variables:
788 // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
789 // End:
790
791Verilog-mode attempts to detect changes to this local variable, but they
37ea4b9b 792are only insured to be correct when the file is first visited. Thus if you
6341f357
DN
793have problems, use \\[find-alternate-file] RET to have these take effect.
794
795See also `verilog-library-flags', `verilog-library-files'
796and `verilog-library-extensions'."
797 :group 'verilog-mode-auto
798 :type '(repeat file))
60618039 799(put 'verilog-library-directories 'safe-local-variable 'listp)
6341f357
DN
800
801(defcustom verilog-library-files '()
60618039
DN
802 "*List of files to search for modules.
803AUTOINST will use this when it needs to resolve a module name.
6341f357
DN
804This is a complete path, usually to a technology file with many standard
805cells defined in it.
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-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
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 `verilog-library-flags', `verilog-library-directories'."
819 :group 'verilog-mode-auto
820 :type '(repeat directory))
60618039 821(put 'verilog-library-files 'safe-local-variable 'listp)
6341f357 822
7cb1c4d7 823(defcustom verilog-library-extensions '(".v" ".sv")
6341f357
DN
824 "*List of extensions to use when looking for files for /*AUTOINST*/.
825See also `verilog-library-flags', `verilog-library-directories'."
826 :type '(repeat string)
827 :group 'verilog-mode-auto)
60618039 828(put 'verilog-library-extensions 'safe-local-variable 'listp)
6341f357
DN
829
830(defcustom verilog-active-low-regexp nil
831 "*If set, treat signals matching this regexp as active low.
832This is used for AUTORESET and AUTOTIEOFF. For proper behavior,
833you will probably also need `verilog-auto-reset-widths' set."
834 :group 'verilog-mode-auto
835 :type 'string)
60618039 836(put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
6341f357
DN
837
838(defcustom verilog-auto-sense-include-inputs nil
839 "*If true, AUTOSENSE should include all inputs.
840If nil, only inputs that are NOT output signals in the same block are
841included."
60618039
DN
842 :group 'verilog-mode-auto
843 :type 'boolean)
eaf7efe9 844(put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
6341f357
DN
845
846(defcustom verilog-auto-sense-defines-constant nil
847 "*If true, AUTOSENSE should assume all defines represent constants.
848When true, the defines will not be included in sensitivity lists. To
849maintain compatibility with other sites, this should be set at the bottom
37ea4b9b 850of each Verilog file that requires it, rather than being set globally."
60618039
DN
851 :group 'verilog-mode-auto
852 :type 'boolean)
eaf7efe9 853(put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
6341f357
DN
854
855(defcustom verilog-auto-reset-widths t
856 "*If true, AUTORESET should determine the width of signals.
857This is then used to set the width of the zero (32'h0 for example). This
858is required by some lint tools that aren't smart enough to ignore widths of
859the constant zero. This may result in ugly code when parameters determine
37ea4b9b 860the MSB or LSB of a signal inside an AUTORESET."
6341f357
DN
861 :type 'boolean
862 :group 'verilog-mode-auto)
eaf7efe9 863(put 'verilog-auto-reset-widths 'safe-local-variable 'verilog-booleanp)
6341f357
DN
864
865(defcustom verilog-assignment-delay ""
866 "*Text used for delays in delayed assignments. Add a trailing space if set."
60618039
DN
867 :group 'verilog-mode-auto
868 :type 'string)
869(put 'verilog-assignment-delay 'safe-local-variable 'stringp)
6341f357 870
a3a8b002
DN
871(defcustom verilog-auto-arg-sort nil
872 "*If set, AUTOARG will sort signal names, rather than leave them in
873declaration order. Declaration order is advantageous with order based
874instantiations and is the default for backward compatibility. Sorted order
875reduces changes when declarations are moved around in a file, and it's bad
876practice to rely on order based instantiations anyhow."
877 :group 'verilog-mode-auto
878 :type 'boolean)
879(put 'verilog-auto-arg-sort 'safe-local-variable 'verilog-booleanp)
880
4c5e69c6
DN
881(defcustom verilog-auto-inst-param-value nil
882 "*If set, AUTOINST will replace parameters with the parameter value.
883If nil, leave parameters as symbolic names.
884
885Parameters must be in Verilog 2001 format #(...), and if a parameter is not
886listed as such there (as when the default value is acceptable), it will not
887be replaced, and will remain symbolic.
888
889For example, imagine a submodule uses parameters to declare the size of its
890inputs. This is then used by a upper module:
891
892 module InstModule (o,i)
893 parameter WIDTH;
894 input [WIDTH-1:0] i;
895 endmodule
896
897 module ExampInst;
898 InstModule
899 #(PARAM(10))
900 instName
901 (/*AUTOINST*/
902 .i (i[PARAM-1:0]));
903
904Note even though PARAM=10, the AUTOINST has left the parameter as a
905symbolic name. If `verilog-auto-inst-param-value' is set, this will
906instead expand to:
907
908 module ExampInst;
909 InstModule
910 #(PARAM(10))
911 instName
912 (/*AUTOINST*/
913 .i (i[9:0]));"
914 :group 'verilog-mode-auto
915 :type 'boolean)
7cb1c4d7 916(put 'verilog-auto-inst-param-value 'safe-local-variable 'verilog-booleanp)
4c5e69c6 917
6341f357
DN
918(defcustom verilog-auto-inst-vector t
919 "*If true, when creating default ports with AUTOINST, use bus subscripts.
920If nil, skip the subscript when it matches the entire bus as declared in
921the module (AUTOWIRE signals always are subscripted, you must manually
37ea4b9b
JB
922declare the wire to have the subscripts removed.) Setting this to nil may
923speed up some simulators, but is less general and harder to read, so avoid."
6341f357 924 :group 'verilog-mode-auto
60618039 925 :type 'boolean)
eaf7efe9 926(put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
6341f357
DN
927
928(defcustom verilog-auto-inst-template-numbers nil
929 "*If true, when creating templated ports with AUTOINST, add a comment.
930The comment will add the line number of the template that was used for that
931port declaration. Setting this aids in debugging, but nil is suggested for
932regular use to prevent large numbers of merge conflicts."
933 :group 'verilog-mode-auto
60618039 934 :type 'boolean)
eaf7efe9 935(put 'verilog-auto-inst-template-numbers 'safe-local-variable 'verilog-booleanp)
6341f357 936
4c5e69c6
DN
937(defcustom verilog-auto-inst-column 40
938 "*Indent-to column number for net name part of AUTOINST created pin."
939 :group 'verilog-mode-indent
940 :type 'integer)
941(put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
6341f357
DN
942
943(defcustom verilog-auto-input-ignore-regexp nil
944 "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
945See the \\[verilog-faq] for examples on using this."
946 :group 'verilog-mode-auto
60618039
DN
947 :type 'string)
948(put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
6341f357
DN
949
950(defcustom verilog-auto-inout-ignore-regexp nil
951 "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
952See the \\[verilog-faq] for examples on using this."
953 :group 'verilog-mode-auto
60618039
DN
954 :type 'string)
955(put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
6341f357
DN
956
957(defcustom verilog-auto-output-ignore-regexp nil
958 "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
959See the \\[verilog-faq] for examples on using this."
960 :group 'verilog-mode-auto
60618039
DN
961 :type 'string)
962(put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
6341f357
DN
963
964(defcustom verilog-auto-unused-ignore-regexp nil
965 "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
966See the \\[verilog-faq] for examples on using this."
967 :group 'verilog-mode-auto
60618039
DN
968 :type 'string)
969(put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
6341f357
DN
970
971(defcustom verilog-typedef-regexp nil
972 "*If non-nil, regular expression that matches Verilog-2001 typedef names.
973For example, \"_t$\" matches typedefs named with _t, as in the C language."
974 :group 'verilog-mode-auto
60618039
DN
975 :type 'string)
976(put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
6341f357
DN
977
978(defcustom verilog-mode-hook 'verilog-set-compile-command
37ea4b9b 979 "*Hook run after Verilog mode is loaded."
6341f357
DN
980 :type 'hook
981 :group 'verilog-mode)
982
983(defcustom verilog-auto-hook nil
984 "*Hook run after `verilog-mode' updates AUTOs."
60618039
DN
985 :group 'verilog-mode-auto
986 :type 'hook)
6341f357
DN
987
988(defcustom verilog-before-auto-hook nil
989 "*Hook run before `verilog-mode' updates AUTOs."
60618039
DN
990 :group 'verilog-mode-auto
991 :type 'hook)
6341f357
DN
992
993(defcustom verilog-delete-auto-hook nil
994 "*Hook run after `verilog-mode' deletes AUTOs."
60618039
DN
995 :group 'verilog-mode-auto
996 :type 'hook)
6341f357
DN
997
998(defcustom verilog-before-delete-auto-hook nil
999 "*Hook run before `verilog-mode' deletes AUTOs."
60618039
DN
1000 :group 'verilog-mode-auto
1001 :type 'hook)
6341f357
DN
1002
1003(defcustom verilog-getopt-flags-hook nil
1004 "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
60618039
DN
1005 :group 'verilog-mode-auto
1006 :type 'hook)
6341f357
DN
1007
1008(defcustom verilog-before-getopt-flags-hook nil
1009 "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
60618039
DN
1010 :group 'verilog-mode-auto
1011 :type 'hook)
6341f357
DN
1012
1013(defvar verilog-imenu-generic-expression
1014 '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
1015 ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
37ea4b9b 1016 "Imenu expression for Verilog mode. See `imenu-generic-expression'.")
6341f357
DN
1017
1018;;
1019;; provide a verilog-header function.
1020;; Customization variables:
1021;;
1022(defvar verilog-date-scientific-format nil
1023 "*If non-nil, dates are written in scientific format (e.g. 1997/09/17).
1024If nil, in European format (e.g. 17.09.1997). The brain-dead American
1025format (e.g. 09/17/1997) is not supported.")
1026
1027(defvar verilog-company nil
37ea4b9b 1028 "*Default name of Company for Verilog header.
6341f357 1029If set will become buffer local.")
7ea26faf
DN
1030(make-variable-buffer-local 'verilog-company)
1031
6341f357 1032(defvar verilog-project nil
37ea4b9b 1033 "*Default name of Project for Verilog header.
6341f357 1034If set will become buffer local.")
7ea26faf
DN
1035(make-variable-buffer-local 'verilog-project)
1036
7d49d8e1 1037(defvar verilog-mode-map
6edb5716
DN
1038 (let ((map (make-sparse-keymap)))
1039 (define-key map ";" 'electric-verilog-semi)
1040 (define-key map [(control 59)] 'electric-verilog-semi-with-comment)
1041 (define-key map ":" 'electric-verilog-colon)
1042 ;;(define-key map "=" 'electric-verilog-equal)
1043 (define-key map "\`" 'electric-verilog-tick)
1044 (define-key map "\t" 'electric-verilog-tab)
1045 (define-key map "\r" 'electric-verilog-terminate-line)
1046 ;; backspace/delete key bindings
1047 (define-key map [backspace] 'backward-delete-char-untabify)
1048 (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
1049 (define-key map [delete] 'delete-char)
1050 (define-key map [(meta delete)] 'kill-word))
1051 (define-key map "\M-\C-b" 'electric-verilog-backward-sexp)
1052 (define-key map "\M-\C-f" 'electric-verilog-forward-sexp)
1053 (define-key map "\M-\r" `electric-verilog-terminate-and-indent)
1054 (define-key map "\M-\t" 'verilog-complete-word)
1055 (define-key map "\M-?" 'verilog-show-completions)
6edb5716
DN
1056 (define-key map "\C-c\`" 'verilog-lint-off)
1057 (define-key map "\C-c\*" 'verilog-delete-auto-star-implicit)
1058 (define-key map "\C-c\C-r" 'verilog-label-be)
1059 (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
1060 (define-key map "\C-c=" 'verilog-pretty-expr)
1061 (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
1062 (define-key map "\M-*" 'verilog-star-comment)
1063 (define-key map "\C-c\C-c" 'verilog-comment-region)
1064 (define-key map "\C-c\C-u" 'verilog-uncomment-region)
e1776067
DN
1065 (when (featurep 'xemacs)
1066 (define-key map [(meta control h)] 'verilog-mark-defun)
1067 (define-key map "\M-\C-a" 'verilog-beg-of-defun)
1068 (define-key map "\M-\C-e" 'verilog-end-of-defun))
6edb5716
DN
1069 (define-key map "\C-c\C-d" 'verilog-goto-defun)
1070 (define-key map "\C-c\C-k" 'verilog-delete-auto)
1071 (define-key map "\C-c\C-a" 'verilog-auto)
1072 (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
1073 (define-key map "\C-c\C-z" 'verilog-inject-auto)
1074 (define-key map "\C-c\C-e" 'verilog-expand-vector)
30d48f20
DN
1075 (define-key map "\C-c\C-h" 'verilog-header)
1076 map)
6341f357 1077 "Keymap used in Verilog mode.")
6341f357
DN
1078
1079;; menus
7d55bf04
DN
1080(easy-menu-define
1081 verilog-menu verilog-mode-map "Menu for Verilog mode"
495ab0d5
DN
1082 (verilog-easy-menu-filter
1083 '("Verilog"
1084 ("Choose Compilation Action"
1085 ["None"
1086 (progn
1087 (setq verilog-tool nil)
1088 (verilog-set-compile-command))
1089 :style radio
1090 :selected (equal verilog-tool nil)
1091 :help "When invoking compilation, use compile-command"]
1092 ["Lint"
1093 (progn
1094 (setq verilog-tool 'verilog-linter)
1095 (verilog-set-compile-command))
1096 :style radio
1097 :selected (equal verilog-tool `verilog-linter)
1098 :help "When invoking compilation, use lint checker"]
1099 ["Coverage"
1100 (progn
1101 (setq verilog-tool 'verilog-coverage)
1102 (verilog-set-compile-command))
1103 :style radio
1104 :selected (equal verilog-tool `verilog-coverage)
1105 :help "When invoking compilation, annotate for coverage"]
1106 ["Simulator"
1107 (progn
1108 (setq verilog-tool 'verilog-simulator)
1109 (verilog-set-compile-command))
1110 :style radio
1111 :selected (equal verilog-tool `verilog-simulator)
1112 :help "When invoking compilation, interpret Verilog source"]
1113 ["Compiler"
1114 (progn
1115 (setq verilog-tool 'verilog-compiler)
1116 (verilog-set-compile-command))
1117 :style radio
1118 :selected (equal verilog-tool `verilog-compiler)
1119 :help "When invoking compilation, compile Verilog source"]
1120 )
1121 ("Move"
1122 ["Beginning of function" verilog-beg-of-defun
1123 :keys "C-M-a"
1124 :help "Move backward to the beginning of the current function or procedure"]
1125 ["End of function" verilog-end-of-defun
1126 :keys "C-M-e"
1127 :help "Move forward to the end of the current function or procedure"]
1128 ["Mark function" verilog-mark-defun
1129 :keys "C-M-h"
1130 :help "Mark the current Verilog function or procedure"]
1131 ["Goto function/module" verilog-goto-defun
1132 :help "Move to specified Verilog module/task/function"]
1133 ["Move to beginning of block" electric-verilog-backward-sexp
1134 :help "Move backward over one balanced expression"]
1135 ["Move to end of block" electric-verilog-forward-sexp
1136 :help "Move forward over one balanced expression"]
1137 )
1138 ("Comments"
1139 ["Comment Region" verilog-comment-region
1140 :help "Put marked area into a comment"]
1141 ["UnComment Region" verilog-uncomment-region
1142 :help "Uncomment an area commented with Comment Region"]
1143 ["Multi-line comment insert" verilog-star-comment
1144 :help "Insert Verilog /* */ comment at point"]
1145 ["Lint error to comment" verilog-lint-off
1146 :help "Convert a Verilog linter warning line into a disable statement"]
1147 )
1148 "----"
1149 ["Compile" compile
1150 :help "Perform compilation-action (above) on the current buffer"]
1151 ["AUTO, Save, Compile" verilog-auto-save-compile
1152 :help "Recompute AUTOs, save buffer, and compile"]
1153 ["Next Compile Error" next-error
1154 :help "Visit next compilation error message and corresponding source code"]
1155 ["Ignore Lint Warning at point" verilog-lint-off
1156 :help "Convert a Verilog linter warning line into a disable statement"]
1157 "----"
1158 ["Line up declarations around point" verilog-pretty-declarations
1159 :help "Line up declarations around point"]
1160 ["Line up equations around point" verilog-pretty-expr
1161 :help "Line up expressions around point"]
1162 ["Redo/insert comments on every end" verilog-label-be
1163 :help "Label matching begin ... end statements"]
1164 ["Expand [x:y] vector line" verilog-expand-vector
1165 :help "Take a signal vector on the current line and expand it to multiple lines"]
1166 ["Insert begin-end block" verilog-insert-block
1167 :help "Insert begin ... end"]
1168 ["Complete word" verilog-complete-word
1169 :help "Complete word at point"]
1170 "----"
1171 ["Recompute AUTOs" verilog-auto
1172 :help "Expand AUTO meta-comment statements"]
1173 ["Kill AUTOs" verilog-delete-auto
1174 :help "Remove AUTO expansions"]
1175 ["Inject AUTOs" verilog-inject-auto
1176 :help "Inject AUTOs into legacy non-AUTO buffer"]
1177 ("AUTO Help..."
1178 ["AUTO General" (describe-function 'verilog-auto)
1179 :help "Help introduction on AUTOs"]
1180 ["AUTO Library Flags" (describe-variable 'verilog-library-flags)
1181 :help "Help on verilog-library-flags"]
1182 ["AUTO Library Path" (describe-variable 'verilog-library-directories)
1183 :help "Help on verilog-library-directories"]
1184 ["AUTO Library Files" (describe-variable 'verilog-library-files)
1185 :help "Help on verilog-library-files"]
1186 ["AUTO Library Extensions" (describe-variable 'verilog-library-extensions)
1187 :help "Help on verilog-library-extensions"]
1188 ["AUTO `define Reading" (describe-function 'verilog-read-defines)
1189 :help "Help on reading `defines"]
1190 ["AUTO `include Reading" (describe-function 'verilog-read-includes)
1191 :help "Help on parsing `includes"]
1192 ["AUTOARG" (describe-function 'verilog-auto-arg)
1193 :help "Help on AUTOARG - declaring module port list"]
1194 ["AUTOASCIIENUM" (describe-function 'verilog-auto-ascii-enum)
1195 :help "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
7cb1c4d7
DN
1196 ["AUTOINOUTCOMP" (describe-function 'verilog-auto-inout-complement)
1197 :help "Help on AUTOINOUTCOMP - copying complemented i/o from another file"]
495ab0d5
DN
1198 ["AUTOINOUTMODULE" (describe-function 'verilog-auto-inout-module)
1199 :help "Help on AUTOINOUTMODULE - copying i/o from another file"]
a3a8b002
DN
1200 ["AUTOINSERTLISP" (describe-function 'verilog-auto-insert-lisp)
1201 :help "Help on AUTOINSERTLISP - insert text from a lisp function"]
495ab0d5
DN
1202 ["AUTOINOUT" (describe-function 'verilog-auto-inout)
1203 :help "Help on AUTOINOUT - adding inouts from cells"]
1204 ["AUTOINPUT" (describe-function 'verilog-auto-input)
1205 :help "Help on AUTOINPUT - adding inputs from cells"]
1206 ["AUTOINST" (describe-function 'verilog-auto-inst)
1207 :help "Help on AUTOINST - adding pins for cells"]
1208 ["AUTOINST (.*)" (describe-function 'verilog-auto-star)
1209 :help "Help on expanding Verilog-2001 .* pins"]
1210 ["AUTOINSTPARAM" (describe-function 'verilog-auto-inst-param)
1211 :help "Help on AUTOINSTPARAM - adding parameter pins to cells"]
1212 ["AUTOOUTPUT" (describe-function 'verilog-auto-output)
1213 :help "Help on AUTOOUTPUT - adding outputs from cells"]
1214 ["AUTOOUTPUTEVERY" (describe-function 'verilog-auto-output-every)
1215 :help "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
1216 ["AUTOREG" (describe-function 'verilog-auto-reg)
1217 :help "Help on AUTOREG - declaring registers for non-wires"]
1218 ["AUTOREGINPUT" (describe-function 'verilog-auto-reg-input)
1219 :help "Help on AUTOREGINPUT - declaring inputs for non-wires"]
1220 ["AUTORESET" (describe-function 'verilog-auto-reset)
1221 :help "Help on AUTORESET - resetting always blocks"]
1222 ["AUTOSENSE" (describe-function 'verilog-auto-sense)
1223 :help "Help on AUTOSENSE - sensitivity lists for always blocks"]
1224 ["AUTOTIEOFF" (describe-function 'verilog-auto-tieoff)
1225 :help "Help on AUTOTIEOFF - tieing off unused outputs"]
1226 ["AUTOUNUSED" (describe-function 'verilog-auto-unused)
1227 :help "Help on AUTOUNUSED - terminating unused inputs"]
1228 ["AUTOWIRE" (describe-function 'verilog-auto-wire)
1229 :help "Help on AUTOWIRE - declaring wires for cells"]
1230 )
1231 "----"
1232 ["Submit bug report" verilog-submit-bug-report
1233 :help "Submit via mail a bug report on verilog-mode.el"]
1234 ["Version and FAQ" verilog-faq
1235 :help "Show the current version, and where to get the FAQ etc"]
1236 ["Customize Verilog Mode..." verilog-customize
1237 :help "Customize variables and other settings used by Verilog-Mode"]
1238 ["Customize Verilog Fonts & Colors" verilog-font-customize
1239 :help "Customize fonts used by Verilog-Mode."])))
7d55bf04
DN
1240
1241(easy-menu-define
1242 verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
495ab0d5
DN
1243 (verilog-easy-menu-filter
1244 '("Statements"
1245 ["Header" verilog-sk-header
1246 :help "Insert a header block at the top of file"]
1247 ["Comment" verilog-sk-comment
1248 :help "Insert a comment block"]
1249 "----"
1250 ["Module" verilog-sk-module
1251 :help "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
1252 ["Primitive" verilog-sk-primitive
1253 :help "Insert a primitive .. (.. );.. endprimitive block"]
1254 "----"
1255 ["Input" verilog-sk-input
1256 :help "Insert an input declaration"]
1257 ["Output" verilog-sk-output
1258 :help "Insert an output declaration"]
1259 ["Inout" verilog-sk-inout
1260 :help "Insert an inout declaration"]
1261 ["Wire" verilog-sk-wire
1262 :help "Insert a wire declaration"]
1263 ["Reg" verilog-sk-reg
1264 :help "Insert a register declaration"]
1265 ["Define thing under point as a register" verilog-sk-define-signal
1266 :help "Define signal under point as a register at the top of the module"]
1267 "----"
1268 ["Initial" verilog-sk-initial
1269 :help "Insert an initial begin .. end block"]
1270 ["Always" verilog-sk-always
1271 :help "Insert an always @(AS) begin .. end block"]
1272 ["Function" verilog-sk-function
1273 :help "Insert a function .. begin .. end endfunction block"]
1274 ["Task" verilog-sk-task
1275 :help "Insert a task .. begin .. end endtask block"]
1276 ["Specify" verilog-sk-specify
1277 :help "Insert a specify .. endspecify block"]
1278 ["Generate" verilog-sk-generate
1279 :help "Insert a generate .. endgenerate block"]
1280 "----"
1281 ["Begin" verilog-sk-begin
1282 :help "Insert a begin .. end block"]
1283 ["If" verilog-sk-if
1284 :help "Insert an if (..) begin .. end block"]
1285 ["(if) else" verilog-sk-else-if
1286 :help "Insert an else if (..) begin .. end block"]
1287 ["For" verilog-sk-for
1288 :help "Insert a for (...) begin .. end block"]
1289 ["While" verilog-sk-while
1290 :help "Insert a while (...) begin .. end block"]
1291 ["Fork" verilog-sk-fork
1292 :help "Insert a fork begin .. end .. join block"]
1293 ["Repeat" verilog-sk-repeat
1294 :help "Insert a repeat (..) begin .. end block"]
1295 ["Case" verilog-sk-case
1296 :help "Insert a case block, prompting for details"]
1297 ["Casex" verilog-sk-casex
1298 :help "Insert a casex (...) item: begin.. end endcase block"]
1299 ["Casez" verilog-sk-casez
1300 :help "Insert a casez (...) item: begin.. end endcase block"])))
6341f357
DN
1301
1302(defvar verilog-mode-abbrev-table nil
1303 "Abbrev table in use in Verilog-mode buffers.")
1304
1305(define-abbrev-table 'verilog-mode-abbrev-table ())
1306
b68a96b9
DN
1307;;
1308;; Macros
1309;;
1310
1311(defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1312 "Replace occurrences of FROM-STRING with TO-STRING.
1313FIXEDCASE and LITERAL as in `replace-match`. STRING is what to replace.
1314The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1315will break, as the o's continuously replace. xa -> x works ok though."
1316 ;; Hopefully soon to a emacs built-in
1317 (let ((start 0))
1318 (while (string-match from-string string start)
1319 (setq string (replace-match to-string fixedcase literal string)
4c5e69c6 1320 start (min (length string) (+ (match-beginning 0) (length to-string)))))
b68a96b9
DN
1321 string))
1322
1323(defsubst verilog-string-remove-spaces (string)
1324 "Remove spaces surrounding STRING."
1325 (save-match-data
1326 (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1327 (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1328 string))
1329
1330(defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1331 ; checkdoc-params: (REGEXP BOUND NOERROR)
1332 "Like `re-search-forward', but skips over match in comments or strings."
7cb1c4d7
DN
1333 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1334 (while (and
1335 (re-search-forward REGEXP BOUND NOERROR)
1336 (setq mdata (match-data))
1337 (and (verilog-skip-forward-comment-or-string)
1338 (progn
1339 (setq mdata '(nil nil))
1340 (if BOUND
1341 (< (point) BOUND)
1342 t)))))
1343 (store-match-data mdata)
1344 (match-end 0)))
b68a96b9
DN
1345
1346(defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1347 ; checkdoc-params: (REGEXP BOUND NOERROR)
1348 "Like `re-search-backward', but skips over match in comments or strings."
7cb1c4d7
DN
1349 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1350 (while (and
1351 (re-search-backward REGEXP BOUND NOERROR)
1352 (setq mdata (match-data))
1353 (and (verilog-skip-backward-comment-or-string)
1354 (progn
1355 (setq mdata '(nil nil))
1356 (if BOUND
1357 (> (point) BOUND)
1358 t)))))
1359 (store-match-data mdata)
1360 (match-end 0)))
b68a96b9
DN
1361
1362(defsubst verilog-re-search-forward-quick (regexp bound noerror)
1363 "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1364but trashes match data and is faster for REGEXP that doesn't match often.
1365This may at some point use text properties to ignore comments,
1366so there may be a large up front penalty for the first search."
1367 (let (pt)
1368 (while (and (not pt)
1369 (re-search-forward regexp bound noerror))
1370 (if (not (verilog-inside-comment-p))
1371 (setq pt (match-end 0))))
1372 pt))
1373
1374(defsubst verilog-re-search-backward-quick (regexp bound noerror)
1375 ; checkdoc-params: (REGEXP BOUND NOERROR)
1376 "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1377but trashes match data and is faster for REGEXP that doesn't match often.
1378This may at some point use text properties to ignore comments,
1379so there may be a large up front penalty for the first search."
1380 (let (pt)
1381 (while (and (not pt)
1382 (re-search-backward regexp bound noerror))
1383 (if (not (verilog-inside-comment-p))
1384 (setq pt (match-end 0))))
1385 pt))
1386
1387(defsubst verilog-get-beg-of-line (&optional arg)
1388 (save-excursion
1389 (beginning-of-line arg)
1390 (point)))
1391
1392(defsubst verilog-get-end-of-line (&optional arg)
1393 (save-excursion
1394 (end-of-line arg)
1395 (point)))
1396
1397(defsubst verilog-within-string ()
1398 (save-excursion
1399 (nth 3 (parse-partial-sexp (verilog-get-beg-of-line) (point)))))
1400
60618039
DN
1401(defvar compile-command)
1402
6341f357
DN
1403;; compilation program
1404(defun verilog-set-compile-command ()
37ea4b9b 1405 "Function to compute shell command to compile Verilog.
6341f357
DN
1406
1407This reads `verilog-tool' and sets `compile-command'. This specifies the
1408program that executes when you type \\[compile] or
1409\\[verilog-auto-save-compile].
1410
1411By default `verilog-tool' uses a Makefile if one exists in the current
1412directory. If not, it is set to the `verilog-linter', `verilog-coverage',
1413`verilog-simulator', or `verilog-compiler' variables, as selected with the
1414Verilog -> \"Choose Compilation Action\" menu.
1415
1416You should set `verilog-tool' or the other variables to the path and
1417arguments for your Verilog simulator. For example:
1418 \"vcs -p123 -O\"
1419or a string like:
1420 \"(cd /tmp; surecov %s)\".
1421
1422In the former case, the path to the current buffer is concat'ed to the
1423value of `verilog-tool'; in the later, the path to the current buffer is
1424substituted for the %s.
1425
37ea4b9b
JB
1426Where __FILE__ appears in the string, the `buffer-file-name' of the
1427current buffer, without the directory portion, will be substituted."
6341f357
DN
1428 (interactive)
1429 (cond
1430 ((or (file-exists-p "makefile") ;If there is a makefile, use it
1431 (file-exists-p "Makefile"))
1432 (make-local-variable 'compile-command)
1433 (setq compile-command "make "))
1434 (t
1435 (make-local-variable 'compile-command)
1436 (setq compile-command
1437 (if verilog-tool
1438 (if (string-match "%s" (eval verilog-tool))
1439 (format (eval verilog-tool) (or buffer-file-name ""))
1440 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1441 ""))))
1442 (verilog-modify-compile-command))
1443
1444(defun verilog-modify-compile-command ()
1445 "Replace meta-information in `compile-command'.
1446Where __FILE__ appears in the string, the current buffer's file-name,
1447without the directory portion, will be substituted."
1448 (when (and
1449 (stringp compile-command)
1450 (string-match "\\b__FILE__\\b" compile-command))
1451 (make-local-variable 'compile-command)
1452 (setq compile-command
1453 (verilog-string-replace-matches
1454 "\\b__FILE__\\b" (file-name-nondirectory (buffer-file-name))
1455 t t compile-command))))
1456
d9e8a018
GM
1457(if (featurep 'xemacs)
1458 ;; Following code only gets called from compilation-mode-hook on XEmacs to add error handling.
1459 (defun verilog-error-regexp-add-xemacs ()
1460 "Teach XEmacs about verilog errors.
7ea26faf
DN
1461Called by `compilation-mode-hook'. This allows \\[next-error] to
1462find the errors."
d9e8a018
GM
1463 (interactive)
1464 (if (boundp 'compilation-error-regexp-systems-alist)
1465 (if (and
1466 (not (equal compilation-error-regexp-systems-list 'all))
1467 (not (member compilation-error-regexp-systems-list 'verilog)))
1468 (push 'verilog compilation-error-regexp-systems-list)))
1469 (if (boundp 'compilation-error-regexp-alist-alist)
1470 (if (not (assoc 'verilog compilation-error-regexp-alist-alist))
1471 (setcdr compilation-error-regexp-alist-alist
1472 (cons verilog-error-regexp-xemacs-alist
1473 (cdr compilation-error-regexp-alist-alist)))))
1474 (if (boundp 'compilation-font-lock-keywords)
1475 (progn
1476 (make-variable-buffer-local 'compilation-font-lock-keywords)
1477 (setq compilation-font-lock-keywords verilog-error-font-lock-keywords)
1478 (font-lock-set-defaults)))
1479 ;; Need to re-run compilation-error-regexp builder
1480 (if (fboundp 'compilation-build-compilation-error-regexp-alist)
1481 (compilation-build-compilation-error-regexp-alist))
1482 ))
d88782c3
DN
1483
1484;; Following code only gets called from compilation-mode-hook on Emacs to add error handling.
a3a8b002
DN
1485(defun verilog-error-regexp-add-emacs ()
1486 "Tell Emacs compile that we are Verilog.
1487Called by `compilation-mode-hook'. This allows \\[next-error] to
1488find the errors."
1489 (interactive)
d88782c3
DN
1490 (if (boundp 'compilation-error-regexp-alist-alist)
1491 (progn
1492 (if (not (assoc 'verilog-xl-1 compilation-error-regexp-alist-alist))
1493 (mapcar
1494 (lambda (item)
1495 (push (car item) compilation-error-regexp-alist)
1496 (push item compilation-error-regexp-alist-alist)
1497 )
1498 verilog-error-regexp-emacs-alist)))))
1499
1500(if (featurep 'xemacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-xemacs))
1501(if (featurep 'emacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-emacs))
6341f357
DN
1502
1503(defconst verilog-directive-re
1504 ;; "`case" "`default" "`define" "`define" "`else" "`endfor" "`endif"
1505 ;; "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1506 ;; "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1507 ;; "`time_scale" "`undef" "`while"
1508 "\\<`\\(case\\|def\\(ault\\|ine\\(\\)?\\)\\|e\\(lse\\|nd\\(for\\|if\\|protect\\|switch\\|while\\)\\)\\|for\\(mat\\)?\\|i\\(f\\(def\\|ndef\\)?\\|nclude\\)\\|let\\|protect\\|switch\\|time\\(_scale\\|scale\\)\\|undef\\|while\\)\\>")
1509
a3a8b002
DN
1510(defconst verilog-directive-re-1
1511 (concat "[ \t]*" verilog-directive-re))
1512
6341f357
DN
1513(defconst verilog-directive-begin
1514 "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1515
1516(defconst verilog-directive-middle
1517 "\\<`\\(else\\|default\\|case\\)\\>")
1518
1519(defconst verilog-directive-end
1520 "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1521
a3a8b002
DN
1522(defconst verilog-ovm-begin-re
1523 (eval-when-compile
1524 (verilog-regexp-opt
1525 '(
1526 "`ovm_component_utils_begin"
1527 "`ovm_field_utils_begin"
1528 "`ovm_object_utils_begin"
1529 "`ovm_sequence_utils_begin"
1530 "`ovm_sequencer_utils_begin"
1531 ) nil )))
1532
1533(defconst verilog-ovm-end-re
1534 (eval-when-compile
1535 (verilog-regexp-opt
1536 '(
1537 "`ovm_component_utils_end"
1538 "`ovm_field_utils_end"
1539 "`ovm_object_utils_end"
1540 "`ovm_sequence_utils_end"
1541 "`ovm_sequencer_utils_end"
1542 ) nil )))
1543
1544(defconst verilog-ovm-statement-re
1545 (eval-when-compile
1546 (verilog-regexp-opt
1547 '(
1548 ;; Statements
1549 "`DUT_ERROR"
1550 "`MESSAGE"
1551 "`dut_error"
1552 "`message"
1553 "`ovm_analysis_imp_decl"
1554 "`ovm_blocking_get_imp_decl"
1555 "`ovm_blocking_get_peek_imp_decl"
1556 "`ovm_blocking_master_imp_decl"
1557 "`ovm_blocking_peek_imp_decl"
1558 "`ovm_blocking_put_imp_decl"
1559 "`ovm_blocking_slave_imp_decl"
1560 "`ovm_blocking_transport_imp_decl"
1561 "`ovm_component_registry"
1562 "`ovm_component_registry_param"
1563 "`ovm_component_utils"
1564 "`ovm_create"
1565 "`ovm_create_seq"
1566 "`ovm_declare_sequence_lib"
1567 "`ovm_do"
1568 "`ovm_do_seq"
1569 "`ovm_do_seq_with"
1570 "`ovm_do_with"
1571 "`ovm_error"
1572 "`ovm_fatal"
1573 "`ovm_field_aa_int_byte"
1574 "`ovm_field_aa_int_byte_unsigned"
1575 "`ovm_field_aa_int_int"
1576 "`ovm_field_aa_int_int_unsigned"
1577 "`ovm_field_aa_int_integer"
1578 "`ovm_field_aa_int_integer_unsigned"
1579 "`ovm_field_aa_int_key"
1580 "`ovm_field_aa_int_longint"
1581 "`ovm_field_aa_int_longint_unsigned"
1582 "`ovm_field_aa_int_shortint"
1583 "`ovm_field_aa_int_shortint_unsigned"
1584 "`ovm_field_aa_int_string"
1585 "`ovm_field_aa_object_int"
1586 "`ovm_field_aa_object_string"
1587 "`ovm_field_aa_string_int"
1588 "`ovm_field_aa_string_string"
1589 "`ovm_field_array_int"
1590 "`ovm_field_array_object"
1591 "`ovm_field_array_string"
1592 "`ovm_field_enum"
1593 "`ovm_field_event"
1594 "`ovm_field_int"
1595 "`ovm_field_object"
1596 "`ovm_field_queue_int"
1597 "`ovm_field_queue_object"
1598 "`ovm_field_queue_string"
1599 "`ovm_field_sarray_int"
1600 "`ovm_field_string"
1601 "`ovm_field_utils"
1602 "`ovm_file"
1603 "`ovm_get_imp_decl"
1604 "`ovm_get_peek_imp_decl"
1605 "`ovm_info"
1606 "`ovm_info1"
1607 "`ovm_info2"
1608 "`ovm_info3"
1609 "`ovm_info4"
1610 "`ovm_line"
1611 "`ovm_master_imp_decl"
1612 "`ovm_msg_detail"
1613 "`ovm_non_blocking_transport_imp_decl"
1614 "`ovm_nonblocking_get_imp_decl"
1615 "`ovm_nonblocking_get_peek_imp_decl"
1616 "`ovm_nonblocking_master_imp_decl"
1617 "`ovm_nonblocking_peek_imp_decl"
1618 "`ovm_nonblocking_put_imp_decl"
1619 "`ovm_nonblocking_slave_imp_decl"
1620 "`ovm_object_registry"
1621 "`ovm_object_registry_param"
1622 "`ovm_object_utils"
1623 "`ovm_peek_imp_decl"
1624 "`ovm_phase_func_decl"
1625 "`ovm_phase_task_decl"
1626 "`ovm_print_aa_int_object"
1627 "`ovm_print_aa_string_int"
1628 "`ovm_print_aa_string_object"
1629 "`ovm_print_aa_string_string"
1630 "`ovm_print_array_int"
1631 "`ovm_print_array_object"
1632 "`ovm_print_array_string"
1633 "`ovm_print_object_queue"
1634 "`ovm_print_queue_int"
1635 "`ovm_print_string_queue"
1636 "`ovm_put_imp_decl"
1637 "`ovm_rand_send"
1638 "`ovm_rand_send_with"
1639 "`ovm_send"
1640 "`ovm_sequence_utils"
1641 "`ovm_slave_imp_decl"
1642 "`ovm_transport_imp_decl"
1643 "`ovm_update_sequence_lib"
1644 "`ovm_update_sequence_lib_and_item"
1645 "`ovm_warning"
1646 "`static_dut_error"
1647 "`static_message") nil )))
1648
6341f357
DN
1649
1650;;
1651;; Regular expressions used to calculate indent, etc.
1652;;
1653(defconst verilog-symbol-re "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
6341f357
DN
1654;; Want to match
1655;; aa :
1656;; aa,bb :
1657;; a[34:32] :
1658;; a,
1659;; b :
1660
1661(defconst verilog-no-indent-begin-re
1662 "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
1663
1664(defconst verilog-ends-re
1665 ;; Parenthesis indicate type of keyword found
1666 (concat
1667 "\\(\\<else\\>\\)\\|" ; 1
1668 "\\(\\<if\\>\\)\\|" ; 2
1669 "\\(\\<end\\>\\)\\|" ; 3
1670 "\\(\\<endcase\\>\\)\\|" ; 4
1671 "\\(\\<endfunction\\>\\)\\|" ; 5
1672 "\\(\\<endtask\\>\\)\\|" ; 6
1673 "\\(\\<endspecify\\>\\)\\|" ; 7
1674 "\\(\\<endtable\\>\\)\\|" ; 8
1675 "\\(\\<endgenerate\\>\\)\\|" ; 9
1676 "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
1677 "\\(\\<endclass\\>\\)\\|" ; 11
a3a8b002
DN
1678 "\\(\\<endgroup\\>\\)\\|" ; 12
1679 ;; OVM
1680 "\\(\\<`ovm_component_utils_end\\>\\)\\|"
1681 "\\(\\<`ovm_field_utils_end\\>\\)\\|"
1682 "\\(\\<`ovm_object_utils_end\\>\\)\\|"
1683 "\\(\\<`ovm_sequence_utils_end\\>\\)\\|"
1684 "\\(\\<`ovm_sequencer_utils_end\\>\\)"
1685
6341f357
DN
1686 ))
1687
1688(defconst verilog-auto-end-comment-lines-re
1689 ;; Matches to names in this list cause auto-end-commentation
1690 (concat "\\("
1691 verilog-directive-re "\\)\\|\\("
1692 (eval-when-compile
1693 (verilog-regexp-words
1694 `( "begin"
1695 "else"
1696 "end"
1697 "endcase"
1698 "endclass"
1699 "endclocking"
1700 "endgroup"
1701 "endfunction"
1702 "endmodule"
1703 "endprogram"
1704 "endprimitive"
1705 "endinterface"
1706 "endpackage"
1707 "endsequence"
1708 "endspecify"
1709 "endtable"
1710 "endtask"
1711 "join"
1712 "join_any"
1713 "join_none"
1714 "module"
1715 "macromodule"
1716 "primitive"
1717 "interface"
1718 "package")))
1719 "\\)"))
1720
1721;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
1722;;; verilog-end-block-ordered-re matches exactly the same strings.
1723(defconst verilog-end-block-ordered-re
1724 ;; Parenthesis indicate type of keyword found
1725 (concat "\\(\\<endcase\\>\\)\\|" ; 1
1726 "\\(\\<end\\>\\)\\|" ; 2
1727 "\\(\\<end" ; 3, but not used
1728 "\\(" ; 4, but not used
1729 "\\(function\\)\\|" ; 5
1730 "\\(task\\)\\|" ; 6
1731 "\\(module\\)\\|" ; 7
1732 "\\(primitive\\)\\|" ; 8
1733 "\\(interface\\)\\|" ; 9
1734 "\\(package\\)\\|" ; 10
1735 "\\(class\\)\\|" ; 11
1736 "\\(group\\)\\|" ; 12
1737 "\\(program\\)\\|" ; 13
1738 "\\(sequence\\)\\|" ; 14
1739 "\\(clocking\\)\\|" ; 15
1740 "\\)\\>\\)"))
1741(defconst verilog-end-block-re
1742 (eval-when-compile
1743 (verilog-regexp-words
1744
1745 `("end" ;; closes begin
1746 "endcase" ;; closes any of case, casex casez or randcase
1747 "join" "join_any" "join_none" ;; closes fork
1748 "endclass"
1749 "endtable"
1750 "endspecify"
1751 "endfunction"
1752 "endgenerate"
1753 "endtask"
1754 "endgroup"
1755 "endproperty"
1756 "endinterface"
1757 "endpackage"
1758 "endprogram"
1759 "endsequence"
1760 "endclocking"
a3a8b002
DN
1761 ;; OVM
1762 "`ovm_component_utils_end"
1763 "`ovm_field_utils_end"
1764 "`ovm_object_utils_end"
1765 "`ovm_sequence_utils_end"
1766 "`ovm_sequencer_utils_end"
1767
60618039 1768 ))))
6341f357
DN
1769
1770
1771(defconst verilog-endcomment-reason-re
1772 ;; Parenthesis indicate type of keyword found
1773 (concat
a3a8b002
DN
1774 "\\(\\<begin\\>\\)\\|" ; 1
1775 "\\(\\<else\\>\\)\\|" ; 2
1776 "\\(\\<end\\>\\s-+\\<else\\>\\)\\|" ; 3
1777 "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|" ; 4
1778 "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|" ; 5
1779 "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|" ; 6
1780 "\\(\\<fork\\>\\)\\|" ; 7
1781 "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
6341f357
DN
1782 "\\(\\<if\\>\\)\\|"
1783 "\\(\\<clocking\\>\\)\\|"
a3a8b002
DN
1784 "\\(\\<task\\>\\)\\|"
1785 "\\(\\<function\\>\\)\\|"
6341f357
DN
1786 "\\(\\<initial\\>\\)\\|"
1787 "\\(\\<interface\\>\\)\\|"
1788 "\\(\\<package\\>\\)\\|"
1789 "\\(\\<final\\>\\)\\|"
6341f357
DN
1790 "\\(@\\)\\|"
1791 "\\(\\<while\\>\\)\\|"
1792 "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
1793 "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
1794 "#"))
1795
1796(defconst verilog-named-block-re "begin[ \t]*:")
1797
1798;; These words begin a block which can occur inside a module which should be indented,
1799;; and closed with the respective word from the end-block list
1800
1801(defconst verilog-beg-block-re
1802 (eval-when-compile
1803 (verilog-regexp-words
1804 `("begin"
1805 "case" "casex" "casez" "randcase"
1806 "clocking"
1807 "generate"
1808 "fork"
1809 "function"
1810 "property"
1811 "specify"
1812 "table"
1813 "task"
a3a8b002
DN
1814 ;;; OVM
1815 "`ovm_component_utils_begin"
1816 "`ovm_field_utils_begin"
1817 "`ovm_object_utils_begin"
1818 "`ovm_sequence_utils_begin"
1819 "`ovm_sequencer_utils_begin"
1820
6341f357
DN
1821 ))))
1822;; These are the same words, in a specific order in the regular
1823;; expression so that matching will work nicely for
1824;; verilog-forward-sexp and verilog-calc-indent
6341f357 1825(defconst verilog-beg-block-re-ordered
4c5e69c6
DN
1826 ( concat "\\(\\<begin\\>\\)" ;1
1827 "\\|\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
1828 "\\|\\(\\(\\<disable\\>\\s-+\\)?fork\\>\\)" ;4,5
1829 "\\|\\(\\<class\\>\\)" ;6
1830 "\\|\\(\\<table\\>\\)" ;7
1831 "\\|\\(\\<specify\\>\\)" ;8
1832 "\\|\\(\\<function\\>\\)" ;9
a3a8b002
DN
1833 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<function\\>\\)" ;10
1834 "\\|\\(\\<task\\>\\)" ;14
1835 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)" ;15
1836 "\\|\\(\\<generate\\>\\)" ;18
1837 "\\|\\(\\<covergroup\\>\\)" ;16 20
1838 "\\|\\(\\(\\(\\<cover\\>\\s-+\\)\\|\\(\\<assert\\>\\s-+\\)\\)*\\<property\\>\\)" ;17 21
1839 "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;21 25
1840 "\\|\\(\\<clocking\\>\\)" ;22 27
1841 "\\|\\(\\<`ovm_[a-z_]+_begin\\>\\)" ;28
1842 ;;
1843
4c5e69c6 1844 ))
6341f357
DN
1845
1846(defconst verilog-end-block-ordered-rry
1847 [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1848 "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
1849 "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1850 "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
1851 "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
1852 "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
1853 "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
1854 "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
1855 "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
1856 "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
1857 "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
1858 "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
1859 "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
1860 ] )
1861
1862(defconst verilog-nameable-item-re
1863 (eval-when-compile
1864 (verilog-regexp-words
1865 `("begin"
1866 "fork"
1867 "join" "join_any" "join_none"
1868 "end"
1869 "endcase"
1870 "endconfig"
1871 "endclass"
1872 "endclocking"
1873 "endfunction"
1874 "endgenerate"
1875 "endmodule"
1876 "endprimative"
1877 "endinterface"
1878 "endpackage"
1879 "endspecify"
1880 "endtable"
1881 "endtask" )
1882 )))
1883
1884(defconst verilog-declaration-opener
1885 (eval-when-compile
1886 (verilog-regexp-words
1887 `("module" "begin" "task" "function"))))
1888
1889(defconst verilog-declaration-prefix-re
1890 (eval-when-compile
1891 (verilog-regexp-words
1892 `(
1893 ;; port direction
6edb5716 1894 "inout" "input" "output" "ref"
6341f357
DN
1895 ;; changeableness
1896 "const" "static" "protected" "local"
1897 ;; parameters
6edb5716 1898 "localparam" "parameter" "var"
6341f357
DN
1899 ;; type creation
1900 "typedef"
1901 ))))
1902(defconst verilog-declaration-core-re
1903 (eval-when-compile
1904 (verilog-regexp-words
1905 `(
7e2a6000 1906 ;; port direction (by themselves)
871c637e 1907 "inout" "input" "output"
6341f357
DN
1908 ;; integer_atom_type
1909 "byte" "shortint" "int" "longint" "integer" "time"
1910 ;; integer_vector_type
1911 "bit" "logic" "reg"
1912 ;; non_integer_type
1913 "shortreal" "real" "realtime"
1914 ;; net_type
1915 "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
1916 ;; misc
1917 "string" "event" "chandle" "virtual" "enum" "genvar"
1918 "struct" "union"
1919 ;; builtin classes
6edb5716 1920 "mailbox" "semaphore"
6341f357 1921 ))))
6edb5716 1922(defconst verilog-declaration-re
6341f357
DN
1923 (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
1924(defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
1925(defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
1926(defconst verilog-optional-signed-range-re
1927 (concat
1928 "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
1929(defconst verilog-macroexp-re "`\\sw+")
1930
1931(defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
1932(defconst verilog-declaration-re-2-no-macro
1933 (concat "\\s-*" verilog-declaration-re
1934 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1935 "\\)?"))
1936(defconst verilog-declaration-re-2-macro
1937 (concat "\\s-*" verilog-declaration-re
1938 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1939 "\\|\\(" verilog-macroexp-re "\\)"
1940 "\\)?"))
1941(defconst verilog-declaration-re-1-macro
1942 (concat "^" verilog-declaration-re-2-macro))
1943
1944(defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
1945
1946(defconst verilog-defun-re
1947 (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
1948(defconst verilog-end-defun-re
1949 (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
1950(defconst verilog-zero-indent-re
1951 (concat verilog-defun-re "\\|" verilog-end-defun-re))
1952
1953(defconst verilog-behavioral-block-beg-re
2a9eb3f5
DN
1954 (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
1955 "function" "task"))))
a3a8b002 1956(defconst verilog-coverpoint-re "\\w+\\s*:\\s*\\(coverpoint\\|cross\\constraint\\)" )
6341f357
DN
1957(defconst verilog-indent-re
1958 (eval-when-compile
1959 (verilog-regexp-words
1960 `(
1961 "{"
1962 "always" "always_latch" "always_ff" "always_comb"
1963 "begin" "end"
1964; "unique" "priority"
1965 "case" "casex" "casez" "randcase" "endcase"
1966 "class" "endclass"
1967 "clocking" "endclocking"
1968 "config" "endconfig"
1969 "covergroup" "endgroup"
1970 "fork" "join" "join_any" "join_none"
1971 "function" "endfunction"
1972 "final"
1973 "generate" "endgenerate"
1974 "initial"
1975 "interface" "endinterface"
1976 "module" "macromodule" "endmodule"
1977 "package" "endpackage"
1978 "primitive" "endprimative"
1979 "program" "endprogram"
1980 "property" "endproperty"
1981 "sequence" "randsequence" "endsequence"
1982 "specify" "endspecify"
1983 "table" "endtable"
1984 "task" "endtask"
4c5e69c6 1985 "virtual"
6341f357
DN
1986 "`case"
1987 "`default"
1988 "`define" "`undef"
1989 "`if" "`ifdef" "`ifndef" "`else" "`endif"
1990 "`while" "`endwhile"
1991 "`for" "`endfor"
1992 "`format"
1993 "`include"
1994 "`let"
1995 "`protect" "`endprotect"
1996 "`switch" "`endswitch"
1997 "`timescale"
1998 "`time_scale"
a3a8b002
DN
1999 ;; OVM Begin tokens
2000 "`ovm_component_utils_begin"
2001 "`ovm_field_utils_begin"
2002 "`ovm_object_utils_begin"
2003 "`ovm_sequence_utils_begin"
2004 "`ovm_sequencer_utils_begin"
2005 ;; OVM End tokens
2006 "`ovm_component_utils_end"
2007 "`ovm_field_utils_end"
2008 "`ovm_object_utils_end"
2009 "`ovm_sequence_utils_end"
2010 "`ovm_sequencer_utils_end"
6341f357
DN
2011 ))))
2012
a3a8b002
DN
2013(defconst verilog-defun-level-not-generate-re
2014 (eval-when-compile
2015 (verilog-regexp-words
2016 `( "module" "macromodule" "primitive" "class" "program"
2017 "interface" "package" "config"))))
2018
6341f357
DN
2019(defconst verilog-defun-level-re
2020 (eval-when-compile
2021 (verilog-regexp-words
a3a8b002
DN
2022 (append
2023 `( "module" "macromodule" "primitive" "class" "program"
2024 "interface" "package" "config")
2025 `( "initial" "final" "always" "always_comb" "always_ff"
2026 "always_latch" "endtask" "endfunction" )))))
6341f357 2027
a3a8b002 2028(defconst verilog-defun-level-generate-only-re
6341f357
DN
2029 (eval-when-compile
2030 (verilog-regexp-words
a3a8b002
DN
2031 `( "initial" "final" "always" "always_comb" "always_ff"
2032 "always_latch" "endtask" "endfunction" ))))
6341f357
DN
2033
2034(defconst verilog-cpp-level-re
2035 (eval-when-compile
2036 (verilog-regexp-words
2037 `(
2038 "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
2039 ))))
2a9eb3f5 2040(defconst verilog-disable-fork-re "disable\\s-+fork")
6341f357
DN
2041(defconst verilog-extended-case-re "\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?")
2042(defconst verilog-extended-complete-re
2043 (concat "\\(\\<extern\\s-+\\|\\<virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)"
2044 "\\|\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)"
a3a8b002 2045 "\\|\\(\\<import\\>\\s-+\\)?\"DPI-C\"\\s-+\\(function\\>\\|task\\>\\)"
6341f357
DN
2046 "\\|" verilog-extended-case-re ))
2047(defconst verilog-basic-complete-re
2048 (eval-when-compile
2049 (verilog-regexp-words
2050 `(
2051 "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
2052 "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
a3a8b002 2053 "if" "for" "forever" "foreach" "else" "parameter" "do" "localparam"
6341f357
DN
2054 ))))
2055(defconst verilog-complete-reg
2056 (concat
2057 verilog-extended-complete-re
2058 "\\|"
2059 verilog-basic-complete-re))
2060
2061(defconst verilog-end-statement-re
2062 (concat "\\(" verilog-beg-block-re "\\)\\|\\("
2063 verilog-end-block-re "\\)"))
2064
2065(defconst verilog-endcase-re
a3a8b002 2066 (concat verilog-extended-case-re "\\|"
6341f357
DN
2067 "\\(endcase\\)\\|"
2068 verilog-defun-re
2069 ))
2070
2071(defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
2072 "String used to mark beginning of excluded text.")
2073(defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
2074 "String used to mark end of excluded text.")
2075(defconst verilog-preprocessor-re
2076 (eval-when-compile
2077 (verilog-regexp-words
2078 `(
2079 "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
2080 ))))
2081
2082(defconst verilog-keywords
2083 '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
2084 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
2085 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
2086 "`time_scale" "`undef" "`while"
2087
2088 "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
2089 "assert" "assign" "assume" "automatic" "before" "begin" "bind"
2090 "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
2091 "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
2092 "config" "const" "constraint" "context" "continue" "cover"
2093 "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
2094 "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
2095 "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
2096 "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
2097 "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
2098 "endtask" "enum" "event" "expect" "export" "extends" "extern"
2099 "final" "first_match" "for" "force" "foreach" "forever" "fork"
2100 "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
2101 "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
2102 "include" "initial" "inout" "input" "inside" "instance" "int"
2103 "integer" "interface" "intersect" "join" "join_any" "join_none"
2104 "large" "liblist" "library" "local" "localparam" "logic"
2105 "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
2106 "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
2107 "notif0" "notif1" "null" "or" "output" "package" "packed"
2108 "parameter" "pmos" "posedge" "primitive" "priority" "program"
2109 "property" "protected" "pull0" "pull1" "pulldown" "pullup"
2110 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2111 "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
2112 "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
2113 "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
2114 "showcancelled" "signed" "small" "solve" "specify" "specparam"
2115 "static" "string" "strong0" "strong1" "struct" "super" "supply0"
2116 "supply1" "table" "tagged" "task" "this" "throughout" "time"
2117 "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
2118 "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
2119 "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
2120 "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
2121 "wire" "with" "within" "wor" "xnor" "xor"
2122 )
2123 "List of Verilog keywords.")
2124
6341f357
DN
2125(defconst verilog-comment-start-regexp "//\\|/\\*"
2126 "Dual comment value for `comment-start-regexp'.")
2127
e1776067
DN
2128(defvar verilog-mode-syntax-table
2129 (let ((table (make-syntax-table)))
2130 ;; Populate the syntax TABLE.
2131 (modify-syntax-entry ?\\ "\\" table)
2132 (modify-syntax-entry ?+ "." table)
2133 (modify-syntax-entry ?- "." table)
2134 (modify-syntax-entry ?= "." table)
2135 (modify-syntax-entry ?% "." table)
2136 (modify-syntax-entry ?< "." table)
2137 (modify-syntax-entry ?> "." table)
2138 (modify-syntax-entry ?& "." table)
2139 (modify-syntax-entry ?| "." table)
2140 (modify-syntax-entry ?` "w" table)
2141 (modify-syntax-entry ?_ "w" table)
2142 (modify-syntax-entry ?\' "." table)
2143
2144 ;; Set up TABLE to handle block and line style comments.
2145 (if (featurep 'xemacs)
2146 (progn
2147 ;; XEmacs (formerly Lucid) has the best implementation
2148 (modify-syntax-entry ?/ ". 1456" table)
2149 (modify-syntax-entry ?* ". 23" table)
2150 (modify-syntax-entry ?\n "> b" table))
d63b01e1 2151 ;; Emacs does things differently, but we can work with it
e1776067
DN
2152 (modify-syntax-entry ?/ ". 124b" table)
2153 (modify-syntax-entry ?* ". 23" table)
2154 (modify-syntax-entry ?\n "> b" table))
2155 table)
37ea4b9b 2156 "Syntax table used in Verilog mode buffers.")
6341f357 2157
7ea26faf 2158(defvar verilog-font-lock-keywords nil
6341f357
DN
2159 "Default highlighting for Verilog mode.")
2160
7ea26faf 2161(defvar verilog-font-lock-keywords-1 nil
6341f357
DN
2162 "Subdued level highlighting for Verilog mode.")
2163
7ea26faf 2164(defvar verilog-font-lock-keywords-2 nil
6341f357
DN
2165 "Medium level highlighting for Verilog mode.
2166See also `verilog-font-lock-extra-types'.")
2167
7ea26faf 2168(defvar verilog-font-lock-keywords-3 nil
6341f357
DN
2169 "Gaudy level highlighting for Verilog mode.
2170See also `verilog-font-lock-extra-types'.")
2171(defvar verilog-font-lock-translate-off-face
2172 'verilog-font-lock-translate-off-face
2173 "Font to use for translated off regions.")
2174(defface verilog-font-lock-translate-off-face
2175 '((((class color)
2176 (background light))
2177 (:background "gray90" :italic t ))
2178 (((class color)
2179 (background dark))
2180 (:background "gray10" :italic t ))
2181 (((class grayscale) (background light))
2182 (:foreground "DimGray" :italic t))
2183 (((class grayscale) (background dark))
2184 (:foreground "LightGray" :italic t))
2185 (t (:italis t)))
2186 "Font lock mode face used to background highlight translate-off regions."
2187 :group 'font-lock-highlighting-faces)
2188
2189(defvar verilog-font-lock-p1800-face
2190 'verilog-font-lock-p1800-face
2191 "Font to use for p1800 keywords.")
2192(defface verilog-font-lock-p1800-face
2193 '((((class color)
2194 (background light))
2195 (:foreground "DarkOrange3" :bold t ))
2196 (((class color)
2197 (background dark))
2198 (:foreground "orange1" :bold t ))
2199 (t (:italic t)))
2200 "Font lock mode face used to highlight P1800 keywords."
2201 :group 'font-lock-highlighting-faces)
2202
2203(defvar verilog-font-lock-ams-face
2204 'verilog-font-lock-ams-face
2205 "Font to use for Analog/Mixed Signal keywords.")
2206(defface verilog-font-lock-ams-face
2207 '((((class color)
2208 (background light))
2209 (:foreground "Purple" :bold t ))
2210 (((class color)
2211 (background dark))
2212 (:foreground "orange1" :bold t ))
2213 (t (:italic t)))
2214 "Font lock mode face used to highlight AMS keywords."
2215 :group 'font-lock-highlighting-faces)
2216
2a9eb3f5
DN
2217(defvar verilog-font-grouping-keywords-face
2218 'verilog-font-lock-grouping-keywords-face
2219 "Font to use for Verilog Grouping Keywords (such as begin..end).")
2220(defface verilog-font-lock-grouping-keywords-face
2221 '((((class color)
2222 (background light))
2223 (:foreground "red4" :bold t ))
2224 (((class color)
2225 (background dark))
2226 (:foreground "red4" :bold t ))
2227 (t (:italic t)))
2228 "Font lock mode face used to highlight verilog grouping keywords."
2229 :group 'font-lock-highlighting-faces)
2230
6341f357
DN
2231(let* ((verilog-type-font-keywords
2232 (eval-when-compile
2233 (verilog-regexp-opt
2234 '(
2235 "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
2236 "event" "genvar" "inout" "input" "integer" "localparam"
2237 "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
2238 "output" "parameter" "pmos" "pull0" "pull1" "pullup"
2239 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
2240 "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
2241 "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
2242 "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
2243 "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
2244 ) nil )))
2245
2246 (verilog-pragma-keywords
2247 (eval-when-compile
2248 (verilog-regexp-opt
9c059794 2249 '("surefire" "synopsys" "rtl_synthesis" "verilint" "leda" "0in") nil
6341f357
DN
2250 )))
2251
2252 (verilog-p1800-keywords
2253 (eval-when-compile
2254 (verilog-regexp-opt
2255 '("alias" "assert" "assume" "automatic" "before" "bind"
2256 "bins" "binsof" "break" "byte" "cell" "chandle" "class"
2257 "clocking" "config" "const" "constraint" "context" "continue"
2258 "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
2259 "dist" "do" "edge" "endclass" "endclocking" "endconfig"
2260 "endgroup" "endprogram" "endproperty" "endsequence" "enum"
2261 "expect" "export" "extends" "extern" "first_match" "foreach"
2262 "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
2263 "illegal_bins" "import" "incdir" "include" "inside" "instance"
2264 "int" "intersect" "large" "liblist" "library" "local" "longint"
2265 "matches" "medium" "modport" "new" "noshowcancelled" "null"
2266 "packed" "program" "property" "protected" "pull0" "pull1"
2267 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2268 "randcase" "randsequence" "ref" "release" "return" "scalared"
2269 "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
2270 "specparam" "static" "string" "strong0" "strong1" "struct"
2271 "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
2272 "type" "union" "unsigned" "use" "var" "virtual" "void"
2273 "wait_order" "weak0" "weak1" "wildcard" "with" "within"
2274 ) nil )))
2275
2276 (verilog-ams-keywords
2277 (eval-when-compile
2278 (verilog-regexp-opt
2279 '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
2280 "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
2281 "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
2282 "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
2283 "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
2284 "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
2285 "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
2286 "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
2287 "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
2288 "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
2289 "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
2290
2291 (verilog-font-keywords
2292 (eval-when-compile
2293 (verilog-regexp-opt
2294 '(
2a9eb3f5
DN
2295 "assign" "case" "casex" "casez" "randcase" "deassign"
2296 "default" "disable" "else" "endcase" "endfunction"
6341f357
DN
2297 "endgenerate" "endinterface" "endmodule" "endprimitive"
2298 "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
2299 "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
2300 "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
2301 "package" "endpackage" "always" "always_comb" "always_ff"
2302 "always_latch" "posedge" "primitive" "priority" "release"
2303 "repeat" "specify" "table" "task" "unique" "wait" "while"
2304 "class" "program" "endclass" "endprogram"
2a9eb3f5
DN
2305 ) nil )))
2306
2307 (verilog-font-grouping-keywords
2308 (eval-when-compile
2309 (verilog-regexp-opt
2310 '( "begin" "end" ) nil ))))
6341f357
DN
2311
2312 (setq verilog-font-lock-keywords
2313 (list
2314 ;; Fontify all builtin keywords
2315 (concat "\\<\\(" verilog-font-keywords "\\|"
2316 ;; And user/system tasks and functions
a1ebd734
DN
2317 "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
2318 "\\)\\>")
b1d0fc86
DN
2319 ;; Fontify all types
2320 (if verilog-highlight-grouping-keywords
2321 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2322 'verilog-font-lock-ams-face)
2323 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2324 'font-lock-type-face))
2325 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
a1ebd734 2326 'font-lock-type-face)
b1d0fc86 2327 ;; Fontify IEEE-P1800 keywords appropriately
6341f357
DN
2328 (if verilog-highlight-p1800-keywords
2329 (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
2330 'verilog-font-lock-p1800-face)
2331 (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
2332 'font-lock-type-face))
2333 ;; Fontify Verilog-AMS keywords
2334 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
60618039 2335 'verilog-font-lock-ams-face)))
6341f357
DN
2336
2337 (setq verilog-font-lock-keywords-1
2338 (append verilog-font-lock-keywords
2339 (list
2340 ;; Fontify module definitions
2341 (list
2342 "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
2343 '(1 font-lock-keyword-face)
2344 '(3 font-lock-function-name-face 'prepend))
2345 ;; Fontify function definitions
2346 (list
2347 (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
2348 '(1 font-lock-keyword-face)
60618039 2349 '(3 font-lock-reference-face prepend))
6341f357
DN
2350 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
2351 (1 font-lock-keyword-face)
60618039 2352 (2 font-lock-reference-face append))
6341f357 2353 '("\\<function\\>\\s-+\\(\\sw+\\)"
60618039 2354 1 'font-lock-reference-face append))))
6341f357
DN
2355
2356 (setq verilog-font-lock-keywords-2
2357 (append verilog-font-lock-keywords-1
2358 (list
2359 ;; Fontify pragmas
2360 (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
2361 ;; Fontify escaped names
2362 '("\\(\\\\\\S-*\\s-\\)" 0 font-lock-function-name-face)
2363 ;; Fontify macro definitions/ uses
2364 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
2365 'font-lock-preprocessor-face
2366 'font-lock-type-face))
2367 ;; Fontify delays/numbers
2368 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
2369 0 font-lock-type-face append)
2370 ;; Fontify instantiation names
2371 '("\\([A-Za-z][A-Za-z0-9_]+\\)\\s-*(" 1 font-lock-function-name-face)
6341f357
DN
2372 )))
2373
2374 (setq verilog-font-lock-keywords-3
2375 (append verilog-font-lock-keywords-2
2376 (when verilog-highlight-translate-off
2377 (list
2378 ;; Fontify things in translate off regions
7ea26faf
DN
2379 '(verilog-match-translate-off
2380 (0 'verilog-font-lock-translate-off-face prepend))
2381 )))))
6341f357
DN
2382
2383
6341f357
DN
2384(defun verilog-inside-comment-p ()
2385 "Check if point inside a nested comment."
2386 (save-excursion
2387 (let ((st-point (point)) hitbeg)
2388 (or (search-backward "//" (verilog-get-beg-of-line) t)
2389 (if (progn
60618039
DN
2390 ;; This is for tricky case //*, we keep searching if /*
2391 ;; is proceeded by // on same line.
7ea26faf
DN
2392 (while
2393 (and (setq hitbeg (search-backward "/*" nil t))
2394 (progn
2395 (forward-char 1)
2396 (search-backward "//" (verilog-get-beg-of-line) t))))
6341f357
DN
2397 hitbeg)
2398 (not (search-forward "*/" st-point t)))))))
2399
2400(defun verilog-declaration-end ()
2401 (search-forward ";"))
2402
2403(defun verilog-point-text (&optional pointnum)
2404 "Return text describing where POINTNUM or current point is (for errors).
2405Use filename, if current buffer being edited shorten to just buffer name."
2406 (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
2407 (buffer-name))
2408 buffer-file-name
2409 (buffer-name))
2410 ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
2411
2412(defun electric-verilog-backward-sexp ()
495ab0d5 2413 "Move backward over one balanced expression."
6341f357
DN
2414 (interactive)
2415 ;; before that see if we are in a comment
60618039
DN
2416 (verilog-backward-sexp))
2417
6341f357 2418(defun electric-verilog-forward-sexp ()
495ab0d5 2419 "Move forward over one balanced expression."
6341f357
DN
2420 (interactive)
2421 ;; before that see if we are in a comment
60618039
DN
2422 (verilog-forward-sexp))
2423
6341f357
DN
2424;;;used by hs-minor-mode
2425(defun verilog-forward-sexp-function (arg)
2426 (if (< arg 0)
2427 (verilog-backward-sexp)
2428 (verilog-forward-sexp)))
2429
2430
2431(defun verilog-backward-sexp ()
2432 (let ((reg)
2433 (elsec 1)
2434 (found nil)
60618039 2435 (st (point)))
6341f357
DN
2436 (if (not (looking-at "\\<"))
2437 (forward-word -1))
2438 (cond
60618039 2439 ((verilog-skip-backward-comment-or-string))
6341f357
DN
2440 ((looking-at "\\<else\\>")
2441 (setq reg (concat
2442 verilog-end-block-re
2443 "\\|\\(\\<else\\>\\)"
60618039 2444 "\\|\\(\\<if\\>\\)"))
6341f357
DN
2445 (while (and (not found)
2446 (verilog-re-search-backward reg nil 'move))
2447 (cond
2448 ((match-end 1) ; matched verilog-end-block-re
2449 ; try to leap back to matching outward block by striding across
2450 ; indent level changing tokens then immediately
2451 ; previous line governs indentation.
2452 (verilog-leap-to-head))
2453 ((match-end 2) ; else, we're in deep
2454 (setq elsec (1+ elsec)))
2455 ((match-end 3) ; found it
2456 (setq elsec (1- elsec))
2457 (if (= 0 elsec)
2458 ;; Now previous line describes syntax
60618039 2459 (setq found 't))))))
6341f357
DN
2460 ((looking-at verilog-end-block-re)
2461 (verilog-leap-to-head))
2462 ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
2463 (cond
2464 ((match-end 1)
2465 (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
2466 ((match-end 2)
2467 (verilog-re-search-backward "\\<primitive\\>" nil 'move))
2468 ((match-end 3)
2469 (verilog-re-search-backward "\\<class\\>" nil 'move))
2470 ((match-end 4)
2471 (verilog-re-search-backward "\\<program\\>" nil 'move))
2472 ((match-end 5)
2473 (verilog-re-search-backward "\\<interface\\>" nil 'move))
2474 ((match-end 6)
2475 (verilog-re-search-backward "\\<package\\>" nil 'move))
2476 (t
2477 (goto-char st)
2478 (backward-sexp 1))))
2479 (t
2480 (goto-char st)
60618039 2481 (backward-sexp)))))
6341f357
DN
2482
2483(defun verilog-forward-sexp ()
2484 (let ((reg)
2485 (md 2)
4c5e69c6
DN
2486 (st (point))
2487 (nest 'yes))
6341f357
DN
2488 (if (not (looking-at "\\<"))
2489 (forward-word -1))
2490 (cond
2491 ((verilog-skip-forward-comment-or-string)
60618039 2492 (verilog-forward-syntactic-ws))
4c5e69c6 2493 ((looking-at verilog-beg-block-re-ordered)
6341f357 2494 (cond
4c5e69c6
DN
2495 ((match-end 1);
2496 ;; Search forward for matching end
6341f357 2497 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
4c5e69c6
DN
2498 ((match-end 2)
2499 ;; Search forward for matching endcase
2a9eb3f5
DN
2500 (setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2501 (setq md 3) ;; ender is third item in regexp
2502 )
4c5e69c6 2503 ((match-end 4)
2a9eb3f5 2504 ;; might be "disable fork"
a3a8b002 2505 (if (or
2a9eb3f5
DN
2506 (looking-at verilog-disable-fork-re)
2507 (and (looking-at "fork")
2508 (progn
2509 (forward-word -1)
2510 (looking-at verilog-disable-fork-re))))
2511 (progn
2512 (goto-char (match-end 0))
a3a8b002 2513 (forward-word 1)
2a9eb3f5
DN
2514 (setq reg nil))
2515 (progn
4c5e69c6 2516 ;; Search forward for matching join
2a9eb3f5 2517 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))))
4c5e69c6
DN
2518 ((match-end 6)
2519 ;; Search forward for matching endclass
6341f357 2520 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
a3a8b002 2521
4c5e69c6
DN
2522 ((match-end 7)
2523 ;; Search forward for matching endtable
2524 (setq reg "\\<endtable\\>" )
2525 (setq nest 'no))
2526 ((match-end 8)
2527 ;; Search forward for matching endspecify
2528 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
2529 ((match-end 9)
2530 ;; Search forward for matching endfunction
2531 (setq reg "\\<endfunction\\>" )
2532 (setq nest 'no))
2533 ((match-end 10)
a3a8b002
DN
2534 ;; Search forward for matching endfunction
2535 (setq reg "\\<endfunction\\>" )
2536 (setq nest 'no))
2537 ((match-end 14)
4c5e69c6
DN
2538 ;; Search forward for matching endtask
2539 (setq reg "\\<endtask\\>" )
2540 (setq nest 'no))
a3a8b002 2541 ((match-end 15)
4c5e69c6
DN
2542 ;; Search forward for matching endtask
2543 (setq reg "\\<endtask\\>" )
2544 (setq nest 'no))
a3a8b002 2545 ((match-end 19)
4c5e69c6
DN
2546 ;; Search forward for matching endgenerate
2547 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
a3a8b002 2548 ((match-end 20)
4c5e69c6
DN
2549 ;; Search forward for matching endgroup
2550 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
a3a8b002 2551 ((match-end 21)
4c5e69c6
DN
2552 ;; Search forward for matching endproperty
2553 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
a3a8b002 2554 ((match-end 25)
4c5e69c6
DN
2555 ;; Search forward for matching endsequence
2556 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
2557 (setq md 3)) ; 3 to get to endsequence in the reg above
a3a8b002 2558 ((match-end 27)
4c5e69c6
DN
2559 ;; Search forward for matching endclocking
2560 (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
2a9eb3f5
DN
2561 (if (and reg
2562 (forward-word 1))
6341f357 2563 (catch 'skip
a3a8b002 2564 (if (eq nest 'yes)
4c5e69c6
DN
2565 (let ((depth 1))
2566 (while (verilog-re-search-forward reg nil 'move)
2567 (cond
2568 ((match-end md) ; the closer in reg, so we are climbing out
2569 (setq depth (1- depth))
2570 (if (= 0 depth) ; we are out!
2571 (throw 'skip 1)))
2572 ((match-end 1) ; the opener in reg, so we are deeper now
2573 (setq depth (1+ depth))))))
2574 (if (verilog-re-search-forward reg nil 'move)
2575 (throw 'skip 1))))))
a3a8b002 2576
6341f357
DN
2577 ((looking-at (concat
2578 "\\(\\<\\(macro\\)?module\\>\\)\\|"
2579 "\\(\\<primitive\\>\\)\\|"
2580 "\\(\\<class\\>\\)\\|"
2581 "\\(\\<program\\>\\)\\|"
2582 "\\(\\<interface\\>\\)\\|"
2583 "\\(\\<package\\>\\)"))
2584 (cond
2585 ((match-end 1)
2586 (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
2587 ((match-end 2)
2588 (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
2589 ((match-end 3)
2590 (verilog-re-search-forward "\\<endclass\\>" nil 'move))
2591 ((match-end 4)
2592 (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
2593 ((match-end 5)
2594 (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
2595 ((match-end 6)
2596 (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
2597 (t
2598 (goto-char st)
2599 (if (= (following-char) ?\) )
2600 (forward-char 1)
2601 (forward-sexp 1)))))
2602 (t
2603 (goto-char st)
2604 (if (= (following-char) ?\) )
2605 (forward-char 1)
60618039 2606 (forward-sexp 1))))))
6341f357
DN
2607
2608(defun verilog-declaration-beg ()
2609 (verilog-re-search-backward verilog-declaration-re (bobp) t))
2610
6341f357
DN
2611;;
2612;;
2613;; Mode
2614;;
2615(defvar verilog-which-tool 1)
6edb5716 2616;;;###autoload
6341f357
DN
2617(defun verilog-mode ()
2618 "Major mode for editing Verilog code.
2619\\<verilog-mode-map>
2620See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
2621AUTOs can improve coding efficiency.
2622
2623Use \\[verilog-faq] for a pointer to frequently asked questions.
2624
2625NEWLINE, TAB indents for Verilog code.
2626Delete converts tabs to spaces as it moves back.
2627
2628Supports highlighting.
2629
2630Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
2631with no args, if that value is non-nil.
2632
2633Variables controlling indentation/edit style:
2634
2635 variable `verilog-indent-level' (default 3)
2636 Indentation of Verilog statements with respect to containing block.
2637 `verilog-indent-level-module' (default 3)
2638 Absolute indentation of Module level Verilog statements.
2639 Set to 0 to get initial and always statements lined up
2640 on the left side of your screen.
2641 `verilog-indent-level-declaration' (default 3)
2642 Indentation of declarations with respect to containing block.
2643 Set to 0 to get them list right under containing block.
2644 `verilog-indent-level-behavioral' (default 3)
2645 Indentation of first begin in a task or function block
37ea4b9b
JB
2646 Set to 0 to get such code to lined up underneath the task or
2647 function keyword.
6341f357 2648 `verilog-indent-level-directive' (default 1)
37ea4b9b 2649 Indentation of `ifdef/`endif blocks.
6341f357
DN
2650 `verilog-cexp-indent' (default 1)
2651 Indentation of Verilog statements broken across lines i.e.:
2652 if (a)
2653 begin
2654 `verilog-case-indent' (default 2)
2655 Indentation for case statements.
2656 `verilog-auto-newline' (default nil)
2657 Non-nil means automatically newline after semicolons and the punctuation
2658 mark after an end.
2659 `verilog-auto-indent-on-newline' (default t)
37ea4b9b 2660 Non-nil means automatically indent line after newline.
6341f357
DN
2661 `verilog-tab-always-indent' (default t)
2662 Non-nil means TAB in Verilog mode should always reindent the current line,
2663 regardless of where in the line point is when the TAB command is used.
2664 `verilog-indent-begin-after-if' (default t)
2665 Non-nil means to indent begin statements following a preceding
37ea4b9b 2666 if, else, while, for and repeat statements, if any. Otherwise,
6341f357
DN
2667 the begin is lined up with the preceding token. If t, you get:
2668 if (a)
2669 begin // amount of indent based on `verilog-cexp-indent'
2670 otherwise you get:
2671 if (a)
2672 begin
2673 `verilog-auto-endcomments' (default t)
2674 Non-nil means a comment /* ... */ is set after the ends which ends
2675 cases, tasks, functions and modules.
2676 The type and name of the object will be set between the braces.
2677 `verilog-minimum-comment-distance' (default 10)
2678 Minimum distance (in lines) between begin and end required before a comment
2679 will be inserted. Setting this variable to zero results in every
2680 end acquiring a comment; the default avoids too many redundant
2681 comments in tight quarters.
a3a8b002 2682 `verilog-auto-lineup' (default 'declarations)
6341f357
DN
2683 List of contexts where auto lineup of code should be done.
2684
2685Variables controlling other actions:
2686
2687 `verilog-linter' (default surelint)
2688 Unix program to call to run the lint checker. This is the default
2689 command for \\[compile-command] and \\[verilog-auto-save-compile].
2690
2691See \\[customize] for the complete list of variables.
2692
2693AUTO expansion functions are, in part:
2694
2695 \\[verilog-auto] Expand AUTO statements.
2696 \\[verilog-delete-auto] Remove the AUTOs.
2697 \\[verilog-inject-auto] Insert AUTOs for the first time.
2698
2699Some other functions are:
2700
2701 \\[verilog-complete-word] Complete word with appropriate possibilities.
2702 \\[verilog-mark-defun] Mark function.
2703 \\[verilog-beg-of-defun] Move to beginning of current function.
2704 \\[verilog-end-of-defun] Move to end of current function.
2705 \\[verilog-label-be] Label matching begin ... end, fork ... join, etc statements.
2706
2707 \\[verilog-comment-region] Put marked area in a comment.
2708 \\[verilog-uncomment-region] Uncomment an area commented with \\[verilog-comment-region].
495ab0d5 2709 \\[verilog-insert-block] Insert begin ... end.
6341f357
DN
2710 \\[verilog-star-comment] Insert /* ... */.
2711
495ab0d5 2712 \\[verilog-sk-always] Insert an always @(AS) begin .. end block.
6341f357
DN
2713 \\[verilog-sk-begin] Insert a begin .. end block.
2714 \\[verilog-sk-case] Insert a case block, prompting for details.
2715 \\[verilog-sk-for] Insert a for (...) begin .. end block, prompting for details.
2716 \\[verilog-sk-generate] Insert a generate .. endgenerate block.
495ab0d5 2717 \\[verilog-sk-header] Insert a header block at the top of file.
6341f357
DN
2718 \\[verilog-sk-initial] Insert an initial begin .. end block.
2719 \\[verilog-sk-fork] Insert a fork begin .. end .. join block.
2720 \\[verilog-sk-module] Insert a module .. (/*AUTOARG*/);.. endmodule block.
2721 \\[verilog-sk-primitive] Insert a primitive .. (.. );.. endprimitive block.
2722 \\[verilog-sk-repeat] Insert a repeat (..) begin .. end block.
2723 \\[verilog-sk-specify] Insert a specify .. endspecify block.
2724 \\[verilog-sk-task] Insert a task .. begin .. end endtask block.
2725 \\[verilog-sk-while] Insert a while (...) begin .. end block, prompting for details.
2726 \\[verilog-sk-casex] Insert a casex (...) item: begin.. end endcase block, prompting for details.
2727 \\[verilog-sk-casez] Insert a casez (...) item: begin.. end endcase block, prompting for details.
2728 \\[verilog-sk-if] Insert an if (..) begin .. end block.
2729 \\[verilog-sk-else-if] Insert an else if (..) begin .. end block.
2730 \\[verilog-sk-comment] Insert a comment block.
2731 \\[verilog-sk-assign] Insert an assign .. = ..; statement.
2732 \\[verilog-sk-function] Insert a function .. begin .. end endfunction block.
2733 \\[verilog-sk-input] Insert an input declaration, prompting for details.
2734 \\[verilog-sk-output] Insert an output declaration, prompting for details.
2735 \\[verilog-sk-state-machine] Insert a state machine definition, prompting for details.
2736 \\[verilog-sk-inout] Insert an inout declaration, prompting for details.
2737 \\[verilog-sk-wire] Insert a wire declaration, prompting for details.
2738 \\[verilog-sk-reg] Insert a register declaration, prompting for details.
2739 \\[verilog-sk-define-signal] Define signal under point as a register at the top of the module.
2740
2741All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
2742Key bindings specific to `verilog-mode-map' are:
2743
2744\\{verilog-mode-map}"
2745 (interactive)
2746 (kill-all-local-variables)
2747 (use-local-map verilog-mode-map)
2748 (setq major-mode 'verilog-mode)
2749 (setq mode-name "Verilog")
2750 (setq local-abbrev-table verilog-mode-abbrev-table)
60618039 2751 (set (make-local-variable 'beginning-of-defun-function)
6edb5716 2752 'verilog-beg-of-defun)
60618039 2753 (set (make-local-variable 'end-of-defun-function)
6edb5716 2754 'verilog-end-of-defun)
6341f357
DN
2755 (set-syntax-table verilog-mode-syntax-table)
2756 (make-local-variable 'indent-line-function)
2757 (setq indent-line-function 'verilog-indent-line-relative)
2758 (setq comment-indent-function 'verilog-comment-indent)
2759 (make-local-variable 'parse-sexp-ignore-comments)
2760 (setq parse-sexp-ignore-comments nil)
2761 (make-local-variable 'comment-start)
2762 (make-local-variable 'comment-end)
2763 (make-local-variable 'comment-multi-line)
2764 (make-local-variable 'comment-start-skip)
2765 (setq comment-start "// "
2766 comment-end ""
2767 comment-start-skip "/\\*+ *\\|// *"
2768 comment-multi-line nil)
2769 ;; Set up for compilation
2770 (setq verilog-which-tool 1)
2771 (setq verilog-tool 'verilog-linter)
2772 (verilog-set-compile-command)
2773 (when (boundp 'hack-local-variables-hook) ;; Also modify any file-local-variables
2774 (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
2775
2776 ;; Setting up menus
6edb5716 2777 (when (featurep 'xemacs)
7d55bf04
DN
2778 (easy-menu-add verilog-stmt-menu)
2779 (easy-menu-add verilog-menu)
2780 (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
60618039 2781
d63b01e1 2782 ;; Stuff for GNU Emacs
7ea26faf 2783 (set (make-local-variable 'font-lock-defaults)
7664ec44 2784 `((verilog-font-lock-keywords verilog-font-lock-keywords-1
7ea26faf
DN
2785 verilog-font-lock-keywords-2
2786 verilog-font-lock-keywords-3)
7664ec44 2787 nil nil nil
a3a8b002
DN
2788 ,(if (functionp 'syntax-ppss)
2789 ;; verilog-beg-of-defun uses syntax-ppss, and syntax-ppss uses
2790 ;; font-lock-beginning-of-syntax-function, so
2791 ;; font-lock-beginning-of-syntax-function, can't use
7664ec44 2792 ;; verilog-beg-of-defun.
a3a8b002
DN
2793 nil
2794 'verilog-beg-of-defun)))
6341f357
DN
2795 ;;------------------------------------------------------------
2796 ;; now hook in 'verilog-colorize-include-files (eldo-mode.el&spice-mode.el)
2797 ;; all buffer local:
7ea26faf
DN
2798 (when (featurep 'xemacs)
2799 (make-local-hook 'font-lock-mode-hook)
d63b01e1 2800 (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
7ea26faf 2801 (make-local-hook 'after-change-functions))
6341f357 2802 (add-hook 'font-lock-mode-hook 'verilog-colorize-include-files-buffer t t)
d63b01e1 2803 (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-colorize-include-files-buffer t t) ; not in Emacs
6341f357
DN
2804 (add-hook 'after-change-functions 'verilog-colorize-include-files t t)
2805
37ea4b9b 2806 ;; Tell imenu how to handle Verilog.
6341f357
DN
2807 (make-local-variable 'imenu-generic-expression)
2808 (setq imenu-generic-expression verilog-imenu-generic-expression)
9c059794
DN
2809 ;; Tell which-func-modes that imenu knows about verilog
2810 (when (boundp 'which-function-modes)
2811 (add-to-list 'which-func-modes 'verilog-mode))
6341f357 2812 ;; hideshow support
9c059794
DN
2813 (when (boundp 'hs-special-modes-alist)
2814 (unless (assq 'verilog-mode hs-special-modes-alist)
2815 (setq hs-special-modes-alist
2816 (cons '(verilog-mode-mode "\\<begin\\>" "\\<end\\>" nil
2817 verilog-forward-sexp-function)
2818 hs-special-modes-alist))))
6341f357
DN
2819
2820 ;; Stuff for autos
2821 (add-hook 'write-contents-hooks 'verilog-auto-save-check) ; already local
6341f357
DN
2822 (run-hooks 'verilog-mode-hook))
2823\f
2824
2825;;
2826;; Electric functions
2827;;
2828(defun electric-verilog-terminate-line (&optional arg)
2829 "Terminate line and indent next line.
2830With optional ARG, remove existing end of line comments."
2831 (interactive)
2832 ;; before that see if we are in a comment
d63b01e1 2833 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
2834 (cond
2835 ((nth 7 state) ; Inside // comment
2836 (if (eolp)
2837 (progn
2838 (delete-horizontal-space)
2839 (newline))
2840 (progn
2841 (newline)
7ea26faf 2842 (insert "// ")
6341f357
DN
2843 (beginning-of-line)))
2844 (verilog-indent-line))
2845 ((nth 4 state) ; Inside any comment (hence /**/)
2846 (newline)
2847 (verilog-more-comment))
2848 ((eolp)
2849 ;; First, check if current line should be indented
2850 (if (save-excursion
2851 (delete-horizontal-space)
2852 (beginning-of-line)
2853 (skip-chars-forward " \t")
2854 (if (looking-at verilog-auto-end-comment-lines-re)
2855 (let ((indent-str (verilog-indent-line)))
2856 ;; Maybe we should set some endcomments
2857 (if verilog-auto-endcomments
2858 (verilog-set-auto-endcomments indent-str arg))
2859 (end-of-line)
2860 (delete-horizontal-space)
2861 (if arg
2862 ()
2863 (newline))
2864 nil)
2865 (progn
2866 (end-of-line)
2867 (delete-horizontal-space)
60618039 2868 't)))
6341f357
DN
2869 ;; see if we should line up assignments
2870 (progn
a3a8b002
DN
2871 (if (or (eq 'all verilog-auto-lineup)
2872 (eq 'assignments verilog-auto-lineup))
2873 (verilog-pretty-expr t "\\(<\\|:\\)?=" ))
60618039
DN
2874 (newline))
2875 (forward-line 1))
6341f357
DN
2876 ;; Indent next line
2877 (if verilog-auto-indent-on-newline
60618039 2878 (verilog-indent-line)))
6341f357 2879 (t
60618039 2880 (newline)))))
6341f357
DN
2881
2882(defun electric-verilog-terminate-and-indent ()
2883 "Insert a newline and indent for the next statement."
2884 (interactive)
2885 (electric-verilog-terminate-line 1))
2886
2887(defun electric-verilog-semi ()
2888 "Insert `;' character and reindent the line."
2889 (interactive)
a3a8b002 2890 (verilog-insert-last-command-event)
6341f357
DN
2891
2892 (if (or (verilog-in-comment-or-string-p)
2893 (verilog-in-escaped-name-p))
2894 ()
2895 (save-excursion
2896 (beginning-of-line)
2897 (verilog-forward-ws&directives)
60618039 2898 (verilog-indent-line))
6341f357
DN
2899 (if (and verilog-auto-newline
2900 (not (verilog-parenthesis-depth)))
2901 (electric-verilog-terminate-line))))
2902
2903(defun electric-verilog-semi-with-comment ()
2904 "Insert `;' character, reindent the line and indent for comment."
2905 (interactive)
2906 (insert "\;")
2907 (save-excursion
2908 (beginning-of-line)
2909 (verilog-indent-line))
2910 (indent-for-comment))
2911
2912(defun electric-verilog-colon ()
2913 "Insert `:' and do all indentations except line indent on this line."
2914 (interactive)
a3a8b002 2915 (verilog-insert-last-command-event)
6341f357
DN
2916 ;; Do nothing if within string.
2917 (if (or
2918 (verilog-within-string)
2919 (not (verilog-in-case-region-p)))
2920 ()
2921 (save-excursion
2922 (let ((p (point))
2923 (lim (progn (verilog-beg-of-statement) (point))))
2924 (goto-char p)
2925 (verilog-backward-case-item lim)
2926 (verilog-indent-line)))
2927;; (let ((verilog-tab-always-indent nil))
2928;; (verilog-indent-line))
2929 ))
2930
2931;;(defun electric-verilog-equal ()
2932;; "Insert `=', and do indentation if within block."
2933;; (interactive)
a3a8b002 2934;; (verilog-insert-last-command-event)
6341f357
DN
2935;; Could auto line up expressions, but not yet
2936;; (if (eq (car (verilog-calculate-indent)) 'block)
2937;; (let ((verilog-tab-always-indent nil))
2938;; (verilog-indent-command)))
2939;; )
2940
2941(defun electric-verilog-tick ()
2942 "Insert back-tick, and indent to column 0 if this is a CPP directive."
2943 (interactive)
a3a8b002 2944 (verilog-insert-last-command-event)
6341f357 2945 (save-excursion
a3a8b002
DN
2946 (if (verilog-in-directive-p)
2947 (verilog-indent-line))))
6341f357
DN
2948
2949(defun electric-verilog-tab ()
2950 "Function called when TAB is pressed in Verilog mode."
2951 (interactive)
2952 ;; If verilog-tab-always-indent, indent the beginning of the line.
7cb1c4d7
DN
2953 (cond
2954 ;; The region is active, indent it.
2955 ((and (region-active-p)
2956 (not (eq (region-beginning) (region-end))))
2957 (indent-region (region-beginning) (region-end) nil))
2958 ((or verilog-tab-always-indent
2959 (save-excursion
2960 (skip-chars-backward " \t")
2961 (bolp)))
2962 (let* ((oldpnt (point))
2963 (boi-point
2964 (save-excursion
2965 (beginning-of-line)
2966 (skip-chars-forward " \t")
2967 (verilog-indent-line)
2968 (back-to-indentation)
2969 (point))))
2970 (if (< (point) boi-point)
2971 (back-to-indentation)
2972 (cond ((not verilog-tab-to-comment))
2973 ((not (eolp))
2974 (end-of-line))
2975 (t
2976 (indent-for-comment)
2977 (when (and (eolp) (= oldpnt (point)))
6341f357 2978 ; kill existing comment
7cb1c4d7
DN
2979 (beginning-of-line)
2980 (re-search-forward comment-start-skip oldpnt 'move)
2981 (goto-char (match-beginning 0))
2982 (skip-chars-backward " \t")
2983 (kill-region (point) oldpnt)))))))
2984 (t (progn (insert "\t")))))
a3a8b002 2985
6341f357
DN
2986\f
2987
2988;;
2989;; Interactive functions
2990;;
2991
2992(defun verilog-indent-buffer ()
2993 "Indent-region the entire buffer as Verilog code.
2994To call this from the command line, see \\[verilog-batch-indent]."
2995 (interactive)
2996 (verilog-mode)
2997 (indent-region (point-min) (point-max) nil))
2998
2999(defun verilog-insert-block ()
3000 "Insert Verilog begin ... end; block in the code with right indentation."
3001 (interactive)
3002 (verilog-indent-line)
3003 (insert "begin")
3004 (electric-verilog-terminate-line)
3005 (save-excursion
3006 (electric-verilog-terminate-line)
3007 (insert "end")
3008 (beginning-of-line)
3009 (verilog-indent-line)))
3010
3011(defun verilog-star-comment ()
3012 "Insert Verilog star comment at point."
3013 (interactive)
3014 (verilog-indent-line)
3015 (insert "/*")
3016 (save-excursion
3017 (newline)
3018 (insert " */"))
3019 (newline)
3020 (insert " * "))
3021
7ea26faf 3022(defun verilog-insert-1 (fmt max)
60618039 3023 "Use format string FMT to insert integers 0 to MAX - 1.
7ea26faf
DN
3024Inserts one integer per line, at the current column. Stops early
3025if it reaches the end of the buffer."
3026 (let ((col (current-column))
3027 (n 0))
3028 (save-excursion
3029 (while (< n max)
3030 (insert (format fmt n))
3031 (forward-line 1)
3032 ;; Note that this function does not bother to check for lines
3033 ;; shorter than col.
3034 (if (eobp)
3035 (setq n max)
3036 (setq n (1+ n))
3037 (move-to-column col))))))
3038
3039(defun verilog-insert-indices (max)
3040 "Insert a set of indices into a rectangle.
3041The upper left corner is defined by point. Indices begin with 0
3042and extend to the MAX - 1. If no prefix arg is given, the user
3043is prompted for a value. The indices are surrounded by square
3044brackets \[]. For example, the following code with the point
3045located after the first 'a' gives:
6341f357
DN
3046
3047 a = b a[ 0] = b
3048 a = b a[ 1] = b
3049 a = b a[ 2] = b
3050 a = b a[ 3] = b
3051 a = b ==> insert-indices ==> a[ 4] = b
3052 a = b a[ 5] = b
3053 a = b a[ 6] = b
3054 a = b a[ 7] = b
3055 a = b a[ 8] = b"
3056
60618039 3057 (interactive "NMAX: ")
7ea26faf 3058 (verilog-insert-1 "[%3d]" max))
6341f357 3059
7ea26faf 3060(defun verilog-generate-numbers (max)
6341f357
DN
3061 "Insert a set of generated numbers into a rectangle.
3062The upper left corner is defined by point. The numbers are padded to three
3063digits, starting with 000 and extending to (MAX - 1). If no prefix argument
7ea26faf 3064is supplied, then the user is prompted for the MAX number. Consider the
6341f357
DN
3065following code fragment:
3066
7ea26faf
DN
3067 buf buf buf buf000
3068 buf buf buf buf001
3069 buf buf buf buf002
3070 buf buf buf buf003
3071 buf buf ==> generate-numbers ==> buf buf004
3072 buf buf buf buf005
3073 buf buf buf buf006
3074 buf buf buf buf007
3075 buf buf buf buf008"
3076
60618039 3077 (interactive "NMAX: ")
7ea26faf 3078 (verilog-insert-1 "%3.3d" max))
6341f357
DN
3079
3080(defun verilog-mark-defun ()
37ea4b9b 3081 "Mark the current Verilog function (or procedure).
6341f357
DN
3082This puts the mark at the end, and point at the beginning."
3083 (interactive)
7d55bf04
DN
3084 (if (featurep 'xemacs)
3085 (progn
3086 (push-mark (point))
3087 (verilog-end-of-defun)
3088 (push-mark (point))
3089 (verilog-beg-of-defun)
3090 (if (fboundp 'zmacs-activate-region)
3091 (zmacs-activate-region)))
3092 (mark-defun)))
6341f357
DN
3093
3094(defun verilog-comment-region (start end)
3095 ; checkdoc-params: (start end)
3096 "Put the region into a Verilog comment.
3097The comments that are in this area are \"deformed\":
3098`*)' becomes `!(*' and `}' becomes `!{'.
3099These deformed comments are returned to normal if you use
3100\\[verilog-uncomment-region] to undo the commenting.
3101
3102The commented area starts with `verilog-exclude-str-start', and ends with
3103`verilog-exclude-str-end'. But if you change these variables,
3104\\[verilog-uncomment-region] won't recognize the comments."
3105 (interactive "r")
3106 (save-excursion
3107 ;; Insert start and endcomments
3108 (goto-char end)
3109 (if (and (save-excursion (skip-chars-forward " \t") (eolp))
3110 (not (save-excursion (skip-chars-backward " \t") (bolp))))
3111 (forward-line 1)
3112 (beginning-of-line))
3113 (insert verilog-exclude-str-end)
3114 (setq end (point))
3115 (newline)
3116 (goto-char start)
3117 (beginning-of-line)
3118 (insert verilog-exclude-str-start)
3119 (newline)
3120 ;; Replace end-comments within commented area
3121 (goto-char end)
3122 (save-excursion
3123 (while (re-search-backward "\\*/" start t)
3124 (replace-match "*-/" t t)))
3125 (save-excursion
3126 (let ((s+1 (1+ start)))
3127 (while (re-search-backward "/\\*" s+1 t)
60618039 3128 (replace-match "/-*" t t))))))
6341f357
DN
3129
3130(defun verilog-uncomment-region ()
3131 "Uncomment a commented area; change deformed comments back to normal.
3132This command does nothing if the pointer is not in a commented
3133area. See also `verilog-comment-region'."
3134 (interactive)
3135 (save-excursion
3136 (let ((start (point))
3137 (end (point)))
3138 ;; Find the boundaries of the comment
3139 (save-excursion
3140 (setq start (progn (search-backward verilog-exclude-str-start nil t)
3141 (point)))
3142 (setq end (progn (search-forward verilog-exclude-str-end nil t)
3143 (point))))
3144 ;; Check if we're really inside a comment
3145 (if (or (equal start (point)) (<= end (point)))
3146 (message "Not standing within commented area.")
3147 (progn
3148 ;; Remove endcomment
3149 (goto-char end)
3150 (beginning-of-line)
3151 (let ((pos (point)))
3152 (end-of-line)
3153 (delete-region pos (1+ (point))))
3154 ;; Change comments back to normal
3155 (save-excursion
3156 (while (re-search-backward "\\*-/" start t)
3157 (replace-match "*/" t t)))
3158 (save-excursion
3159 (while (re-search-backward "/-\\*" start t)
3160 (replace-match "/*" t t)))
3161 ;; Remove start comment
3162 (goto-char start)
3163 (beginning-of-line)
3164 (let ((pos (point)))
3165 (end-of-line)
3166 (delete-region pos (1+ (point)))))))))
3167
3168(defun verilog-beg-of-defun ()
3169 "Move backward to the beginning of the current function or procedure."
3170 (interactive)
3171 (verilog-re-search-backward verilog-defun-re nil 'move))
3172
3173(defun verilog-end-of-defun ()
3174 "Move forward to the end of the current function or procedure."
3175 (interactive)
3176 (verilog-re-search-forward verilog-end-defun-re nil 'move))
3177
3178(defun verilog-get-beg-of-defun (&optional warn)
3179 (save-excursion
3180 (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
3181 (point))
3182 (t
3183 (error "%s: Can't find module beginning" (verilog-point-text))
3184 (point-max)))))
3185(defun verilog-get-end-of-defun (&optional warn)
3186 (save-excursion
3187 (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
3188 (point))
3189 (t
3190 (error "%s: Can't find endmodule" (verilog-point-text))
3191 (point-max)))))
3192
3193(defun verilog-label-be (&optional arg)
3194 "Label matching begin ... end, fork ... join and case ... endcase statements.
3195With ARG, first kill any existing labels."
3196 (interactive)
3197 (let ((cnt 0)
3198 (oldpos (point))
3199 (b (progn
3200 (verilog-beg-of-defun)
3201 (point-marker)))
3202 (e (progn
3203 (verilog-end-of-defun)
60618039 3204 (point-marker))))
6341f357
DN
3205 (goto-char (marker-position b))
3206 (if (> (- e b) 200)
3207 (message "Relabeling module..."))
3208 (while (and
3209 (> (marker-position e) (point))
3210 (verilog-re-search-forward
3211 (concat
3212 "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
3213 "\\|\\(`endif\\)\\|\\(`else\\)")
3214 nil 'move))
3215 (goto-char (match-beginning 0))
3216 (let ((indent-str (verilog-indent-line)))
3217 (verilog-set-auto-endcomments indent-str 't)
3218 (end-of-line)
60618039 3219 (delete-horizontal-space))
6341f357
DN
3220 (setq cnt (1+ cnt))
3221 (if (= 9 (% cnt 10))
60618039 3222 (message "%d..." cnt)))
6341f357
DN
3223 (goto-char oldpos)
3224 (if (or
3225 (> (- e b) 200)
3226 (> cnt 20))
60618039 3227 (message "%d lines auto commented" cnt))))
6341f357
DN
3228
3229(defun verilog-beg-of-statement ()
3230 "Move backward to beginning of statement."
3231 (interactive)
3232 ;; Move back token by token until we see the end
3233 ;; of some ealier line.
3234 (while
3235 ;; If the current point does not begin a new
3236 ;; statement, as in the character ahead of us is a ';', or SOF
3237 ;; or the string after us unambiguosly starts a statement,
3238 ;; or the token before us unambiguously ends a statement,
3239 ;; then move back a token and test again.
3240 (not (or
3241 (bolp)
3242 (= (preceding-char) ?\;)
a3a8b002 3243 (looking-at "\\w+\\W*:\\W*\\(coverpoint\\|cross\\|constraint\\)")
6341f357
DN
3244 (not (or
3245 (looking-at "\\<")
3246 (forward-word -1)))
3247 (and
3248 (looking-at verilog-extended-complete-re)
3249 (not (save-excursion
3250 (verilog-backward-token)
60618039 3251 (looking-at verilog-extended-complete-re))))
6341f357
DN
3252 (looking-at verilog-basic-complete-re)
3253 (save-excursion
3254 (verilog-backward-token)
3255 (or
3256 (looking-at verilog-end-block-re)
60618039 3257 (looking-at verilog-preprocessor-re)))))
6341f357
DN
3258 (verilog-backward-syntactic-ws)
3259 (verilog-backward-token))
3260 ;; Now point is where the previous line ended.
3261 (verilog-forward-syntactic-ws))
3262
3263(defun verilog-beg-of-statement-1 ()
3264 "Move backward to beginning of statement."
3265 (interactive)
a3a8b002
DN
3266 (if (verilog-in-comment-p)
3267 (verilog-backward-syntactic-ws))
6341f357 3268 (let ((pt (point)))
a3a8b002
DN
3269 (catch 'done
3270 (while (not (looking-at verilog-complete-reg))
3271 (setq pt (point))
3272 (verilog-backward-syntactic-ws)
3273 (if (or (bolp)
3274 (= (preceding-char) ?\;))
3275 (progn
3276 (goto-char pt)
3277 (throw 'done t))
3278 (verilog-backward-token))))
3279 (verilog-forward-syntactic-ws)))
3280;
3281; (while (and
3282; (not (looking-at verilog-complete-reg))
3283; (not (bolp))
3284; (not (= (preceding-char) ?\;)))
3285; (verilog-backward-token)
3286; (verilog-backward-syntactic-ws)
3287; (setq pt (point)))
3288; (goto-char pt)
3289; ;(verilog-forward-syntactic-ws)
6341f357
DN
3290
3291(defun verilog-end-of-statement ()
3292 "Move forward to end of current statement."
3293 (interactive)
3294 (let ((nest 0) pos)
a3a8b002
DN
3295 (cond
3296 ((verilog-in-directive-p)
3297 (forward-line 1)
3298 (backward-char 1))
3299
3300 ((looking-at verilog-beg-block-re)
3301 (verilog-forward-sexp))
3302
3303 ((equal (char-after) ?\})
3304 (forward-char))
3305
3306 ;; Skip to end of statement
3307 ((condition-case nil
3308 (setq pos
3309 (catch 'found
3310 (while t
3311 (forward-sexp 1)
3312 (verilog-skip-forward-comment-or-string)
3313 (if (eolp)
3314 (forward-line 1))
3315 (cond ((looking-at "[ \t]*;")
3316 (skip-chars-forward "^;")
3317 (forward-char 1)
3318 (throw 'found (point)))
3319 ((save-excursion
3320 (forward-sexp -1)
3321 (looking-at verilog-beg-block-re))
3322 (goto-char (match-beginning 0))
3323 (throw 'found nil))
3324 ((looking-at "[ \t]*)")
3325 (throw 'found (point)))
3326 ((eobp)
3327 (throw 'found (point)))
3328 )))
3329
3330 )
3331 (error nil))
3332 (if (not pos)
3333 ;; Skip a whole block
3334 (catch 'found
3335 (while t
3336 (verilog-re-search-forward verilog-end-statement-re nil 'move)
3337 (setq nest (if (match-end 1)
3338 (1+ nest)
3339 (1- nest)))
3340 (cond ((eobp)
3341 (throw 'found (point)))
3342 ((= 0 nest)
3343 (throw 'found (verilog-end-of-statement))))))
3344 pos)))))
6341f357
DN
3345
3346(defun verilog-in-case-region-p ()
37ea4b9b
JB
3347 "Return true if in a case region.
3348More specifically, point @ in the line foo : @ begin"
6341f357
DN
3349 (interactive)
3350 (save-excursion
3351 (if (and
3352 (progn (verilog-forward-syntactic-ws)
3353 (looking-at "\\<begin\\>"))
3354 (progn (verilog-backward-syntactic-ws)
3355 (= (preceding-char) ?\:)))
3356 (catch 'found
3357 (let ((nest 1))
3358 (while t
3359 (verilog-re-search-backward
3360 (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
3361 "\\(\\<endcase\\>\\)\\>")
3362 nil 'move)
3363 (cond
3364 ((match-end 3)
3365 (setq nest (1+ nest)))
3366 ((match-end 2)
3367 (if (= nest 1)
3368 (throw 'found 1))
3369 (setq nest (1- nest)))
3370 (t
60618039 3371 (throw 'found (= nest 0)))))))
6341f357
DN
3372 nil)))
3373(defun verilog-in-struct-region-p ()
37ea4b9b
JB
3374 "Return true if in a struct region.
3375More specifically, in a list after a struct|union keyword."
6341f357
DN
3376 (interactive)
3377 (save-excursion
d63b01e1 3378 (let* ((state (verilog-syntax-ppss))
6341f357
DN
3379 (depth (nth 0 state)))
3380 (if depth
3381 (progn (backward-up-list depth)
3382 (verilog-beg-of-statement)
60618039 3383 (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>"))))))
6341f357
DN
3384
3385(defun verilog-in-generate-region-p ()
37ea4b9b
JB
3386 "Return true if in a generate region.
3387More specifically, after a generate and before an endgenerate."
6341f357 3388 (interactive)
a3a8b002 3389 (let ((nest 1))
6341f357 3390 (save-excursion
a3a8b002
DN
3391 (catch 'done
3392 (while (and
3393 (/= nest 0)
3394 (verilog-re-search-backward
3395 "\\<\\(module\\)\\|\\(generate\\)\\|\\(endgenerate\\)\\>" nil 'move)
3396 (cond
3397 ((match-end 1) ; module - we have crawled out
3398 (throw 'done 1))
3399 ((match-end 2) ; generate
3400 (setq nest (1- nest)))
3401 ((match-end 3) ; endgenerate
3402 (setq nest (1+ nest))))))))
6341f357
DN
3403 (= nest 0) )) ; return nest
3404
3405(defun verilog-in-fork-region-p ()
3406 "Return true if between a fork and join."
3407 (interactive)
3408 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
60618039 3409 (nest 1))
6341f357
DN
3410 (save-excursion
3411 (while (and
3412 (/= nest 0)
3413 (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
3414 (cond
3415 ((match-end 1) ; fork
3416 (setq nest (1- nest)))
3417 ((match-end 2) ; join
60618039 3418 (setq nest (1+ nest)))))))
6341f357
DN
3419 (= nest 0) )) ; return nest
3420
3421(defun verilog-backward-case-item (lim)
3422 "Skip backward to nearest enclosing case item.
3423Limit search to point LIM."
3424 (interactive)
3425 (let ((str 'nil)
3426 (lim1
3427 (progn
3428 (save-excursion
3429 (verilog-re-search-backward verilog-endcomment-reason-re
3430 lim 'move)
3431 (point)))))
3432 ;; Try to find the real :
3433 (if (save-excursion (search-backward ":" lim1 t))
3434 (let ((colon 0)
3435 b e )
3436 (while
3437 (and
3438 (< colon 1)
3439 (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
3440 lim1 'move))
3441 (cond
3442 ((match-end 1) ;; [
3443 (setq colon (1+ colon))
3444 (if (>= colon 0)
3445 (error "%s: unbalanced [" (verilog-point-text))))
3446 ((match-end 2) ;; ]
3447 (setq colon (1- colon)))
3448
3449 ((match-end 3) ;; :
60618039 3450 (setq colon (1+ colon)))))
6341f357
DN
3451 ;; Skip back to beginning of case item
3452 (skip-chars-backward "\t ")
3453 (verilog-skip-backward-comment-or-string)
3454 (setq e (point))
3455 (setq b
3456 (progn
3457 (if
3458 (verilog-re-search-backward
3459 "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
3460 (progn
3461 (cond
3462 ((match-end 1)
3463 (goto-char (match-end 1))
3464 (verilog-forward-ws&directives)
3465 (if (looking-at "(")
3466 (progn
3467 (forward-sexp)
3468 (verilog-forward-ws&directives)))
3469 (point))
3470 (t
3471 (goto-char (match-end 0))
3472 (verilog-forward-ws&directives)
60618039
DN
3473 (point))))
3474 (error "Malformed case item"))))
6341f357
DN
3475 (setq str (buffer-substring b e))
3476 (if
3477 (setq e
3478 (string-match
3479 "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3480 (setq str (concat (substring str 0 e) "...")))
3481 str)
3482 'nil)))
3483\f
3484
3485;;
3486;; Other functions
3487;;
3488
6ca0ff73 3489(defun verilog-kill-existing-comment ()
6341f357
DN
3490 "Kill auto comment on this line."
3491 (save-excursion
3492 (let* (
3493 (e (progn
3494 (end-of-line)
3495 (point)))
3496 (b (progn
3497 (beginning-of-line)
3498 (search-forward "//" e t))))
3499 (if b
3500 (delete-region (- b 2) e)))))
3501
3502(defconst verilog-directive-nest-re
3503 (concat "\\(`else\\>\\)\\|"
3504 "\\(`endif\\>\\)\\|"
3505 "\\(`if\\>\\)\\|"
3506 "\\(`ifdef\\>\\)\\|"
3507 "\\(`ifndef\\>\\)"))
3508(defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
3509 "Add ending comment with given INDENT-STR.
3510With KILL-EXISTING-COMMENT, remove what was there before.
3511Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
3512Insert `// case expr ' if this line ends a case block.
3513Insert `// ifdef FOO ' if this line ends code conditional on FOO.
37ea4b9b
JB
3514Insert `// NAME ' if this line ends a function, task, module,
3515primitive or interface named NAME."
6341f357
DN
3516 (save-excursion
3517 (cond
3518 (; Comment close preprocessor directives
3519 (and
3520 (looking-at "\\(`endif\\)\\|\\(`else\\)")
3521 (or kill-existing-comment
3522 (not (save-excursion
3523 (end-of-line)
3524 (search-backward "//" (verilog-get-beg-of-line) t)))))
3525 (let ((nest 1) b e
3526 m
60618039 3527 (else (if (match-end 2) "!" " ")))
6341f357
DN
3528 (end-of-line)
3529 (if kill-existing-comment
6ca0ff73 3530 (verilog-kill-existing-comment))
6341f357
DN
3531 (delete-horizontal-space)
3532 (save-excursion
3533 (backward-sexp 1)
3534 (while (and (/= nest 0)
3535 (verilog-re-search-backward verilog-directive-nest-re nil 'move))
3536 (cond
3537 ((match-end 1) ; `else
3538 (if (= nest 1)
3539 (setq else "!")))
3540 ((match-end 2) ; `endif
3541 (setq nest (1+ nest)))
3542 ((match-end 3) ; `if
3543 (setq nest (1- nest)))
3544 ((match-end 4) ; `ifdef
3545 (setq nest (1- nest)))
3546 ((match-end 5) ; `ifndef
60618039 3547 (setq nest (1- nest)))))
6341f357
DN
3548 (if (match-end 0)
3549 (setq
3550 m (buffer-substring
3551 (match-beginning 0)
3552 (match-end 0))
3553 b (progn
3554 (skip-chars-forward "^ \t")
3555 (verilog-forward-syntactic-ws)
3556 (point))
3557 e (progn
3558 (skip-chars-forward "a-zA-Z0-9_")
60618039 3559 (point)))))
6341f357
DN
3560 (if b
3561 (if (> (count-lines (point) b) verilog-minimum-comment-distance)
3562 (insert (concat " // " else m " " (buffer-substring b e))))
3563 (progn
3564 (insert " // unmatched `else or `endif")
60618039 3565 (ding 't)))))
6341f357
DN
3566
3567 (; Comment close case/class/function/task/module and named block
3568 (and (looking-at "\\<end")
3569 (or kill-existing-comment
3570 (not (save-excursion
3571 (end-of-line)
3572 (search-backward "//" (verilog-get-beg-of-line) t)))))
3573 (let ((type (car indent-str)))
3574 (unless (eq type 'declaration)
3575 (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
3576 (if (looking-at verilog-end-block-ordered-re)
3577 (cond
3578 (;- This is a case block; search back for the start of this case
3579 (match-end 1) ;; of verilog-end-block-ordered-re
3580
3581 (let ((err 't)
3582 (str "UNMATCHED!!"))
3583 (save-excursion
3584 (verilog-leap-to-head)
3585 (cond
3586 ((looking-at "\\<randcase\\>")
3587 (setq str "randcase")
7ea26faf 3588 (setq err nil))
a3a8b002
DN
3589 ((looking-at "\\(\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?\\)")
3590 (goto-char (match-end 0))
3591 (setq str (concat (match-string 0) " " (verilog-get-expr)))
3592 (setq err nil))
3593 ))
6341f357
DN
3594 (end-of-line)
3595 (if kill-existing-comment
6ca0ff73 3596 (verilog-kill-existing-comment))
6341f357
DN
3597 (delete-horizontal-space)
3598 (insert (concat " // " str ))
7ea26faf 3599 (if err (ding 't))))
6341f357
DN
3600
3601 (;- This is a begin..end block
3602 (match-end 2) ;; of verilog-end-block-ordered-re
3603 (let ((str " // UNMATCHED !!")
3604 (err 't)
3605 (here (point))
3606 there
60618039 3607 cntx)
6341f357
DN
3608 (save-excursion
3609 (verilog-leap-to-head)
3610 (setq there (point))
3611 (if (not (match-end 0))
3612 (progn
3613 (goto-char here)
3614 (end-of-line)
3615 (if kill-existing-comment
6ca0ff73 3616 (verilog-kill-existing-comment))
6341f357
DN
3617 (delete-horizontal-space)
3618 (insert str)
60618039 3619 (ding 't))
6341f357
DN
3620 (let ((lim
3621 (save-excursion (verilog-beg-of-defun) (point)))
60618039 3622 (here (point)))
6341f357
DN
3623 (cond
3624 (;-- handle named block differently
3625 (looking-at verilog-named-block-re)
3626 (search-forward ":")
3627 (setq there (point))
3628 (setq str (verilog-get-expr))
3629 (setq err nil)
3630 (setq str (concat " // block: " str )))
3631
3632 ((verilog-in-case-region-p) ;-- handle case item differently
3633 (goto-char here)
3634 (setq str (verilog-backward-case-item lim))
3635 (setq there (point))
3636 (setq err nil)
3637 (setq str (concat " // case: " str )))
3638
3639 (;- try to find "reason" for this begin
3640 (cond
3641 (;
3642 (eq here (progn
3643 (verilog-backward-token)
3644 (verilog-beg-of-statement-1)
3645 (point)))
3646 (setq err nil)
3647 (setq str ""))
3648 ((looking-at verilog-endcomment-reason-re)
3649 (setq there (match-end 0))
a3a8b002 3650 (setq cntx (concat (match-string 0) " "))
6341f357
DN
3651 (cond
3652 (;- begin
a3a8b002 3653 (match-end 1)
6341f357
DN
3654 (setq err nil)
3655 (save-excursion
3656 (if (and (verilog-continued-line)
3657 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
3658 (progn
3659 (goto-char (match-end 0))
3660 (setq there (point))
3661 (setq str
a3a8b002 3662 (concat " // " (match-string 0) " " (verilog-get-expr))))
6341f357
DN
3663 (setq str ""))))
3664
3665 (;- else
a3a8b002 3666 (match-end 2)
6341f357 3667 (let ((nest 0)
60618039 3668 ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
6341f357
DN
3669 (catch 'skip
3670 (while (verilog-re-search-backward reg nil 'move)
3671 (cond
3672 ((match-end 1) ; begin
3673 (setq nest (1- nest)))
3674 ((match-end 2) ; end
3675 (setq nest (1+ nest)))
3676 ((match-end 3)
3677 (if (= 0 nest)
3678 (progn
3679 (goto-char (match-end 0))
3680 (setq there (point))
3681 (setq err nil)
3682 (setq str (verilog-get-expr))
3683 (setq str (concat " // else: !if" str ))
60618039 3684 (throw 'skip 1)))))))))
6341f357
DN
3685
3686 (;- end else
a3a8b002 3687 (match-end 3)
6341f357
DN
3688 (goto-char there)
3689 (let ((nest 0)
60618039 3690 (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
6341f357
DN
3691 (catch 'skip
3692 (while (verilog-re-search-backward reg nil 'move)
3693 (cond
3694 ((match-end 1) ; begin
3695 (setq nest (1- nest)))
3696 ((match-end 2) ; end
3697 (setq nest (1+ nest)))
3698 ((match-end 3)
3699 (if (= 0 nest)
3700 (progn
3701 (goto-char (match-end 0))
3702 (setq there (point))
3703 (setq err nil)
3704 (setq str (verilog-get-expr))
3705 (setq str (concat " // else: !if" str ))
60618039 3706 (throw 'skip 1)))))))))
a3a8b002
DN
3707 (; always_comb, always_ff, always_latch
3708 (or (match-end 4) (match-end 5) (match-end 6))
3709 (goto-char (match-end 0))
3710 (setq there (point))
3711 (setq err nil)
3712 (setq str (concat " // " cntx )))
6341f357
DN
3713
3714 (;- task/function/initial et cetera
3715 t
3716 (match-end 0)
3717 (goto-char (match-end 0))
3718 (setq there (point))
3719 (setq err nil)
a3a8b002 3720 (setq str (concat " // " cntx (verilog-get-expr))))
6341f357
DN
3721
3722 (;-- otherwise...
60618039 3723 (setq str " // auto-endcomment confused "))))
6341f357
DN
3724
3725 ((and
3726 (verilog-in-case-region-p) ;-- handle case item differently
3727 (progn
3728 (setq there (point))
3729 (goto-char here)
3730 (setq str (verilog-backward-case-item lim))))
3731 (setq err nil)
3732 (setq str (concat " // case: " str )))
3733
3734 ((verilog-in-fork-region-p)
3735 (setq err nil)
3736 (setq str " // fork branch" ))
3737
3738 ((looking-at "\\<end\\>")
3739 ;; HERE
3740 (forward-word 1)
3741 (verilog-forward-syntactic-ws)
3742 (setq err nil)
3743 (setq str (verilog-get-expr))
3744 (setq str (concat " // " cntx str )))
3745
3746 ))))
3747 (goto-char here)
3748 (end-of-line)
3749 (if kill-existing-comment
6ca0ff73 3750 (verilog-kill-existing-comment))
6341f357
DN
3751 (delete-horizontal-space)
3752 (if (or err
3753 (> (count-lines here there) verilog-minimum-comment-distance))
3754 (insert str))
3755 (if err (ding 't))
3756 ))))
3757 (;- this is endclass, which can be nested
3758 (match-end 11) ;; of verilog-end-block-ordered-re
3759 ;;(goto-char there)
3760 (let ((nest 0)
60618039
DN
3761 (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
3762 string)
6341f357
DN
3763 (save-excursion
3764 (catch 'skip
3765 (while (verilog-re-search-backward reg nil 'move)
3766 (cond
3767 ((match-end 3) ; endclass
3768 (ding 't)
3769 (setq string "unmatched endclass")
3770 (throw 'skip 1))
3771
3772 ((match-end 2) ; endclass
3773 (setq nest (1+ nest)))
3774
3775 ((match-end 1) ; class
3776 (setq nest (1- nest))
3777 (if (< nest 0)
3778 (progn
3779 (goto-char (match-end 0))
3780 (let (b e)
3781 (setq b (progn
3782 (skip-chars-forward "^ \t")
3783 (verilog-forward-ws&directives)
3784 (point))
3785 e (progn
3786 (skip-chars-forward "a-zA-Z0-9_")
3787 (point)))
3788 (setq string (buffer-substring b e)))
3789 (throw 'skip 1))))
3790 ))))
3791 (end-of-line)
60618039 3792 (insert (concat " // " string ))))
6341f357
DN
3793
3794 (;- this is end{function,generate,task,module,primitive,table,generate}
3795 ;- which can not be nested.
3796 t
9c059794 3797 (let (string reg (name-re nil))
6341f357
DN
3798 (end-of-line)
3799 (if kill-existing-comment
3800 (save-match-data
6ca0ff73 3801 (verilog-kill-existing-comment)))
6341f357
DN
3802 (delete-horizontal-space)
3803 (backward-sexp)
3804 (cond
3805 ((match-end 5) ;; of verilog-end-block-ordered-re
3806 (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
9c059794
DN
3807 (setq name-re "\\w+\\s-*(")
3808 )
6341f357
DN
3809 ((match-end 6) ;; of verilog-end-block-ordered-re
3810 (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
3811 ((match-end 7) ;; of verilog-end-block-ordered-re
3812 (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
3813 ((match-end 8) ;; of verilog-end-block-ordered-re
3814 (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3815 ((match-end 9) ;; of verilog-end-block-ordered-re
3816 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
3817 ((match-end 10) ;; of verilog-end-block-ordered-re
3818 (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3819 ((match-end 11) ;; of verilog-end-block-ordered-re
3820 (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3821 ((match-end 12) ;; of verilog-end-block-ordered-re
3822 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3823 ((match-end 13) ;; of verilog-end-block-ordered-re
3824 (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3825 ((match-end 14) ;; of verilog-end-block-ordered-re
3826 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3827 ((match-end 15) ;; of verilog-end-block-ordered-re
3828 (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
3829
60618039 3830 (t (error "Problem in verilog-set-auto-endcomments")))
6341f357
DN
3831 (let (b e)
3832 (save-excursion
3833 (verilog-re-search-backward reg nil 'move)
3834 (cond
3835 ((match-end 1)
3836 (setq b (progn
3837 (skip-chars-forward "^ \t")
3838 (verilog-forward-ws&directives)
9c059794 3839 (if (and name-re (verilog-re-search-forward name-re nil 'move))
6341f357 3840 (progn
9c059794 3841 (goto-char (match-beginning 0))
60618039 3842 (verilog-forward-ws&directives)))
6341f357
DN
3843 (point))
3844 e (progn
3845 (skip-chars-forward "a-zA-Z0-9_")
3846 (point)))
3847 (setq string (buffer-substring b e)))
3848 (t
3849 (ding 't)
3850 (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
3851 (end-of-line)
3852 (insert (concat " // " string )))
3853 ))))))))))
3854
3855(defun verilog-get-expr()
37ea4b9b 3856 "Grab expression at point, e.g, case ( a | b & (c ^d))."
6341f357
DN
3857 (let* ((b (progn
3858 (verilog-forward-syntactic-ws)
3859 (skip-chars-forward " \t")
3860 (point)))
3861 (e (let ((par 1))
3862 (cond
3863 ((looking-at "@")
3864 (forward-char 1)
3865 (verilog-forward-syntactic-ws)
3866 (if (looking-at "(")
3867 (progn
3868 (forward-char 1)
3869 (while (and (/= par 0)
3870 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3871 (cond
3872 ((match-end 1)
3873 (setq par (1+ par)))
3874 ((match-end 2)
3875 (setq par (1- par)))))))
3876 (point))
3877 ((looking-at "(")
3878 (forward-char 1)
3879 (while (and (/= par 0)
3880 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3881 (cond
3882 ((match-end 1)
3883 (setq par (1+ par)))
3884 ((match-end 2)
3885 (setq par (1- par)))))
3886 (point))
3887 ((looking-at "\\[")
3888 (forward-char 1)
3889 (while (and (/= par 0)
3890 (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
3891 (cond
3892 ((match-end 1)
3893 (setq par (1+ par)))
3894 ((match-end 2)
3895 (setq par (1- par)))))
3896 (verilog-forward-syntactic-ws)
3897 (skip-chars-forward "^ \t\n\f")
3898 (point))
3899 ((looking-at "/[/\\*]")
3900 b)
3901 ('t
3902 (skip-chars-forward "^: \t\n\f")
60618039 3903 (point)))))
6341f357
DN
3904 (str (buffer-substring b e)))
3905 (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3906 (setq str (concat (substring str 0 e) "...")))
3907 str))
3908
3909(defun verilog-expand-vector ()
3910 "Take a signal vector on the current line and expand it to multiple lines.
3911Useful for creating tri's and other expanded fields."
3912 (interactive)
3913 (verilog-expand-vector-internal "[" "]"))
3914
3915(defun verilog-expand-vector-internal (bra ket)
3916 "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
3917 (save-excursion
3918 (forward-line 0)
3919 (let ((signal-string (buffer-substring (point)
3920 (progn
3921 (end-of-line) (point)))))
7ea26faf
DN
3922 (if (string-match
3923 (concat "\\(.*\\)"
3924 (regexp-quote bra)
3925 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
60618039
DN
3926 (regexp-quote ket)
3927 "\\(.*\\)$") signal-string)
6341f357 3928 (let* ((sig-head (match-string 1 signal-string))
7ea26faf 3929 (vec-start (string-to-number (match-string 2 signal-string)))
6341f357
DN
3930 (vec-end (if (= (match-beginning 3) (match-end 3))
3931 vec-start
7ea26faf
DN
3932 (string-to-number
3933 (substring signal-string (1+ (match-beginning 3))
3934 (match-end 3)))))
3935 (vec-range
3936 (if (= (match-beginning 4) (match-end 4))
3937 1
3938 (string-to-number
3939 (substring signal-string (+ 2 (match-beginning 4))
3940 (match-end 4)))))
6341f357
DN
3941 (sig-tail (match-string 5 signal-string))
3942 vec)
3943 ;; Decode vectors
3944 (setq vec nil)
3945 (if (< vec-range 0)
3946 (let ((tmp vec-start))
3947 (setq vec-start vec-end
3948 vec-end tmp
3949 vec-range (- vec-range))))
3950 (if (< vec-end vec-start)
3951 (while (<= vec-end vec-start)
3952 (setq vec (append vec (list vec-start)))
3953 (setq vec-start (- vec-start vec-range)))
3954 (while (<= vec-start vec-end)
3955 (setq vec (append vec (list vec-start)))
3956 (setq vec-start (+ vec-start vec-range))))
3957 ;;
3958 ;; Delete current line
3959 (delete-region (point) (progn (forward-line 0) (point)))
3960 ;;
3961 ;; Expand vector
3962 (while vec
7ea26faf
DN
3963 (insert (concat sig-head bra
3964 (int-to-string (car vec)) ket sig-tail "\n"))
6341f357
DN
3965 (setq vec (cdr vec)))
3966 (delete-char -1)
3967 ;;
3968 )))))
3969
3970(defun verilog-strip-comments ()
37ea4b9b 3971 "Strip all comments from the Verilog code."
6341f357
DN
3972 (interactive)
3973 (goto-char (point-min))
3974 (while (re-search-forward "//" nil t)
3975 (if (verilog-within-string)
3976 (re-search-forward "\"" nil t)
3977 (if (verilog-in-star-comment-p)
3978 (re-search-forward "\*/" nil t)
3979 (let ((bpt (- (point) 2)))
3980 (end-of-line)
3981 (delete-region bpt (point))))))
3982 ;;
3983 (goto-char (point-min))
3984 (while (re-search-forward "/\\*" nil t)
3985 (if (verilog-within-string)
3986 (re-search-forward "\"" nil t)
3987 (let ((bpt (- (point) 2)))
3988 (re-search-forward "\\*/")
3989 (delete-region bpt (point))))))
3990
3991(defun verilog-one-line ()
37ea4b9b 3992 "Convert structural Verilog instances to occupy one line."
6341f357
DN
3993 (interactive)
3994 (goto-char (point-min))
3995 (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
3996 (replace-match "\\1 " nil nil)))
3997
3998(defun verilog-linter-name ()
3999 "Return name of linter, either surelint or verilint."
4000 (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4001 compile-command))
4002 (lint-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4003 verilog-linter)))
4004 (cond ((equal compile-word1 "surelint") `surelint)
4005 ((equal compile-word1 "verilint") `verilint)
4006 ((equal lint-word1 "surelint") `surelint)
4007 ((equal lint-word1 "verilint") `verilint)
4008 (t `surelint)))) ;; back compatibility
4009
4010(defun verilog-lint-off ()
4011 "Convert a Verilog linter warning line into a disable statement.
4012For example:
4013 pci_bfm_null.v, line 46: Unused input: pci_rst_
4014becomes a comment for the appropriate tool.
4015
4016The first word of the `compile-command' or `verilog-linter'
37ea4b9b 4017variables is used to determine which product is being used.
6341f357
DN
4018
4019See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
4020 (interactive)
4021 (let ((linter (verilog-linter-name)))
4022 (cond ((equal linter `surelint)
4023 (verilog-surelint-off))
4024 ((equal linter `verilint)
4025 (verilog-verilint-off))
4026 (t (error "Linter name not set")))))
4027
7ea26faf 4028(defvar compilation-last-buffer)
a3a8b002 4029(defvar next-error-last-buffer)
7ea26faf 4030
6341f357
DN
4031(defun verilog-surelint-off ()
4032 "Convert a SureLint warning line into a disable statement.
4033Run from Verilog source window; assumes there is a *compile* buffer
4034with point set appropriately.
4035
4036For example:
4037 WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
4038becomes:
4039 // surefire lint_line_off UDDONX"
4040 (interactive)
7ea26faf
DN
4041 (let ((buff (if (boundp 'next-error-last-buffer)
4042 next-error-last-buffer
4043 compilation-last-buffer)))
4044 (when (buffer-live-p buff)
4045 ;; FIXME with-current-buffer?
4046 (save-excursion
4047 (switch-to-buffer buff)
4048 (beginning-of-line)
4049 (when
4050 (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
4051 (let* ((code (match-string 2))
4052 (file (match-string 3))
4053 (line (match-string 4))
4054 (buffer (get-file-buffer file))
4055 dir filename)
4056 (unless buffer
4057 (progn
4058 (setq buffer
4059 (and (file-exists-p file)
4060 (find-file-noselect file)))
4061 (or buffer
4062 (let* ((pop-up-windows t))
4063 (let ((name (expand-file-name
4064 (read-file-name
4065 (format "Find this error in: (default %s) "
4066 file)
4067 dir file t))))
4068 (if (file-directory-p name)
4069 (setq name (expand-file-name filename name)))
4070 (setq buffer
4071 (and (file-exists-p name)
4072 (find-file-noselect name))))))))
4073 (switch-to-buffer buffer)
4074 (goto-line (string-to-number line))
4075 (end-of-line)
4076 (catch 'already
4077 (cond
4078 ((verilog-in-slash-comment-p)
4079 (re-search-backward "//")
4080 (cond
4081 ((looking-at "// surefire lint_off_line ")
4082 (goto-char (match-end 0))
4083 (let ((lim (save-excursion (end-of-line) (point))))
4084 (if (re-search-forward code lim 'move)
4085 (throw 'already t)
4086 (insert (concat " " code)))))
4087 (t
4088 )))
4089 ((verilog-in-star-comment-p)
4090 (re-search-backward "/\*")
60618039 4091 (insert (format " // surefire lint_off_line %6s" code )))
7ea26faf
DN
4092 (t
4093 (insert (format " // surefire lint_off_line %6s" code ))
4094 )))))))))
6341f357
DN
4095
4096(defun verilog-verilint-off ()
4097 "Convert a Verilint warning line into a disable statement.
4098
4099For example:
4100 (W240) pci_bfm_null.v, line 46: Unused input: pci_rst_
4101becomes:
4102 //Verilint 240 off // WARNING: Unused input"
4103 (interactive)
4104 (save-excursion
4105 (beginning-of-line)
4106 (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
4107 (replace-match (format
4108 ;; %3s makes numbers 1-999 line up nicely
4109 "\\1//Verilint %3s off // WARNING: \\3"
4110 (match-string 2)))
4111 (beginning-of-line)
4112 (verilog-indent-line))))
4113
4114(defun verilog-auto-save-compile ()
4115 "Update automatics with \\[verilog-auto], save the buffer, and compile."
4116 (interactive)
4117 (verilog-auto) ; Always do it for safety
4118 (save-buffer)
4119 (compile compile-command))
4120
4121\f
4122
4123;;
4124;; Batch
4125;;
4126
4127(defmacro verilog-batch-error-wrapper (&rest body)
4128 "Execute BODY and add error prefix to any errors found.
4129This lets programs calling batch mode to easily extract error messages."
6edb5716
DN
4130 `(condition-case err
4131 (progn ,@body)
4132 (error
4133 (error "%%Error: %s%s" (error-message-string err)
d63b01e1 4134 (if (featurep 'xemacs) "\n" ""))))) ;; XEmacs forgets to add a newline
6341f357
DN
4135
4136(defun verilog-batch-execute-func (funref)
4137 "Internal processing of a batch command, running FUNREF on all command arguments."
4138 (verilog-batch-error-wrapper
4139 ;; General globals needed
4140 (setq make-backup-files nil)
4141 (setq-default make-backup-files nil)
4142 (setq enable-local-variables t)
4143 (setq enable-local-eval t)
4144 ;; Make sure any sub-files we read get proper mode
4145 (setq default-major-mode `verilog-mode)
4146 ;; Ditto files already read in
7ea26faf 4147 (mapc (lambda (buf)
60618039
DN
4148 (when (buffer-file-name buf)
4149 (save-excursion
4150 (set-buffer buf)
4151 (verilog-mode))))
4152 (buffer-list))
6341f357
DN
4153 ;; Process the files
4154 (mapcar '(lambda (buf)
4155 (when (buffer-file-name buf)
4156 (save-excursion
4157 (if (not (file-exists-p (buffer-file-name buf)))
7ea26faf
DN
4158 (error
4159 (concat "File not found: " (buffer-file-name buf))))
6341f357
DN
4160 (message (concat "Processing " (buffer-file-name buf)))
4161 (set-buffer buf)
4162 (funcall funref)
4163 (save-buffer))))
4164 (buffer-list))))
4165
4166(defun verilog-batch-auto ()
4167 "For use with --batch, perform automatic expansions as a stand-alone tool.
37ea4b9b 4168This sets up the appropriate Verilog mode environment, updates automatics
6341f357
DN
4169with \\[verilog-auto] on all command-line files, and saves the buffers.
4170For proper results, multiple filenames need to be passed on the command
4171line in bottom-up order."
4172 (unless noninteractive
4173 (error "Use verilog-batch-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4174 (verilog-batch-execute-func `verilog-auto))
4175
4176(defun verilog-batch-delete-auto ()
4177 "For use with --batch, perform automatic deletion as a stand-alone tool.
37ea4b9b 4178This sets up the appropriate Verilog mode environment, deletes automatics
6341f357
DN
4179with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
4180 (unless noninteractive
4181 (error "Use verilog-batch-delete-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4182 (verilog-batch-execute-func `verilog-delete-auto))
4183
4184(defun verilog-batch-inject-auto ()
4185 "For use with --batch, perform automatic injection as a stand-alone tool.
37ea4b9b 4186This sets up the appropriate Verilog mode environment, injects new automatics
6341f357
DN
4187with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
4188For proper results, multiple filenames need to be passed on the command
4189line in bottom-up order."
4190 (unless noninteractive
4191 (error "Use verilog-batch-inject-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4192 (verilog-batch-execute-func `verilog-inject-auto))
4193
4194(defun verilog-batch-indent ()
4195 "For use with --batch, reindent an a entire file as a stand-alone tool.
37ea4b9b 4196This sets up the appropriate Verilog mode environment, calls
6341f357
DN
4197\\[verilog-indent-buffer] on all command-line files, and saves the buffers."
4198 (unless noninteractive
4199 (error "Use verilog-batch-indent only with --batch")) ;; Otherwise we'd mess up buffer modes
4200 (verilog-batch-execute-func `verilog-indent-buffer))
4201\f
4202
4203;;
4204;; Indentation
4205;;
4206(defconst verilog-indent-alist
4207 '((block . (+ ind verilog-indent-level))
4208 (case . (+ ind verilog-case-indent))
4209 (cparenexp . (+ ind verilog-indent-level))
4210 (cexp . (+ ind verilog-cexp-indent))
4211 (defun . verilog-indent-level-module)
4212 (declaration . verilog-indent-level-declaration)
4213 (directive . (verilog-calculate-indent-directive))
4214 (tf . verilog-indent-level)
4215 (behavioral . (+ verilog-indent-level-behavioral verilog-indent-level-module))
4216 (statement . ind)
4217 (cpp . 0)
4218 (comment . (verilog-comment-indent))
4219 (unknown . 3)
4220 (string . 0)))
4221
4222(defun verilog-continued-line-1 (lim)
4223 "Return true if this is a continued line.
4224Set point to where line starts. Limit search to point LIM."
4225 (let ((continued 't))
4226 (if (eq 0 (forward-line -1))
4227 (progn
4228 (end-of-line)
4229 (verilog-backward-ws&directives lim)
4230 (if (bobp)
4231 (setq continued nil)
4232 (setq continued (verilog-backward-token))))
4233 (setq continued nil))
4234 continued))
4235
4236(defun verilog-calculate-indent ()
4237 "Calculate the indent of the current Verilog line.
4238Examine previous lines. Once a line is found that is definitive as to the
37ea4b9b
JB
4239type of the current line, return that lines' indent level and its type.
4240Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
6341f357
DN
4241 (save-excursion
4242 (let* ((starting_position (point))
4243 (par 0)
4244 (begin (looking-at "[ \t]*begin\\>"))
4245 (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
4246 (type (catch 'nesting
4247 ;; Keep working backwards until we can figure out
4248 ;; what type of statement this is.
4249 ;; Basically we need to figure out
4250 ;; 1) if this is a continuation of the previous line;
4251 ;; 2) are we in a block scope (begin..end)
4252
4253 ;; if we are in a comment, done.
4254 (if (verilog-in-star-comment-p)
4255 (throw 'nesting 'comment))
4256
4257 ;; if we have a directive, done.
a3a8b002
DN
4258 (if (save-excursion (beginning-of-line)
4259 (and (looking-at verilog-directive-re-1)
4260 (not (looking-at "[ \t]*`ovm_"))))
6341f357 4261 (throw 'nesting 'directive))
a3a8b002
DN
4262 ;; indent structs as if there were module level
4263 (if (verilog-in-struct-p)
4264 (throw 'nesting 'block))
6341f357
DN
4265
4266 ;; unless we are in the newfangled coverpoint or constraint blocks
4267 ;; if we are in a parenthesized list, and the user likes to indent these, return.
4268 (if (and
a3a8b002
DN
4269 verilog-indent-lists
4270 (verilog-in-paren)
4271 (not (verilog-in-coverage-p))
4272 )
6341f357 4273 (progn (setq par 1)
a3a8b002 4274 (throw 'nesting 'block)))
6341f357
DN
4275
4276 ;; See if we are continuing a previous line
4277 (while t
4278 ;; trap out if we crawl off the top of the buffer
4279 (if (bobp) (throw 'nesting 'cpp))
4280
4281 (if (verilog-continued-line-1 lim)
4282 (let ((sp (point)))
4283 (if (and
4284 (not (looking-at verilog-complete-reg))
4285 (verilog-continued-line-1 lim))
4286 (progn (goto-char sp)
4287 (throw 'nesting 'cexp))
4288
4289 (goto-char sp))
4290
4291 (if (and begin
4292 (not verilog-indent-begin-after-if)
4293 (looking-at verilog-no-indent-begin-re))
4294 (progn
4295 (beginning-of-line)
4296 (skip-chars-forward " \t")
4297 (throw 'nesting 'statement))
4298 (progn
4299 (throw 'nesting 'cexp))))
4300 ;; not a continued line
4301 (goto-char starting_position))
4302
4303 (if (looking-at "\\<else\\>")
4304 ;; search back for governing if, striding across begin..end pairs
4305 ;; appropriately
4306 (let ((elsec 1))
4307 (while (verilog-re-search-backward verilog-ends-re nil 'move)
4308 (cond
4309 ((match-end 1) ; else, we're in deep
4310 (setq elsec (1+ elsec)))
4311 ((match-end 2) ; if
4312 (setq elsec (1- elsec))
4313 (if (= 0 elsec)
4314 (if verilog-align-ifelse
4315 (throw 'nesting 'statement)
4316 (progn ;; back up to first word on this line
4317 (beginning-of-line)
4318 (verilog-forward-syntactic-ws)
4319 (throw 'nesting 'statement)))))
4320 (t ; endblock
4321 ; try to leap back to matching outward block by striding across
4322 ; indent level changing tokens then immediately
4323 ; previous line governs indentation.
4324 (let (( reg) (nest 1))
4325;; verilog-ends => else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
4326 (cond
4327 ((match-end 3) ; end
4328 ;; Search back for matching begin
4329 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
4330 ((match-end 4) ; endcase
4331 ;; Search back for matching case
4332 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4333 ((match-end 5) ; endfunction
4334 ;; Search back for matching function
4335 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4336 ((match-end 6) ; endtask
4337 ;; Search back for matching task
4338 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
4339 ((match-end 7) ; endspecify
4340 ;; Search back for matching specify
4341 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4342 ((match-end 8) ; endtable
4343 ;; Search back for matching table
4344 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4345 ((match-end 9) ; endgenerate
4346 ;; Search back for matching generate
4347 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4348 ((match-end 10) ; joins
4349 ;; Search back for matching fork
4350 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
4351 ((match-end 11) ; class
4352 ;; Search back for matching class
4353 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4354 ((match-end 12) ; covergroup
4355 ;; Search back for matching covergroup
60618039 4356 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
6341f357
DN
4357 (catch 'skip
4358 (while (verilog-re-search-backward reg nil 'move)
4359 (cond
4360 ((match-end 1) ; begin
4361 (setq nest (1- nest))
4362 (if (= 0 nest)
4363 (throw 'skip 1)))
4364 ((match-end 2) ; end
4365 (setq nest (1+ nest)))))
60618039
DN
4366 )))))))
4367 (throw 'nesting (verilog-calc-1)))
6341f357
DN
4368 );; catch nesting
4369 );; type
4370 )
4371 ;; Return type of block and indent level.
4372 (if (not type)
4373 (setq type 'cpp))
4374 (if (> par 0) ; Unclosed Parenthesis
4375 (list 'cparenexp par)
4376 (cond
4377 ((eq type 'case)
4378 (list type (verilog-case-indent-level)))
4379 ((eq type 'statement)
4380 (list type (current-column)))
4381 ((eq type 'defun)
4382 (list type 0))
4383 (t
60618039
DN
4384 (list type (verilog-current-indent-level))))))))
4385
6341f357
DN
4386(defun verilog-wai ()
4387 "Show matching nesting block for debugging."
4388 (interactive)
4389 (save-excursion
4c5e69c6
DN
4390 (let* ((type (verilog-calc-1))
4391 depth)
4392 ;; Return type of block and indent level.
4393 (if (not type)
4394 (setq type 'cpp))
4395 (if (and
4396 verilog-indent-lists
a3a8b002
DN
4397 (not(or (verilog-in-coverage-p)
4398 (verilog-in-struct-p)))
4c5e69c6
DN
4399 (verilog-in-paren))
4400 (setq depth 1)
4401 (cond
4402 ((eq type 'case)
4403 (setq depth (verilog-case-indent-level)))
4404 ((eq type 'statement)
4405 (setq depth (current-column)))
4406 ((eq type 'defun)
4407 (setq depth 0))
4408 (t
4409 (setq depth (verilog-current-indent-level)))))
4410 (message "You are at nesting %s depth %d" type depth))))
6341f357
DN
4411
4412(defun verilog-calc-1 ()
4413 (catch 'nesting
a3a8b002
DN
4414 (let ((re (concat "\\({\\|}\\|" verilog-indent-re "\\)")))
4415 (while (verilog-re-search-backward re nil 'move)
4416 (catch 'continue
4417 (cond
4418 ((equal (char-after) ?\{)
4419 (if (verilog-at-constraint-p)
4420 (throw 'nesting 'block)))
6341f357 4421
a3a8b002
DN
4422 ((equal (char-after) ?\})
4423 (let ((there (verilog-at-close-constraint-p)))
4424 (if there ;; we are at the } that closes a constraing. Find the { that opens it
4425 (progn
4426 (forward-char 1)
4427 (backward-list 1)
4428 (verilog-beg-of-statement)))))
6341f357 4429
a3a8b002
DN
4430 ((looking-at verilog-beg-block-re-ordered)
4431 (cond
4432 ((match-end 2) ; *sigh* could be "unique case" or "priority casex"
4433 (let ((here (point)))
4434 (verilog-beg-of-statement)
4435 (if (looking-at verilog-extended-case-re)
4436 (throw 'nesting 'case)
4437 (goto-char here)))
4438 (throw 'nesting 'case))
4439
4440 ((match-end 4) ; *sigh* could be "disable fork"
4441 (let ((here (point)))
4442 (verilog-beg-of-statement)
4443 (if (looking-at verilog-disable-fork-re)
4444 t ; is disable fork, this is a normal statement
4445 (progn ; or is fork, starts a new block
4446 (goto-char here)
4447 (throw 'nesting 'block)))))
4448
4449
4450 ;; need to consider typedef struct here...
4451 ((looking-at "\\<class\\|struct\\|function\\|task\\>")
6341f357
DN
4452 ; *sigh* These words have an optional prefix:
4453 ; extern {virtual|protected}? function a();
6341f357
DN
4454 ; typedef class foo;
4455 ; and we don't want to confuse this with
4456 ; function a();
4457 ; property
4458 ; ...
4459 ; endfunction
a3a8b002
DN
4460 (verilog-beg-of-statement)
4461 (if (looking-at verilog-beg-block-re-ordered)
4462 (throw 'nesting 'block)
4463 (throw 'nesting 'defun)))
7cb1c4d7 4464
a3a8b002
DN
4465 ((looking-at "\\<property\\>")
4466 ; *sigh*
7cb1c4d7
DN
4467 ; {assert|assume|cover} property (); are complete
4468 ; but
4469 ; property ID () ... needs end_property
a3a8b002
DN
4470 (verilog-beg-of-statement)
4471 (if (looking-at "\\(assert\\|assume\\|cover\\)\\s-+property\\>")
4472 (throw 'nesting 'statement) ; We don't need an endproperty for these
4473 (throw 'nesting 'block) ;We still need a endproperty
4474 ))
6341f357 4475
a3a8b002 4476 (t (throw 'nesting 'block))))
6341f357 4477
a3a8b002
DN
4478 ((looking-at verilog-end-block-re)
4479 (verilog-leap-to-head)
4480 (if (verilog-in-case-region-p)
4481 (progn
4482 (verilog-leap-to-case-head)
4483 (if (looking-at verilog-extended-case-re)
4484 (throw 'nesting 'case)))))
6341f357 4485
a3a8b002
DN
4486 ((looking-at verilog-defun-level-re)
4487 (if (looking-at verilog-defun-level-generate-only-re)
4488 (if (verilog-in-generate-region-p)
4489 (throw 'continue 'foo) ; always block in a generate
4490 (throw 'nesting 'defun))
4491 (throw 'nesting 'defun)))
4492
4493 ((looking-at verilog-cpp-level-re)
4494 (throw 'nesting 'cpp))
4495
4496 ((bobp)
4497 (throw 'nesting 'cpp)))))
4498
4499 (throw 'nesting 'cpp))))
6341f357
DN
4500
4501(defun verilog-calculate-indent-directive ()
4502 "Return indentation level for directive.
4503For speed, the searcher looks at the last directive, not the indent
4504of the appropriate enclosing block."
4505 (let ((base -1) ;; Indent of the line that determines our indentation
60618039 4506 (ind 0)) ;; Relative offset caused by other directives (like `endif on same line as `else)
6341f357
DN
4507 ;; Start at current location, scan back for another directive
4508
4509 (save-excursion
4510 (beginning-of-line)
4511 (while (and (< base 0)
4512 (verilog-re-search-backward verilog-directive-re nil t))
4513 (cond ((save-excursion (skip-chars-backward " \t") (bolp))
60618039 4514 (setq base (current-indentation))))
6341f357
DN
4515 (cond ((and (looking-at verilog-directive-end) (< base 0)) ;; Only matters when not at BOL
4516 (setq ind (- ind verilog-indent-level-directive)))
4517 ((and (looking-at verilog-directive-middle) (>= base 0)) ;; Only matters when at BOL
4518 (setq ind (+ ind verilog-indent-level-directive)))
4519 ((looking-at verilog-directive-begin)
4520 (setq ind (+ ind verilog-indent-level-directive)))))
4521 ;; Adjust indent to starting indent of critical line
4522 (setq ind (max 0 (+ ind base))))
4523
4524 (save-excursion
4525 (beginning-of-line)
4526 (skip-chars-forward " \t")
4527 (cond ((or (looking-at verilog-directive-middle)
4528 (looking-at verilog-directive-end))
4529 (setq ind (max 0 (- ind verilog-indent-level-directive))))))
4530 ind))
4531
4532(defun verilog-leap-to-case-head ()
4533 (let ((nest 1))
4534 (while (/= 0 nest)
a3a8b002
DN
4535 (verilog-re-search-backward
4536 (concat
4537 "\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?\\<case[xz]?\\>\\)"
4538 "\\|\\(\\<endcase\\>\\)" )
4539 nil 'move)
6341f357
DN
4540 (cond
4541 ((match-end 1)
a3a8b002
DN
4542 (let ((here (point)))
4543 (verilog-beg-of-statement)
4544 (unless (looking-at verilog-extended-case-re)
4545 (goto-char here)))
6341f357 4546 (setq nest (1- nest)))
a3a8b002 4547 ((match-end 3)
6341f357
DN
4548 (setq nest (1+ nest)))
4549 ((bobp)
4550 (ding 't)
4551 (setq nest 0))))))
4552
4553(defun verilog-leap-to-head ()
37ea4b9b
JB
4554 "Move point to the head of this block.
4555Jump from end to matching begin, from endcase to matching case, and so on."
6341f357
DN
4556 (let ((reg nil)
4557 snest
4c5e69c6 4558 (nesting 'yes)
6341f357
DN
4559 (nest 1))
4560 (cond
4561 ((looking-at "\\<end\\>")
4562 ;; 1: Search back for matching begin
4563 (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
4564 "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
4c5e69c6 4565 ((looking-at "\\<endtask\\>")
a3a8b002 4566 ;; 2: Search back for matching task
4c5e69c6
DN
4567 (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
4568 (setq nesting 'no))
6341f357 4569 ((looking-at "\\<endcase\\>")
a3a8b002
DN
4570 (catch 'nesting
4571 (verilog-leap-to-case-head) )
4572 (setq reg nil) ; to force skip
4573 )
4574
6341f357 4575 ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
a3a8b002 4576 ;; 4: Search back for matching fork
6341f357
DN
4577 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4578 ((looking-at "\\<endclass\\>")
a3a8b002 4579 ;; 5: Search back for matching class
6341f357
DN
4580 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4581 ((looking-at "\\<endtable\\>")
a3a8b002 4582 ;; 6: Search back for matching table
6341f357
DN
4583 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4584 ((looking-at "\\<endspecify\\>")
a3a8b002 4585 ;; 7: Search back for matching specify
6341f357
DN
4586 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4587 ((looking-at "\\<endfunction\\>")
a3a8b002
DN
4588 ;; 8: Search back for matching function
4589 (setq reg "\\(\\<function\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<function\\>\\)")
4590 (setq nesting 'no))
4591 ;;(setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
6341f357
DN
4592 ((looking-at "\\<endgenerate\\>")
4593 ;; 8: Search back for matching generate
4594 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
6341f357
DN
4595 ((looking-at "\\<endgroup\\>")
4596 ;; 10: Search back for matching covergroup
4597 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
4598 ((looking-at "\\<endproperty\\>")
4599 ;; 11: Search back for matching property
4600 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
a3a8b002
DN
4601 ((looking-at verilog-ovm-end-re)
4602 ;; 12: Search back for matching sequence
4603 (setq reg (concat "\\(" verilog-ovm-begin-re "\\|" verilog-ovm-end-re "\\)")))
6341f357
DN
4604 ((looking-at "\\<endinterface\\>")
4605 ;; 12: Search back for matching interface
4606 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
4607 ((looking-at "\\<endsequence\\>")
4608 ;; 12: Search back for matching sequence
4609 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
4610 ((looking-at "\\<endclocking\\>")
4611 ;; 12: Search back for matching clocking
60618039 4612 (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
6341f357
DN
4613 (if reg
4614 (catch 'skip
4c5e69c6
DN
4615 (if (eq nesting 'yes)
4616 (let (sreg)
4617 (while (verilog-re-search-backward reg nil 'move)
4618 (cond
4619 ((match-end 1) ; begin
4620 (setq nest (1- nest))
4621 (if (= 0 nest)
4622 ;; Now previous line describes syntax
4623 (throw 'skip 1))
4624 (if (and snest
4625 (= snest nest))
4626 (setq reg sreg)))
4627 ((match-end 2) ; end
4628 (setq nest (1+ nest)))
4629 ((match-end 3)
4630 ;; endcase, jump to case
4631 (setq snest nest)
4632 (setq nest (1+ nest))
4633 (setq sreg reg)
4634 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4635 ((match-end 4)
4636 ;; join, jump to fork
4637 (setq snest nest)
4638 (setq nest (1+ nest))
4639 (setq sreg reg)
4640 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4641 )))
4642 ;no nesting
4643 (if (and
a3a8b002 4644 (verilog-re-search-backward reg nil 'move)
4c5e69c6
DN
4645 (match-end 1)) ; task -> could be virtual and/or protected
4646 (progn
4647 (verilog-beg-of-statement)
4648 (throw 'skip 1))
4649 (throw 'skip 1)))))))
6341f357
DN
4650
4651(defun verilog-continued-line ()
4652 "Return true if this is a continued line.
37ea4b9b 4653Set point to where line starts."
6341f357
DN
4654 (let ((continued 't))
4655 (if (eq 0 (forward-line -1))
4656 (progn
4657 (end-of-line)
4658 (verilog-backward-ws&directives)
4659 (if (bobp)
4660 (setq continued nil)
4661 (while (and continued
4662 (save-excursion
4663 (skip-chars-backward " \t")
4664 (not (bolp))))
60618039 4665 (setq continued (verilog-backward-token)))))
6341f357
DN
4666 (setq continued nil))
4667 continued))
4668
4669(defun verilog-backward-token ()
a3a8b002 4670 "Step backward token, returing true if nil if continued line."
6341f357
DN
4671 (interactive)
4672 (verilog-backward-syntactic-ws)
4673 (cond
4674 ((bolp)
4675 nil)
4676 (;-- Anything ending in a ; is complete
4677 (= (preceding-char) ?\;)
4678 nil)
4679 (; If a "}" is prefixed by a ";", then this is a complete statement
4680 ; i.e.: constraint foo { a = b; }
4681 (= (preceding-char) ?\})
4682 (progn
4683 (backward-char)
a3a8b002 4684 (not(verilog-at-close-constraint-p))))
6341f357
DN
4685 (;-- constraint foo { a = b }
4686 ; is a complete statement. *sigh*
4687 (= (preceding-char) ?\{)
4688 (progn
4689 (backward-char)
60618039 4690 (not (verilog-at-constraint-p))))
a3a8b002
DN
4691 (;" string "
4692 (= (preceding-char) ?\")
4693 (backward-char)
4694 (verilog-skip-backward-comment-or-string)
4695 nil)
4696
4697 (; [3:4]
4698 (= (preceding-char) ?\])
4699 (backward-char)
4700 (verilog-backward-open-bracket)
4701 t)
4702
6341f357
DN
4703 (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
4704 ; also could be simply '@(foo)'
4705 ; or foo u1 #(a=8)
4706 ; (b, ... which ISN'T complete
4707 ;;;; Do we need this???
4708 (= (preceding-char) ?\))
4709 (progn
4710 (backward-char)
4711 (backward-up-list 1)
4712 (verilog-backward-syntactic-ws)
4713 (let ((back (point)))
4714 (forward-word -1)
4715 (cond
a3a8b002 4716 ;;XX
6341f357
DN
4717 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
4718 (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
a3a8b002
DN
4719 ((looking-at verilog-ovm-statement-re)
4720 nil)
4721 ((looking-at verilog-ovm-begin-re)
4722 t)
4723 ((looking-at verilog-ovm-end-re)
4724 t)
6341f357
DN
4725 (t
4726 (goto-char back)
4727 (cond
4728 ((= (preceding-char) ?\@)
4729 (backward-char)
4730 (save-excursion
4731 (verilog-backward-token)
4732 (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
4733 ((= (preceding-char) ?\#)
60618039
DN
4734 (backward-char))
4735 (t t)))))))
6341f357
DN
4736
4737 (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
4738 t
4739 (forward-word -1)
4740 (cond
4741 ((looking-at "\\<else\\>")
4742 t)
2a9eb3f5
DN
4743 ((looking-at verilog-behavioral-block-beg-re)
4744 t)
6341f357
DN
4745 ((looking-at verilog-indent-re)
4746 nil)
4747 (t
4748 (let
4749 ((back (point)))
4750 (verilog-backward-syntactic-ws)
4751 (cond
4752 ((= (preceding-char) ?\:)
4753 (backward-char)
4754 (verilog-backward-syntactic-ws)
4755 (backward-sexp)
4756 (if (looking-at verilog-nameable-item-re )
4757 nil
60618039 4758 t))
6341f357
DN
4759 ((= (preceding-char) ?\#)
4760 (backward-char)
4761 t)
4762 ((= (preceding-char) ?\`)
4763 (backward-char)
4764 t)
4765
4766 (t
4767 (goto-char back)
60618039 4768 t))))))))
6341f357
DN
4769
4770(defun verilog-backward-syntactic-ws (&optional bound)
4771 "Backward skip over syntactic whitespace for Emacs 19.
4772Optional BOUND limits search."
4773 (save-restriction
4774 (let* ((bound (or bound (point-min))) (here bound) )
4775 (if (< bound (point))
4776 (progn
4777 (narrow-to-region bound (point))
4778 (while (/= here (point))
4779 (setq here (point))
60618039 4780 (verilog-skip-backward-comments))))))
6341f357
DN
4781 t)
4782
4783(defun verilog-forward-syntactic-ws (&optional bound)
4784 "Forward skip over syntactic whitespace for Emacs 19.
4785Optional BOUND limits search."
4786 (save-restriction
4787 (let* ((bound (or bound (point-max)))
60618039 4788 (here bound))
6341f357
DN
4789 (if (> bound (point))
4790 (progn
4791 (narrow-to-region (point) bound)
4792 (while (/= here (point))
4793 (setq here (point))
60618039 4794 (forward-comment (buffer-size))))))))
6341f357
DN
4795
4796(defun verilog-backward-ws&directives (&optional bound)
4797 "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
4798Optional BOUND limits search."
4799 (save-restriction
4800 (let* ((bound (or bound (point-min)))
4801 (here bound)
4802 (p nil) )
4803 (if (< bound (point))
4804 (progn
d63b01e1 4805 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4806 (cond
4807 ((nth 7 state) ;; in // comment
4808 (verilog-re-search-backward "//" nil 'move)
4809 (skip-chars-backward "/"))
4810 ((nth 4 state) ;; in /* */ comment
4811 (verilog-re-search-backward "/\*" nil 'move))))
4812 (narrow-to-region bound (point))
4813 (while (/= here (point))
4814 (setq here (point))
4815 (verilog-skip-backward-comments)
4816 (setq p
4817 (save-excursion
4818 (beginning-of-line)
4819 (cond
a3a8b002
DN
4820 ((and verilog-highlight-translate-off
4821 (verilog-within-translate-off))
6341f357
DN
4822 (verilog-back-to-start-translate-off (point-min)))
4823 ((looking-at verilog-directive-re-1)
4824 (point))
4825 (t
4826 nil))))
60618039 4827 (if p (goto-char p))))))))
6341f357
DN
4828
4829(defun verilog-forward-ws&directives (&optional bound)
4830 "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
4831Optional BOUND limits search."
4832 (save-restriction
4833 (let* ((bound (or bound (point-max)))
4834 (here bound)
60618039 4835 jump)
6341f357
DN
4836 (if (> bound (point))
4837 (progn
d63b01e1 4838 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4839 (cond
4840 ((nth 7 state) ;; in // comment
4841 (verilog-re-search-forward "//" nil 'move))
4842 ((nth 4 state) ;; in /* */ comment
4843 (verilog-re-search-forward "/\*" nil 'move))))
4844 (narrow-to-region (point) bound)
4845 (while (/= here (point))
4846 (setq here (point)
4847 jump nil)
4848 (forward-comment (buffer-size))
4849 (save-excursion
4850 (beginning-of-line)
4851 (if (looking-at verilog-directive-re-1)
4852 (setq jump t)))
4853 (if jump
60618039 4854 (beginning-of-line 2))))))))
6341f357
DN
4855
4856(defun verilog-in-comment-p ()
4857 "Return true if in a star or // comment."
d63b01e1 4858 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4859 (or (nth 4 state) (nth 7 state))))
4860
4861(defun verilog-in-star-comment-p ()
4862 "Return true if in a star comment."
d63b01e1 4863 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4864 (and
4865 (nth 4 state) ; t if in a comment of style a // or b /**/
4866 (not
4867 (nth 7 state) ; t if in a comment of style b /**/
4868 ))))
4869
4870(defun verilog-in-slash-comment-p ()
4871 "Return true if in a slash comment."
d63b01e1 4872 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4873 (nth 7 state)))
4874
4875(defun verilog-in-comment-or-string-p ()
4876 "Return true if in a string or comment."
d63b01e1 4877 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4878 (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
4879
4880(defun verilog-in-escaped-name-p ()
4881 "Return true if in an escaped name."
4882 (save-excursion
4883 (backward-char)
4884 (skip-chars-backward "^ \t\n\f")
4885 (if (equal (char-after (point) ) ?\\ )
4886 t
4887 nil)))
a3a8b002
DN
4888(defun verilog-in-directive-p ()
4889 "Return true if in a star or // comment."
4890 (save-excursion
4891 (beginning-of-line)
4892 (looking-at verilog-directive-re-1)))
6341f357
DN
4893
4894(defun verilog-in-paren ()
4895 "Return true if in a parenthetical expression."
d63b01e1 4896 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4897 (> (nth 0 state) 0 )))
4898
a3a8b002
DN
4899(defun verilog-in-struct-p ()
4900 "Return true if in a struct declaration."
4901 (interactive)
4902 (save-excursion
4903 (if (verilog-in-paren)
4904 (progn
4905 (backward-up-list 1)
4906 (verilog-at-struct-p)
4907 )
4908 nil)))
4909
4910(defun verilog-in-coverage-p ()
6341f357
DN
4911 "Return true if in a constraint or coverpoint expression."
4912 (interactive)
4913 (save-excursion
4914 (if (verilog-in-paren)
4915 (progn
4916 (backward-up-list 1)
4917 (verilog-at-constraint-p)
4918 )
4919 nil)))
4920(defun verilog-at-close-constraint-p ()
4921 "If at the } that closes a constraint or covergroup, return true."
4922 (if (and
4923 (equal (char-after) ?\})
4924 (verilog-in-paren))
4925
4926 (save-excursion
4927 (verilog-backward-ws&directives)
4928 (if (equal (char-before) ?\;)
4929 (point)
4930 nil))))
4931
4932(defun verilog-at-constraint-p ()
4933 "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
4934 (if (save-excursion
4935 (and
4936 (equal (char-after) ?\{)
4937 (forward-list)
4938 (progn (backward-char 1)
4939 (verilog-backward-ws&directives)
60618039 4940 (equal (char-before) ?\;))))
6341f357
DN
4941 ;; maybe
4942 (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
4943 ;; not
60618039 4944 nil))
6341f357 4945
a3a8b002
DN
4946(defun verilog-at-struct-p ()
4947 "If at the { of a struct, return true, moving point to struct."
4948 (save-excursion
4949 (if (and (equal (char-after) ?\{)
4950 (verilog-backward-token))
4951 (looking-at "\\<struct\\|union\\|packed\\>")
4952 nil)))
4953
6341f357
DN
4954(defun verilog-parenthesis-depth ()
4955 "Return non zero if in parenthetical-expression."
d63b01e1 4956 (save-excursion (nth 1 (verilog-syntax-ppss))))
6341f357
DN
4957
4958
4959(defun verilog-skip-forward-comment-or-string ()
4960 "Return true if in a string or comment."
d63b01e1 4961 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4962 (cond
4963 ((nth 3 state) ;Inside string
495ab0d5 4964 (search-forward "\"")
6341f357
DN
4965 t)
4966 ((nth 7 state) ;Inside // comment
4967 (forward-line 1)
4968 t)
4969 ((nth 4 state) ;Inside any comment (hence /**/)
4970 (search-forward "*/"))
4971 (t
4972 nil))))
4973
4974(defun verilog-skip-backward-comment-or-string ()
4975 "Return true if in a string or comment."
d63b01e1 4976 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4977 (cond
4978 ((nth 3 state) ;Inside string
4979 (search-backward "\"")
4980 t)
4981 ((nth 7 state) ;Inside // comment
4982 (search-backward "//")
4983 (skip-chars-backward "/")
4984 t)
4985 ((nth 4 state) ;Inside /* */ comment
4986 (search-backward "/*")
4987 t)
4988 (t
4989 nil))))
4990
4991(defun verilog-skip-backward-comments ()
4992 "Return true if a comment was skipped."
4993 (let ((more t))
4994 (while more
4995 (setq more
d63b01e1 4996 (let ((state (save-excursion (verilog-syntax-ppss))))
6341f357
DN
4997 (cond
4998 ((nth 7 state) ;Inside // comment
4999 (search-backward "//")
5000 (skip-chars-backward "/")
5001 (skip-chars-backward " \t\n\f")
5002 t)
5003 ((nth 4 state) ;Inside /* */ comment
5004 (search-backward "/*")
5005 (skip-chars-backward " \t\n\f")
5006 t)
5007 ((and (not (bobp))
5008 (= (char-before) ?\/)
60618039 5009 (= (char-before (1- (point))) ?\*))
6341f357
DN
5010 (goto-char (- (point) 2))
5011 t)
5012 (t
5013 (skip-chars-backward " \t\n\f")
5014 nil)))))))
5015
5016(defun verilog-skip-forward-comment-p ()
5017 "If in comment, move to end and return true."
5018 (let (state)
5019 (progn
d63b01e1 5020 (setq state (save-excursion (verilog-syntax-ppss)))
6341f357
DN
5021 (cond
5022 ((nth 3 state)
5023 t)
5024 ((nth 7 state) ;Inside // comment
5025 (end-of-line)
5026 (forward-char 1)
5027 t)
5028 ((nth 4 state) ;Inside any comment
5029 t)
5030 (t
5031 nil)))))
5032
5033(defun verilog-indent-line-relative ()
5034 "Cheap version of indent line.
5035Only look at a few lines to determine indent level."
5036 (interactive)
5037 (let ((indent-str)
5038 (sp (point)))
5039 (if (looking-at "^[ \t]*$")
5040 (cond ;- A blank line; No need to be too smart.
5041 ((bobp)
5042 (setq indent-str (list 'cpp 0)))
5043 ((verilog-continued-line)
5044 (let ((sp1 (point)))
5045 (if (verilog-continued-line)
7ea26faf
DN
5046 (progn
5047 (goto-char sp)
60618039
DN
5048 (setq indent-str
5049 (list 'statement (verilog-current-indent-level))))
6341f357
DN
5050 (goto-char sp1)
5051 (setq indent-str (list 'block (verilog-current-indent-level)))))
5052 (goto-char sp))
5053 ((goto-char sp)
5054 (setq indent-str (verilog-calculate-indent))))
5055 (progn (skip-chars-forward " \t")
5056 (setq indent-str (verilog-calculate-indent))))
5057 (verilog-do-indent indent-str)))
5058
5059(defun verilog-indent-line ()
5060 "Indent for special part of code."
5061 (verilog-do-indent (verilog-calculate-indent)))
5062
5063(defun verilog-do-indent (indent-str)
5064 (let ((type (car indent-str))
5065 (ind (car (cdr indent-str))))
5066 (cond
5067 (; handle continued exp
5068 (eq type 'cexp)
5069 (let ((here (point)))
5070 (verilog-backward-syntactic-ws)
5071 (cond
5072 ((or
5073 (= (preceding-char) ?\,)
5074 (= (preceding-char) ?\])
5075 (save-excursion
5076 (verilog-beg-of-statement-1)
5077 (looking-at verilog-declaration-re)))
5078 (let* ( fst
5079 (val
5080 (save-excursion
5081 (backward-char 1)
5082 (verilog-beg-of-statement-1)
5083 (setq fst (point))
5084 (if (looking-at verilog-declaration-re)
5085 (progn ;; we have multiple words
5086 (goto-char (match-end 0))
5087 (skip-chars-forward " \t")
5088 (cond
5089 ((and verilog-indent-declaration-macros
5090 (= (following-char) ?\`))
5091 (progn
5092 (forward-char 1)
5093 (forward-word 1)
5094 (skip-chars-forward " \t")))
5095 ((= (following-char) ?\[)
5096 (progn
5097 (forward-char 1)
5098 (backward-up-list -1)
60618039 5099 (skip-chars-forward " \t"))))
6341f357
DN
5100 (current-column))
5101 (progn
5102 (goto-char fst)
60618039 5103 (+ (current-column) verilog-cexp-indent))))))
6341f357 5104 (goto-char here)
60618039 5105 (indent-line-to val)))
6341f357
DN
5106 ((= (preceding-char) ?\) )
5107 (goto-char here)
5108 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5109 (indent-line-to val)))
5110 (t
5111 (goto-char here)
5112 (let ((val))
5113 (verilog-beg-of-statement-1)
5114 (if (and (< (point) here)
5115 (verilog-re-search-forward "=[ \\t]*" here 'move))
5116 (setq val (current-column))
5117 (setq val (eval (cdr (assoc type verilog-indent-alist)))))
5118 (goto-char here)
60618039 5119 (indent-line-to val))))))
6341f357
DN
5120
5121 (; handle inside parenthetical expressions
5122 (eq type 'cparenexp)
5123 (let ((val (save-excursion
5124 (backward-up-list 1)
5125 (forward-char 1)
5126 (skip-chars-forward " \t")
5127 (current-column))))
5128 (indent-line-to val)
9c059794 5129 ))
a3a8b002 5130
6341f357
DN
5131 (;-- Handle the ends
5132 (or
5133 (looking-at verilog-end-block-re )
5134 (verilog-at-close-constraint-p))
5135 (let ((val (if (eq type 'statement)
5136 (- ind verilog-indent-level)
5137 ind)))
5138 (indent-line-to val)))
5139
5140 (;-- Case -- maybe line 'em up
5141 (and (eq type 'case) (not (looking-at "^[ \t]*$")))
5142 (progn
5143 (cond
5144 ((looking-at "\\<endcase\\>")
5145 (indent-line-to ind))
5146 (t
5147 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5148 (indent-line-to val))))))
5149
5150 (;-- defun
5151 (and (eq type 'defun)
5152 (looking-at verilog-zero-indent-re))
5153 (indent-line-to 0))
5154
5155 (;-- declaration
5156 (and (or
5157 (eq type 'defun)
5158 (eq type 'block))
5159 (looking-at verilog-declaration-re))
5160 (verilog-indent-declaration ind))
5161
5162 (;-- Everything else
5163 t
5164 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
60618039
DN
5165 (indent-line-to val))))
5166
6341f357
DN
5167 (if (looking-at "[ \t]+$")
5168 (skip-chars-forward " \t"))
5169 indent-str ; Return indent data
5170 ))
5171
5172(defun verilog-current-indent-level ()
37ea4b9b 5173 "Return the indent-level of the current statement."
6341f357
DN
5174 (save-excursion
5175 (let (par-pos)
5176 (beginning-of-line)
5177 (setq par-pos (verilog-parenthesis-depth))
5178 (while par-pos
5179 (goto-char par-pos)
5180 (beginning-of-line)
5181 (setq par-pos (verilog-parenthesis-depth)))
5182 (skip-chars-forward " \t")
5183 (current-column))))
5184
5185(defun verilog-case-indent-level ()
37ea4b9b 5186 "Return the indent-level of the current statement.
6341f357
DN
5187Do not count named blocks or case-statements."
5188 (save-excursion
5189 (skip-chars-forward " \t")
5190 (cond
5191 ((looking-at verilog-named-block-re)
5192 (current-column))
a3a8b002 5193 ((and (not (looking-at verilog-extended-case-re))
6341f357
DN
5194 (looking-at "^[^:;]+[ \t]*:"))
5195 (verilog-re-search-forward ":" nil t)
5196 (skip-chars-forward " \t")
5197 (current-column))
5198 (t
5199 (current-column)))))
5200
5201(defun verilog-indent-comment ()
5202 "Indent current line as comment."
5203 (let* ((stcol
5204 (cond
5205 ((verilog-in-star-comment-p)
5206 (save-excursion
5207 (re-search-backward "/\\*" nil t)
5208 (1+(current-column))))
5209 (comment-column
5210 comment-column )
5211 (t
5212 (save-excursion
5213 (re-search-backward "//" nil t)
60618039 5214 (current-column))))))
6341f357
DN
5215 (indent-line-to stcol)
5216 stcol))
5217
5218(defun verilog-more-comment ()
5219 "Make more comment lines like the previous."
5220 (let* ((star 0)
5221 (stcol
5222 (cond
5223 ((verilog-in-star-comment-p)
5224 (save-excursion
5225 (setq star 1)
5226 (re-search-backward "/\\*" nil t)
5227 (1+(current-column))))
5228 (comment-column
5229 comment-column )
5230 (t
5231 (save-excursion
5232 (re-search-backward "//" nil t)
60618039 5233 (current-column))))))
6341f357
DN
5234 (progn
5235 (indent-to stcol)
5236 (if (and star
5237 (save-excursion
5238 (forward-line -1)
5239 (skip-chars-forward " \t")
5240 (looking-at "\*")))
5241 (insert "* ")))))
5242
5243(defun verilog-comment-indent (&optional arg)
5244 "Return the column number the line should be indented to.
5245ARG is ignored, for `comment-indent-function' compatibility."
5246 (cond
5247 ((verilog-in-star-comment-p)
5248 (save-excursion
5249 (re-search-backward "/\\*" nil t)
5250 (1+(current-column))))
5251 ( comment-column
5252 comment-column )
5253 (t
5254 (save-excursion
5255 (re-search-backward "//" nil t)
5256 (current-column)))))
5257
5258;;
5259
7e2a6000 5260(defun verilog-pretty-declarations (&optional quiet)
a3a8b002
DN
5261 "Line up declarations around point.
5262Be verbose about progress unless optional QUIET set."
6341f357
DN
5263 (interactive)
5264 (save-excursion
5265 (if (progn
a3a8b002
DN
5266 (verilog-beg-of-statement-1)
5267 (and (not (verilog-in-directive-p)) ;; could have `define input foo
5268 (not (verilog-parenthesis-depth)) ;; could be in a #(param block )
5269 (looking-at verilog-declaration-re)))
5270 (let* ((m1 (make-marker))
5271 (e (point))
5272 (r)
5273 (here (point))
5274 ;; Start of declaration range
5275 (start
5276 (progn
5277 (verilog-beg-of-statement-1)
5278 (while (and (looking-at verilog-declaration-re)
5279 (not (bobp)))
5280 (skip-chars-backward " \t")
5281 (setq e (point))
5282 (beginning-of-line)
5283 (verilog-backward-syntactic-ws)
5284 (backward-char)
5285 (verilog-beg-of-statement-1))
5286 e))
5287 ;; End of declaration range
5288 (end
5289 (progn
5290 (goto-char here)
5291 (verilog-end-of-statement)
5292 (setq e (point)) ;Might be on last line
5293 (verilog-forward-syntactic-ws)
5294 (while (looking-at verilog-declaration-re)
5295 ;;(beginning-of-line)
5296 (verilog-end-of-statement)
5297 (setq e (point))
5298 (verilog-forward-syntactic-ws))
5299 e))
5300 (edpos (set-marker (make-marker) end))
5301 (ind)
5302 (base-ind
5303 (progn
5304 (goto-char start)
5305 (verilog-do-indent (verilog-calculate-indent))
5306 (verilog-forward-ws&directives)
5307 (current-column))))
5308 (goto-char start)
5309 (if (and (not quiet)
5310 (> (- end start) 100))
5311 (message "Lining up declarations..(please stand by)"))
5312 ;; Get the beginning of line indent first
5313 (while (progn (setq e (marker-position edpos))
5314 (< (point) e))
5315 (cond
5316 ( (save-excursion (skip-chars-backward " \t")
5317 (bolp))
5318 (verilog-forward-ws&directives)
5319 (indent-line-to base-ind)
5320 (verilog-forward-ws&directives)
5321 (verilog-re-search-forward "[ \t\n\f]" e 'move))
5322 (t
5323 (just-one-space)
5324 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5325 ;;(forward-line)
5326 )
5327 ;; Now find biggest prefix
5328 (setq ind (verilog-get-lineup-indent start edpos))
5329 ;; Now indent each line.
5330 (goto-char start)
5331 (while (progn (setq e (marker-position edpos))
5332 (setq r (- e (point)))
5333 (> r 0))
5334 (setq e (point))
5335 (unless quiet (message "%d" r))
5336 (verilog-indent-line)
5337 (cond
5338 ((or (and verilog-indent-declaration-macros
5339 (looking-at verilog-declaration-re-2-macro))
5340 (looking-at verilog-declaration-re-2-no-macro))
5341 (let ((p (match-end 0)))
5342 (set-marker m1 p)
5343 (if (verilog-re-search-forward "[[#`]" p 'move)
5344 (progn
5345 (forward-char -1)
5346 (just-one-space)
5347 (goto-char (marker-position m1))
5348 (just-one-space)
5349 (indent-to ind))
5350 (progn
5351 (just-one-space)
5352 (indent-to ind)))))
5353 ((verilog-continued-line-1 start)
5354 (goto-char e)
5355 (indent-line-to ind))
5356 ((verilog-in-struct-p)
5357 ;; could have a declaration of a user defined item
5358 (goto-char e)
5359 (verilog-end-of-statement))
5360 (t ; Must be comment or white space
5361 (goto-char e)
5362 (verilog-forward-ws&directives)
5363 (forward-line -1)))
5364 (forward-line 1))
5365 (unless quiet (message ""))))))
6341f357 5366
7e2a6000 5367(defun verilog-pretty-expr (&optional quiet myre)
60618039 5368 "Line up expressions around point, or optional regexp MYRE."
6341f357
DN
5369 (interactive "sRegular Expression: ((<|:)?=) ")
5370 (save-excursion
5371 (if (or (eq myre nil)
5372 (string-equal myre ""))
5373 (setq myre "\\(<\\|:\\)?="))
a3a8b002 5374 (setq myre (concat "\\(^[^;#:<=>]*\\)\\(" myre "\\)"))
7e2a6000
DN
5375 (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
5376 (beginning-of-line)
5377 (if (and (not (looking-at rexp ))
a3a8b002
DN
5378 (looking-at myre)
5379 (save-excursion
5380 (goto-char (match-beginning 2))
5381 (not (verilog-in-comment-or-string-p))))
5382 (let* ((here (point))
5383 (e) (r)
5384 (start
5385 (progn
5386 (beginning-of-line)
5387 (setq e (point))
5388 (verilog-backward-syntactic-ws)
5389 (beginning-of-line)
5390 (while (and (not (looking-at rexp ))
5391 (looking-at myre)
5392 (not (bobp))
5393 )
5394 (setq e (point))
5395 (verilog-backward-syntactic-ws)
5396 (beginning-of-line)
5397 ) ;Ack, need to grok `define
5398 e))
5399 (end
5400 (progn
5401 (goto-char here)
5402 (end-of-line)
5403 (setq e (point)) ;Might be on last line
5404 (verilog-forward-syntactic-ws)
5405 (beginning-of-line)
5406 (while (and
5407 (not (looking-at rexp ))
5408 (looking-at myre)
5409 (progn
5410 (end-of-line)
5411 (not (eq e (point)))))
5412 (setq e (point))
5413 (verilog-forward-syntactic-ws)
5414 (beginning-of-line)
5415 )
5416 e))
5417 (edpos (set-marker (make-marker) end))
5418 (ind)
5419 )
5420 (goto-char start)
5421 (verilog-do-indent (verilog-calculate-indent))
5422 (if (and (not quiet)
5423 (> (- end start) 100))
5424 (message "Lining up expressions..(please stand by)"))
5425
5426 ;; Set indent to minimum throughout region
5427 (while (< (point) (marker-position edpos))
5428 (beginning-of-line)
5429 (verilog-just-one-space myre)
5430 (end-of-line)
5431 (verilog-forward-syntactic-ws)
5432 )
5433
5434 ;; Now find biggest prefix
5435 (setq ind (verilog-get-lineup-indent-2 myre start edpos))
5436
5437 ;; Now indent each line.
5438 (goto-char start)
5439 (while (progn (setq e (marker-position edpos))
5440 (setq r (- e (point)))
5441 (> r 0))
5442 (setq e (point))
5443 (if (not quiet) (message "%d" r))
5444 (cond
5445 ((looking-at myre)
5446 (goto-char (match-beginning 2))
5447 (if (not (verilog-parenthesis-depth)) ;; ignore parenthsized exprs
5448 (if (eq (char-after) ?=)
5449 (indent-to (1+ ind)) ; line up the = of the <= with surrounding =
5450 (indent-to ind)
5451 )))
5452 ((verilog-continued-line-1 start)
5453 (goto-char e)
5454 (indent-line-to ind))
5455 (t ; Must be comment or white space
5456 (goto-char e)
5457 (verilog-forward-ws&directives)
5458 (forward-line -1))
5459 )
5460 (forward-line 1))
5461 (unless quiet (message ""))
5462 )))))
6341f357
DN
5463
5464(defun verilog-just-one-space (myre)
5465 "Remove extra spaces around regular expression MYRE."
5466 (interactive)
5467 (if (and (not(looking-at verilog-complete-reg))
5468 (looking-at myre))
5469 (let ((p1 (match-end 1))
5470 (p2 (match-end 2)))
5471 (progn
5472 (goto-char p2)
60618039 5473 (if (looking-at "\\s-") (just-one-space))
6341f357
DN
5474 (goto-char p1)
5475 (forward-char -1)
7e2a6000
DN
5476 (if (looking-at "\\s-") (just-one-space))
5477 ))))
6341f357
DN
5478
5479(defun verilog-indent-declaration (baseind)
5480 "Indent current lines as declaration.
5481Line up the variable names based on previous declaration's indentation.
5482BASEIND is the base indent to offset everything."
5483 (interactive)
5484 (let ((pos (point-marker))
5485 (lim (save-excursion
5486 ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
5487 (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
5488 (point)))
5489 (ind)
5490 (val)
60618039 5491 (m1 (make-marker)))
7ea26faf
DN
5492 (setq val
5493 (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6341f357
DN
5494 (indent-line-to val)
5495
5496 ;; Use previous declaration (in this module) as template.
a3a8b002
DN
5497 (if (or (eq 'all verilog-auto-lineup)
5498 (eq 'declarations verilog-auto-lineup))
6edb5716 5499 (if (verilog-re-search-backward
6341f357
DN
5500 (or (and verilog-indent-declaration-macros
5501 verilog-declaration-re-1-macro)
5502 verilog-declaration-re-1-no-macro) lim t)
5503 (progn
5504 (goto-char (match-end 0))
5505 (skip-chars-forward " \t")
5506 (setq ind (current-column))
5507 (goto-char pos)
7ea26faf
DN
5508 (setq val
5509 (+ baseind
5510 (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6341f357
DN
5511 (indent-line-to val)
5512 (if (and verilog-indent-declaration-macros
5513 (looking-at verilog-declaration-re-2-macro))
5514 (let ((p (match-end 0)))
5515 (set-marker m1 p)
5516 (if (verilog-re-search-forward "[[#`]" p 'move)
5517 (progn
5518 (forward-char -1)
5519 (just-one-space)
5520 (goto-char (marker-position m1))
5521 (just-one-space)
60618039 5522 (indent-to ind))
6341f357
DN
5523 (if (/= (current-column) ind)
5524 (progn
5525 (just-one-space)
60618039 5526 (indent-to ind)))))
6341f357
DN
5527 (if (looking-at verilog-declaration-re-2-no-macro)
5528 (let ((p (match-end 0)))
5529 (set-marker m1 p)
5530 (if (verilog-re-search-forward "[[`#]" p 'move)
5531 (progn
5532 (forward-char -1)
5533 (just-one-space)
5534 (goto-char (marker-position m1))
5535 (just-one-space)
5536 (indent-to ind))
5537 (if (/= (current-column) ind)
5538 (progn
5539 (just-one-space)
7ea26faf
DN
5540 (indent-to ind))))))))))
5541 (goto-char pos)))
6341f357
DN
5542
5543(defun verilog-get-lineup-indent (b edpos)
5544 "Return the indent level that will line up several lines within the region.
5545Region is defined by B and EDPOS."
5546 (save-excursion
5547 (let ((ind 0) e)
5548 (goto-char b)
5549 ;; Get rightmost position
5550 (while (progn (setq e (marker-position edpos))
5551 (< (point) e))
6edb5716 5552 (if (verilog-re-search-forward
6341f357
DN
5553 (or (and verilog-indent-declaration-macros
5554 verilog-declaration-re-1-macro)
5555 verilog-declaration-re-1-no-macro) e 'move)
5556 (progn
5557 (goto-char (match-end 0))
5558 (verilog-backward-syntactic-ws)
5559 (if (> (current-column) ind)
5560 (setq ind (current-column)))
5561 (goto-char (match-end 0)))))
5562 (if (> ind 0)
5563 (1+ ind)
5564 ;; No lineup-string found
5565 (goto-char b)
5566 (end-of-line)
5567 (skip-chars-backward " \t")
5568 (1+ (current-column))))))
5569
5570(defun verilog-get-lineup-indent-2 (myre b edpos)
5571 "Return the indent level that will line up several lines within the region."
5572 (save-excursion
5573 (let ((ind 0) e)
5574 (goto-char b)
5575 ;; Get rightmost position
5576 (while (progn (setq e (marker-position edpos))
5577 (< (point) e))
7e2a6000
DN
5578 (if (and (verilog-re-search-forward myre e 'move)
5579 (not (verilog-parenthesis-depth))) ;; skip parenthsized exprs
6341f357 5580 (progn
7e2a6000 5581 (goto-char (match-beginning 2))
6341f357
DN
5582 (verilog-backward-syntactic-ws)
5583 (if (> (current-column) ind)
5584 (setq ind (current-column)))
7e2a6000
DN
5585 (goto-char (match-end 0)))
5586 ))
6341f357
DN
5587 (if (> ind 0)
5588 (1+ ind)
5589 ;; No lineup-string found
5590 (goto-char b)
5591 (end-of-line)
5592 (skip-chars-backward " \t")
5593 (1+ (current-column))))))
5594
5595(defun verilog-comment-depth (type val)
5596 "A useful mode debugging aide. TYPE and VAL are comments for insertion."
5597 (save-excursion
5598 (let
5599 ((b (prog2
5600 (beginning-of-line)
5601 (point-marker)
5602 (end-of-line)))
5603 (e (point-marker)))
5604 (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
5605 (progn
5606 (replace-match " /* -# ## */")
5607 (end-of-line))
5608 (progn
5609 (end-of-line)
5610 (insert " /* ## ## */"))))
5611 (backward-char 6)
5612 (insert
5613 (format "%s %d" type val))))
5614
5615;; \f
5616;;
5617;; Completion
5618;;
5619(defvar verilog-str nil)
5620(defvar verilog-all nil)
5621(defvar verilog-pred nil)
5622(defvar verilog-buffer-to-use nil)
5623(defvar verilog-flag nil)
5624(defvar verilog-toggle-completions nil
5625 "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
5626Repeated use of \\[verilog-complete-word] will show you all of them.
5627Normally, when there is more than one possible completion,
5628it displays a list of all possible completions.")
5629
5630
5631(defvar verilog-type-keywords
5632 '(
5633 "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
5634 "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
5635 "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pullup"
5636 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
5637 "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
5638 "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
5639 )
5640 "*Keywords for types used when completing a word in a declaration or parmlist.
37ea4b9b 5641\(Eg. integer, real, reg...)")
6341f357
DN
5642
5643(defvar verilog-cpp-keywords
5644 '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
5645 "endif")
5646 "*Keywords to complete when at first word of a line in declarative scope.
37ea4b9b 5647\(Eg. initial, always, begin, assign.)
6341f357 5648The procedures and variables defined within the Verilog program
37ea4b9b 5649will be completed at runtime and should not be added to this list.")
6341f357
DN
5650
5651(defvar verilog-defun-keywords
5652 (append
5653 '(
5654 "always" "always_comb" "always_ff" "always_latch" "assign"
5655 "begin" "end" "generate" "endgenerate" "module" "endmodule"
5656 "specify" "endspecify" "function" "endfunction" "initial" "final"
5657 "task" "endtask" "primitive" "endprimitive"
5658 )
5659 verilog-type-keywords)
5660 "*Keywords to complete when at first word of a line in declarative scope.
37ea4b9b 5661\(Eg. initial, always, begin, assign.)
6341f357 5662The procedures and variables defined within the Verilog program
37ea4b9b 5663will be completed at runtime and should not be added to this list.")
6341f357
DN
5664
5665(defvar verilog-block-keywords
5666 '(
5667 "begin" "break" "case" "continue" "else" "end" "endfunction"
5668 "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
5669 "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
5670 "while")
5671 "*Keywords to complete when at first word of a line in behavioral scope.
37ea4b9b 5672\(Eg. begin, if, then, else, for, fork.)
6341f357 5673The procedures and variables defined within the Verilog program
37ea4b9b 5674will be completed at runtime and should not be added to this list.")
6341f357
DN
5675
5676(defvar verilog-tf-keywords
5677 '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
5678 "*Keywords to complete when at first word of a line in a task or function.
37ea4b9b 5679\(Eg. begin, if, then, else, for, fork.)
6341f357 5680The procedures and variables defined within the Verilog program
37ea4b9b 5681will be completed at runtime and should not be added to this list.")
6341f357
DN
5682
5683(defvar verilog-case-keywords
5684 '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
5685 "*Keywords to complete when at first word of a line in case scope.
37ea4b9b 5686\(Eg. begin, if, then, else, for, fork.)
6341f357 5687The procedures and variables defined within the Verilog program
37ea4b9b 5688will be completed at runtime and should not be added to this list.")
6341f357
DN
5689
5690(defvar verilog-separator-keywords
5691 '("else" "then" "begin")
5692 "*Keywords to complete when NOT standing at the first word of a statement.
37ea4b9b
JB
5693\(Eg. else, then.)
5694Variables and function names defined within the Verilog program
5695will be completed at runtime and should not be added to this list.")
6341f357
DN
5696
5697(defun verilog-string-diff (str1 str2)
5698 "Return index of first letter where STR1 and STR2 differs."
5699 (catch 'done
5700 (let ((diff 0))
5701 (while t
5702 (if (or (> (1+ diff) (length str1))
5703 (> (1+ diff) (length str2)))
5704 (throw 'done diff))
5705 (or (equal (aref str1 diff) (aref str2 diff))
5706 (throw 'done diff))
5707 (setq diff (1+ diff))))))
5708
5709;; Calculate all possible completions for functions if argument is `function',
5710;; completions for procedures if argument is `procedure' or both functions and
5711;; procedures otherwise.
5712
5713(defun verilog-func-completion (type)
5714 "Build regular expression for module/task/function names.
5715TYPE is 'module, 'tf for task or function, or t if unknown."
5716 (if (string= verilog-str "")
5717 (setq verilog-str "[a-zA-Z_]"))
5718 (let ((verilog-str (concat (cond
5719 ((eq type 'module) "\\<\\(module\\)\\s +")
5720 ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
5721 (t "\\<\\(task\\|function\\|module\\)\\s +"))
5722 "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
5723 match)
5724
5725 (if (not (looking-at verilog-defun-re))
5726 (verilog-re-search-backward verilog-defun-re nil t))
5727 (forward-char 1)
5728
5729 ;; Search through all reachable functions
5730 (goto-char (point-min))
5731 (while (verilog-re-search-forward verilog-str (point-max) t)
5732 (progn (setq match (buffer-substring (match-beginning 2)
5733 (match-end 2)))
5734 (if (or (null verilog-pred)
5735 (funcall verilog-pred match))
5736 (setq verilog-all (cons match verilog-all)))))
5737 (if (match-beginning 0)
5738 (goto-char (match-beginning 0)))))
5739
5740(defun verilog-get-completion-decl (end)
5741 "Macro for searching through current declaration (var, type or const)
5742for matches of `str' and adding the occurrence tp `all' through point END."
5743 (let ((re (or (and verilog-indent-declaration-macros
5744 verilog-declaration-re-2-macro)
5745 verilog-declaration-re-2-no-macro))
5746 decl-end match)
5747 ;; Traverse lines
5748 (while (and (< (point) end)
5749 (verilog-re-search-forward re end t))
5750 ;; Traverse current line
5751 (setq decl-end (save-excursion (verilog-declaration-end)))
5752 (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
5753 (not (match-end 1)))
5754 (setq match (buffer-substring (match-beginning 0) (match-end 0)))
5755 (if (string-match (concat "\\<" verilog-str) match)
5756 (if (or (null verilog-pred)
5757 (funcall verilog-pred match))
5758 (setq verilog-all (cons match verilog-all)))))
60618039
DN
5759 (forward-line 1)))
5760 verilog-all)
6341f357
DN
5761
5762(defun verilog-type-completion ()
5763 "Calculate all possible completions for types."
5764 (let ((start (point))
5765 goon)
5766 ;; Search for all reachable type declarations
5767 (while (or (verilog-beg-of-defun)
5768 (setq goon (not goon)))
5769 (save-excursion
5770 (if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
5771 (point))
5772 (forward-char 1)))
5773 (verilog-re-search-forward
5774 "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
5775 start t)
5776 (not (match-end 1)))
5777 ;; Check current type declaration
5778 (verilog-get-completion-decl start))))))
5779
5780(defun verilog-var-completion ()
5781 "Calculate all possible completions for variables (or constants)."
5782 (let ((start (point)))
5783 ;; Search for all reachable var declarations
5784 (verilog-beg-of-defun)
5785 (save-excursion
5786 ;; Check var declarations
5787 (verilog-get-completion-decl start))))
5788
5789(defun verilog-keyword-completion (keyword-list)
5790 "Give list of all possible completions of keywords in KEYWORD-LIST."
5791 (mapcar '(lambda (s)
5792 (if (string-match (concat "\\<" verilog-str) s)
5793 (if (or (null verilog-pred)
5794 (funcall verilog-pred s))
5795 (setq verilog-all (cons s verilog-all)))))
5796 keyword-list))
5797
5798
5799(defun verilog-completion (verilog-str verilog-pred verilog-flag)
5800 "Function passed to `completing-read', `try-completion' or `all-completions'.
5801Called to get completion on VERILOG-STR. If VERILOG-PRED is non-nil, it
5802must be a function to be called for every match to check if this should
37ea4b9b
JB
5803really be a match. If VERILOG-FLAG is t, the function returns a list of
5804all possible completions. If VERILOG-FLAG is nil it returns a string,
5805the longest possible completion, or t if VERILOG-STR is an exact match.
5806If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
5807exact match, nil otherwise."
6341f357
DN
5808 (save-excursion
5809 (let ((verilog-all nil))
5810 ;; Set buffer to use for searching labels. This should be set
5811 ;; within functions which use verilog-completions
5812 (set-buffer verilog-buffer-to-use)
5813
5814 ;; Determine what should be completed
5815 (let ((state (car (verilog-calculate-indent))))
5816 (cond ((eq state 'defun)
5817 (save-excursion (verilog-var-completion))
5818 (verilog-func-completion 'module)
5819 (verilog-keyword-completion verilog-defun-keywords))
5820
5821 ((eq state 'behavioral)
5822 (save-excursion (verilog-var-completion))
5823 (verilog-func-completion 'module)
5824 (verilog-keyword-completion verilog-defun-keywords))
5825
5826 ((eq state 'block)
5827 (save-excursion (verilog-var-completion))
5828 (verilog-func-completion 'tf)
5829 (verilog-keyword-completion verilog-block-keywords))
5830
5831 ((eq state 'case)
5832 (save-excursion (verilog-var-completion))
5833 (verilog-func-completion 'tf)
5834 (verilog-keyword-completion verilog-case-keywords))
5835
5836 ((eq state 'tf)
5837 (save-excursion (verilog-var-completion))
5838 (verilog-func-completion 'tf)
5839 (verilog-keyword-completion verilog-tf-keywords))
5840
5841 ((eq state 'cpp)
5842 (save-excursion (verilog-var-completion))
5843 (verilog-keyword-completion verilog-cpp-keywords))
5844
5845 ((eq state 'cparenexp)
5846 (save-excursion (verilog-var-completion)))
5847
5848 (t;--Anywhere else
5849 (save-excursion (verilog-var-completion))
5850 (verilog-func-completion 'both)
5851 (verilog-keyword-completion verilog-separator-keywords))))
5852
5853 ;; Now we have built a list of all matches. Give response to caller
5854 (verilog-completion-response))))
5855
5856(defun verilog-completion-response ()
5857 (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
5858 ;; This was not called by all-completions
5859 (if (null verilog-all)
5860 ;; Return nil if there was no matching label
5861 nil
5862 ;; Get longest string common in the labels
5863 (let* ((elm (cdr verilog-all))
5864 (match (car verilog-all))
5865 (min (length match))
5866 tmp)
5867 (if (string= match verilog-str)
5868 ;; Return t if first match was an exact match
5869 (setq match t)
5870 (while (not (null elm))
5871 ;; Find longest common string
5872 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
5873 (progn
5874 (setq min tmp)
5875 (setq match (substring match 0 min))))
5876 ;; Terminate with match=t if this is an exact match
5877 (if (string= (car elm) verilog-str)
5878 (progn
5879 (setq match t)
5880 (setq elm nil))
5881 (setq elm (cdr elm)))))
5882 ;; If this is a test just for exact match, return nil ot t
5883 (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
5884 nil
5885 match))))
5886 ;; If flag is t, this was called by all-completions. Return
5887 ;; list of all possible completions
5888 (verilog-flag
5889 verilog-all)))
5890
5891(defvar verilog-last-word-numb 0)
5892(defvar verilog-last-word-shown nil)
5893(defvar verilog-last-completions nil)
5894
5895(defun verilog-complete-word ()
5896 "Complete word at current point.
5897\(See also `verilog-toggle-completions', `verilog-type-keywords',
5898and `verilog-separator-keywords'.)"
5899 (interactive)
5900 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5901 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5902 (verilog-str (buffer-substring b e))
5903 ;; The following variable is used in verilog-completion
5904 (verilog-buffer-to-use (current-buffer))
5905 (allcomp (if (and verilog-toggle-completions
5906 (string= verilog-last-word-shown verilog-str))
5907 verilog-last-completions
5908 (all-completions verilog-str 'verilog-completion)))
5909 (match (if verilog-toggle-completions
5910 "" (try-completion
5911 verilog-str (mapcar '(lambda (elm)
5912 (cons elm 0)) allcomp)))))
5913 ;; Delete old string
5914 (delete-region b e)
5915
5916 ;; Toggle-completions inserts whole labels
5917 (if verilog-toggle-completions
5918 (progn
5919 ;; Update entry number in list
5920 (setq verilog-last-completions allcomp
5921 verilog-last-word-numb
5922 (if (>= verilog-last-word-numb (1- (length allcomp)))
5923 0
5924 (1+ verilog-last-word-numb)))
5925 (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
5926 ;; Display next match or same string if no match was found
5927 (if (not (null allcomp))
5928 (insert "" verilog-last-word-shown)
5929 (insert "" verilog-str)
5930 (message "(No match)")))
5931 ;; The other form of completion does not necessarily do that.
5932
5933 ;; Insert match if found, or the original string if no match
5934 (if (or (null match) (equal match 't))
5935 (progn (insert "" verilog-str)
5936 (message "(No match)"))
5937 (insert "" match))
5938 ;; Give message about current status of completion
5939 (cond ((equal match 't)
5940 (if (not (null (cdr allcomp)))
5941 (message "(Complete but not unique)")
5942 (message "(Sole completion)")))
5943 ;; Display buffer if the current completion didn't help
5944 ;; on completing the label.
5945 ((and (not (null (cdr allcomp))) (= (length verilog-str)
5946 (length match)))
5947 (with-output-to-temp-buffer "*Completions*"
5948 (display-completion-list allcomp))
5949 ;; Wait for a key press. Then delete *Completion* window
5950 (momentary-string-display "" (point))
5951 (delete-window (get-buffer-window (get-buffer "*Completions*")))
5952 )))))
5953
5954(defun verilog-show-completions ()
5955 "Show all possible completions at current point."
5956 (interactive)
5957 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5958 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5959 (verilog-str (buffer-substring b e))
5960 ;; The following variable is used in verilog-completion
5961 (verilog-buffer-to-use (current-buffer))
5962 (allcomp (if (and verilog-toggle-completions
5963 (string= verilog-last-word-shown verilog-str))
5964 verilog-last-completions
5965 (all-completions verilog-str 'verilog-completion))))
5966 ;; Show possible completions in a temporary buffer.
5967 (with-output-to-temp-buffer "*Completions*"
5968 (display-completion-list allcomp))
5969 ;; Wait for a key press. Then delete *Completion* window
5970 (momentary-string-display "" (point))
5971 (delete-window (get-buffer-window (get-buffer "*Completions*")))))
5972
5973
5974(defun verilog-get-default-symbol ()
5975 "Return symbol around current point as a string."
5976 (save-excursion
5977 (buffer-substring (progn
5978 (skip-chars-backward " \t")
5979 (skip-chars-backward "a-zA-Z0-9_")
5980 (point))
5981 (progn
5982 (skip-chars-forward "a-zA-Z0-9_")
5983 (point)))))
5984
5985(defun verilog-build-defun-re (str &optional arg)
5986 "Return function/task/module starting with STR as regular expression.
5987With optional second ARG non-nil, STR is the complete name of the instruction."
5988 (if arg
5989 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
5990 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
5991
5992(defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
5993 "Function passed to `completing-read', `try-completion' or `all-completions'.
5994Returns a completion on any function name based on VERILOG-STR prefix. If
5995VERILOG-PRED is non-nil, it must be a function to be called for every match
5996to check if this should really be a match. If VERILOG-FLAG is t, the
5997function returns a list of all possible completions. If it is nil it
5998returns a string, the longest possible completion, or t if VERILOG-STR is
5999an exact match. If VERILOG-FLAG is 'lambda, the function returns t if
6000VERILOG-STR is an exact match, nil otherwise."
6001 (save-excursion
6002 (let ((verilog-all nil)
6003 match)
6004
6005 ;; Set buffer to use for searching labels. This should be set
6006 ;; within functions which use verilog-completions
6007 (set-buffer verilog-buffer-to-use)
6008
6009 (let ((verilog-str verilog-str))
6010 ;; Build regular expression for functions
6011 (if (string= verilog-str "")
6012 (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
6013 (setq verilog-str (verilog-build-defun-re verilog-str)))
6014 (goto-char (point-min))
6015
6016 ;; Build a list of all possible completions
6017 (while (verilog-re-search-forward verilog-str nil t)
6018 (setq match (buffer-substring (match-beginning 2) (match-end 2)))
6019 (if (or (null verilog-pred)
6020 (funcall verilog-pred match))
6021 (setq verilog-all (cons match verilog-all)))))
6022
6023 ;; Now we have built a list of all matches. Give response to caller
6024 (verilog-completion-response))))
6025
6026(defun verilog-goto-defun ()
6027 "Move to specified Verilog module/task/function.
6028The default is a name found in the buffer around point.
6029If search fails, other files are checked based on
6030`verilog-library-flags'."
6031 (interactive)
6032 (let* ((default (verilog-get-default-symbol))
6033 ;; The following variable is used in verilog-comp-function
6034 (verilog-buffer-to-use (current-buffer))
6035 (label (if (not (string= default ""))
6036 ;; Do completion with default
a3a8b002
DN
6037 (completing-read (concat "Goto-Label: (default "
6038 default ") ")
6341f357
DN
6039 'verilog-comp-defun nil nil "")
6040 ;; There is no default value. Complete without it
a3a8b002 6041 (completing-read "Goto-Label: "
6341f357
DN
6042 'verilog-comp-defun nil nil "")))
6043 pt)
a3a8b002
DN
6044 ;; Make sure library paths are correct, in case need to resolve module
6045 (verilog-auto-reeval-locals)
6046 (verilog-getopt-flags)
6341f357
DN
6047 ;; If there was no response on prompt, use default value
6048 (if (string= label "")
6049 (setq label default))
6050 ;; Goto right place in buffer if label is not an empty string
6051 (or (string= label "")
6052 (progn
6053 (save-excursion
6054 (goto-char (point-min))
7ea26faf
DN
6055 (setq pt
6056 (re-search-forward (verilog-build-defun-re label t) nil t)))
6341f357
DN
6057 (when pt
6058 (goto-char pt)
6059 (beginning-of-line))
6060 pt)
60618039 6061 (verilog-goto-defun-file label))))
6341f357
DN
6062
6063;; Eliminate compile warning
7d55bf04 6064(defvar occur-pos-list)
6341f357
DN
6065
6066(defun verilog-showscopes ()
6067 "List all scopes in this module."
6068 (interactive)
6069 (let ((buffer (current-buffer))
6070 (linenum 1)
6071 (nlines 0)
6072 (first 1)
6073 (prevpos (point-min))
6074 (final-context-start (make-marker))
60618039 6075 (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
6341f357
DN
6076 (with-output-to-temp-buffer "*Occur*"
6077 (save-excursion
6078 (message (format "Searching for %s ..." regexp))
6079 ;; Find next match, but give up if prev match was at end of buffer.
6080 (while (and (not (= prevpos (point-max)))
6081 (verilog-re-search-forward regexp nil t))
6082 (goto-char (match-beginning 0))
6083 (beginning-of-line)
6084 (save-match-data
6085 (setq linenum (+ linenum (count-lines prevpos (point)))))
6086 (setq prevpos (point))
6087 (goto-char (match-end 0))
6088 (let* ((start (save-excursion
6089 (goto-char (match-beginning 0))
6090 (forward-line (if (< nlines 0) nlines (- nlines)))
6091 (point)))
6092 (end (save-excursion
6093 (goto-char (match-end 0))
6094 (if (> nlines 0)
6095 (forward-line (1+ nlines))
6096 (forward-line 1))
6097 (point)))
6098 (tag (format "%3d" linenum))
6099 (empty (make-string (length tag) ?\ ))
6100 tem)
6101 (save-excursion
6102 (setq tem (make-marker))
6103 (set-marker tem (point))
6104 (set-buffer standard-output)
6105 (setq occur-pos-list (cons tem occur-pos-list))
6106 (or first (zerop nlines)
6107 (insert "--------\n"))
6108 (setq first nil)
6109 (insert-buffer-substring buffer start end)
6110 (backward-char (- end start))
6111 (setq tem (if (< nlines 0) (- nlines) nlines))
6112 (while (> tem 0)
6113 (insert empty ?:)
6114 (forward-line 1)
6115 (setq tem (1- tem)))
6116 (let ((this-linenum linenum))
6117 (set-marker final-context-start
6118 (+ (point) (- (match-end 0) (match-beginning 0))))
6119 (while (< (point) final-context-start)
6120 (if (null tag)
6121 (setq tag (format "%3d" this-linenum)))
6122 (insert tag ?:)))))))
6123 (set-buffer-modified-p nil))))
6124
6125
6126;; Highlight helper functions
6127(defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
6128(defun verilog-within-translate-off ()
6129 "Return point if within translate-off region, else nil."
6130 (and (save-excursion
6131 (re-search-backward
6132 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
6133 nil t))
6134 (equal "off" (match-string 2))
6135 (point)))
6136
6137(defun verilog-start-translate-off (limit)
6138 "Return point before translate-off directive if before LIMIT, else nil."
6139 (when (re-search-forward
6140 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6141 limit t)
6142 (match-beginning 0)))
6143
6144(defun verilog-back-to-start-translate-off (limit)
6145 "Return point before translate-off directive if before LIMIT, else nil."
6146 (when (re-search-backward
6147 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6148 limit t)
6149 (match-beginning 0)))
6150
6151(defun verilog-end-translate-off (limit)
6152 "Return point after translate-on directive if before LIMIT, else nil."
6153
6154 (re-search-forward (concat
6155 "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
6156
6157(defun verilog-match-translate-off (limit)
6158 "Match a translate-off block, setting `match-data' and returning t, else nil.
6159Bound search by LIMIT."
6160 (when (< (point) limit)
6161 (let ((start (or (verilog-within-translate-off)
6162 (verilog-start-translate-off limit)))
6163 (case-fold-search t))
6164 (when start
6165 (let ((end (or (verilog-end-translate-off limit) limit)))
6166 (set-match-data (list start end))
6167 (goto-char end))))))
6168
6169(defun verilog-font-lock-match-item (limit)
6170 "Match, and move over, any declaration item after point.
6171Bound search by LIMIT. Adapted from
6172`font-lock-match-c-style-declaration-item-and-skip-to-next'."
6173 (condition-case nil
6174 (save-restriction
6175 (narrow-to-region (point-min) limit)
6176 ;; match item
6177 (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
6178 (save-match-data
6179 (goto-char (match-end 1))
6180 ;; move to next item
6181 (if (looking-at "\\(\\s-*,\\)")
6182 (goto-char (match-end 1))
6183 (end-of-line) t))))
6184 (error nil)))
6185
6186
6187;; Added by Subbu Meiyappan for Header
6188
6189(defun verilog-header ()
a3a8b002
DN
6190 "Insert a standard Verilog file header.
6191See also `verilog-sk-header' for an alternative format."
6341f357
DN
6192 (interactive)
6193 (let ((start (point)))
6194 (insert "\
6195//-----------------------------------------------------------------------------
6196// Title : <title>
6197// Project : <project>
6198//-----------------------------------------------------------------------------
6199// File : <filename>
6200// Author : <author>
6201// Created : <credate>
6202// Last modified : <moddate>
6203//-----------------------------------------------------------------------------
6204// Description :
6205// <description>
6206//-----------------------------------------------------------------------------
6207// Copyright (c) <copydate> by <company> This model is the confidential and
6208// proprietary property of <company> and the possession or use of this
6209// file requires a written license from <company>.
6210//------------------------------------------------------------------------------
6211// Modification history :
6212// <modhist>
6213//-----------------------------------------------------------------------------
6214
6215")
6216 (goto-char start)
6217 (search-forward "<filename>")
6218 (replace-match (buffer-name) t t)
6219 (search-forward "<author>") (replace-match "" t t)
6220 (insert (user-full-name))
6221 (insert " <" (user-login-name) "@" (system-name) ">")
6222 (search-forward "<credate>") (replace-match "" t t)
6ca0ff73 6223 (verilog-insert-date)
6341f357 6224 (search-forward "<moddate>") (replace-match "" t t)
6ca0ff73 6225 (verilog-insert-date)
6341f357 6226 (search-forward "<copydate>") (replace-match "" t t)
6ca0ff73 6227 (verilog-insert-year)
6341f357 6228 (search-forward "<modhist>") (replace-match "" t t)
6ca0ff73 6229 (verilog-insert-date)
6341f357
DN
6230 (insert " : created")
6231 (goto-char start)
6232 (let (string)
6233 (setq string (read-string "title: "))
6234 (search-forward "<title>")
6235 (replace-match string t t)
6236 (setq string (read-string "project: " verilog-project))
6341f357
DN
6237 (setq verilog-project string)
6238 (search-forward "<project>")
6239 (replace-match string t t)
6240 (setq string (read-string "Company: " verilog-company))
6341f357
DN
6241 (setq verilog-company string)
6242 (search-forward "<company>")
6243 (replace-match string t t)
6244 (search-forward "<company>")
6245 (replace-match string t t)
6246 (search-forward "<company>")
6247 (replace-match string t t)
6248 (search-backward "<description>")
60618039 6249 (replace-match "" t t))))
6341f357 6250
6ca0ff73 6251;; verilog-header Uses the verilog-insert-date function
6341f357 6252
6ca0ff73 6253(defun verilog-insert-date ()
6341f357
DN
6254 "Insert date from the system."
6255 (interactive)
a3a8b002
DN
6256 (if verilog-date-scientific-format
6257 (insert (format-time-string "%Y/%m/%d"))
6258 (insert (format-time-string "%d.%m.%Y"))))
6341f357 6259
6ca0ff73 6260(defun verilog-insert-year ()
6341f357
DN
6261 "Insert year from the system."
6262 (interactive)
a3a8b002 6263 (insert (format-time-string "%Y")))
6341f357
DN
6264
6265\f
6266;;
6267;; Signal list parsing
6268;;
6269
6270;; Elements of a signal list
6271(defsubst verilog-sig-name (sig)
6272 (car sig))
6273(defsubst verilog-sig-bits (sig)
6274 (nth 1 sig))
6275(defsubst verilog-sig-comment (sig)
6276 (nth 2 sig))
6277(defsubst verilog-sig-memory (sig)
6278 (nth 3 sig))
6279(defsubst verilog-sig-enum (sig)
6280 (nth 4 sig))
6281(defsubst verilog-sig-signed (sig)
6282 (nth 5 sig))
6283(defsubst verilog-sig-type (sig)
6284 (nth 6 sig))
6285(defsubst verilog-sig-multidim (sig)
6286 (nth 7 sig))
6287(defsubst verilog-sig-multidim-string (sig)
6288 (if (verilog-sig-multidim sig)
6289 (let ((str "") (args (verilog-sig-multidim sig)))
6290 (while args
6291 (setq str (concat str (car args)))
6292 (setq args (cdr args)))
6293 str)))
a3a8b002
DN
6294(defsubst verilog-sig-modport (sig)
6295 (nth 8 sig))
6341f357
DN
6296(defsubst verilog-sig-width (sig)
6297 (verilog-make-width-expression (verilog-sig-bits sig)))
6298
6299(defsubst verilog-alw-get-inputs (sigs)
6300 (nth 2 sigs))
6301(defsubst verilog-alw-get-outputs (sigs)
6302 (nth 0 sigs))
6303(defsubst verilog-alw-get-uses-delayed (sigs)
6304 (nth 3 sigs))
6305
6306(defun verilog-signals-not-in (in-list not-list)
37ea4b9b
JB
6307 "Return list of signals in IN-LIST that aren't also in NOT-LIST.
6308Also remove any duplicates in IN-LIST.
6341f357
DN
6309Signals must be in standard (base vector) form."
6310 (let (out-list)
6311 (while in-list
6312 (if (not (or (assoc (car (car in-list)) not-list)
6313 (assoc (car (car in-list)) out-list)))
6314 (setq out-list (cons (car in-list) out-list)))
6315 (setq in-list (cdr in-list)))
6316 (nreverse out-list)))
6317;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
6318
6319(defun verilog-signals-in (in-list other-list)
6320 "Return list of signals in IN-LIST that are also in OTHER-LIST.
6321Signals must be in standard (base vector) form."
6322 (let (out-list)
6323 (while in-list
6324 (if (assoc (car (car in-list)) other-list)
6325 (setq out-list (cons (car in-list) out-list)))
6326 (setq in-list (cdr in-list)))
6327 (nreverse out-list)))
6328;;(verilog-signals-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
6329
6330(defun verilog-signals-memory (in-list)
6331 "Return list of signals in IN-LIST that are memoried (multidimensional)."
6332 (let (out-list)
6333 (while in-list
6334 (if (nth 3 (car in-list))
6335 (setq out-list (cons (car in-list) out-list)))
6336 (setq in-list (cdr in-list)))
6337 out-list))
6338;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
6339
6340(defun verilog-signals-sort-compare (a b)
6341 "Compare signal A and B for sorting."
6342 (string< (car a) (car b)))
6343
6344(defun verilog-signals-not-params (in-list)
6345 "Return list of signals in IN-LIST that aren't parameters or numeric constants."
6346 (let (out-list)
6347 (while in-list
6348 (unless (boundp (intern (concat "vh-" (car (car in-list)))))
6349 (setq out-list (cons (car in-list) out-list)))
6350 (setq in-list (cdr in-list)))
6351 (nreverse out-list)))
6352
6353(defun verilog-signals-combine-bus (in-list)
6354 "Return a list of signals in IN-LIST, with busses combined.
6355Duplicate signals are also removed. For example A[2] and A[1] become A[2:1]."
6356 (let (combo buswarn
6357 out-list
6358 sig highbit lowbit ; Temp information about current signal
6359 sv-name sv-highbit sv-lowbit ; Details about signal we are forming
6360 sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
a3a8b002 6361 sv-modport
6341f357
DN
6362 bus)
6363 ;; Shove signals so duplicated signals will be adjacent
6364 (setq in-list (sort in-list `verilog-signals-sort-compare))
6365 (while in-list
6366 (setq sig (car in-list))
6367 ;; No current signal; form from existing details
6368 (unless sv-name
6369 (setq sv-name (verilog-sig-name sig)
6370 sv-highbit nil
6371 sv-busstring nil
6372 sv-comment (verilog-sig-comment sig)
6373 sv-memory (verilog-sig-memory sig)
6374 sv-enum (verilog-sig-enum sig)
6375 sv-signed (verilog-sig-signed sig)
6376 sv-type (verilog-sig-type sig)
6377 sv-multidim (verilog-sig-multidim sig)
a3a8b002 6378 sv-modport (verilog-sig-modport sig)
6341f357 6379 combo ""
60618039 6380 buswarn ""))
6341f357
DN
6381 ;; Extract bus details
6382 (setq bus (verilog-sig-bits sig))
6383 (cond ((and bus
6384 (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
7ea26faf
DN
6385 (setq highbit (string-to-number (match-string 1 bus))
6386 lowbit (string-to-number
6387 (match-string 2 bus))))
6341f357 6388 (and (string-match "\\[\\([0-9]+\\)\\]" bus)
7ea26faf 6389 (setq highbit (string-to-number (match-string 1 bus))
6341f357
DN
6390 lowbit highbit))))
6391 ;; Combine bits in bus
6392 (if sv-highbit
6393 (setq sv-highbit (max highbit sv-highbit)
6394 sv-lowbit (min lowbit sv-lowbit))
6395 (setq sv-highbit highbit
6396 sv-lowbit lowbit)))
6397 (bus
6398 ;; String, probably something like `preproc:0
6399 (setq sv-busstring bus)))
6400 ;; Peek ahead to next signal
6401 (setq in-list (cdr in-list))
6402 (setq sig (car in-list))
6403 (cond ((and sig (equal sv-name (verilog-sig-name sig)))
6404 ;; Combine with this signal
7ea26faf
DN
6405 (when (and sv-busstring
6406 (not (equal sv-busstring (verilog-sig-bits sig))))
6341f357
DN
6407 (when nil ;; Debugging
6408 (message (concat "Warning, can't merge into single bus "
6409 sv-name bus
6410 ", the AUTOs may be wrong")))
6411 (setq buswarn ", Couldn't Merge"))
6412 (if (verilog-sig-comment sig) (setq combo ", ..."))
6413 (setq sv-memory (or sv-memory (verilog-sig-memory sig))
6414 sv-enum (or sv-enum (verilog-sig-enum sig))
6415 sv-signed (or sv-signed (verilog-sig-signed sig))
6416 sv-type (or sv-type (verilog-sig-type sig))
a3a8b002
DN
6417 sv-multidim (or sv-multidim (verilog-sig-multidim sig))
6418 sv-modport (or sv-modport (verilog-sig-modport sig))))
6341f357
DN
6419 ;; Doesn't match next signal, add to queue, zero in prep for next
6420 ;; Note sig may also be nil for the last signal in the list
6421 (t
6422 (setq out-list
7ea26faf
DN
6423 (cons
6424 (list sv-name
6425 (or sv-busstring
6426 (if sv-highbit
6427 (concat "[" (int-to-string sv-highbit) ":"
6428 (int-to-string sv-lowbit) "]")))
60618039 6429 (concat sv-comment combo buswarn)
a3a8b002 6430 sv-memory sv-enum sv-signed sv-type sv-multidim sv-modport)
60618039
DN
6431 out-list)
6432 sv-name nil))))
6341f357
DN
6433 ;;
6434 out-list))
6435
6436(defun verilog-sig-tieoff (sig &optional no-width)
60618039 6437 "Return tieoff expression for given SIG, with appropriate width.
6341f357
DN
6438Ignore width if optional NO-WIDTH is set."
6439 (let* ((width (if no-width nil (verilog-sig-width sig))))
6440 (concat
6441 (if (and verilog-active-low-regexp
6442 (string-match verilog-active-low-regexp (verilog-sig-name sig)))
6443 "~" "")
6444 (cond ((not width)
6445 "0")
6446 ((string-match "^[0-9]+$" width)
6447 (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
6448 (t
6449 (concat "{" width "{1'b0}}"))))))
6450
6451;;
6452;; Port/Wire/Etc Reading
6453;;
6454
6455(defun verilog-read-inst-backward-name ()
6456 "Internal. Move point back to beginning of inst-name."
6457 (verilog-backward-open-paren)
6458 (let (done)
6459 (while (not done)
6460 (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil) ; ] isn't word boundary
6461 (cond ((looking-at ")")
6462 (verilog-backward-open-paren))
6463 (t (setq done t)))))
6464 (while (looking-at "\\]")
6465 (verilog-backward-open-bracket)
6466 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
6467 (skip-chars-backward "a-zA-Z0-9`_$"))
6468
6469(defun verilog-read-inst-module ()
6470 "Return module_name when point is inside instantiation."
6471 (save-excursion
6472 (verilog-read-inst-backward-name)
6473 ;; Skip over instantiation name
6474 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
6475 ;; Check for parameterized instantiations
6476 (when (looking-at ")")
6477 (verilog-backward-open-paren)
6478 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
6479 (skip-chars-backward "a-zA-Z0-9'_$")
6480 (looking-at "[a-zA-Z0-9`_\$]+")
d63b01e1 6481 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6341f357
DN
6482 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
6483
6484(defun verilog-read-inst-name ()
6485 "Return instance_name when point is inside instantiation."
6486 (save-excursion
6487 (verilog-read-inst-backward-name)
6488 (looking-at "[a-zA-Z0-9`_\$]+")
d63b01e1 6489 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6341f357
DN
6490 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
6491
6492(defun verilog-read-module-name ()
6493 "Return module name when after its ( or ;."
6494 (save-excursion
6495 (re-search-backward "[(;]")
6496 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
6497 (skip-chars-backward "a-zA-Z0-9`_$")
6498 (looking-at "[a-zA-Z0-9`_\$]+")
d63b01e1 6499 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
a3a8b002
DN
6500 (verilog-symbol-detick
6501 (buffer-substring-no-properties (match-beginning 0) (match-end 0)) t)))
6341f357 6502
4c5e69c6
DN
6503(defun verilog-read-inst-param-value ()
6504 "Return list of parameters and values when point is inside instantiation."
6505 (save-excursion
6506 (verilog-read-inst-backward-name)
6507 ;; Skip over instantiation name
6508 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
6509 ;; If there are parameterized instantiations
6510 (when (looking-at ")")
6511 (let ((end-pt (point))
6512 params
6513 param-name paren-beg-pt param-value)
6514 (verilog-backward-open-paren)
6515 (while (verilog-re-search-forward-quick "\\." end-pt t)
6516 (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
6517 (skip-chars-backward "a-zA-Z0-9'_$")
6518 (looking-at "[a-zA-Z0-9`_\$]+")
6519 (setq param-name (buffer-substring-no-properties
6520 (match-beginning 0) (match-end 0)))
6521 (verilog-re-search-forward-quick "(" nil nil)
6522 (setq paren-beg-pt (point))
6523 (verilog-forward-close-paren)
6524 (setq param-value (verilog-string-remove-spaces
6525 (buffer-substring-no-properties
6526 paren-beg-pt (1- (point)))))
6527 (setq params (cons (list param-name param-value) params)))
6528 params))))
6529
6341f357
DN
6530(defun verilog-read-auto-params (num-param &optional max-param)
6531 "Return parameter list inside auto.
6532Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
6533 (let ((olist))
6534 (save-excursion
6535 ;; /*AUTOPUNT("parameter", "parameter")*/
6536 (search-backward "(")
6537 (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
6538 (setq olist (cons (match-string 1) olist))
6539 (goto-char (match-end 0))))
6540 (or (eq nil num-param)
6541 (<= num-param (length olist))
6542 (error "%s: Expected %d parameters" (verilog-point-text) num-param))
6543 (if (eq max-param nil) (setq max-param num-param))
6544 (or (eq nil max-param)
6545 (>= max-param (length olist))
6546 (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
6547 (nreverse olist)))
6548
6549(defun verilog-read-decls ()
6550 "Compute signal declaration information for the current module at point.
6551Return a array of [outputs inouts inputs wire reg assign const]."
6552 (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
a3a8b002
DN
6553 (functask 0) (paren 0) (sig-paren 0) (v2kargs-ok t)
6554 sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const
6555 sigs-gparam sigs-intf
6556 vec expect-signal keywd newsig rvalue enum io signed typedefed multidim
6557 modport)
6341f357
DN
6558 (save-excursion
6559 (verilog-beg-of-defun)
6560 (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
6561 (while (< (point) end-mod-point)
6562 ;;(if dbg (setq dbg (cons (format "Pt %s Vec %s Kwd'%s'\n" (point) vec keywd) dbg)))
6563 (cond
6564 ((looking-at "//")
6565 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6566 (setq enum (match-string 1)))
6567 (search-forward "\n"))
6568 ((looking-at "/\\*")
6569 (forward-char 2)
6570 (if (looking-at "[^*]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6571 (setq enum (match-string 1)))
6572 (or (search-forward "*/")
6573 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6574 ((looking-at "(\\*")
6575 (forward-char 2)
a3a8b002 6576 (or (looking-at "\\s-*)") ; It's an "always @ (*)"
6341f357
DN
6577 (search-forward "*)")
6578 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
6579 ((eq ?\" (following-char))
6580 (or (re-search-forward "[^\\]\"" nil t) ;; don't forward-char first, since we look for a non backslash first
6581 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
6582 ((eq ?\; (following-char))
a3a8b002
DN
6583 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil
6584 v2kargs-ok nil)
6341f357
DN
6585 (forward-char 1))
6586 ((eq ?= (following-char))
6587 (setq rvalue t newsig nil)
6588 (forward-char 1))
6589 ((and (or rvalue sig-paren)
6590 (cond ((and (eq ?, (following-char))
6591 (eq paren sig-paren))
6592 (setq rvalue nil)
6593 (forward-char 1)
6594 t)
6595 ;; ,'s can occur inside {} & funcs
6596 ((looking-at "[{(]")
6597 (setq paren (1+ paren))
6598 (forward-char 1)
6599 t)
6600 ((looking-at "[})]")
6601 (setq paren (1- paren))
6602 (forward-char 1)
6603 (when (< paren sig-paren)
6604 (setq expect-signal nil)) ; ) that ends variables inside v2k arg list
60618039 6605 t))))
6341f357
DN
6606 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
6607 (goto-char (match-end 0))
6608 (cond (newsig ; Memory, not just width. Patch last signal added's memory (nth 3)
6609 (setcar (cdr (cdr (cdr newsig))) (match-string 1)))
6610 (vec ;; Multidimensional
6611 (setq multidim (cons vec multidim))
6612 (setq vec (verilog-string-replace-matches
6613 "\\s-+" "" nil nil (match-string 1))))
6614 (t ;; Bit width
6615 (setq vec (verilog-string-replace-matches
6616 "\\s-+" "" nil nil (match-string 1))))))
6617 ;; Normal or escaped identifier -- note we remember the \ if escaped
6618 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
6619 (goto-char (match-end 0))
6620 (setq keywd (match-string 1))
6621 (when (string-match "^\\\\" keywd)
6622 (setq keywd (concat keywd " "))) ;; Escaped ID needs space at end
6623 (cond ((equal keywd "input")
6624 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002 6625 expect-signal 'sigs-in io t modport nil))
6341f357
DN
6626 ((equal keywd "output")
6627 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002 6628 expect-signal 'sigs-out io t modport nil))
6341f357
DN
6629 ((equal keywd "inout")
6630 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002
DN
6631 expect-signal 'sigs-inout io t modport nil))
6632 ((equal keywd "parameter")
6633 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6634 expect-signal 'sigs-gparam io t modport nil))
6635 ((member keywd '("wire" "tri" "tri0" "tri1" "triand" "trior" "wand" "wor"))
6341f357 6636 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002
DN
6637 expect-signal 'sigs-wire modport nil)))
6638 ((member keywd '("reg" "trireg"
6639 "byte" "shortint" "int" "longint" "integer" "time"
6640 "bit" "logic"))
6341f357 6641 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002 6642 expect-signal 'sigs-reg modport nil)))
6341f357
DN
6643 ((equal keywd "assign")
6644 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002
DN
6645 expect-signal 'sigs-assign modport nil))
6646 ((member keywd '("supply0" "supply1" "supply"
6647 "localparam" "genvar"))
6341f357 6648 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
a3a8b002 6649 expect-signal 'sigs-const modport nil)))
6341f357
DN
6650 ((equal keywd "signed")
6651 (setq signed "signed"))
a3a8b002
DN
6652 ((member keywd '("class" "clocking" "covergroup" "function"
6653 "property" "randsequence" "sequence" "task"))
6341f357 6654 (setq functask (1+ functask)))
a3a8b002
DN
6655 ((member keywd '("endclass" "endclocking" "endgroup" "endfunction"
6656 "endproperty" "endsequence" "endtask"))
6341f357 6657 (setq functask (1- functask)))
a3a8b002
DN
6658 ;; Ifdef? Ignore name of define
6659 ((member keywd '("`ifdef" "`ifndef"))
6341f357 6660 (setq rvalue t))
a3a8b002 6661 ;; Type?
6341f357
DN
6662 ((verilog-typedef-name-p keywd)
6663 (setq typedefed keywd))
a3a8b002
DN
6664 ;; Interface with optional modport in v2k arglist?
6665 ;; Skip over parsing modport, and take the interface name as the type
6666 ((and v2kargs-ok
6667 (eq paren 1)
6668 (looking-at "\\s-*\\(\\.\\(\\s-*[a-zA-Z0-9`_$]+\\)\\|\\)\\s-*[a-zA-Z0-9`_$]+"))
6669 (when (match-end 2) (goto-char (match-end 2)))
6670 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed keywd multidim nil sig-paren paren
6671 expect-signal 'sigs-intf io t modport (match-string 2)))
6672 ;; New signal, maybe?
6341f357
DN
6673 ((and expect-signal
6674 (eq functask 0)
6675 (not rvalue)
6676 (eq paren sig-paren)
6677 (not (member keywd verilog-keywords)))
6678 ;; Add new signal to expect-signal's variable
a3a8b002 6679 (setq newsig (list keywd vec nil nil enum signed typedefed multidim modport))
6341f357
DN
6680 (set expect-signal (cons newsig
6681 (symbol-value expect-signal))))))
6682 (t
6683 (forward-char 1)))
6684 (skip-syntax-forward " "))
6685 ;; Return arguments
6686 (vector (nreverse sigs-out)
6687 (nreverse sigs-inout)
6688 (nreverse sigs-in)
6689 (nreverse sigs-wire)
6690 (nreverse sigs-reg)
6691 (nreverse sigs-assign)
6692 (nreverse sigs-const)
a3a8b002
DN
6693 (nreverse sigs-gparam)
6694 (nreverse sigs-intf)))))
6341f357 6695
60618039
DN
6696(eval-when-compile
6697 ;; Prevent compile warnings; these are let's, not globals
6698 ;; Do not remove the eval-when-compile
6699 ;; - we want a error when we are debugging this code if they are refed.
6700 (defvar sigs-in)
6701 (defvar sigs-inout)
a3a8b002
DN
6702 (defvar sigs-out)
6703 (defvar sigs-intf))
7ea26faf
DN
6704
6705
6706(defsubst verilog-modi-get-decls (modi)
6707 (verilog-modi-cache-results modi 'verilog-read-decls))
6708
6709(defsubst verilog-modi-get-sub-decls (modi)
6710 (verilog-modi-cache-results modi 'verilog-read-sub-decls))
6711
6712
6713;; Signal reading for given module
6714;; Note these all take modi's - as returned from the
6715;; verilog-modi-current function.
5509c6ad
DN
6716(defsubst verilog-decls-get-outputs (decls)
6717 (aref decls 0))
6718(defsubst verilog-decls-get-inouts (decls)
6719 (aref decls 1))
6720(defsubst verilog-decls-get-inputs (decls)
6721 (aref decls 2))
6722(defsubst verilog-decls-get-wires (decls)
6723 (aref decls 3))
6724(defsubst verilog-decls-get-regs (decls)
6725 (aref decls 4))
6726(defsubst verilog-decls-get-assigns (decls)
6727 (aref decls 5))
6728(defsubst verilog-decls-get-consts (decls)
6729 (aref decls 6))
6730(defsubst verilog-decls-get-gparams (decls)
6731 (aref decls 7))
a3a8b002
DN
6732(defsubst verilog-decls-get-interfaces (decls)
6733 (aref decls 8))
5509c6ad
DN
6734(defsubst verilog-subdecls-get-outputs (subdecls)
6735 (aref subdecls 0))
6736(defsubst verilog-subdecls-get-inouts (subdecls)
6737 (aref subdecls 1))
6738(defsubst verilog-subdecls-get-inputs (subdecls)
6739 (aref subdecls 2))
a3a8b002
DN
6740(defsubst verilog-subdecls-get-interfaces (subdecls)
6741 (aref subdecls 3))
5509c6ad
DN
6742
6743
6744(defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
37ea4b9b 6745 "For `verilog-read-sub-decls-line', add a signal."
6341f357
DN
6746 (let (portdata)
6747 (when sig
6748 (setq port (verilog-symbol-detick-denumber port))
6749 (setq sig (verilog-symbol-detick-denumber sig))
a3a8b002 6750 (if sig (setq sig (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil sig)))
6341f357
DN
6751 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
6752 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
6753 (unless (or (not sig)
6754 (equal sig "")) ;; Ignore .foo(1'b1) assignments
5509c6ad 6755 (cond ((setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
6341f357
DN
6756 (setq sigs-inout (cons (list sig vec (concat "To/From " comment) nil nil
6757 (verilog-sig-signed portdata)
6758 (verilog-sig-type portdata)
6759 multidim)
6760 sigs-inout)))
5509c6ad 6761 ((setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
6341f357
DN
6762 (setq sigs-out (cons (list sig vec (concat "From " comment) nil nil
6763 (verilog-sig-signed portdata)
6764 (verilog-sig-type portdata)
6765 multidim)
6766 sigs-out)))
5509c6ad 6767 ((setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
6341f357
DN
6768 (setq sigs-in (cons (list sig vec (concat "To " comment) nil nil
6769 (verilog-sig-signed portdata)
6770 (verilog-sig-type portdata)
6771 multidim)
6772 sigs-in)))
a3a8b002
DN
6773 ((setq portdata (assoc port (verilog-decls-get-interfaces submoddecls)))
6774 (setq sigs-intf (cons (list sig vec (concat "To/From " comment) nil nil
6775 (verilog-sig-signed portdata)
6776 (verilog-sig-type portdata)
6777 multidim)
6778 sigs-intf)))
6341f357
DN
6779 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
6780 )))))
6781
a3a8b002
DN
6782(defun verilog-read-sub-decls-expr (submoddecls comment port expr)
6783 "For `verilog-read-sub-decls-line', parse a subexpression and add signals."
6784 ;;(message "vrsde: '%s'" expr)
6785 ;; Replace special /*[....]*/ comments inserted by verilog-auto-inst-port
6786 (setq expr (verilog-string-replace-matches "/\\*\\(\\[[^*]+\\]\\)\\*/" "\\1" nil nil expr))
6787 ;; Remove front operators
6788 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
6789 ;;
6790 (cond
6791 ;; {..., a, b} requires us to recurse on a,b
6792 ((string-match "^\\s-*{\\([^{}]*\\)}\\s-*$" expr)
6793 (let ((mlst (split-string (match-string 1 expr) ","))
6794 mstr)
6795 (while (setq mstr (pop mlst))
6796 (verilog-read-sub-decls-expr submoddecls comment port mstr))))
6797 (t
6798 (let (sig vec multidim)
6799 (cond ;; Find \signal. Final space is part of escaped signal name
6800 ((string-match "^\\s-*\\(\\\\[^ \t\n\f]+\\s-\\)" expr)
6801 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
6802 (setq sig (match-string 1 expr)
6803 expr (substring expr (match-end 0))))
6804 ;; Find signal
6805 ((string-match "^\\s-*\\([^[({).\\]+\\)" expr)
6806 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
6807 (setq sig (verilog-string-remove-spaces (match-string 1 expr))
6808 expr (substring expr (match-end 0)))))
6809 ;; Find [vector] or [multi][multi][multi][vector]
6810 (while (string-match "^\\s-*\\(\\[[^]]+\\]\\)" expr)
6811 ;;(message "vrsde-v: '%s'" (match-string 1 expr))
6812 (when vec (setq multidim (cons vec multidim)))
6813 (setq vec (match-string 1 expr)
6814 expr (substring expr (match-end 0))))
6815 ;; If found signal, and nothing unrecognized, add the signal
6816 ;;(message "vrsde-rem: '%s'" expr)
6817 (when (and sig (string-match "^\\s-*$" expr))
6818 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))))
6819
5509c6ad 6820(defun verilog-read-sub-decls-line (submoddecls comment)
37ea4b9b 6821 "For `verilog-read-sub-decls', read lines of port defs until none match anymore.
6341f357 6822Return the list of signals found, using submodi to look up each port."
a3a8b002 6823 (let (done port)
6341f357
DN
6824 (save-excursion
6825 (forward-line 1)
6826 (while (not done)
6827 ;; Get port name
6828 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
6829 (setq port (match-string 1))
6830 (goto-char (match-end 0)))
6831 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
6832 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
6833 (goto-char (match-end 0)))
6834 ((looking-at "\\s-*\\.[^(]*(")
6835 (setq port nil) ;; skip this line
6836 (goto-char (match-end 0)))
6837 (t
6838 (setq port nil done t))) ;; Unknown, ignore rest of line
a3a8b002
DN
6839 ;; Get signal name. Point is at the first-non-space after (
6840 ;; We intentionally ignore (non-escaped) signals with .s in them
6841 ;; this prevents AUTOWIRE etc from noticing hierarchical sigs.
6341f357 6842 (when port
a3a8b002
DN
6843 (cond ((looking-at "\\([^[({).\\]*\\)\\s-*)")
6844 (verilog-read-sub-decls-sig
6845 submoddecls comment port
6846 (verilog-string-remove-spaces (match-string 1)) ; sig
6847 nil nil)) ; vec multidim
6848 ;;
6849 ((looking-at "\\([^[({).\\]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
6850 (verilog-read-sub-decls-sig
6851 submoddecls comment port
6852 (verilog-string-remove-spaces (match-string 1)) ; sig
6853 (match-string 2) nil)) ; vec multidim
6854 ;; Fastpath was above looking-at's.
6855 ;; For something more complicated invoke a parser
6856 ((looking-at "[^)]+")
6857 (verilog-read-sub-decls-expr
6858 submoddecls comment port
6859 (buffer-substring
6860 (point) (1- (progn (backward-char 1) ; start at (
6861 (forward-sexp 1) (point)))))))) ; expr
6341f357
DN
6862 ;;
6863 (forward-line 1)))))
6864
6865(defun verilog-read-sub-decls ()
6866 "Internally parse signals going to modules under this module.
6867Return a array of [ outputs inouts inputs ] signals for modules that are
6868instantiated in this module. For example if declare A A (.B(SIG)) and SIG
6869is a output, then SIG will be included in the list.
6870
6871This only works on instantiations created with /*AUTOINST*/ converted by
6872\\[verilog-auto-inst]. Otherwise, it would have to read in the whole
6873component library to determine connectivity of the design.
6874
6875One work around for this problem is to manually create // Inputs and //
6876Outputs comments above subcell signals, for example:
6877
1dd4b004 6878 module ModuleName (
6341f357
DN
6879 // Outputs
6880 .out (out),
6881 // Inputs
6882 .in (in));"
6883 (save-excursion
6884 (let ((end-mod-point (verilog-get-end-of-defun t))
6885 st-point end-inst-point
6886 ;; below 3 modified by verilog-read-sub-decls-line
a3a8b002 6887 sigs-out sigs-inout sigs-in sigs-intf)
6341f357 6888 (verilog-beg-of-defun)
495ab0d5 6889 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
6341f357
DN
6890 (save-excursion
6891 (goto-char (match-beginning 0))
6892 (unless (verilog-inside-comment-p)
6893 ;; Attempt to snarf a comment
6894 (let* ((submod (verilog-read-inst-module))
6895 (inst (verilog-read-inst-name))
5509c6ad
DN
6896 (comment (concat inst " of " submod ".v"))
6897 submodi submoddecls)
6341f357 6898 (when (setq submodi (verilog-modi-lookup submod t))
5509c6ad 6899 (setq submoddecls (verilog-modi-get-decls submodi))
6341f357
DN
6900 ;; This could have used a list created by verilog-auto-inst
6901 ;; However I want it to be runnable even on user's manually added signals
6902 (verilog-backward-open-paren)
6903 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
6904 st-point (point))
a3a8b002
DN
6905 (while (re-search-forward "\\s *(?\\s *// Interfaces" end-inst-point t)
6906 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
6907 (goto-char st-point)
6341f357 6908 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
5509c6ad 6909 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
6341f357
DN
6910 (goto-char st-point)
6911 (while (re-search-forward "\\s *// Inouts" end-inst-point t)
5509c6ad 6912 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
6341f357
DN
6913 (goto-char st-point)
6914 (while (re-search-forward "\\s *// Inputs" end-inst-point t)
5509c6ad 6915 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
6341f357
DN
6916 )))))
6917 ;; Combine duplicate bits
6918 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
6919 (vector (verilog-signals-combine-bus (nreverse sigs-out))
6920 (verilog-signals-combine-bus (nreverse sigs-inout))
a3a8b002
DN
6921 (verilog-signals-combine-bus (nreverse sigs-in))
6922 (verilog-signals-combine-bus (nreverse sigs-intf))))))
6341f357
DN
6923
6924(defun verilog-read-inst-pins ()
37ea4b9b 6925 "Return an array of [ pins ] for the current instantiation at point.
6341f357
DN
6926For example if declare A A (.B(SIG)) then B will be included in the list."
6927 (save-excursion
6928 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
6929 pins pin)
6930 (verilog-backward-open-paren)
6931 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
6932 (setq pin (match-string 1))
6933 (unless (verilog-inside-comment-p)
6934 (setq pins (cons (list pin) pins))
6935 (when (looking-at "(")
6936 (forward-sexp 1))))
6937 (vector pins))))
6938
6939(defun verilog-read-arg-pins ()
37ea4b9b 6940 "Return an array of [ pins ] for the current argument declaration at point."
6341f357
DN
6941 (save-excursion
6942 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
6943 pins pin)
6944 (verilog-backward-open-paren)
6945 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
6946 (setq pin (match-string 1))
6947 (unless (verilog-inside-comment-p)
6948 (setq pins (cons (list pin) pins))))
6949 (vector pins))))
6950
6951(defun verilog-read-auto-constants (beg end-mod-point)
6952 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
6953 ;; Insert new
6954 (save-excursion
6955 (let (sig-list tpl-end-pt)
6956 (goto-char beg)
6957 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
6958 (if (not (looking-at "\\s *("))
6959 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
6960 (search-forward "(" end-mod-point)
6961 (setq tpl-end-pt (save-excursion
6962 (backward-char 1)
6963 (forward-sexp 1) ;; Moves to paren that closes argdecl's
6964 (backward-char 1)
6965 (point)))
6966 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
6967 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
6968 sig-list)))
6969
6970(defun verilog-read-auto-lisp (start end)
6971 "Look for and evaluate a AUTO_LISP between START and END."
6972 (save-excursion
6973 (goto-char start)
6974 (while (re-search-forward "\\<AUTO_LISP(" end t)
6975 (backward-char)
6976 (let* ((beg-pt (prog1 (point)
6977 (forward-sexp 1))) ;; Closing paren
6978 (end-pt (point)))
6979 (eval-region beg-pt end-pt nil)))))
6980
60618039
DN
6981(eval-when-compile
6982 ;; Prevent compile warnings; these are let's, not globals
6983 ;; Do not remove the eval-when-compile
6984 ;; - we want a error when we are debugging this code if they are refed.
6985 (defvar sigs-in)
6986 (defvar sigs-out)
6987 (defvar got-sig)
6988 (defvar got-rvalue)
6989 (defvar uses-delayed)
6990 (defvar vector-skip-list))
6341f357
DN
6991
6992(defun verilog-read-always-signals-recurse
6993 (exit-keywd rvalue ignore-next)
6994 "Recursive routine for parentheses/bracket matching.
6995EXIT-KEYWD is expression to stop at, nil if top level.
6996RVALUE is true if at right hand side of equal.
6997IGNORE-NEXT is true to ignore next token, fake from inside case statement."
6998 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
6999 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-rvalue end-else-check)
7000 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue ignore-next))))
7001 (while (not (or (eobp) gotend))
7002 (cond
7003 ((looking-at "//")
7004 (search-forward "\n"))
7005 ((looking-at "/\\*")
7006 (or (search-forward "*/")
7007 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7008 ((looking-at "(\\*")
7009 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7010 (search-forward "*)")
7011 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7012 (t (setq keywd (buffer-substring-no-properties
7013 (point)
7014 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7015 (forward-char 1))
7016 (point)))
7017 sig-last-tolk sig-tolk
7018 sig-tolk nil)
7019 ;;(if dbg (setq dbg (concat dbg (format "\tPt=%S %S\trv=%S in=%S ee=%S\n" (point) keywd rvalue ignore-next end-else-check))))
7020 (cond
7021 ((equal keywd "\"")
7022 (or (re-search-forward "[^\\]\"" nil t)
7023 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
7024 ;; else at top level loop, keep parsing
7025 ((and end-else-check (equal keywd "else"))
7026 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
7027 ;; no forward movement, want to see else in lower loop
7028 (setq end-else-check nil))
7029 ;; End at top level loop
7030 ((and end-else-check (looking-at "[^ \t\n\f]"))
7031 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
7032 (setq gotend t))
7033 ;; Final statement?
7034 ((and exit-keywd (equal keywd exit-keywd))
7035 (setq gotend t)
7036 (forward-char (length keywd)))
7037 ;; Standard tokens...
7038 ((equal keywd ";")
7039 (setq ignore-next nil rvalue semi-rvalue)
7040 ;; Final statement at top level loop?
7041 (when (not exit-keywd)
7042 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
7043 (setq end-else-check t))
7044 (forward-char 1))
7045 ((equal keywd "'")
7046 (if (looking-at "'s?[hdxbo][0-9a-fA-F_xz? \t]*")
7047 (goto-char (match-end 0))
7048 (forward-char 1)))
7049 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
7050 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
7051 (setq ignore-next nil rvalue nil))
7052 ((equal "?" exit-keywd) ;; x?y:z rvalue
7053 ) ;; NOP
a3a8b002
DN
7054 ((equal "]" exit-keywd) ;; [x:y] rvalue
7055 ) ;; NOP
6341f357
DN
7056 (got-sig ;; label: statement
7057 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
7058 ((not rvalue) ;; begin label
7059 (setq ignore-next t rvalue nil)))
7060 (forward-char 1))
7061 ((equal keywd "=")
a3a8b002
DN
7062 (if (and (eq (char-before) ?< )
7063 (not rvalue))
6341f357
DN
7064 (setq uses-delayed 1))
7065 (setq ignore-next nil rvalue t)
7066 (forward-char 1))
7067 ((equal keywd "?")
7068 (forward-char 1)
7069 (verilog-read-always-signals-recurse ":" rvalue nil))
7070 ((equal keywd "[")
7071 (forward-char 1)
7072 (verilog-read-always-signals-recurse "]" t nil))
7073 ((equal keywd "(")
7074 (forward-char 1)
7075 (cond (sig-last-tolk ;; Function call; zap last signal
7076 (setq got-sig nil)))
7077 (cond ((equal last-keywd "for")
7078 (verilog-read-always-signals-recurse ";" nil nil)
7079 (verilog-read-always-signals-recurse ";" t nil)
7080 (verilog-read-always-signals-recurse ")" nil nil))
7081 (t (verilog-read-always-signals-recurse ")" t nil))))
7082 ((equal keywd "begin")
7083 (skip-syntax-forward "w_")
7084 (verilog-read-always-signals-recurse "end" nil nil)
7085 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
7086 (setq ignore-next nil rvalue semi-rvalue)
7087 (if (not exit-keywd) (setq end-else-check t)))
7088 ((or (equal keywd "case")
7089 (equal keywd "casex")
7090 (equal keywd "casez"))
7091 (skip-syntax-forward "w_")
7092 (verilog-read-always-signals-recurse "endcase" t nil)
7093 (setq ignore-next nil rvalue semi-rvalue)
7094 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
7095 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
7096 (cond ((or (equal keywd "`ifdef")
7097 (equal keywd "`ifndef"))
7098 (setq ignore-next t))
7099 ((or ignore-next
7100 (member keywd verilog-keywords)
7101 (string-match "^\\$" keywd)) ;; PLI task
7102 (setq ignore-next nil))
7103 (t
7104 (setq keywd (verilog-symbol-detick-denumber keywd))
7105 (when got-sig
7106 (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
7107 (setq sigs-out (cons got-sig sigs-out)))
7108 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
7109 )
7110 (setq got-rvalue rvalue
7111 got-sig (if (or (not keywd)
7112 (assoc keywd (if got-rvalue sigs-in sigs-out)))
7113 nil (list keywd nil nil))
7114 sig-tolk t)))
7115 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7116 (t
7117 (forward-char 1)))
7118 ;; End of non-comment token
60618039 7119 (setq last-keywd keywd)))
6341f357
DN
7120 (skip-syntax-forward " "))
7121 ;; Append the final pending signal
7122 (when got-sig
7123 (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
7124 (setq sigs-out (cons got-sig sigs-out)))
7125 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
7126 (setq got-sig nil))
7127 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
7128 ))
7129
7130(defun verilog-read-always-signals ()
7131 "Parse always block at point and return list of (outputs inout inputs)."
7132 ;; Insert new
7133 (save-excursion
7134 (let* (;;(dbg "")
7135 sigs-in sigs-out
7136 uses-delayed) ;; Found signal/rvalue; push if not function
7137 (search-forward ")")
7138 (verilog-read-always-signals-recurse nil nil nil)
7139 ;;(if dbg (save-excursion (set-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg "")))
7140 ;; Return what was found
7141 (list sigs-out nil sigs-in uses-delayed))))
7142
7143(defun verilog-read-instants ()
7144 "Parse module at point and return list of ( ( file instance ) ... )."
7145 (verilog-beg-of-defun)
7146 (let* ((end-mod-point (verilog-get-end-of-defun t))
7147 (state nil)
7148 (instants-list nil))
7149 (save-excursion
7150 (while (< (point) end-mod-point)
7151 ;; Stay at level 0, no comments
7152 (while (progn
7153 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
7154 (or (> (car state) 0) ; in parens
7155 (nth 5 state) ; comment
7156 ))
7157 (forward-line 1))
7158 (beginning-of-line)
7159 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
7160 ;;(if (looking-at "^\\(.+\\)$")
7161 (let ((module (match-string 1))
7162 (instant (match-string 2)))
7163 (if (not (member module verilog-keywords))
7164 (setq instants-list (cons (list module instant) instants-list)))))
60618039 7165 (forward-line 1)))
6341f357
DN
7166 instants-list))
7167
7168
7169(defun verilog-read-auto-template (module)
7170 "Look for a auto_template for the instantiation of the given MODULE.
7171If found returns the signal name connections. Return REGEXP and
37ea4b9b 7172list of ( (signal_name connection_name)... )."
6341f357
DN
7173 (save-excursion
7174 ;; Find beginning
7175 (let ((tpl-regexp "\\([0-9]+\\)")
7176 (lineno 0)
7177 (templateno 0)
7178 tpl-sig-list tpl-wild-list tpl-end-pt rep)
7179 (cond ((or
7180 (re-search-backward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
7181 (progn
7182 (goto-char (point-min))
7183 (re-search-forward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
7184 (goto-char (match-end 0))
7185 ;; Parse "REGEXP"
7186 ;; We reserve @"..." for future lisp expressions that evaluate once-per-AUTOINST
7187 (when (looking-at "\\s-*\"\\([^\"]*)\\)\"")
7188 (setq tpl-regexp (match-string 1))
7189 (goto-char (match-end 0)))
7190 (search-forward "(")
7191 ;; Parse lines in the template
7192 (when verilog-auto-inst-template-numbers
7193 (save-excursion
7194 (goto-char (point-min))
7195 (while (search-forward "AUTO_TEMPLATE" nil t)
7196 (setq templateno (1+ templateno)))))
7197 (setq tpl-end-pt (save-excursion
7198 (backward-char 1)
7199 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7200 (backward-char 1)
7201 (point)))
7202 ;;
7203 (while (< (point) tpl-end-pt)
7204 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7205 (setq tpl-sig-list (cons (list
7206 (match-string-no-properties 1)
7207 (match-string-no-properties 2)
7208 templateno lineno)
7209 tpl-sig-list))
7210 (goto-char (match-end 0)))
7211 ;; Regexp form??
7212 ((looking-at
d63b01e1 7213 ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
6341f357
DN
7214 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7215 (setq rep (match-string-no-properties 3))
7216 (goto-char (match-end 0))
7217 (setq tpl-wild-list
7218 (cons (list
7219 (concat "^"
7220 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
7221 (match-string 1))
7222 "$")
7223 rep
7224 templateno lineno)
7225 tpl-wild-list)))
7226 ((looking-at "[ \t\f]+")
7227 (goto-char (match-end 0)))
7228 ((looking-at "\n")
7229 (setq lineno (1+ lineno))
7230 (goto-char (match-end 0)))
7231 ((looking-at "//")
7232 (search-forward "\n"))
7233 ((looking-at "/\\*")
7234 (forward-char 2)
7235 (or (search-forward "*/")
7236 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7237 (t
7238 (error "%s: AUTO_TEMPLATE parsing error: %s"
7239 (verilog-point-text)
60618039 7240 (progn (looking-at ".*$") (match-string 0))))))
6341f357
DN
7241 ;; Return
7242 (vector tpl-regexp
7243 (list tpl-sig-list tpl-wild-list)))
7244 ;; If no template found
7245 (t (vector tpl-regexp nil))))))
7246;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
7247
7248(defun verilog-set-define (defname defvalue &optional buffer enumname)
7249 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
7250Optionally associate it with the specified enumeration ENUMNAME."
7251 (save-excursion
7252 (set-buffer (or buffer (current-buffer)))
7253 (let ((mac (intern (concat "vh-" defname))))
7254 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
7255 ;; Need to define to a constant if no value given
7256 (set (make-variable-buffer-local mac)
7257 (if (equal defvalue "") "1" defvalue)))
7258 (if enumname
7259 (let ((enumvar (intern (concat "venum-" enumname))))
7260 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
a3a8b002 7261 (unless (boundp enumvar) (set enumvar nil))
6341f357 7262 (make-variable-buffer-local enumvar)
60618039 7263 (add-to-list enumvar defname)))))
6341f357
DN
7264
7265(defun verilog-read-defines (&optional filename recurse subcall)
7266 "Read `defines and parameters for the current file, or optional FILENAME.
7267If the filename is provided, `verilog-library-flags' will be used to
7268resolve it. If optional RECURSE is non-nil, recurse through `includes.
7269
7270Parameters must be simple assignments to constants, or have their own
7271\"parameter\" label rather than a list of parameters. Thus:
7272
7273 parameter X = 5, Y = 10; // Ok
7274 parameter X = {1'b1, 2'h2}; // Ok
7275 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
7276
7277Defines must be simple text substitutions, one on a line, starting
7278at the beginning of the line. Any ifdefs or multiline comments around the
7279define are ignored.
7280
7281Defines are stored inside Emacs variables using the name vh-{definename}.
7282
7283This function is useful for setting vh-* variables. The file variables
7284feature can be used to set defines that `verilog-mode' can see; put at the
7285*END* of your file something like:
7286
7287 // Local Variables:
7288 // vh-macro:\"macro_definition\"
7289 // End:
7290
7291If macros are defined earlier in the same file and you want their values,
7292you can read them automatically (provided `enable-local-eval' is on):
7293
7294 // Local Variables:
7295 // eval:(verilog-read-defines)
7296 // eval:(verilog-read-defines \"group_standard_includes.v\")
7297 // End:
7298
7299Note these are only read when the file is first visited, you must use
7300\\[find-alternate-file] RET to have these take effect after editing them!
7301
7302If you want to disable the \"Process `eval' or hook local variables\"
7303warning message, you need to add to your .emacs file:
7304
7305 (setq enable-local-eval t)"
7306 (let ((origbuf (current-buffer)))
7307 (save-excursion
7308 (unless subcall (verilog-getopt-flags))
7309 (when filename
7310 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
7311 (if fns
7312 (set-buffer (find-file-noselect (car fns)))
7313 (error (concat (verilog-point-text)
7314 ": Can't find verilog-read-defines file: " filename)))))
7315 (when recurse
7316 (goto-char (point-min))
7317 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
7318 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string-no-properties 1))))
7319 (unless (verilog-inside-comment-p)
7320 (verilog-read-defines inc recurse t)))))
7321 ;; Read `defines
7322 ;; note we don't use verilog-re... it's faster this way, and that
7323 ;; function has problems when comments are at the end of the define
7324 (goto-char (point-min))
7325 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
7326 (let ((defname (match-string-no-properties 1))
7327 (defvalue (match-string-no-properties 2)))
7328 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
7329 (verilog-set-define defname defvalue origbuf)))
7330 ;; Hack: Read parameters
7331 (goto-char (point-min))
7332 (while (re-search-forward
a3a8b002
DN
7333 "^\\s-*\\(parameter\\|localparam\\)\\(\\s-*\\[[^]]*\\]\\)?\\s-+" nil t)
7334 (let (enumname)
6341f357
DN
7335 ;; The primary way of getting defines is verilog-read-decls
7336 ;; However, that isn't called yet for included files, so we'll add another scheme
7337 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
7338 (setq enumname (match-string-no-properties 1)))
6341f357
DN
7339 (forward-comment 999)
7340 (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
7341 (verilog-set-define (match-string-no-properties 1) (match-string-no-properties 2) origbuf enumname)
7342 (goto-char (match-end 0))
60618039 7343 (forward-comment 999)))))))
6341f357
DN
7344
7345(defun verilog-read-includes ()
7346 "Read `includes for the current file.
7347This will find all of the `includes which are at the beginning of lines,
7348ignoring any ifdefs or multiline comments around them.
7349`verilog-read-defines' is then performed on the current and each included
7350file.
7351
7352It is often useful put at the *END* of your file something like:
7353
7354 // Local Variables:
7355 // eval:(verilog-read-defines)
7356 // eval:(verilog-read-includes)
7357 // End:
7358
7359Note includes are only read when the file is first visited, you must use
7360\\[find-alternate-file] RET to have these take effect after editing them!
7361
7362It is good to get in the habit of including all needed files in each .v
7363file that needs it, rather than waiting for compile time. This will aid
7364this process, Verilint, and readability. To prevent defining the same
7365variable over and over when many modules are compiled together, put a test
7366around the inside each include file:
7367
7368foo.v (a include):
7369 `ifdef _FOO_V // include if not already included
7370 `else
7371 `define _FOO_V
7372 ... contents of file
7373 `endif // _FOO_V"
7374;;slow: (verilog-read-defines nil t))
7375 (save-excursion
7376 (verilog-getopt-flags)
7377 (goto-char (point-min))
7378 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
7379 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
7380 (verilog-read-defines inc nil t)))))
7381
7382(defun verilog-read-signals (&optional start end)
7383 "Return a simple list of all possible signals in the file.
7384Bounded by optional region from START to END. Overly aggressive but fast.
37ea4b9b 7385Some macros and such are also found and included. For dinotrace.el."
6341f357
DN
7386 (let (sigs-all keywd)
7387 (progn;save-excursion
7388 (goto-char (or start (point-min)))
7389 (setq end (or end (point-max)))
7390 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
7391 (forward-char -1)
7392 (cond
7393 ((looking-at "//")
7394 (search-forward "\n"))
7395 ((looking-at "/\\*")
7396 (search-forward "*/"))
7397 ((looking-at "(\\*")
7398 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7399 (search-forward "*)")))
7400 ((eq ?\" (following-char))
7401 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
7402 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
7403 (goto-char (match-end 0))
7404 (setq keywd (match-string-no-properties 1))
7405 (or (member keywd verilog-keywords)
7406 (member keywd sigs-all)
7407 (setq sigs-all (cons keywd sigs-all))))
60618039 7408 (t (forward-char 1))))
6341f357
DN
7409 ;; Return list
7410 sigs-all)))
7411
7412;;
7413;; Argument file parsing
7414;;
7415
7416(defun verilog-getopt (arglist)
7417 "Parse -f, -v etc arguments in ARGLIST list or string."
7418 (unless (listp arglist) (setq arglist (list arglist)))
7419 (let ((space-args '())
7420 arg next-param)
7421 ;; Split on spaces, so users can pass whole command lines
7422 (while arglist
7423 (setq arg (car arglist)
7424 arglist (cdr arglist))
7425 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
7426 (setq space-args (append space-args
7427 (list (match-string-no-properties 1 arg))))
7428 (setq arg (match-string 2 arg))))
7429 ;; Parse arguments
7430 (while space-args
7431 (setq arg (car space-args)
7432 space-args (cdr space-args))
7433 (cond
7434 ;; Need another arg
7435 ((equal arg "-f")
7436 (setq next-param arg))
7437 ((equal arg "-v")
7438 (setq next-param arg))
7439 ((equal arg "-y")
7440 (setq next-param arg))
7441 ;; +libext+(ext1)+(ext2)...
7442 ((string-match "^\\+libext\\+\\(.*\\)" arg)
7443 (setq arg (match-string 1 arg))
7444 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
7445 (verilog-add-list-unique `verilog-library-extensions
7446 (match-string 1 arg))
7447 (setq arg (match-string 2 arg))))
7448 ;;
7449 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
7450 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
7451 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
7452 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
7453 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
7454 ;;
7455 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
7456 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
7457 (verilog-add-list-unique `verilog-library-directories
a3a8b002 7458 (match-string 1 (substitute-in-file-name arg))))
6341f357
DN
7459 ;; Ignore
7460 ((equal "+librescan" arg))
7461 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
7462 ;; Second parameters
7463 ((equal next-param "-f")
7464 (setq next-param nil)
a3a8b002 7465 (verilog-getopt-file (substitute-in-file-name arg)))
6341f357
DN
7466 ((equal next-param "-v")
7467 (setq next-param nil)
a3a8b002
DN
7468 (verilog-add-list-unique `verilog-library-files
7469 (substitute-in-file-name arg)))
6341f357
DN
7470 ((equal next-param "-y")
7471 (setq next-param nil)
a3a8b002
DN
7472 (verilog-add-list-unique `verilog-library-directories
7473 (substitute-in-file-name arg)))
6341f357
DN
7474 ;; Filename
7475 ((string-match "^[^-+]" arg)
a3a8b002
DN
7476 (verilog-add-list-unique `verilog-library-files
7477 (substitute-in-file-name arg)))
6341f357 7478 ;; Default - ignore; no warning
60618039 7479 ))))
6341f357
DN
7480;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
7481
7482(defun verilog-getopt-file (filename)
37ea4b9b 7483 "Read Verilog options from the specified FILENAME."
6341f357
DN
7484 (save-excursion
7485 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
7486 (orig-buffer (current-buffer))
7487 line)
7488 (if fns
7489 (set-buffer (find-file-noselect (car fns)))
7490 (error (concat (verilog-point-text)
5509c6ad 7491 ": Can't find verilog-getopt-file -f file: " filename)))
6341f357
DN
7492 (goto-char (point-min))
7493 (while (not (eobp))
7494 (setq line (buffer-substring (point)
7495 (save-excursion (end-of-line) (point))))
7496 (forward-line 1)
7497 (when (string-match "//" line)
7498 (setq line (substring line 0 (match-beginning 0))))
7499 (save-excursion
7500 (set-buffer orig-buffer) ; Variables are buffer-local, so need right context.
7501 (verilog-getopt line))))))
7502
7503(defun verilog-getopt-flags ()
7504 "Convert `verilog-library-flags' into standard library variables."
7505 ;; If the flags are local, then all the outputs should be local also
7506 (when (local-variable-p `verilog-library-flags (current-buffer))
7ea26faf
DN
7507 (mapc 'make-local-variable '(verilog-library-extensions
7508 verilog-library-directories
7509 verilog-library-files
7510 verilog-library-flags)))
6341f357
DN
7511 ;; Allow user to customize
7512 (run-hooks 'verilog-before-getopt-flags-hook)
7513 ;; Process arguments
7514 (verilog-getopt verilog-library-flags)
7515 ;; Allow user to customize
7516 (run-hooks 'verilog-getopt-flags-hook))
7517
7518(defun verilog-add-list-unique (varref object)
7519 "Append to VARREF list the given OBJECT,
37ea4b9b 7520unless it is already a member of the variable's list."
6341f357
DN
7521 (unless (member object (symbol-value varref))
7522 (set varref (append (symbol-value varref) (list object))))
7523 varref)
7524;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
7525
7526\f
5509c6ad
DN
7527;;
7528;; Cached directory support
7529;;
7530
7531(defvar verilog-dir-cache-preserving nil
7532 "If set, the directory cache is enabled, and file system changes are ignored.
7533See `verilog-dir-exists-p' and `verilog-dir-files'.")
7534
7535;; If adding new cached variable, add also to verilog-preserve-dir-cache
7536(defvar verilog-dir-cache-list nil
7537 "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
7538(defvar verilog-dir-cache-lib-filenames nil
7539 "Cached data for `verilog-library-filenames'.")
7540
7541(defmacro verilog-preserve-dir-cache (&rest body)
7542 "Execute the BODY forms, allowing directory cache preservation within BODY.
7543This means that changes inside BODY made to the file system will not be
7544seen by the `verilog-dir-files' and related functions."
7545 `(let ((verilog-dir-cache-preserving t)
7546 verilog-dir-cache-list
7547 verilog-dir-cache-lib-filenames)
7548 (progn ,@body)))
7549
7550(defun verilog-dir-files (dirname)
7551 "Return all filenames in the DIRNAME directory.
7552Relative paths depend on the `default-directory'.
7553Results are cached if inside `verilog-preserve-dir-cache'."
7554 (unless verilog-dir-cache-preserving
7555 (setq verilog-dir-cache-list nil)) ;; Cache disabled
7556 ;; We don't use expand-file-name on the dirname to make key, as it's slow
7557 (let* ((cache-key (list dirname default-directory))
7558 (fass (assoc cache-key verilog-dir-cache-list))
7559 exp-dirname data)
7560 (cond (fass ;; Return data from cache hit
7561 (nth 1 fass))
7562 (t
7563 (setq exp-dirname (expand-file-name dirname)
7564 data (and (file-directory-p exp-dirname)
7565 (directory-files exp-dirname nil nil nil)))
7566 ;; Note we also encache nil for non-existing dirs.
7567 (setq verilog-dir-cache-list (cons (list cache-key data)
7568 verilog-dir-cache-list))
7569 data))))
7570;; Miss-and-hit test:
7571;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
7572;; (prin1 (verilog-dir-files ".")) nil)
7573
7574(defun verilog-dir-file-exists-p (filename)
7575 "Return true if FILENAME exists.
7576Like `file-exists-p' but results are cached if inside
7577`verilog-preserve-dir-cache'."
7578 (let* ((dirname (file-name-directory filename))
7579 ;; Correct for file-name-nondirectory returning same if no slash.
7580 (dirnamed (if (or (not dirname) (equal dirname filename))
7581 default-directory dirname))
7582 (flist (verilog-dir-files dirnamed)))
7583 (and flist
7584 (member (file-name-nondirectory filename) flist)
7585 t)))
7586;;(verilog-dir-file-exists-p "verilog-mode.el")
7587;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
7588
7589\f
6341f357
DN
7590;;
7591;; Module name lookup
7592;;
7593
7594(defun verilog-module-inside-filename-p (module filename)
7595 "Return point if MODULE is specified inside FILENAME, else nil.
7596Allows version control to check out the file if need be."
7597 (and (or (file-exists-p filename)
7ea26faf
DN
7598 (and (fboundp 'vc-backend)
7599 (vc-backend filename)))
6341f357
DN
7600 (let (pt)
7601 (save-excursion
7602 (set-buffer (find-file-noselect filename))
7603 (goto-char (point-min))
7604 (while (and
7605 ;; It may be tempting to look for verilog-defun-re, don't, it slows things down a lot!
7606 (verilog-re-search-forward-quick "\\<module\\>" nil t)
7607 (verilog-re-search-forward-quick "[(;]" nil t))
7608 (if (equal module (verilog-read-module-name))
7609 (setq pt (point))))
7610 pt))))
7611
7612(defun verilog-is-number (symbol)
7613 "Return true if SYMBOL is number-like."
7614 (or (string-match "^[0-9 \t:]+$" symbol)
7615 (string-match "^[---]*[0-9]+$" symbol)
60618039 7616 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
6341f357
DN
7617
7618(defun verilog-symbol-detick (symbol wing-it)
37ea4b9b 7619 "Return an expanded SYMBOL name without any defines.
6341f357
DN
7620If the variable vh-{symbol} is defined, return that value.
7621If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
7622 (while (and symbol (string-match "^`" symbol))
7623 (setq symbol (substring symbol 1))
7624 (setq symbol
7625 (if (boundp (intern (concat "vh-" symbol)))
7626 ;; Emacs has a bug where boundp on a buffer-local
7627 ;; variable in only one buffer returns t in another.
7628 ;; This can confuse, so check for nil.
7629 (let ((val (eval (intern (concat "vh-" symbol)))))
7630 (if (eq val nil)
7631 (if wing-it symbol nil)
7632 val))
7633 (if wing-it symbol nil))))
7634 symbol)
7635;;(verilog-symbol-detick "`mod" nil)
7636
7637(defun verilog-symbol-detick-denumber (symbol)
7638 "Return SYMBOL with defines converted and any numbers dropped to nil."
7639 (when (string-match "^`" symbol)
7640 ;; This only will work if the define is a simple signal, not
7641 ;; something like a[b]. Sorry, it should be substituted into the parser
7642 (setq symbol
7643 (verilog-string-replace-matches
7644 "\[[^0-9: \t]+\]" "" nil nil
7645 (or (verilog-symbol-detick symbol nil)
7646 (if verilog-auto-sense-defines-constant
7647 "0"
7648 symbol)))))
7649 (if (verilog-is-number symbol)
7650 nil
7651 symbol))
7652
7653(defun verilog-symbol-detick-text (text)
37ea4b9b 7654 "Return TEXT without any known defines.
6341f357
DN
7655If the variable vh-{symbol} is defined, substitute that value."
7656 (let ((ok t) symbol val)
7657 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
7658 (setq symbol (match-string 1 text))
a3a8b002 7659 ;;(message symbol)
6341f357
DN
7660 (cond ((and
7661 (boundp (intern (concat "vh-" symbol)))
7662 ;; Emacs has a bug where boundp on a buffer-local
7663 ;; variable in only one buffer returns t in another.
7664 ;; This can confuse, so check for nil.
7665 (setq val (eval (intern (concat "vh-" symbol)))))
7666 (setq text (replace-match val nil nil text)))
7667 (t (setq ok nil)))))
7668 text)
7669;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
7670
7671(defun verilog-expand-dirnames (&optional dirnames)
7672 "Return a list of existing directories given a list of wildcarded DIRNAMES.
7673Or, just the existing dirnames themselves if there are no wildcards."
5509c6ad
DN
7674 ;; Note this function is performance critical.
7675 ;; Do not call anything that requires disk access that cannot be cached.
6341f357
DN
7676 (interactive)
7677 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
7678 (setq dirnames (reverse dirnames)) ; not nreverse
7679 (let ((dirlist nil)
5509c6ad 7680 pattern dirfile dirfiles dirname root filename rest basefile)
6341f357
DN
7681 (while dirnames
7682 (setq dirname (substitute-in-file-name (car dirnames))
7683 dirnames (cdr dirnames))
7684 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
7685 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
7686 "\\(.*\\)") ;; rest
7687 dirname)
7688 (setq root (match-string 1 dirname)
7689 filename (match-string 2 dirname)
7690 rest (match-string 3 dirname)
7691 pattern filename)
7692 ;; now replace those * and ? with .+ and .
7693 ;; use ^ and /> to get only whole file names
6341f357
DN
7694 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
7695 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
5509c6ad
DN
7696 pattern (concat "^" pattern "$")
7697 dirfiles (verilog-dir-files root))
6341f357 7698 (while dirfiles
5509c6ad
DN
7699 (setq basefile (car dirfiles)
7700 dirfile (expand-file-name (concat root basefile rest))
6341f357 7701 dirfiles (cdr dirfiles))
5509c6ad
DN
7702 (if (and (string-match pattern basefile)
7703 ;; Don't allow abc/*/rtl to match abc/rtl via ..
7704 (not (equal basefile "."))
7705 (not (equal basefile ".."))
7706 (file-directory-p dirfile))
60618039 7707 (setq dirlist (cons dirfile dirlist)))))
6341f357
DN
7708 ;; Defaults
7709 (t
7710 (if (file-directory-p dirname)
60618039 7711 (setq dirlist (cons dirname dirlist))))))
6341f357
DN
7712 dirlist))
7713;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
7714
7715(defun verilog-library-filenames (filename current &optional check-ext)
5509c6ad 7716 "Return a search path to find the given FILENAME or module name.
6341f357
DN
7717Uses the CURRENT filename, `verilog-library-directories' and
7718`verilog-library-extensions' variables to build the path.
7719With optional CHECK-EXT also check `verilog-library-extensions'."
5509c6ad
DN
7720 (unless verilog-dir-cache-preserving
7721 (setq verilog-dir-cache-lib-filenames nil))
7722 (let* ((cache-key (list filename current check-ext))
7723 (fass (assoc cache-key verilog-dir-cache-lib-filenames))
7724 chkdirs chkdir chkexts fn outlist)
7725 (cond (fass ;; Return data from cache hit
7726 (nth 1 fass))
7727 (t
7728 ;; Note this expand can't be easily cached, as we need to
7729 ;; pick up buffer-local variables for newly read sub-module files
7730 (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
7731 (while chkdirs
7732 (setq chkdir (expand-file-name (car chkdirs)
7733 (file-name-directory current))
7734 chkexts (if check-ext verilog-library-extensions `("")))
7735 (while chkexts
7736 (setq fn (expand-file-name (concat filename (car chkexts))
7737 chkdir))
7738 ;;(message "Check for %s" fn)
7739 (if (verilog-dir-file-exists-p fn)
7740 (setq outlist (cons (expand-file-name
7741 fn (file-name-directory current))
7742 outlist)))
7743 (setq chkexts (cdr chkexts)))
7744 (setq chkdirs (cdr chkdirs)))
7745 (setq outlist (nreverse outlist))
7746 (setq verilog-dir-cache-lib-filenames
7747 (cons (list cache-key outlist)
7748 verilog-dir-cache-lib-filenames))
7749 outlist))))
6341f357
DN
7750
7751(defun verilog-module-filenames (module current)
7752 "Return a search path to find the given MODULE name.
7753Uses the CURRENT filename, `verilog-library-extensions',
7754`verilog-library-directories' and `verilog-library-files'
7755variables to build the path."
7756 ;; Return search locations for it
7757 (append (list current) ; first, current buffer
7758 (verilog-library-filenames module current t)
7759 verilog-library-files)) ; finally, any libraries
7760
7761;;
7762;; Module Information
7763;;
7764;; Many of these functions work on "modi" a module information structure
7765;; A modi is: [module-name-string file-name begin-point]
7766
7767(defvar verilog-cache-enabled t
7768 "If true, enable caching of signals, etc. Set to nil for debugging to make things SLOW!")
7769
7770(defvar verilog-modi-cache-list nil
7771 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
7772For speeding up verilog-modi-get-* commands.
7773Buffer-local.")
7774
7ea26faf
DN
7775(make-variable-buffer-local 'verilog-modi-cache-list)
7776
6341f357
DN
7777(defvar verilog-modi-cache-preserve-tick nil
7778 "Modification tick after which the cache is still considered valid.
5509c6ad 7779Use `verilog-preserve-modi-cache' to set it.")
6341f357
DN
7780(defvar verilog-modi-cache-preserve-buffer nil
7781 "Modification tick after which the cache is still considered valid.
5509c6ad 7782Use `verilog-preserve-modi-cache' to set it.")
6341f357
DN
7783
7784(defun verilog-modi-current ()
7785 "Return the modi structure for the module currently at point."
7786 (let* (name pt)
7787 ;; read current module's name
7788 (save-excursion
7789 (verilog-re-search-backward-quick verilog-defun-re nil nil)
7790 (verilog-re-search-forward-quick "(" nil nil)
7791 (setq name (verilog-read-module-name))
7792 (setq pt (point)))
7793 ;; return
7794 (vector name (or (buffer-file-name) (current-buffer)) pt)))
7795
7796(defvar verilog-modi-lookup-last-mod nil "Cache of last module looked up.")
7797(defvar verilog-modi-lookup-last-modi nil "Cache of last modi returned.")
7798(defvar verilog-modi-lookup-last-current nil "Cache of last `current-buffer' looked up.")
7799(defvar verilog-modi-lookup-last-tick nil "Cache of last `buffer-modified-tick' looked up.")
7800
7801(defun verilog-modi-lookup (module allow-cache &optional ignore-error)
7802 "Find the file and point at which MODULE is defined.
7803If ALLOW-CACHE is set, check and remember cache of previous lookups.
7804Return modi if successful, else print message unless IGNORE-ERROR is true."
7805 (let* ((current (or (buffer-file-name) (current-buffer))))
7806 (cond ((and verilog-modi-lookup-last-modi
7807 verilog-cache-enabled
7808 allow-cache
7809 (equal verilog-modi-lookup-last-mod module)
7810 (equal verilog-modi-lookup-last-current current)
7811 (equal verilog-modi-lookup-last-tick (buffer-modified-tick)))
7812 ;; ok as is
7813 )
7814 (t (let* ((realmod (verilog-symbol-detick module t))
7815 (orig-filenames (verilog-module-filenames realmod current))
7816 (filenames orig-filenames)
7817 pt)
7818 (while (and filenames (not pt))
7819 (if (not (setq pt (verilog-module-inside-filename-p realmod (car filenames))))
7820 (setq filenames (cdr filenames))))
7821 (cond (pt (setq verilog-modi-lookup-last-modi
7822 (vector realmod (car filenames) pt)))
7823 (t (setq verilog-modi-lookup-last-modi nil)
7824 (or ignore-error
7825 (error (concat (verilog-point-text)
7826 ": Can't locate " module " module definition"
7827 (if (not (equal module realmod))
7828 (concat " (Expanded macro to " realmod ")")
7829 "")
7830 "\n Check the verilog-library-directories variable."
7831 "\n I looked in (if not listed, doesn't exist):\n\t"
60618039 7832 (mapconcat 'concat orig-filenames "\n\t"))))))
6341f357
DN
7833 (setq verilog-modi-lookup-last-mod module
7834 verilog-modi-lookup-last-current current
7835 verilog-modi-lookup-last-tick (buffer-modified-tick)))))
60618039 7836 verilog-modi-lookup-last-modi))
6341f357
DN
7837
7838(defsubst verilog-modi-name (modi)
7839 (aref modi 0))
7840(defsubst verilog-modi-file-or-buffer (modi)
7841 (aref modi 1))
7842(defsubst verilog-modi-point (modi)
7843 (aref modi 2))
7844
7845(defun verilog-modi-filename (modi)
37ea4b9b 7846 "Filename of MODI, or name of buffer if it's never been saved."
6341f357
DN
7847 (if (bufferp (verilog-modi-file-or-buffer modi))
7848 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
7849 (buffer-name (verilog-modi-file-or-buffer modi)))
7850 (verilog-modi-file-or-buffer modi)))
7851
7852(defun verilog-modi-goto (modi)
7853 "Move point/buffer to specified MODI."
7854 (or modi (error "Passed unfound modi to goto, check earlier"))
7855 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
7856 (verilog-modi-file-or-buffer modi)
7857 (find-file-noselect (verilog-modi-file-or-buffer modi))))
37ea4b9b 7858 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
6341f357
DN
7859 (verilog-mode))
7860 (goto-char (verilog-modi-point modi)))
7861
7862(defun verilog-goto-defun-file (module)
7863 "Move point to the file at which a given MODULE is defined."
7864 (interactive "sGoto File for Module: ")
7865 (let* ((modi (verilog-modi-lookup module nil)))
7866 (when modi
7867 (verilog-modi-goto modi)
7868 (switch-to-buffer (current-buffer)))))
7869
7870(defun verilog-modi-cache-results (modi function)
7871 "Run on MODI the given FUNCTION. Locate the module in a file.
7872Cache the output of function so next call may have faster access."
5509c6ad
DN
7873 (let (fass)
7874 (save-excursion ;; Cache is buffer-local so can't avoid this.
6341f357 7875 (verilog-modi-goto modi)
5509c6ad 7876 (if (and (setq fass (assoc (list modi function)
6341f357
DN
7877 verilog-modi-cache-list))
7878 ;; Destroy caching when incorrect; Modified or file changed
7879 (not (and verilog-cache-enabled
7880 (or (equal (buffer-modified-tick) (nth 1 fass))
7881 (and verilog-modi-cache-preserve-tick
7882 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
7883 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
7884 (equal (visited-file-modtime) (nth 2 fass)))))
7885 (setq verilog-modi-cache-list nil
7886 fass nil))
7887 (cond (fass
5509c6ad
DN
7888 ;; Return data from cache hit
7889 (nth 3 fass))
6341f357
DN
7890 (t
7891 ;; Read from file
5509c6ad 7892 ;; Clear then restore any hilighting to make emacs19 happy
6341f357
DN
7893 (let ((fontlocked (when (and (boundp 'font-lock-mode)
7894 font-lock-mode)
7cb1c4d7 7895 (font-lock-mode 0)
5509c6ad
DN
7896 t))
7897 func-returns)
6341f357 7898 (setq func-returns (funcall function))
5509c6ad 7899 (when fontlocked (font-lock-mode t))
9c059794
DN
7900 ;; Cache for next time
7901 (setq verilog-modi-cache-list
5509c6ad 7902 (cons (list (list modi function)
9c059794
DN
7903 (buffer-modified-tick)
7904 (visited-file-modtime)
7905 func-returns)
5509c6ad
DN
7906 verilog-modi-cache-list))
7907 func-returns))))))
6341f357
DN
7908
7909(defun verilog-modi-cache-add (modi function element sig-list)
7910 "Add function return results to the module cache.
7911Update MODI's cache for given FUNCTION so that the return ELEMENT of that
7912function now contains the additional SIG-LIST parameters."
7913 (let (fass)
7914 (save-excursion
7915 (verilog-modi-goto modi)
5509c6ad 7916 (if (setq fass (assoc (list modi function)
6341f357
DN
7917 verilog-modi-cache-list))
7918 (let ((func-returns (nth 3 fass)))
7919 (aset func-returns element
7920 (append sig-list (aref func-returns element))))))))
7921
5509c6ad 7922(defmacro verilog-preserve-modi-cache (&rest body)
6341f357
DN
7923 "Execute the BODY forms, allowing cache preservation within BODY.
7924This means that changes to the buffer will not result in the cache being
7925flushed. If the changes affect the modsig state, they must call the
7926modsig-cache-add-* function, else the results of later calls may be
7927incorrect. Without this, changes are assumed to be adding/removing signals
7928and invalidating the cache."
7929 `(let ((verilog-modi-cache-preserve-tick (buffer-modified-tick))
7930 (verilog-modi-cache-preserve-buffer (current-buffer)))
7931 (progn ,@body)))
7932
6341f357
DN
7933
7934(defun verilog-signals-matching-enum (in-list enum)
7935 "Return all signals in IN-LIST matching the given ENUM."
7936 (let (out-list)
7937 (while in-list
7938 (if (equal (verilog-sig-enum (car in-list)) enum)
7939 (setq out-list (cons (car in-list) out-list)))
7940 (setq in-list (cdr in-list)))
7941 ;; New scheme
7942 (let* ((enumvar (intern (concat "venum-" enum)))
7943 (enumlist (and (boundp enumvar) (eval enumvar))))
7944 (while enumlist
7945 (add-to-list 'out-list (list (car enumlist)))
7946 (setq enumlist (cdr enumlist))))
7947 (nreverse out-list)))
7948
e2076c2c
DN
7949(defun verilog-signals-matching-regexp (in-list regexp)
7950 "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
a3a8b002 7951 (if (or (not regexp) (equal regexp ""))
e2076c2c
DN
7952 in-list
7953 (let (out-list)
7954 (while in-list
7955 (if (string-match regexp (verilog-sig-name (car in-list)))
7956 (setq out-list (cons (car in-list) out-list)))
7957 (setq in-list (cdr in-list)))
7958 (nreverse out-list))))
7959
6341f357
DN
7960(defun verilog-signals-not-matching-regexp (in-list regexp)
7961 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
a3a8b002 7962 (if (or (not regexp) (equal regexp ""))
6341f357
DN
7963 in-list
7964 (let (out-list)
7965 (while in-list
7966 (if (not (string-match regexp (verilog-sig-name (car in-list))))
7967 (setq out-list (cons (car in-list) out-list)))
7968 (setq in-list (cdr in-list)))
7969 (nreverse out-list))))
7970
a3a8b002
DN
7971(defun verilog-signals-matching-dir-re (in-list decl-type regexp)
7972 "Return all signals in IN-LIST matching the given directional REGEXP,
7973if non-nil."
7974 (if (or (not regexp) (equal regexp ""))
7975 in-list
7976 (let (out-list to-match)
7977 (while in-list
7978 ;; Note verilog-insert-one-definition matches on this order
7979 (setq to-match (concat
7980 decl-type
7981 " " (verilog-sig-signed (car in-list))
7982 " " (verilog-sig-multidim (car in-list))
7983 (verilog-sig-bits (car in-list))))
7984 (if (string-match regexp to-match)
7985 (setq out-list (cons (car in-list) out-list)))
7986 (setq in-list (cdr in-list)))
7987 (nreverse out-list))))
7988
6341f357 7989;; Combined
5509c6ad 7990(defun verilog-decls-get-signals (decls)
6341f357 7991 (append
5509c6ad
DN
7992 (verilog-decls-get-outputs decls)
7993 (verilog-decls-get-inouts decls)
7994 (verilog-decls-get-inputs decls)
7995 (verilog-decls-get-wires decls)
7996 (verilog-decls-get-regs decls)
7997 (verilog-decls-get-assigns decls)
7998 (verilog-decls-get-consts decls)
7999 (verilog-decls-get-gparams decls)))
8000
8001(defun verilog-decls-get-ports (decls)
6341f357 8002 (append
5509c6ad
DN
8003 (verilog-decls-get-outputs decls)
8004 (verilog-decls-get-inouts decls)
8005 (verilog-decls-get-inputs decls)))
6341f357
DN
8006
8007(defsubst verilog-modi-cache-add-outputs (modi sig-list)
8008 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
8009(defsubst verilog-modi-cache-add-inouts (modi sig-list)
8010 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
8011(defsubst verilog-modi-cache-add-inputs (modi sig-list)
8012 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
8013(defsubst verilog-modi-cache-add-wires (modi sig-list)
8014 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
8015(defsubst verilog-modi-cache-add-regs (modi sig-list)
8016 (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
8017
8018(defun verilog-signals-from-signame (signame-list)
8019 "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
8020 (mapcar (function (lambda (name) (list name nil nil)))
8021 signame-list))
8022\f
8023;;
8024;; Auto creation utilities
8025;;
8026
495ab0d5
DN
8027(defun verilog-auto-re-search-do (search-for func)
8028 "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
6341f357 8029 (goto-char (point-min))
495ab0d5
DN
8030 (while (verilog-re-search-forward search-for nil t)
8031 (funcall func)))
6341f357 8032
6341f357 8033(defun verilog-insert-one-definition (sig type indent-pt)
60618039 8034 "Print out a definition for SIG of the given TYPE,
6341f357
DN
8035with appropriate INDENT-PT indentation."
8036 (indent-to indent-pt)
a3a8b002 8037 ;; Note verilog-signals-matching-dir-re matches on this order
6341f357 8038 (insert type)
a3a8b002
DN
8039 (when (verilog-sig-modport sig)
8040 (insert "." (verilog-sig-modport sig)))
6341f357
DN
8041 (when (verilog-sig-signed sig)
8042 (insert " " (verilog-sig-signed sig)))
8043 (when (verilog-sig-multidim sig)
8044 (insert " " (verilog-sig-multidim-string sig)))
8045 (when (verilog-sig-bits sig)
8046 (insert " " (verilog-sig-bits sig)))
8047 (indent-to (max 24 (+ indent-pt 16)))
8048 (unless (= (char-syntax (preceding-char)) ?\ )
8049 (insert " ")) ; Need space between "]name" if indent-to did nothing
8050 (insert (verilog-sig-name sig)))
8051
8052(defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
8053 "Print out a definition for a list of SIGS of the given DIRECTION,
8054with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
8055format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output."
8056 (or dont-sort
8057 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
8058 (while sigs
8059 (let ((sig (car sigs)))
8060 (verilog-insert-one-definition
8061 sig
8062 ;; Want "type x" or "output type x", not "wire type x"
8063 (cond ((verilog-sig-type sig)
8064 (concat
a3a8b002 8065 (if (not (member direction '("wire" "interface")))
6341f357
DN
8066 (concat direction " "))
8067 (verilog-sig-type sig)))
8068 (t direction))
8069 indent-pt)
8070 (insert (if v2k "," ";"))
8071 (if (or (not (verilog-sig-comment sig))
8072 (equal "" (verilog-sig-comment sig)))
8073 (insert "\n")
8074 (indent-to (max 48 (+ indent-pt 40)))
8075 (insert (concat "// " (verilog-sig-comment sig) "\n")))
8076 (setq sigs (cdr sigs)))))
8077
8078(eval-when-compile
8079 (if (not (boundp 'indent-pt))
8080 (defvar indent-pt nil "Local used by insert-indent")))
8081
8082(defun verilog-insert-indent (&rest stuff)
8083 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
8084Presumes that any newlines end a list element."
8085 (let ((need-indent t))
8086 (while stuff
8087 (if need-indent (indent-to indent-pt))
8088 (setq need-indent nil)
8089 (insert (car stuff))
8090 (setq need-indent (string-match "\n$" (car stuff))
8091 stuff (cdr stuff)))))
8092;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
8093
8094(defun verilog-repair-open-comma ()
a3a8b002
DN
8095 "Insert comma if previous argument is other than a open parenthesis or endif."
8096 ;; We can't just search backward for ) as it might be inside another expression.
8097 ;; Also want "`ifdef X input foo `endif" to just leave things to the human to deal with
6341f357
DN
8098 (save-excursion
8099 (verilog-backward-syntactic-ws)
a3a8b002
DN
8100 (when (and (not (save-excursion ;; Not beginning (, or existing ,
8101 (backward-char 1)
8102 (looking-at "[(,]")))
8103 (not (save-excursion ;; Not `endif, or user define
8104 (backward-char 1)
8105 (skip-chars-backward "[a-zA-Z0-9_`]")
8106 (looking-at "`"))))
8107 (insert ","))))
6341f357
DN
8108
8109(defun verilog-repair-close-comma ()
8110 "If point is at a comma followed by a close parenthesis, fix it.
8111This repairs those mis-inserted by a AUTOARG."
8112 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
8113 (save-excursion
8114 (verilog-forward-close-paren)
8115 (backward-char 1)
8116 (verilog-backward-syntactic-ws)
8117 (backward-char 1)
8118 (when (looking-at ",")
8119 (delete-char 1))))
8120
8121(defun verilog-get-list (start end)
8122 "Return the elements of a comma separated list between START and END."
8123 (interactive)
8124 (let ((my-list (list))
8125 my-string)
8126 (save-excursion
8127 (while (< (point) end)
8128 (when (re-search-forward "\\([^,{]+\\)" end t)
8129 (setq my-string (verilog-string-remove-spaces (match-string 1)))
8130 (setq my-list (nconc my-list (list my-string) ))
8131 (goto-char (match-end 0))))
8132 my-list)))
8133
8134(defun verilog-make-width-expression (range-exp)
8135 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
8136 ;; strip off the []
8137 (cond ((not range-exp)
8138 "1")
8139 (t
8140 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
8141 (setq range-exp (match-string 1 range-exp)))
8142 (cond ((not range-exp)
8143 "1")
a3a8b002 8144 ;; [#:#] We can compute a numeric result
7ea26faf
DN
8145 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
8146 range-exp)
8147 (int-to-string
8148 (1+ (abs (- (string-to-number (match-string 1 range-exp))
8149 (string-to-number (match-string 2 range-exp)))))))
a3a8b002
DN
8150 ;; [PARAM-1:0] can just return PARAM
8151 ((string-match "^\\s *\\([a-zA-Z_][a-zA-Z0-9_]*\\)\\s *-\\s *1\\s *:\\s *0\\s *$" range-exp)
8152 (match-string 1 range-exp))
8153 ;; [arbitrary] need math
6341f357 8154 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
7ea26faf 8155 (concat "(1+(" (match-string 1 range-exp) ")"
60618039
DN
8156 (if (equal "0" (match-string 2 range-exp))
8157 "" ;; Don't bother with -(0)
6341f357
DN
8158 (concat "-(" (match-string 2 range-exp) ")"))
8159 ")"))
8160 (t nil)))))
8161;;(verilog-make-width-expression "`A:`B")
8162
4c5e69c6
DN
8163(defun verilog-simplify-range-expression (range-exp)
8164 "Return a simplified range expression with constants eliminated from RANGE-EXP."
8165 (let ((out range-exp)
8166 (last-pass ""))
8167 (while (not (equal last-pass out))
8168 (setq last-pass out)
7cb1c4d7 8169 (while (string-match "(\\<\\([0-9A-Z-az_]+\\)\\>)" out)
4c5e69c6
DN
8170 (setq out (replace-match "\\1" nil nil out)))
8171 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\+\\s *\\<\\([0-9]+\\)\\>" out)
a3a8b002 8172 (setq out (replace-match
4c5e69c6
DN
8173 (int-to-string (+ (string-to-number (match-string 1 out))
8174 (string-to-number (match-string 2 out))))
8175 nil nil out)))
8176 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\-\\s *\\<\\([0-9]+\\)\\>" out)
a3a8b002 8177 (setq out (replace-match
4c5e69c6
DN
8178 (int-to-string (- (string-to-number (match-string 1 out))
8179 (string-to-number (match-string 2 out))))
8180 nil nil out))))
8181 out))
8182;;(verilog-simplify-range-expression "1")
8183;;(verilog-simplify-range-expression "(((16)+1)-3)")
8184
6341f357
DN
8185(defun verilog-typedef-name-p (variable-name)
8186 "Return true if the VARIABLE-NAME is a type definition."
8187 (when verilog-typedef-regexp
8188 (string-match verilog-typedef-regexp variable-name)))
8189\f
8190;;
8191;; Auto deletion
8192;;
8193
8194(defun verilog-delete-autos-lined ()
8195 "Delete autos that occupy multiple lines, between begin and end comments."
8196 (let ((pt (point)))
8197 (forward-line 1)
8198 (when (and
8199 (looking-at "\\s-*// Beginning")
8200 (search-forward "// End of automatic" nil t))
8201 ;; End exists
8202 (end-of-line)
8203 (delete-region pt (point))
60618039 8204 (forward-line 1))))
6341f357
DN
8205
8206(defun verilog-forward-close-paren ()
37ea4b9b
JB
8207 "Find the close parenthesis that match the current point.
8208Ignore other close parenthesis with matching open parens."
6341f357
DN
8209 (let ((parens 1))
8210 (while (> parens 0)
8211 (unless (verilog-re-search-forward-quick "[()]" nil t)
8212 (error "%s: Mismatching ()" (verilog-point-text)))
8213 (cond ((= (preceding-char) ?\( )
8214 (setq parens (1+ parens)))
8215 ((= (preceding-char) ?\) )
8216 (setq parens (1- parens)))))))
8217
8218(defun verilog-backward-open-paren ()
37ea4b9b
JB
8219 "Find the open parenthesis that match the current point.
8220Ignore other open parenthesis with matching close parens."
6341f357
DN
8221 (let ((parens 1))
8222 (while (> parens 0)
8223 (unless (verilog-re-search-backward-quick "[()]" nil t)
8224 (error "%s: Mismatching ()" (verilog-point-text)))
8225 (cond ((= (following-char) ?\) )
8226 (setq parens (1+ parens)))
8227 ((= (following-char) ?\( )
8228 (setq parens (1- parens)))))))
8229
8230(defun verilog-backward-open-bracket ()
37ea4b9b
JB
8231 "Find the open bracket that match the current point.
8232Ignore other open bracket with matching close bracket."
6341f357
DN
8233 (let ((parens 1))
8234 (while (> parens 0)
8235 (unless (verilog-re-search-backward-quick "[][]" nil t)
8236 (error "%s: Mismatching []" (verilog-point-text)))
8237 (cond ((= (following-char) ?\] )
8238 (setq parens (1+ parens)))
8239 ((= (following-char) ?\[ )
8240 (setq parens (1- parens)))))))
8241
8242(defun verilog-delete-to-paren ()
8243 "Delete the automatic inst/sense/arg created by autos.
8244Deletion stops at the matching end parenthesis."
8245 (delete-region (point)
8246 (save-excursion
8247 (verilog-backward-open-paren)
8248 (forward-sexp 1) ;; Moves to paren that closes argdecl's
8249 (backward-char 1)
8250 (point))))
8251
8252(defun verilog-auto-star-safe ()
8253 "Return if a .* AUTOINST is safe to delete or expand.
8254It was created by the AUTOS themselves, or by the user."
8255 (and verilog-auto-star-expand
8256 (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\)\\)")))
8257
8258(defun verilog-delete-auto-star-all ()
8259 "Delete a .* AUTOINST, if it is safe."
8260 (when (verilog-auto-star-safe)
8261 (verilog-delete-to-paren)))
8262
8263(defun verilog-delete-auto-star-implicit ()
8264 "Delete all .* implicit connections created by `verilog-auto-star'.
8265This function will be called automatically at save unless
8266`verilog-auto-star-save' is set, any non-templated expanded pins will be
8267removed."
8268 (interactive)
8269 (let (paren-pt indent have-close-paren)
8270 (save-excursion
8271 (goto-char (point-min))
8272 ;; We need to match these even outside of comments.
8273 ;; For reasonable performance, we don't check if inside comments, sorry.
8274 (while (re-search-forward "// Implicit \\.\\*" nil t)
8275 (setq paren-pt (point))
8276 (beginning-of-line)
8277 (setq have-close-paren
8278 (save-excursion
8279 (when (search-forward ");" paren-pt t)
8280 (setq indent (current-indentation))
8281 t)))
8282 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
8283 (when have-close-paren
8284 ;; Delete extra commentary
8285 (save-excursion
8286 (while (progn
8287 (forward-line -1)
8288 (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\)\n"))
8289 (delete-region (match-beginning 0) (match-end 0))))
8290 ;; If it is simple, we can put the ); on the same line as the last text
8291 (let ((rtn-pt (point)))
8292 (save-excursion
8293 (while (progn (backward-char 1)
8294 (looking-at "[ \t\n\f]")))
8295 (when (looking-at ",")
8296 (delete-region (+ 1 (point)) rtn-pt))))
8297 (when (bolp)
8298 (indent-to indent))
8299 (insert ");\n")
8300 ;; Still need to kill final comma - always is one as we put one after the .*
8301 (re-search-backward ",")
8302 (delete-char 1))))))
8303
8304(defun verilog-delete-auto ()
8305 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
8306Use \\[verilog-auto] to re-insert the updated AUTOs.
8307
8308The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
8309called before and after this function, respectively."
8310 (interactive)
8311 (save-excursion
8312 (if (buffer-file-name)
8313 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
8314 ;; Allow user to customize
8315 (run-hooks 'verilog-before-delete-auto-hook)
8316
e2076c2c 8317 ;; Remove those that have multi-line insertions, possibly with parameters
7cb1c4d7 8318 (verilog-auto-re-search-do
e2076c2c
DN
8319 (concat "/\\*"
8320 (eval-when-compile
8321 (verilog-regexp-words
8322 `("AUTOASCIIENUM" "AUTOCONCATCOMMENT" "AUTODEFINEVALUE"
7cb1c4d7 8323 "AUTOINOUT" "AUTOINOUTCOMP" "AUTOINOUTMODULE"
a3a8b002 8324 "AUTOINPUT" "AUTOINSERTLISP" "AUTOOUTPUT" "AUTOOUTPUTEVERY"
e2076c2c
DN
8325 "AUTOREG" "AUTOREGINPUT" "AUTORESET" "AUTOTIEOFF"
8326 "AUTOUNUSED" "AUTOWIRE")))
a3a8b002
DN
8327 ;; Optional parens or quoted parameter or .* for (((...)))
8328 "\\(\\|([^)]*)\\|(\"[^\"]*\")\\|.*?\\)"
e2076c2c
DN
8329 "\\*/")
8330 'verilog-delete-autos-lined)
6341f357 8331 ;; Remove those that are in parenthesis
e2076c2c
DN
8332 (verilog-auto-re-search-do
8333 (concat "/\\*"
8334 (eval-when-compile
8335 (verilog-regexp-words
8336 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
8337 "AUTOSENSE")))
8338 "\\*/")
8339 'verilog-delete-to-paren)
6341f357
DN
8340 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
8341 (verilog-auto-re-search-do "\\.\\*"
8342 'verilog-delete-auto-star-all)
8343 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
8344 (goto-char (point-min))
8345 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
8346 (replace-match ""))
8347
8348 ;; Final customize
8349 (run-hooks 'verilog-delete-auto-hook)))
8350\f
8351;;
8352;; Auto inject
8353;;
8354
8355(defun verilog-inject-auto ()
8356 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
8357
8358Any always @ blocks with sensitivity lists that match computed lists will
8359be replaced with /*AS*/ comments.
8360
37ea4b9b
JB
8361Any cells will get /*AUTOINST*/ added to the end of the pin list.
8362Pins with have identical names will be deleted.
6341f357
DN
8363
8364Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
8365support adding new ports. You may wish to delete older ports yourself.
8366
8367For example:
8368
1dd4b004 8369 module ExampInject (i, o);
6341f357
DN
8370 input i;
8371 input j;
8372 output o;
8373 always @ (i or j)
8374 o = i | j;
1dd4b004
DN
8375 InstModule instName
8376 (.foobar(baz),
8377 j(j));
6341f357
DN
8378 endmodule
8379
8380Typing \\[verilog-inject-auto] will make this into:
8381
1dd4b004 8382 module ExampInject (i, o/*AUTOARG*/
6341f357
DN
8383 // Inputs
8384 j);
8385 input i;
8386 output o;
8387 always @ (/*AS*/i or j)
8388 o = i | j;
1dd4b004
DN
8389 InstModule instName
8390 (.foobar(baz),
8391 /*AUTOINST*/
8392 // Outputs
8393 j(j));
6341f357
DN
8394 endmodule"
8395 (interactive)
8396 (verilog-auto t))
8397
8398(defun verilog-inject-arg ()
8399 "Inject AUTOARG into new code. See `verilog-inject-auto'."
8400 ;; Presume one module per file.
8401 (save-excursion
8402 (goto-char (point-min))
8403 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
8404 (let ((endmodp (save-excursion
8405 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
8406 (point))))
8407 ;; See if there's already a comment .. inside a comment so not verilog-re-search
8408 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
8409 (verilog-re-search-forward-quick ";" nil t)
8410 (backward-char 1)
8411 (verilog-backward-syntactic-ws)
8412 (backward-char 1) ; Moves to paren that closes argdecl's
8413 (when (looking-at ")")
8414 (insert "/*AUTOARG*/")))))))
8415
8416(defun verilog-inject-sense ()
8417 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
8418 (save-excursion
8419 (goto-char (point-min))
8420 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
5509c6ad 8421 (let* ((start-pt (point))
9c059794 8422 (modi (verilog-modi-current))
5509c6ad 8423 (moddecls (verilog-modi-get-decls modi))
9c059794
DN
8424 pre-sigs
8425 got-sigs)
6341f357
DN
8426 (backward-char 1)
8427 (forward-sexp 1)
8428 (backward-char 1) ;; End )
8429 (when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
8430 (setq pre-sigs (verilog-signals-from-signame
8431 (verilog-read-signals start-pt (point)))
5509c6ad 8432 got-sigs (verilog-auto-sense-sigs moddecls nil))
6341f357
DN
8433 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
8434 (verilog-signals-not-in got-sigs pre-sigs)))
8435 (delete-region start-pt (point))
8436 (insert "/*AS*/")))))))
8437
8438(defun verilog-inject-inst ()
8439 "Inject AUTOINST into new code. See `verilog-inject-auto'."
8440 (save-excursion
8441 (goto-char (point-min))
8442 ;; It's hard to distinguish modules; we'll instead search for pins.
8443 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
8444 (verilog-backward-open-paren) ;; Inst start
8445 (cond
8446 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
8447 (forward-char 1)
8448 (verilog-forward-close-paren)) ;; Parameters done
8449 (t
8450 (forward-char 1)
8451 (let ((indent-pt (+ (current-column)))
8452 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
8453 (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
8454 (goto-char end-pt)) ;; Already there, continue search with next instance
8455 (t
8456 ;; Delete identical interconnect
8457 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
8458 (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
8459 (delete-region (match-beginning 0) (match-end 0))
8460 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
8461 (while (or (looking-at "[ \t\n\f,]+")
8462 (looking-at "//[^\n]*"))
8463 (delete-region (match-beginning 0) (match-end 0))
8464 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
8465 (verilog-forward-close-paren)
8466 (backward-char 1)
8467 ;; Not verilog-re-search, as we don't want to strip comments
8468 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
8469 (delete-region (match-beginning 0) (match-end 0)))
8470 (insert "\n")
8471 (indent-to indent-pt)
8472 (insert "/*AUTOINST*/")))))))))
8473\f
8474;;
8475;; Auto save
8476;;
8477
8478(defun verilog-auto-save-check ()
8479 "On saving see if we need auto update."
8480 (cond ((not verilog-auto-save-policy)) ; disabled
8481 ((not (save-excursion
8482 (save-match-data
8483 (let ((case-fold-search nil))
8484 (goto-char (point-min))
8485 (re-search-forward "AUTO" nil t))))))
8486 ((eq verilog-auto-save-policy 'force)
8487 (verilog-auto))
8488 ((not (buffer-modified-p)))
8489 ((eq verilog-auto-update-tick (buffer-modified-tick))) ; up-to-date
8490 ((eq verilog-auto-save-policy 'detect)
8491 (verilog-auto))
8492 (t
8493 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
8494 (verilog-auto))
8495 ;; Don't ask again if didn't update
60618039 8496 (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))))
6341f357
DN
8497 (when (not verilog-auto-star-save)
8498 (verilog-delete-auto-star-implicit))
8499 nil) ;; Always return nil -- we don't write the file ourselves
8500
8501(defun verilog-auto-read-locals ()
8502 "Return file local variable segment at bottom of file."
8503 (save-excursion
8504 (goto-char (point-max))
8505 (if (re-search-backward "Local Variables:" nil t)
8506 (buffer-substring-no-properties (point) (point-max))
8507 "")))
8508
8509(defun verilog-auto-reeval-locals (&optional force)
8510 "Read file local variable segment at bottom of file if it has changed.
8511If FORCE, always reread it."
7ea26faf 8512 (make-local-variable 'verilog-auto-last-file-locals)
6341f357
DN
8513 (let ((curlocal (verilog-auto-read-locals)))
8514 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
8515 (setq verilog-auto-last-file-locals curlocal)
a3a8b002
DN
8516 ;; Note this may cause this function to be recursively invoked,
8517 ;; because hack-local-variables may call (verilog-mode)
6341f357
DN
8518 ;; The above when statement will prevent it from recursing forever.
8519 (hack-local-variables)
8520 t)))
8521\f
8522;;
8523;; Auto creation
8524;;
8525
8526(defun verilog-auto-arg-ports (sigs message indent-pt)
8527 "Print a list of ports for a AUTOINST.
8528Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
8529 (when sigs
a3a8b002
DN
8530 (when verilog-auto-arg-sort
8531 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
6341f357
DN
8532 (insert "\n")
8533 (indent-to indent-pt)
8534 (insert message)
8535 (insert "\n")
8536 (let ((space ""))
8537 (indent-to indent-pt)
8538 (while sigs
8539 (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
8540 (insert "\n")
8541 (indent-to indent-pt))
8542 (t (insert space)))
8543 (insert (verilog-sig-name (car sigs)) ",")
8544 (setq sigs (cdr sigs)
8545 space " ")))))
8546
8547(defun verilog-auto-arg ()
8548 "Expand AUTOARG statements.
8549Replace the argument declarations at the beginning of the
8550module with ones automatically derived from input and output
8551statements. This can be dangerous if the module is instantiated
8552using position-based connections, so use only name-based when
8553instantiating the resulting module. Long lines are split based
8554on the `fill-column', see \\[set-fill-column].
8555
8556Limitations:
8557 Concatenation and outputting partial busses is not supported.
8558
8559 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8560
8561For example:
8562
1dd4b004 8563 module ExampArg (/*AUTOARG*/);
6341f357
DN
8564 input i;
8565 output o;
8566 endmodule
8567
8568Typing \\[verilog-auto] will make this into:
8569
1dd4b004 8570 module ExampArg (/*AUTOARG*/
6341f357
DN
8571 // Outputs
8572 o,
8573 // Inputs
8574 i
8575 );
8576 input i;
8577 output o;
8578 endmodule
8579
a3a8b002
DN
8580The argument declarations may be printed in declaration order to best suit
8581order based instantiations, or alphabetically, based on the
8582`verilog-auto-arg-sort' variable.
8583
6341f357
DN
8584Any ports declared between the ( and /*AUTOARG*/ are presumed to be
8585predeclared and are not redeclared by AUTOARG. AUTOARG will make a
37ea4b9b
JB
8586conservative guess on adding a comma for the first signal, if you have
8587any ifdefs or complicated expressions before the AUTOARG you will need
8588to choose the comma yourself.
6341f357
DN
8589
8590Avoid declaring ports manually, as it makes code harder to maintain."
8591 (save-excursion
5509c6ad
DN
8592 (let* ((modi (verilog-modi-current))
8593 (moddecls (verilog-modi-get-decls modi))
9c059794 8594 (skip-pins (aref (verilog-read-arg-pins) 0)))
6341f357
DN
8595 (verilog-repair-open-comma)
8596 (verilog-auto-arg-ports (verilog-signals-not-in
5509c6ad 8597 (verilog-decls-get-outputs moddecls)
6341f357
DN
8598 skip-pins)
8599 "// Outputs"
8600 verilog-indent-level-declaration)
8601 (verilog-auto-arg-ports (verilog-signals-not-in
5509c6ad 8602 (verilog-decls-get-inouts moddecls)
6341f357
DN
8603 skip-pins)
8604 "// Inouts"
8605 verilog-indent-level-declaration)
8606 (verilog-auto-arg-ports (verilog-signals-not-in
5509c6ad 8607 (verilog-decls-get-inputs moddecls)
6341f357
DN
8608 skip-pins)
8609 "// Inputs"
8610 verilog-indent-level-declaration)
8611 (verilog-repair-close-comma)
8612 (unless (eq (char-before) ?/ )
8613 (insert "\n"))
60618039 8614 (indent-to verilog-indent-level-declaration))))
6341f357
DN
8615
8616(defun verilog-auto-inst-port-map (port-st)
8617 nil)
8618
6341f357
DN
8619(defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
8620(defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
a3a8b002 8621(defvar vl-modport nil "See `verilog-auto-inst'.") ; Prevent compile warning
6341f357
DN
8622(defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
8623(defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
8624(defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
8625
4c5e69c6 8626(defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
6341f357
DN
8627 "Print out a instantiation connection for this PORT-ST.
8628Insert to INDENT-PT, use template TPL-LIST.
8629@ are instantiation numbers, replaced with TPL-NUM.
60618039 8630@\"(expression @)\" are evaluated, with @ as a variable.
4c5e69c6
DN
8631If FOR-STAR add comment it is a .* expansion.
8632If PAR-VALUES replace final strings with these parameter values."
6341f357
DN
8633 (let* ((port (verilog-sig-name port-st))
8634 (tpl-ass (or (assoc port (car tpl-list))
8635 (verilog-auto-inst-port-map port-st)))
8636 ;; vl-* are documented for user use
8637 (vl-name (verilog-sig-name port-st))
8638 (vl-width (verilog-sig-width port-st))
a3a8b002 8639 (vl-modport (verilog-sig-modport port-st))
6341f357
DN
8640 (vl-bits (if (or verilog-auto-inst-vector
8641 (not (assoc port vector-skip-list))
8642 (not (equal (verilog-sig-bits port-st)
8643 (verilog-sig-bits (assoc port vector-skip-list)))))
8644 (or (verilog-sig-bits port-st) "")
8645 ""))
4c5e69c6 8646 (case-fold-search nil)
7cb1c4d7
DN
8647 (check-values par-values)
8648 tpl-net)
4c5e69c6
DN
8649 ;; Replace parameters in bit-width
8650 (when (and check-values
8651 (not (equal vl-bits "")))
8652 (while check-values
8653 (setq vl-bits (verilog-string-replace-matches
8654 (concat "\\<" (nth 0 (car check-values)) "\\>")
8655 (concat "(" (nth 1 (car check-values)) ")")
8656 t t vl-bits)
8657 check-values (cdr check-values)))
8658 (setq vl-bits (verilog-simplify-range-expression vl-bits))) ; Not in the loop for speed
7cb1c4d7 8659 ;; Default net value if not found
a3a8b002
DN
8660 (setq tpl-net (concat port
8661 (if vl-modport (concat "." vl-modport) "")
8662 (if (verilog-sig-multidim port-st)
8663 (concat "/*" (verilog-sig-multidim-string port-st)
8664 vl-bits "*/")
8665 (concat vl-bits))))
6341f357
DN
8666 ;; Find template
8667 (cond (tpl-ass ; Template of exact port name
8668 (setq tpl-net (nth 1 tpl-ass)))
8669 ((nth 1 tpl-list) ; Wildcards in template, search them
8670 (let ((wildcards (nth 1 tpl-list)))
8671 (while wildcards
8672 (when (string-match (nth 0 (car wildcards)) port)
8673 (setq tpl-ass (car wildcards) ; so allow @ parsing
8674 tpl-net (replace-match (nth 1 (car wildcards))
8675 t nil port)))
8676 (setq wildcards (cdr wildcards))))))
8677 ;; Parse Templated variable
8678 (when tpl-ass
8679 ;; Evaluate @"(lispcode)"
8680 (when (string-match "@\".*[^\\]\"" tpl-net)
8681 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
8682 (setq tpl-net
8683 (concat
8684 (substring tpl-net 0 (match-beginning 0))
8685 (save-match-data
8686 (let* ((expr (match-string 1 tpl-net))
8687 (value
8688 (progn
8689 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
8690 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
8691 (prin1 (eval (car (read-from-string expr)))
8692 (lambda (ch) ())))))
8693 (if (numberp value) (setq value (number-to-string value)))
60618039 8694 value))
6341f357
DN
8695 (substring tpl-net (match-end 0))))))
8696 ;; Replace @ and [] magic variables in final output
8697 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
60618039 8698 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
4c5e69c6 8699 ;; Insert it
6341f357
DN
8700 (indent-to indent-pt)
8701 (insert "." port)
8702 (indent-to verilog-auto-inst-column)
8703 (insert "(" tpl-net "),")
8704 (cond (tpl-ass
8705 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
8706 verilog-auto-inst-column))
8707 (insert " // Templated")
8708 (when verilog-auto-inst-template-numbers
8709 (insert " T" (int-to-string (nth 2 tpl-ass))
8710 " L" (int-to-string (nth 3 tpl-ass)))))
8711 (for-star
8712 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
8713 verilog-auto-inst-column))
8714 (insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
8715 (insert "\n")))
8716;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
8717;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
8718;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
8719
8720(defun verilog-auto-inst-first ()
8721 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
8722 ;; Do we need a trailing comma?
8723 ;; There maybe a ifdef or something similar before us. What a mess. Thus
8724 ;; to avoid trouble we only insert on preceeding ) or *.
8725 ;; Insert first port on new line
8726 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
8727 (save-excursion
8728 (verilog-re-search-backward "[^ \t\n\f]" nil nil)
8729 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
8730 (forward-char 1)
8731 (insert ","))))
8732
8733(defun verilog-auto-star ()
8734 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
8735
8736If `verilog-auto-star-expand' is set, .* pins are treated if they were
37ea4b9b 8737AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
6341f357
DN
8738will also ignore any .* that are not last in your pin list (this prevents
8739it from deleting pins following the .* when it expands the AUTOINST.)
8740
8741On writing your file, unless `verilog-auto-star-save' is set, any
8742non-templated expanded pins will be removed. You may do this at any time
8743with \\[verilog-delete-auto-star-implicit].
8744
8745If you are converting a module to use .* for the first time, you may wish
8746to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
8747
8748See `verilog-auto-inst' for examples, templates, and more information."
8749 (when (verilog-auto-star-safe)
8750 (verilog-auto-inst)))
8751
8752(defun verilog-auto-inst ()
8753 "Expand AUTOINST statements, as part of \\[verilog-auto].
8754Replace the pin connections to an instantiation with ones
8755automatically derived from the module header of the instantiated netlist.
8756
8757If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
8758and delete them before saving unless `verilog-auto-star-save' is set.
8759See `verilog-auto-star' for more information.
8760
8761Limitations:
8762 Module names must be resolvable to filenames by adding a
8763 `verilog-library-extensions', and being found in the same directory, or
8764 by changing the variable `verilog-library-flags' or
8765 `verilog-library-directories'. Macros `modname are translated through the
8766 vh-{name} Emacs variable, if that is not found, it just ignores the `.
8767
8768 In templates you must have one signal per line, ending in a ), or ));,
8769 and have proper () nesting, including a final ); to end the template.
8770
8771 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8772
37ea4b9b 8773 SystemVerilog multidimensional input/output has only experimental support.
6341f357 8774
4c5e69c6
DN
8775 Parameters referenced by the instantiation will remain symbolic, unless
8776 `verilog-auto-inst-param-value' is set.
8777
1dd4b004 8778For example, first take the submodule InstModule.v:
6341f357 8779
1dd4b004 8780 module InstModule (o,i)
6341f357
DN
8781 output [31:0] o;
8782 input i;
8783 wire [31:0] o = {32{i}};
8784 endmodule
8785
8786This is then used in a upper level module:
8787
1dd4b004 8788 module ExampInst (o,i)
6341f357
DN
8789 output o;
8790 input i;
1dd4b004
DN
8791 InstModule instName
8792 (/*AUTOINST*/);
6341f357
DN
8793 endmodule
8794
8795Typing \\[verilog-auto] will make this into:
8796
1dd4b004 8797 module ExampInst (o,i)
6341f357
DN
8798 output o;
8799 input i;
1dd4b004
DN
8800 InstModule instName
8801 (/*AUTOINST*/
8802 // Outputs
8803 .ov (ov[31:0]),
8804 // Inputs
8805 .i (i));
6341f357
DN
8806 endmodule
8807
8808Where the list of inputs and outputs came from the inst module.
8809\f
8810Exceptions:
8811
8812 Unless you are instantiating a module multiple times, or the module is
37ea4b9b 8813 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
6341f357 8814 It just makes for unmaintainable code. To sanitize signal names, try
855b42a2 8815 vrename from URL `http://www.veripool.org'.
6341f357
DN
8816
8817 When you need to violate this suggestion there are two ways to list
8818 exceptions, placing them before the AUTOINST, or using templates.
8819
8820 Any ports defined before the /*AUTOINST*/ are not included in the list of
8821 automatics. This is similar to making a template as described below, but
8822 is restricted to simple connections just like you normally make. Also note
8823 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
8824 you have the appropriate // Input or // Output comment, and exactly the
8825 same line formatting as AUTOINST itself uses.
8826
1dd4b004
DN
8827 InstModule instName
8828 (// Inputs
8829 .i (my_i_dont_mess_with_it),
8830 /*AUTOINST*/
8831 // Outputs
8832 .ov (ov[31:0]));
6341f357
DN
8833
8834\f
8835Templates:
8836
8837 For multiple instantiations based upon a single template, create a
8838 commented out template:
8839
1dd4b004 8840 /* InstModule AUTO_TEMPLATE (
6341f357
DN
8841 .sig3 (sigz[]),
8842 );
8843 */
8844
37ea4b9b 8845 Templates go ABOVE the instantiation(s). When an instantiation is
6341f357
DN
8846 expanded `verilog-mode' simply searches up for the closest template.
8847 Thus you can have multiple templates for the same module, just alternate
37ea4b9b 8848 between the template for an instantiation and the instantiation itself.
6341f357
DN
8849
8850 The module name must be the same as the name of the module in the
8851 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
8852 words and capitalized. Only signals that must be different for each
8853 instantiation need to be listed.
8854
8855 Inside a template, a [] in a connection name (with nothing else inside
8856 the brackets) will be replaced by the same bus subscript as it is being
8857 connected to, or the [] will be removed if it is a single bit signal.
8858 Generally it is a good idea to do this for all connections in a template,
8859 as then they will work for any width signal, and with AUTOWIRE. See
8860 PTL_BUS becoming PTL_BUSNEW below.
8861
8862 If you have a complicated template, set `verilog-auto-inst-template-numbers'
8863 to see which regexps are matching. Don't leave that mode set after
8864 debugging is completed though, it will result in lots of extra differences
8865 and merge conflicts.
8866
8867 For example:
8868
1dd4b004 8869 /* InstModule AUTO_TEMPLATE (
6341f357
DN
8870 .ptl_bus (ptl_busnew[]),
8871 );
8872 */
1dd4b004 8873 InstModule ms2m (/*AUTOINST*/);
6341f357
DN
8874
8875 Typing \\[verilog-auto] will make this into:
8876
1dd4b004 8877 InstModule ms2m (/*AUTOINST*/
6341f357
DN
8878 // Outputs
8879 .NotInTemplate (NotInTemplate),
8880 .ptl_bus (ptl_busnew[3:0]), // Templated
8881 ....
8882\f
8883@ Templates:
8884
8885 It is common to instantiate a cell multiple times, so templates make it
8886 trivial to substitute part of the cell name into the connection name.
8887
1dd4b004 8888 /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
6341f357
DN
8889 .sig1 (sigx[@]),
8890 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
8891 );
8892 */
8893
8894 If no regular expression is provided immediately after the AUTO_TEMPLATE
8895 keyword, then the @ character in any connection names will be replaced
8896 with the instantiation number; the first digits found in the cell's
8897 instantiation name.
8898
8899 If a regular expression is provided, the @ character will be replaced
8900 with the first \(\) grouping that matches against the cell name. Using a
8901 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
8902 regexp is provided. If you use multiple layers of parenthesis,
8903 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
8904 characters after test and before _, whereas
8905 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
8906 match.
8907
8908 For example:
8909
1dd4b004 8910 /* InstModule AUTO_TEMPLATE (
6341f357
DN
8911 .ptl_mapvalidx (ptl_mapvalid[@]),
8912 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
8913 );
8914 */
1dd4b004 8915 InstModule ms2m (/*AUTOINST*/);
6341f357
DN
8916
8917 Typing \\[verilog-auto] will make this into:
8918
1dd4b004 8919 InstModule ms2m (/*AUTOINST*/
6341f357
DN
8920 // Outputs
8921 .ptl_mapvalidx (ptl_mapvalid[2]),
8922 .ptl_mapvalidp1x (ptl_mapvalid[3]));
8923
8924 Note the @ character was replaced with the 2 from \"ms2m\".
8925
8926 Alternatively, using a regular expression for @:
8927
1dd4b004 8928 /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
6341f357
DN
8929 .ptl_mapvalidx (@_ptl_mapvalid),
8930 .ptl_mapvalidp1x (ptl_mapvalid_@),
8931 );
8932 */
1dd4b004
DN
8933 InstModule ms2_FOO (/*AUTOINST*/);
8934 InstModule ms2_BAR (/*AUTOINST*/);
6341f357
DN
8935
8936 Typing \\[verilog-auto] will make this into:
8937
1dd4b004 8938 InstModule ms2_FOO (/*AUTOINST*/
6341f357
DN
8939 // Outputs
8940 .ptl_mapvalidx (FOO_ptl_mapvalid),
8941 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
1dd4b004 8942 InstModule ms2_BAR (/*AUTOINST*/
6341f357
DN
8943 // Outputs
8944 .ptl_mapvalidx (BAR_ptl_mapvalid),
8945 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
8946
8947\f
8948Regexp Templates:
8949
8950 A template entry of the form
8951
8952 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
8953
37ea4b9b 8954 will apply an Emacs style regular expression search for any port beginning
6341f357
DN
8955 in pci_req followed by numbers and ending in _l and connecting that to
8956 the pci_req_jtag_[] net, with the bus subscript coming from what matches
8957 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
8958
8959 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
8960 does the same thing. (Note a @ in the connection/replacement text is
8961 completely different -- still use \\1 there!) Thus this is the same as
8962 the above template:
8963
8964 .pci_req@_l (pci_req_jtag_[\\1]),
8965
8966 Here's another example to remove the _l, useful when naming conventions
8967 specify _ alone to mean active low. Note the use of [] to keep the bus
8968 subscript:
8969
8970 .\\(.*\\)_l (\\1_[]),
8971\f
8972Lisp Templates:
8973
8974 First any regular expression template is expanded.
8975
8976 If the syntax @\"( ... )\" is found in a connection, the expression in
8977 quotes will be evaluated as a Lisp expression, with @ replaced by the
8978 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
8979 4 into the brackets. Quote all double-quotes inside the expression with
8980 a leading backslash (\\\"). There are special variables defined that are
8981 useful in these Lisp functions:
8982
37ea4b9b
JB
8983 vl-name Name portion of the input/output port.
8984 vl-bits Bus bits portion of the input/output port ('[2:0]').
8985 vl-width Width of the input/output port ('3' for [2:0]).
6341f357 8986 May be a (...) expression if bits isn't a constant.
a3a8b002
DN
8987 vl-dir Direction of the pin input/output/inout/interface.
8988 vl-modport The modport, if an interface with a modport.
1dd4b004
DN
8989 vl-cell-type Module name/type of the cell ('InstModule').
8990 vl-cell-name Instance name of the cell ('instName').
6341f357
DN
8991
8992 Normal Lisp variables may be used in expressions. See
8993 `verilog-read-defines' which can set vh-{definename} variables for use
8994 here. Also, any comments of the form:
8995
8996 /*AUTO_LISP(setq foo 1)*/
8997
8998 will evaluate any Lisp expression inside the parenthesis between the
8999 beginning of the buffer and the point of the AUTOINST. This allows
9000 functions to be defined or variables to be changed between instantiations.
a3a8b002
DN
9001 (See also `verilog-auto-insert-lisp' if you want the output from your
9002 lisp function to be inserted.)
6341f357
DN
9003
9004 Note that when using lisp expressions errors may occur when @ is not a
37ea4b9b 9005 number; you may need to use the standard Emacs Lisp functions
6341f357
DN
9006 `number-to-string' and `string-to-number'.
9007
9008 After the evaluation is completed, @ substitution and [] substitution
9009 occur."
9010 (save-excursion
9011 ;; Find beginning
9012 (let* ((pt (point))
9013 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
9014 (indent-pt (save-excursion (verilog-backward-open-paren)
9015 (1+ (current-column))))
9016 (verilog-auto-inst-column (max verilog-auto-inst-column
9017 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
9018 (modi (verilog-modi-current))
5509c6ad 9019 (moddecls (verilog-modi-get-decls modi))
6341f357 9020 (vector-skip-list (unless verilog-auto-inst-vector
5509c6ad
DN
9021 (verilog-decls-get-signals moddecls)))
9022 submod submodi submoddecls
4c5e69c6
DN
9023 inst skip-pins tpl-list tpl-num did-first par-values)
9024
6341f357
DN
9025 ;; Find module name that is instantiated
9026 (setq submod (verilog-read-inst-module)
9027 inst (verilog-read-inst-name)
9028 vl-cell-type submod
9029 vl-cell-name inst
9030 skip-pins (aref (verilog-read-inst-pins) 0))
9031
9032 ;; Parse any AUTO_LISP() before here
9033 (verilog-read-auto-lisp (point-min) pt)
9034
4c5e69c6
DN
9035 ;; Read parameters (after AUTO_LISP)
9036 (setq par-values (and verilog-auto-inst-param-value
9037 (verilog-read-inst-param-value)))
9038
6341f357
DN
9039 ;; Lookup position, etc of submodule
9040 ;; Note this may raise an error
9041 (when (setq submodi (verilog-modi-lookup submod t))
5509c6ad 9042 (setq submoddecls (verilog-modi-get-decls submodi))
6341f357
DN
9043 ;; If there's a number in the instantiation, it may be a argument to the
9044 ;; automatic variable instantiation program.
9045 (let* ((tpl-info (verilog-read-auto-template submod))
9046 (tpl-regexp (aref tpl-info 0)))
9047 (setq tpl-num (if (string-match tpl-regexp inst)
9048 (match-string 1 inst)
9049 "")
9050 tpl-list (aref tpl-info 1)))
9051 ;; Find submodule's signals and dump
a3a8b002
DN
9052 (let ((sig-list (verilog-signals-not-in
9053 (verilog-decls-get-interfaces submoddecls)
9054 skip-pins))
9055 (vl-dir "interface"))
9056 (when sig-list
9057 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9058 (indent-to indent-pt)
9059 ;; Note these are searched for in verilog-read-sub-decls.
9060 (insert "// Interfaces\n")
9061 (mapc (lambda (port)
9062 (verilog-auto-inst-port port indent-pt
9063 tpl-list tpl-num for-star par-values))
9064 sig-list)))
6341f357 9065 (let ((sig-list (verilog-signals-not-in
5509c6ad 9066 (verilog-decls-get-outputs submoddecls)
6341f357
DN
9067 skip-pins))
9068 (vl-dir "output"))
9069 (when sig-list
9070 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9071 (indent-to indent-pt)
7ea26faf
DN
9072 (insert "// Outputs\n")
9073 (mapc (lambda (port)
9074 (verilog-auto-inst-port port indent-pt
4c5e69c6 9075 tpl-list tpl-num for-star par-values))
7ea26faf 9076 sig-list)))
6341f357 9077 (let ((sig-list (verilog-signals-not-in
5509c6ad 9078 (verilog-decls-get-inouts submoddecls)
6341f357
DN
9079 skip-pins))
9080 (vl-dir "inout"))
9081 (when sig-list
9082 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9083 (indent-to indent-pt)
9084 (insert "// Inouts\n")
7ea26faf
DN
9085 (mapc (lambda (port)
9086 (verilog-auto-inst-port port indent-pt
4c5e69c6 9087 tpl-list tpl-num for-star par-values))
7ea26faf 9088 sig-list)))
6341f357 9089 (let ((sig-list (verilog-signals-not-in
5509c6ad 9090 (verilog-decls-get-inputs submoddecls)
6341f357
DN
9091 skip-pins))
9092 (vl-dir "input"))
9093 (when sig-list
9094 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9095 (indent-to indent-pt)
9096 (insert "// Inputs\n")
7ea26faf
DN
9097 (mapc (lambda (port)
9098 (verilog-auto-inst-port port indent-pt
4c5e69c6 9099 tpl-list tpl-num for-star par-values))
7ea26faf 9100 sig-list)))
6341f357
DN
9101 ;; Kill extra semi
9102 (save-excursion
9103 (cond (did-first
9104 (re-search-backward "," pt t)
9105 (delete-char 1)
9106 (insert ");")
9107 (search-forward "\n") ;; Added by inst-port
9108 (delete-backward-char 1)
9109 (if (search-forward ")" nil t) ;; From user, moved up a line
9110 (delete-backward-char 1))
9111 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
60618039 9112 (delete-backward-char 1)))))))))
6341f357
DN
9113
9114(defun verilog-auto-inst-param ()
9115 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
9116Replace the parameter connections to an instantiation with ones
9117automatically derived from the module header of the instantiated netlist.
9118
9119See \\[verilog-auto-inst] for limitations, and templates to customize the
9120output.
9121
1dd4b004 9122For example, first take the submodule InstModule.v:
6341f357 9123
1dd4b004 9124 module InstModule (o,i)
6341f357
DN
9125 parameter PAR;
9126 endmodule
9127
9128This is then used in a upper level module:
9129
1dd4b004 9130 module ExampInst (o,i)
6341f357 9131 parameter PAR;
1dd4b004
DN
9132 InstModule #(/*AUTOINSTPARAM*/)
9133 instName (/*AUTOINST*/);
6341f357
DN
9134 endmodule
9135
9136Typing \\[verilog-auto] will make this into:
9137
1dd4b004 9138 module ExampInst (o,i)
6341f357
DN
9139 output o;
9140 input i;
1dd4b004
DN
9141 InstModule #(/*AUTOINSTPARAM*/
9142 // Parameters
9143 .PAR (PAR));
9144 instName (/*AUTOINST*/);
6341f357
DN
9145 endmodule
9146
9147Where the list of parameter connections come from the inst module.
9148\f
9149Templates:
9150
9151 You can customize the parameter connections using AUTO_TEMPLATEs,
9152 just as you would with \\[verilog-auto-inst]."
9153 (save-excursion
9154 ;; Find beginning
9155 (let* ((pt (point))
9156 (indent-pt (save-excursion (verilog-backward-open-paren)
9157 (1+ (current-column))))
9158 (verilog-auto-inst-column (max verilog-auto-inst-column
9159 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
9160 (modi (verilog-modi-current))
5509c6ad 9161 (moddecls (verilog-modi-get-decls modi))
6341f357 9162 (vector-skip-list (unless verilog-auto-inst-vector
5509c6ad
DN
9163 (verilog-decls-get-signals moddecls)))
9164 submod submodi submoddecls
9165 inst skip-pins tpl-list tpl-num did-first)
6341f357
DN
9166 ;; Find module name that is instantiated
9167 (setq submod (save-excursion
9168 ;; Get to the point where AUTOINST normally is to read the module
9169 (verilog-re-search-forward-quick "[(;]" nil nil)
9170 (verilog-read-inst-module))
9171 inst (save-excursion
9172 ;; Get to the point where AUTOINST normally is to read the module
9173 (verilog-re-search-forward-quick "[(;]" nil nil)
9174 (verilog-read-inst-name))
9175 vl-cell-type submod
9176 vl-cell-name inst
9177 skip-pins (aref (verilog-read-inst-pins) 0))
9178
9179 ;; Parse any AUTO_LISP() before here
9180 (verilog-read-auto-lisp (point-min) pt)
9181
9182 ;; Lookup position, etc of submodule
9183 ;; Note this may raise an error
9184 (when (setq submodi (verilog-modi-lookup submod t))
5509c6ad 9185 (setq submoddecls (verilog-modi-get-decls submodi))
6341f357
DN
9186 ;; If there's a number in the instantiation, it may be a argument to the
9187 ;; automatic variable instantiation program.
9188 (let* ((tpl-info (verilog-read-auto-template submod))
9189 (tpl-regexp (aref tpl-info 0)))
9190 (setq tpl-num (if (string-match tpl-regexp inst)
9191 (match-string 1 inst)
9192 "")
9193 tpl-list (aref tpl-info 1)))
9194 ;; Find submodule's signals and dump
9195 (let ((sig-list (verilog-signals-not-in
5509c6ad 9196 (verilog-decls-get-gparams submoddecls)
6341f357
DN
9197 skip-pins))
9198 (vl-dir "parameter"))
9199 (when sig-list
9200 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9201 (indent-to indent-pt)
7ea26faf
DN
9202 ;; Note these are searched for in verilog-read-sub-decls.
9203 (insert "// Parameters\n")
9204 (mapc (lambda (port)
9205 (verilog-auto-inst-port port indent-pt
4c5e69c6 9206 tpl-list tpl-num nil nil))
7ea26faf 9207 sig-list)))
6341f357
DN
9208 ;; Kill extra semi
9209 (save-excursion
9210 (cond (did-first
9211 (re-search-backward "," pt t)
9212 (delete-char 1)
9213 (insert ")")
9214 (search-forward "\n") ;; Added by inst-port
9215 (delete-backward-char 1)
9216 (if (search-forward ")" nil t) ;; From user, moved up a line
60618039 9217 (delete-backward-char 1)))))))))
6341f357
DN
9218
9219(defun verilog-auto-reg ()
9220 "Expand AUTOREG statements, as part of \\[verilog-auto].
9221Make reg statements for any output that isn't already declared,
9222and isn't a wire output from a block.
9223
9224Limitations:
9225 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9226
9227 This does NOT work on memories, declare those yourself.
9228
9229An example:
9230
1dd4b004 9231 module ExampReg (o,i)
6341f357
DN
9232 output o;
9233 input i;
9234 /*AUTOREG*/
9235 always o = i;
9236 endmodule
9237
9238Typing \\[verilog-auto] will make this into:
9239
1dd4b004 9240 module ExampReg (o,i)
6341f357
DN
9241 output o;
9242 input i;
9243 /*AUTOREG*/
9244 // Beginning of automatic regs (for this module's undeclared outputs)
1dd4b004 9245 reg o;
6341f357
DN
9246 // End of automatics
9247 always o = i;
9248 endmodule"
9249 (save-excursion
9250 ;; Point must be at insertion point.
9251 (let* ((indent-pt (current-indentation))
9252 (modi (verilog-modi-current))
5509c6ad
DN
9253 (moddecls (verilog-modi-get-decls modi))
9254 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 9255 (sig-list (verilog-signals-not-in
5509c6ad
DN
9256 (verilog-decls-get-outputs moddecls)
9257 (append (verilog-decls-get-wires moddecls)
9258 (verilog-decls-get-regs moddecls)
9259 (verilog-decls-get-assigns moddecls)
9260 (verilog-decls-get-consts moddecls)
9261 (verilog-decls-get-gparams moddecls)
9262 (verilog-subdecls-get-outputs modsubdecls)
9263 (verilog-subdecls-get-inouts modsubdecls)))))
6341f357
DN
9264 (forward-line 1)
9265 (when sig-list
9266 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
9267 (verilog-insert-definition sig-list "reg" indent-pt nil)
9268 (verilog-modi-cache-add-regs modi sig-list)
60618039 9269 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
9270
9271(defun verilog-auto-reg-input ()
9272 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
9273Make reg statements instantiation inputs that aren't already declared.
9274This is useful for making a top level shell for testing the module that is
9275to be instantiated.
9276
9277Limitations:
9278 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
9279
9280 This does NOT work on memories, declare those yourself.
9281
9282An example (see `verilog-auto-inst' for what else is going on here):
9283
1dd4b004 9284 module ExampRegInput (o,i)
6341f357
DN
9285 output o;
9286 input i;
9287 /*AUTOREGINPUT*/
1dd4b004
DN
9288 InstModule instName
9289 (/*AUTOINST*/);
6341f357
DN
9290 endmodule
9291
9292Typing \\[verilog-auto] will make this into:
9293
1dd4b004 9294 module ExampRegInput (o,i)
6341f357
DN
9295 output o;
9296 input i;
9297 /*AUTOREGINPUT*/
9298 // Beginning of automatic reg inputs (for undeclared ...
1dd4b004 9299 reg [31:0] iv; // From inst of inst.v
6341f357 9300 // End of automatics
1dd4b004
DN
9301 InstModule instName
9302 (/*AUTOINST*/
9303 // Outputs
9304 .o (o[31:0]),
9305 // Inputs
9306 .iv (iv));
6341f357
DN
9307 endmodule"
9308 (save-excursion
9309 ;; Point must be at insertion point.
9310 (let* ((indent-pt (current-indentation))
9311 (modi (verilog-modi-current))
5509c6ad
DN
9312 (moddecls (verilog-modi-get-decls modi))
9313 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357
DN
9314 (sig-list (verilog-signals-combine-bus
9315 (verilog-signals-not-in
5509c6ad
DN
9316 (append (verilog-subdecls-get-inputs modsubdecls)
9317 (verilog-subdecls-get-inouts modsubdecls))
9318 (verilog-decls-get-signals moddecls)))))
6341f357
DN
9319 (forward-line 1)
9320 (when sig-list
9321 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
9322 (verilog-insert-definition sig-list "reg" indent-pt nil)
9323 (verilog-modi-cache-add-regs modi sig-list)
60618039 9324 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
9325
9326(defun verilog-auto-wire ()
9327 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
9328Make wire statements for instantiations outputs that aren't
9329already declared.
9330
9331Limitations:
9332 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
9333 and all busses must have widths, such as those from AUTOINST, or using []
9334 in AUTO_TEMPLATEs.
9335
9336 This does NOT work on memories or SystemVerilog .name connections,
9337 declare those yourself.
9338
37ea4b9b
JB
9339 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
9340 determine how to bus together. This occurs when you have ports with
9341 non-numeric or non-sequential bus subscripts. If Verilog mode
6341f357
DN
9342 mis-guessed, you'll have to declare them yourself.
9343
9344An example (see `verilog-auto-inst' for what else is going on here):
9345
1dd4b004 9346 module ExampWire (o,i)
6341f357
DN
9347 output o;
9348 input i;
9349 /*AUTOWIRE*/
1dd4b004
DN
9350 InstModule instName
9351 (/*AUTOINST*/);
6341f357
DN
9352 endmodule
9353
9354Typing \\[verilog-auto] will make this into:
9355
1dd4b004 9356 module ExampWire (o,i)
6341f357
DN
9357 output o;
9358 input i;
9359 /*AUTOWIRE*/
9360 // Beginning of automatic wires
9361 wire [31:0] ov; // From inst of inst.v
9362 // End of automatics
1dd4b004
DN
9363 InstModule instName
9364 (/*AUTOINST*/
9365 // Outputs
9366 .ov (ov[31:0]),
9367 // Inputs
9368 .i (i));
6341f357
DN
9369 wire o = | ov;
9370 endmodule"
9371 (save-excursion
9372 ;; Point must be at insertion point.
9373 (let* ((indent-pt (current-indentation))
9374 (modi (verilog-modi-current))
5509c6ad
DN
9375 (moddecls (verilog-modi-get-decls modi))
9376 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357
DN
9377 (sig-list (verilog-signals-combine-bus
9378 (verilog-signals-not-in
5509c6ad
DN
9379 (append (verilog-subdecls-get-outputs modsubdecls)
9380 (verilog-subdecls-get-inouts modsubdecls))
9381 (verilog-decls-get-signals moddecls)))))
6341f357
DN
9382 (forward-line 1)
9383 (when sig-list
9384 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
9385 (verilog-insert-definition sig-list "wire" indent-pt nil)
9386 (verilog-modi-cache-add-wires modi sig-list)
9387 (verilog-insert-indent "// End of automatics\n")
9388 (when nil ;; Too slow on huge modules, plus makes everyone's module change
9389 (beginning-of-line)
9390 (setq pnt (point))
7e2a6000 9391 (verilog-pretty-declarations quiet)
6341f357 9392 (goto-char pnt)
a3a8b002 9393 (verilog-pretty-expr t "//"))))))
6341f357 9394
e2076c2c 9395(defun verilog-auto-output (&optional with-params)
6341f357
DN
9396 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
9397Make output statements for any output signal from an /*AUTOINST*/ that
9398isn't a input to another AUTOINST. This is useful for modules which
9399only instantiate other modules.
9400
9401Limitations:
9402 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9403
9404 If placed inside the parenthesis of a module declaration, it creates
9405 Verilog 2001 style, else uses Verilog 1995 style.
9406
9407 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
9408 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
9409
9410 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9411
9412 Signals matching `verilog-auto-output-ignore-regexp' are not included.
9413
9414An example (see `verilog-auto-inst' for what else is going on here):
9415
1dd4b004 9416 module ExampOutput (ov,i)
6341f357
DN
9417 input i;
9418 /*AUTOOUTPUT*/
1dd4b004
DN
9419 InstModule instName
9420 (/*AUTOINST*/);
6341f357
DN
9421 endmodule
9422
9423Typing \\[verilog-auto] will make this into:
9424
1dd4b004 9425 module ExampOutput (ov,i)
6341f357
DN
9426 input i;
9427 /*AUTOOUTPUT*/
9428 // Beginning of automatic outputs (from unused autoinst outputs)
1dd4b004 9429 output [31:0] ov; // From inst of inst.v
6341f357 9430 // End of automatics
1dd4b004
DN
9431 InstModule instName
9432 (/*AUTOINST*/
9433 // Outputs
9434 .ov (ov[31:0]),
9435 // Inputs
9436 .i (i));
e2076c2c
DN
9437 endmodule
9438
9439You may also provide an optional regular expression, in which case only
9440signals matching the regular expression will be included. For example the
9441same expansion will result from only extracting outputs starting with ov:
9442
9443 /*AUTOOUTPUT(\"^ov\")*/"
6341f357
DN
9444 (save-excursion
9445 ;; Point must be at insertion point.
9446 (let* ((indent-pt (current-indentation))
e2076c2c
DN
9447 (regexp (and with-params
9448 (nth 0 (verilog-read-auto-params 1))))
6341f357
DN
9449 (v2k (verilog-in-paren))
9450 (modi (verilog-modi-current))
5509c6ad
DN
9451 (moddecls (verilog-modi-get-decls modi))
9452 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 9453 (sig-list (verilog-signals-not-in
5509c6ad
DN
9454 (verilog-subdecls-get-outputs modsubdecls)
9455 (append (verilog-decls-get-outputs moddecls)
9456 (verilog-decls-get-inouts moddecls)
9457 (verilog-subdecls-get-inputs modsubdecls)
9458 (verilog-subdecls-get-inouts modsubdecls)))))
e2076c2c
DN
9459 (when regexp
9460 (setq sig-list (verilog-signals-matching-regexp
9461 sig-list regexp)))
6341f357
DN
9462 (setq sig-list (verilog-signals-not-matching-regexp
9463 sig-list verilog-auto-output-ignore-regexp))
9464 (forward-line 1)
9465 (when v2k (verilog-repair-open-comma))
9466 (when sig-list
9467 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
9468 (verilog-insert-definition sig-list "output" indent-pt v2k)
9469 (verilog-modi-cache-add-outputs modi sig-list)
9470 (verilog-insert-indent "// End of automatics\n"))
60618039 9471 (when v2k (verilog-repair-close-comma)))))
6341f357
DN
9472
9473(defun verilog-auto-output-every ()
9474 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
9475Make output statements for any signals that aren't primary inputs or
9476outputs already. This makes every signal in the design a output. This is
9477useful to get Synopsys to preserve every signal in the design, since it
9478won't optimize away the outputs.
9479
9480An example:
9481
1dd4b004 9482 module ExampOutputEvery (o,i,tempa,tempb)
6341f357
DN
9483 output o;
9484 input i;
9485 /*AUTOOUTPUTEVERY*/
9486 wire tempa = i;
9487 wire tempb = tempa;
9488 wire o = tempb;
9489 endmodule
9490
9491Typing \\[verilog-auto] will make this into:
9492
1dd4b004 9493 module ExampOutputEvery (o,i,tempa,tempb)
6341f357
DN
9494 output o;
9495 input i;
9496 /*AUTOOUTPUTEVERY*/
9497 // Beginning of automatic outputs (every signal)
1dd4b004
DN
9498 output tempb;
9499 output tempa;
6341f357
DN
9500 // End of automatics
9501 wire tempa = i;
9502 wire tempb = tempa;
9503 wire o = tempb;
9504 endmodule"
9505 (save-excursion
9506 ;;Point must be at insertion point
9507 (let* ((indent-pt (current-indentation))
9508 (v2k (verilog-in-paren))
9509 (modi (verilog-modi-current))
5509c6ad 9510 (moddecls (verilog-modi-get-decls modi))
6341f357
DN
9511 (sig-list (verilog-signals-combine-bus
9512 (verilog-signals-not-in
5509c6ad
DN
9513 (verilog-decls-get-signals moddecls)
9514 (verilog-decls-get-ports moddecls)))))
6341f357
DN
9515 (forward-line 1)
9516 (when v2k (verilog-repair-open-comma))
9517 (when sig-list
9518 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
9519 (verilog-insert-definition sig-list "output" indent-pt v2k)
9520 (verilog-modi-cache-add-outputs modi sig-list)
9521 (verilog-insert-indent "// End of automatics\n"))
60618039 9522 (when v2k (verilog-repair-close-comma)))))
6341f357 9523
e2076c2c 9524(defun verilog-auto-input (&optional with-params)
6341f357
DN
9525 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
9526Make input statements for any input signal into an /*AUTOINST*/ that
9527isn't declared elsewhere inside the module. This is useful for modules which
9528only instantiate other modules.
9529
9530Limitations:
9531 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9532
9533 If placed inside the parenthesis of a module declaration, it creates
9534 Verilog 2001 style, else uses Verilog 1995 style.
9535
9536 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
9537 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
9538
9539 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9540
9541 Signals matching `verilog-auto-input-ignore-regexp' are not included.
9542
9543An example (see `verilog-auto-inst' for what else is going on here):
9544
1dd4b004 9545 module ExampInput (ov,i)
6341f357
DN
9546 output [31:0] ov;
9547 /*AUTOINPUT*/
1dd4b004
DN
9548 InstModule instName
9549 (/*AUTOINST*/);
6341f357
DN
9550 endmodule
9551
9552Typing \\[verilog-auto] will make this into:
9553
1dd4b004 9554 module ExampInput (ov,i)
6341f357
DN
9555 output [31:0] ov;
9556 /*AUTOINPUT*/
9557 // Beginning of automatic inputs (from unused autoinst inputs)
1dd4b004 9558 input i; // From inst of inst.v
6341f357 9559 // End of automatics
1dd4b004
DN
9560 InstModule instName
9561 (/*AUTOINST*/
9562 // Outputs
9563 .ov (ov[31:0]),
9564 // Inputs
9565 .i (i));
e2076c2c
DN
9566 endmodule
9567
9568You may also provide an optional regular expression, in which case only
9569signals matching the regular expression will be included. For example the
9570same expansion will result from only extracting inputs starting with i:
9571
9572 /*AUTOINPUT(\"^i\")*/"
6341f357
DN
9573 (save-excursion
9574 (let* ((indent-pt (current-indentation))
e2076c2c
DN
9575 (regexp (and with-params
9576 (nth 0 (verilog-read-auto-params 1))))
6341f357
DN
9577 (v2k (verilog-in-paren))
9578 (modi (verilog-modi-current))
5509c6ad
DN
9579 (moddecls (verilog-modi-get-decls modi))
9580 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 9581 (sig-list (verilog-signals-not-in
5509c6ad
DN
9582 (verilog-subdecls-get-inputs modsubdecls)
9583 (append (verilog-decls-get-inputs moddecls)
9584 (verilog-decls-get-inouts moddecls)
9585 (verilog-decls-get-wires moddecls)
9586 (verilog-decls-get-regs moddecls)
9587 (verilog-decls-get-consts moddecls)
9588 (verilog-decls-get-gparams moddecls)
9589 (verilog-subdecls-get-outputs modsubdecls)
9590 (verilog-subdecls-get-inouts modsubdecls)))))
e2076c2c
DN
9591 (when regexp
9592 (setq sig-list (verilog-signals-matching-regexp
9593 sig-list regexp)))
6341f357
DN
9594 (setq sig-list (verilog-signals-not-matching-regexp
9595 sig-list verilog-auto-input-ignore-regexp))
9596 (forward-line 1)
9597 (when v2k (verilog-repair-open-comma))
9598 (when sig-list
9599 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
9600 (verilog-insert-definition sig-list "input" indent-pt v2k)
9601 (verilog-modi-cache-add-inputs modi sig-list)
9602 (verilog-insert-indent "// End of automatics\n"))
60618039 9603 (when v2k (verilog-repair-close-comma)))))
6341f357 9604
e2076c2c 9605(defun verilog-auto-inout (&optional with-params)
6341f357
DN
9606 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
9607Make inout statements for any inout signal in an /*AUTOINST*/ that
9608isn't declared elsewhere inside the module.
9609
9610Limitations:
9611 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9612
9613 If placed inside the parenthesis of a module declaration, it creates
9614 Verilog 2001 style, else uses Verilog 1995 style.
9615
9616 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
9617 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
9618
9619 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9620
9621 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
9622
9623An example (see `verilog-auto-inst' for what else is going on here):
9624
1dd4b004 9625 module ExampInout (ov,i)
6341f357
DN
9626 input i;
9627 /*AUTOINOUT*/
1dd4b004
DN
9628 InstModule instName
9629 (/*AUTOINST*/);
6341f357
DN
9630 endmodule
9631
9632Typing \\[verilog-auto] will make this into:
9633
1dd4b004 9634 module ExampInout (ov,i)
6341f357
DN
9635 input i;
9636 /*AUTOINOUT*/
9637 // Beginning of automatic inouts (from unused autoinst inouts)
1dd4b004 9638 inout [31:0] ov; // From inst of inst.v
6341f357 9639 // End of automatics
1dd4b004
DN
9640 InstModule instName
9641 (/*AUTOINST*/
9642 // Inouts
9643 .ov (ov[31:0]),
9644 // Inputs
9645 .i (i));
e2076c2c
DN
9646 endmodule
9647
9648You may also provide an optional regular expression, in which case only
9649signals matching the regular expression will be included. For example the
9650same expansion will result from only extracting inouts starting with i:
9651
9652 /*AUTOINOUT(\"^i\")*/"
6341f357
DN
9653 (save-excursion
9654 ;; Point must be at insertion point.
9655 (let* ((indent-pt (current-indentation))
e2076c2c
DN
9656 (regexp (and with-params
9657 (nth 0 (verilog-read-auto-params 1))))
6341f357
DN
9658 (v2k (verilog-in-paren))
9659 (modi (verilog-modi-current))
5509c6ad
DN
9660 (moddecls (verilog-modi-get-decls modi))
9661 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 9662 (sig-list (verilog-signals-not-in
5509c6ad
DN
9663 (verilog-subdecls-get-inouts modsubdecls)
9664 (append (verilog-decls-get-outputs moddecls)
9665 (verilog-decls-get-inouts moddecls)
9666 (verilog-decls-get-inputs moddecls)
9667 (verilog-subdecls-get-inputs modsubdecls)
9668 (verilog-subdecls-get-outputs modsubdecls)))))
e2076c2c
DN
9669 (when regexp
9670 (setq sig-list (verilog-signals-matching-regexp
9671 sig-list regexp)))
6341f357
DN
9672 (setq sig-list (verilog-signals-not-matching-regexp
9673 sig-list verilog-auto-inout-ignore-regexp))
9674 (forward-line 1)
9675 (when v2k (verilog-repair-open-comma))
9676 (when sig-list
9677 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
9678 (verilog-insert-definition sig-list "inout" indent-pt v2k)
9679 (verilog-modi-cache-add-inouts modi sig-list)
9680 (verilog-insert-indent "// End of automatics\n"))
60618039 9681 (when v2k (verilog-repair-close-comma)))))
6341f357 9682
7cb1c4d7 9683(defun verilog-auto-inout-module (&optional complement)
6341f357
DN
9684 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
9685Take input/output/inout statements from the specified module and insert
9686into the current module. This is useful for making null templates and
37ea4b9b
JB
9687shell modules which need to have identical I/O with another module.
9688Any I/O which are already defined in this module will not be redefined.
6341f357
DN
9689
9690Limitations:
9691 If placed inside the parenthesis of a module declaration, it creates
9692 Verilog 2001 style, else uses Verilog 1995 style.
9693
9694 Concatenation and outputting partial busses is not supported.
9695
9696 Module names must be resolvable to filenames. See `verilog-auto-inst'.
9697
9698 Signals are not inserted in the same order as in the original module,
9699 though they will appear to be in the same order to a AUTOINST
9700 instantiating either module.
9701
9702An example:
9703
1dd4b004
DN
9704 module ExampShell (/*AUTOARG*/)
9705 /*AUTOINOUTMODULE(\"ExampMain\")*/
6341f357
DN
9706 endmodule
9707
1dd4b004 9708 module ExampMain (i,o,io)
6341f357
DN
9709 input i;
9710 output o;
9711 inout io;
9712 endmodule
9713
9714Typing \\[verilog-auto] will make this into:
9715
1dd4b004
DN
9716 module ExampShell (/*AUTOARG*/i,o,io)
9717 /*AUTOINOUTMODULE(\"ExampMain\")*/
6341f357 9718 // Beginning of automatic in/out/inouts (from specific module)
6341f357
DN
9719 output o;
9720 inout io;
7cb1c4d7 9721 input i;
6341f357 9722 // End of automatics
1dd4b004
DN
9723 endmodule
9724
9725You may also provide an optional regular expression, in which case only
9726signals matching the regular expression will be included. For example the
9727same expansion will result from only extracting signals starting with i:
9728
a3a8b002
DN
9729 /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/
9730
9731You may also provide an optional second regulat expression, in
9732which case only signals which have that pin direction and data
9733type will be included. This matches against everything before
9734the signal name in the declaration, for example against
9735\"input\" (single bit), \"output logic\" (direction and type) or
9736\"output [1:0]\" (direction and implicit type). You also
9737probably want to skip spaces in your regexp.
9738
9739For example, the below will result in matching the output \"o\"
9740against the previous example's module:
9741
9742 /*AUTOINOUTMODULE(\"ExampMain\",\"\",\"^output.*\")*/"
6341f357 9743 (save-excursion
a3a8b002 9744 (let* ((params (verilog-read-auto-params 1 3))
1dd4b004
DN
9745 (submod (nth 0 params))
9746 (regexp (nth 1 params))
a3a8b002 9747 (direction-re (nth 2 params))
1dd4b004 9748 submodi)
6341f357
DN
9749 ;; Lookup position, etc of co-module
9750 ;; Note this may raise an error
9751 (when (setq submodi (verilog-modi-lookup submod t))
9752 (let* ((indent-pt (current-indentation))
9753 (v2k (verilog-in-paren))
9754 (modi (verilog-modi-current))
5509c6ad
DN
9755 (moddecls (verilog-modi-get-decls modi))
9756 (submoddecls (verilog-modi-get-decls submodi))
6341f357 9757 (sig-list-i (verilog-signals-not-in
7cb1c4d7
DN
9758 (if complement
9759 (verilog-decls-get-outputs submoddecls)
9760 (verilog-decls-get-inputs submoddecls))
5509c6ad 9761 (append (verilog-decls-get-inputs moddecls))))
6341f357 9762 (sig-list-o (verilog-signals-not-in
7cb1c4d7
DN
9763 (if complement
9764 (verilog-decls-get-inputs submoddecls)
9765 (verilog-decls-get-outputs submoddecls))
5509c6ad 9766 (append (verilog-decls-get-outputs moddecls))))
6341f357 9767 (sig-list-io (verilog-signals-not-in
5509c6ad 9768 (verilog-decls-get-inouts submoddecls)
a3a8b002
DN
9769 (append (verilog-decls-get-inouts moddecls))))
9770 (sig-list-if (verilog-signals-not-in
9771 (verilog-decls-get-interfaces submoddecls)
9772 (append (verilog-decls-get-interfaces moddecls)))))
6341f357 9773 (forward-line 1)
a3a8b002
DN
9774 (setq sig-list-i (verilog-signals-matching-dir-re
9775 (verilog-signals-matching-regexp sig-list-i regexp)
9776 "input" direction-re)
9777 sig-list-o (verilog-signals-matching-dir-re
9778 (verilog-signals-matching-regexp sig-list-o regexp)
9779 "output" direction-re)
9780 sig-list-io (verilog-signals-matching-dir-re
9781 (verilog-signals-matching-regexp sig-list-io regexp)
9782 "inout" direction-re)
9783 sig-list-if (verilog-signals-matching-dir-re
9784 (verilog-signals-matching-regexp sig-list-if regexp)
9785 "interface" direction-re))
6341f357
DN
9786 (when v2k (verilog-repair-open-comma))
9787 (when (or sig-list-i sig-list-o sig-list-io)
9788 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
9789 ;; Don't sort them so a upper AUTOINST will match the main module
9790 (verilog-insert-definition sig-list-o "output" indent-pt v2k t)
9791 (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
9792 (verilog-insert-definition sig-list-i "input" indent-pt v2k t)
a3a8b002 9793 (verilog-insert-definition sig-list-if "interface" indent-pt v2k t)
6341f357
DN
9794 (verilog-modi-cache-add-inputs modi sig-list-i)
9795 (verilog-modi-cache-add-outputs modi sig-list-o)
9796 (verilog-modi-cache-add-inouts modi sig-list-io)
9797 (verilog-insert-indent "// End of automatics\n"))
60618039 9798 (when v2k (verilog-repair-close-comma)))))))
6341f357 9799
7cb1c4d7
DN
9800(defun verilog-auto-inout-comp ()
9801 "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
9802Take input/output/inout statements from the specified module and
9803insert the inverse into the current module (inputs become outputs
9804and vice-versa.) This is useful for making test and stimulus
9805modules which need to have complementing I/O with another module.
9806Any I/O which are already defined in this module will not be
9807redefined.
9808
9809Limitations:
9810 If placed inside the parenthesis of a module declaration, it creates
9811 Verilog 2001 style, else uses Verilog 1995 style.
9812
9813 Concatenation and outputting partial busses is not supported.
9814
9815 Module names must be resolvable to filenames. See `verilog-auto-inst'.
9816
9817 Signals are not inserted in the same order as in the original module,
9818 though they will appear to be in the same order to a AUTOINST
9819 instantiating either module.
9820
9821An example:
9822
9823 module ExampShell (/*AUTOARG*/)
9824 /*AUTOINOUTCOMP(\"ExampMain\")*/
9825 endmodule
9826
9827 module ExampMain (i,o,io)
9828 input i;
9829 output o;
9830 inout io;
9831 endmodule
9832
9833Typing \\[verilog-auto] will make this into:
9834
9835 module ExampShell (/*AUTOARG*/i,o,io)
9836 /*AUTOINOUTCOMP(\"ExampMain\")*/
9837 // Beginning of automatic in/out/inouts (from specific module)
9838 output i;
9839 inout io;
9840 input o;
9841 // End of automatics
9842 endmodule
9843
9844You may also provide an optional regular expression, in which case only
9845signals matching the regular expression will be included. For example the
9846same expansion will result from only extracting signals starting with i:
9847
9848 /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/"
9849 (verilog-auto-inout-module t))
9850
a3a8b002
DN
9851(defun verilog-auto-insert-lisp ()
9852 "Expand AUTOINSERTLISP statements, as part of \\[verilog-auto].
9853The Lisp code provided is called, and the Lisp code calls
9854`insert` to insert text into the current file beginning on the
9855line after the AUTOINSERTLISP.
9856
9857See also AUTO_LISP, which takes a Lisp expression and evaluates
9858it during `verilog-auto-inst' but does not insert any text.
9859
9860An example:
9861
9862 module ExampInsertLisp;
9863 /*AUTOINSERTLISP(my-verilog-insert-hello \"world\")*/
9864 endmodule
9865
9866 // For this example we declare the function in the
9867 // module's file itself. Often you'd define it instead
9868 // in a site-start.el or .emacs file.
9869 /*
9870 Local Variables:
9871 eval:
9872 (defun my-verilog-insert-hello (who)
9873 (insert (concat \"initial $write(\\\"hello \" who \"\\\");\\n\")))
9874 End:
9875 */
9876
9877Typing \\[verilog-auto] will call my-verilog-insert-hello and
9878expand the above into:
9879
9880 // Beginning of automatic insert lisp
9881 initial $write(\"hello world\");
9882 // End of automatics
9883
9884You can also call an external program and insert the returned
9885text:
9886
9887 /*AUTOINSERTLISP(insert (shell-command-to-string \"echo //hello\"))*/
9888 // Beginning of automatic insert lisp
9889 //hello
9890 // End of automatics"
9891 (save-excursion
9892 ;; Point is at end of /*AUTO...*/
9893 (let* ((indent-pt (current-indentation))
9894 (cmd-end-pt (save-excursion (search-backward ")")
9895 (forward-char)
9896 (point))) ;; Closing paren
9897 (cmd-beg-pt (save-excursion (goto-char cmd-end-pt)
9898 (backward-sexp 1)
9899 (point))) ;; Beginning paren
9900 (cmd (buffer-substring-no-properties cmd-beg-pt cmd-end-pt)))
9901 (forward-line 1)
9902 (let ((pre-eval-pt (point)))
9903 ;;Debug: (insert cmd)
9904 ;; Don't use eval-region as Xemacs has a bug where it goto-char's begin-pt
9905 (eval (read cmd))
9906 ;; If inserted something add the begin/end blocks
9907 (when (not (equal pre-eval-pt (point)))
9908 (when (not (bolp)) (insert "\n")) ;; If user forgot final newline, add it
9909 (save-excursion
9910 (goto-char pre-eval-pt)
9911 (verilog-insert-indent "// Beginning of automatic insert lisp\n"))
9912 (verilog-insert-indent "// End of automatics\n"))))))
9913
5509c6ad 9914(defun verilog-auto-sense-sigs (moddecls presense-sigs)
6341f357
DN
9915 "Return list of signals for current AUTOSENSE block."
9916 (let* ((sigss (verilog-read-always-signals))
9917 (sig-list (verilog-signals-not-params
9918 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
9919 (append (and (not verilog-auto-sense-include-inputs)
9920 (verilog-alw-get-outputs sigss))
5509c6ad
DN
9921 (verilog-decls-get-consts moddecls)
9922 (verilog-decls-get-gparams moddecls)
6341f357
DN
9923 presense-sigs)))))
9924 sig-list))
9925
9926(defun verilog-auto-sense ()
9927 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
9928Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
9929with one automatically derived from all inputs declared in the always
9930statement. Signals that are generated within the same always block are NOT
9931placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
9932Long lines are split based on the `fill-column', see \\[set-fill-column].
9933
9934Limitations:
9935 Verilog does not allow memories (multidimensional arrays) in sensitivity
9936 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
9937
9938Constant signals:
9939 AUTOSENSE cannot always determine if a `define is a constant or a signal
9940 (it could be in a include file for example). If a `define or other signal
9941 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
9942 declaration anywhere in the module (parenthesis are required):
9943
9944 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
9945
9946 Better yet, use a parameter, which will be understood to be constant
9947 automatically.
9948
9949OOps!
9950 If AUTOSENSE makes a mistake, please report it. (First try putting
9951 a begin/end after your always!) As a workaround, if a signal that
9952 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
9953 If a signal should be in the sensitivity list wasn't, placing it before
9954 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
9955 autos are updated (or added if it occurs there already).
9956
9957An example:
9958
1dd4b004 9959 always @ (/*AS*/) begin
6341f357
DN
9960 /* AUTO_CONSTANT (`constant) */
9961 outin = ina | inb | `constant;
9962 out = outin;
9963 end
9964
9965Typing \\[verilog-auto] will make this into:
9966
1dd4b004 9967 always @ (/*AS*/ina or inb) begin
6341f357
DN
9968 /* AUTO_CONSTANT (`constant) */
9969 outin = ina | inb | `constant;
9970 out = outin;
1dd4b004
DN
9971 end
9972
9973Note in Verilog 2001, you can often get the same result from the new @*
9974operator. (This was added to the language in part due to AUTOSENSE!)
9975
9976 always @* begin
9977 outin = ina | inb | `constant;
9978 out = outin;
6341f357
DN
9979 end"
9980 (save-excursion
9981 ;; Find beginning
9982 (let* ((start-pt (save-excursion
9983 (verilog-re-search-backward "(" nil t)
9984 (point)))
9985 (indent-pt (save-excursion
9986 (or (and (goto-char start-pt) (1+ (current-column)))
9987 (current-indentation))))
9988 (modi (verilog-modi-current))
5509c6ad 9989 (moddecls (verilog-modi-get-decls modi))
6341f357
DN
9990 (sig-memories (verilog-signals-memory
9991 (append
5509c6ad
DN
9992 (verilog-decls-get-regs moddecls)
9993 (verilog-decls-get-wires moddecls))))
6341f357
DN
9994 sig-list not-first presense-sigs)
9995 ;; Read signals in always, eliminate outputs from sense list
9996 (setq presense-sigs (verilog-signals-from-signame
9997 (save-excursion
9998 (verilog-read-signals start-pt (point)))))
5509c6ad 9999 (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
6341f357
DN
10000 (when sig-memories
10001 (let ((tlen (length sig-list)))
10002 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
10003 (if (not (eq tlen (length sig-list))) (insert " /*memory or*/ "))))
10004 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
10005 (save-excursion (goto-char (point))
10006 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10007 (verilog-re-search-backward "\\s-" start-pt t)
10008 (while (looking-at "\\s-`endif")
10009 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10010 (verilog-re-search-backward "\\s-" start-pt t))
10011 (not (looking-at "\\s-or\\b"))))
10012 (setq not-first t))
10013 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10014 (while sig-list
10015 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
10016 (insert "\n")
10017 (indent-to indent-pt)
10018 (if not-first (insert "or ")))
10019 (not-first (insert " or ")))
10020 (insert (verilog-sig-name (car sig-list)))
10021 (setq sig-list (cdr sig-list)
60618039 10022 not-first t)))))
6341f357
DN
10023
10024(defun verilog-auto-reset ()
10025 "Expand AUTORESET statements, as part of \\[verilog-auto].
10026Replace the /*AUTORESET*/ comment with code to initialize all
10027registers set elsewhere in the always block.
10028
10029Limitations:
10030 AUTORESET will not clear memories.
10031
a3a8b002
DN
10032 AUTORESET uses <= if there are any <= assigmnents in the block,
10033 else it uses =.
6341f357
DN
10034
10035/*AUTORESET*/ presumes that any signals mentioned between the previous
10036begin/case/if statement and the AUTORESET comment are being reset manually
10037and should not be automatically reset. This includes omitting any signals
10038used on the right hand side of assignments.
10039
10040By default, AUTORESET will include the width of the signal in the autos,
10041this is a recent change. To control this behavior, see
10042`verilog-auto-reset-widths'.
10043
10044AUTORESET ties signals to deasserted, which is presumed to be zero.
10045Signals that match `verilog-active-low-regexp' will be deasserted by tieing
10046them to a one.
10047
10048An example:
10049
10050 always @(posedge clk or negedge reset_l) begin
10051 if (!reset_l) begin
10052 c <= 1;
10053 /*AUTORESET*/
10054 end
10055 else begin
10056 a <= in_a;
10057 b <= in_b;
10058 c <= in_c;
10059 end
10060 end
10061
10062Typing \\[verilog-auto] will make this into:
10063
10064 always @(posedge core_clk or negedge reset_l) begin
10065 if (!reset_l) begin
10066 c <= 1;
10067 /*AUTORESET*/
10068 // Beginning of autoreset for uninitialized flops
10069 a <= 0;
10070 b <= 0;
10071 // End of automatics
10072 end
10073 else begin
10074 a <= in_a;
10075 b <= in_b;
10076 c <= in_c;
10077 end
10078 end"
10079
10080 (interactive)
10081 (save-excursion
10082 ;; Find beginning
10083 (let* ((indent-pt (current-indentation))
10084 (modi (verilog-modi-current))
5509c6ad
DN
10085 (moddecls (verilog-modi-get-decls modi))
10086 (all-list (verilog-decls-get-signals moddecls))
6341f357
DN
10087 sigss sig-list prereset-sigs assignment-str)
10088 ;; Read signals in always, eliminate outputs from reset list
10089 (setq prereset-sigs (verilog-signals-from-signame
10090 (save-excursion
10091 (verilog-read-signals
10092 (save-excursion
10093 (verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
10094 (point))
10095 (point)))))
10096 (save-excursion
10097 (verilog-re-search-backward "@" nil t)
10098 (setq sigss (verilog-read-always-signals)))
10099 (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
10100 (concat " <= " verilog-assignment-delay)
10101 " = "))
10102 (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
10103 prereset-sigs))
10104 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10105 (when sig-list
10106 (insert "\n");
10107 (indent-to indent-pt)
10108 (insert "// Beginning of autoreset for uninitialized flops\n");
10109 (indent-to indent-pt)
10110 (while sig-list
10111 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
10112 (car sig-list))))
10113 (insert (verilog-sig-name sig)
10114 assignment-str
10115 (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
10116 ";\n")
10117 (indent-to indent-pt)
10118 (setq sig-list (cdr sig-list))))
60618039 10119 (insert "// End of automatics")))))
6341f357
DN
10120
10121(defun verilog-auto-tieoff ()
10122 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
10123Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
10124signals to deasserted.
10125
10126/*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
10127input/output list as another module, but no internals. Specifically, it
10128finds all outputs in the module, and if that input is not otherwise declared
10129as a register or wire, creates a tieoff.
10130
10131AUTORESET ties signals to deasserted, which is presumed to be zero.
10132Signals that match `verilog-active-low-regexp' will be deasserted by tieing
10133them to a one.
10134
10135An example of making a stub for another module:
10136
1dd4b004 10137 module ExampStub (/*AUTOINST*/);
6341f357
DN
10138 /*AUTOINOUTMODULE(\"Foo\")*/
10139 /*AUTOTIEOFF*/
10140 // verilator lint_off UNUSED
10141 wire _unused_ok = &{1'b0,
10142 /*AUTOUNUSED*/
10143 1'b0};
10144 // verilator lint_on UNUSED
10145 endmodule
10146
10147Typing \\[verilog-auto] will make this into:
10148
1dd4b004 10149 module ExampStub (/*AUTOINST*/...);
6341f357
DN
10150 /*AUTOINOUTMODULE(\"Foo\")*/
10151 // Beginning of autotieoff
10152 output [2:0] foo;
10153 // End of automatics
10154
10155 /*AUTOTIEOFF*/
10156 // Beginning of autotieoff
10157 wire [2:0] foo = 3'b0;
10158 // End of automatics
10159 ...
10160 endmodule"
10161 (interactive)
10162 (save-excursion
10163 ;; Find beginning
10164 (let* ((indent-pt (current-indentation))
10165 (modi (verilog-modi-current))
5509c6ad
DN
10166 (moddecls (verilog-modi-get-decls modi))
10167 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 10168 (sig-list (verilog-signals-not-in
5509c6ad
DN
10169 (verilog-decls-get-outputs moddecls)
10170 (append (verilog-decls-get-wires moddecls)
10171 (verilog-decls-get-regs moddecls)
10172 (verilog-decls-get-assigns moddecls)
10173 (verilog-decls-get-consts moddecls)
10174 (verilog-decls-get-gparams moddecls)
10175 (verilog-subdecls-get-outputs modsubdecls)
10176 (verilog-subdecls-get-inouts modsubdecls)))))
6341f357
DN
10177 (when sig-list
10178 (forward-line 1)
10179 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
10180 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
10181 (verilog-modi-cache-add-wires modi sig-list) ; Before we trash list
10182 (while sig-list
10183 (let ((sig (car sig-list)))
10184 (verilog-insert-one-definition sig "wire" indent-pt)
10185 (indent-to (max 48 (+ indent-pt 40)))
10186 (insert "= " (verilog-sig-tieoff sig)
10187 ";\n")
10188 (setq sig-list (cdr sig-list))))
60618039 10189 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
10190
10191(defun verilog-auto-unused ()
10192 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
10193Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
10194input and inout signals.
10195
10196/*AUTOUNUSED*/ is used to make stub modules; modules that have the same
10197input/output list as another module, but no internals. Specifically, it
10198finds all inputs and inouts in the module, and if that input is not otherwise
10199used, adds it to a comma separated list.
10200
10201The comma separated list is intended to be used to create a _unused_ok
10202signal. Using the exact name \"_unused_ok\" for name of the temporary
10203signal is recommended as it will insure maximum forward compatibility, it
10204also makes lint warnings easy to understand; ignore any unused warnings
10205with \"unused\" in the signal name.
10206
10207To reduce simulation time, the _unused_ok signal should be forced to a
10208constant to prevent wiggling. The easiest thing to do is use a
10209reduction-and with 1'b0 as shown.
10210
10211This way all unused signals are in one place, making it convenient to add
10212your tool's specific pragmas around the assignment to disable any unused
10213warnings.
10214
10215You can add signals you do not want included in AUTOUNUSED with
10216`verilog-auto-unused-ignore-regexp'.
10217
10218An example of making a stub for another module:
10219
1dd4b004
DN
10220 module ExampStub (/*AUTOINST*/);
10221 /*AUTOINOUTMODULE(\"Examp\")*/
6341f357
DN
10222 /*AUTOTIEOFF*/
10223 // verilator lint_off UNUSED
10224 wire _unused_ok = &{1'b0,
10225 /*AUTOUNUSED*/
10226 1'b0};
10227 // verilator lint_on UNUSED
10228 endmodule
10229
10230Typing \\[verilog-auto] will make this into:
10231
10232 ...
10233 // verilator lint_off UNUSED
10234 wire _unused_ok = &{1'b0,
10235 /*AUTOUNUSED*/
10236 // Beginning of automatics
10237 unused_input_a,
10238 unused_input_b,
10239 unused_input_c,
10240 // End of automatics
10241 1'b0};
10242 // verilator lint_on UNUSED
10243 endmodule"
10244 (interactive)
10245 (save-excursion
10246 ;; Find beginning
10247 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
10248 (modi (verilog-modi-current))
5509c6ad
DN
10249 (moddecls (verilog-modi-get-decls modi))
10250 (modsubdecls (verilog-modi-get-sub-decls modi))
6341f357 10251 (sig-list (verilog-signals-not-in
5509c6ad
DN
10252 (append (verilog-decls-get-inputs moddecls)
10253 (verilog-decls-get-inouts moddecls))
10254 (append (verilog-subdecls-get-inputs modsubdecls)
10255 (verilog-subdecls-get-inouts modsubdecls)))))
6341f357
DN
10256 (setq sig-list (verilog-signals-not-matching-regexp
10257 sig-list verilog-auto-unused-ignore-regexp))
10258 (when sig-list
10259 (forward-line 1)
10260 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
10261 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
10262 (while sig-list
10263 (let ((sig (car sig-list)))
10264 (indent-to indent-pt)
10265 (insert (verilog-sig-name sig) ",\n")
10266 (setq sig-list (cdr sig-list))))
60618039 10267 (verilog-insert-indent "// End of automatics\n")))))
6341f357
DN
10268
10269(defun verilog-enum-ascii (signm elim-regexp)
37ea4b9b 10270 "Convert an enum name SIGNM to an ascii string for insertion.
6341f357
DN
10271Remove user provided prefix ELIM-REGEXP."
10272 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
10273 (let ((case-fold-search t))
10274 ;; All upper becomes all lower for readability
10275 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
10276
10277(defun verilog-auto-ascii-enum ()
10278 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
10279Create a register to contain the ASCII decode of a enumerated signal type.
10280This will allow trace viewers to show the ASCII name of states.
10281
10282First, parameters are built into a enumeration using the synopsys enum
10283comment. The comment must be between the keyword and the symbol.
6edb5716 10284\(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
6341f357
DN
10285
10286Next, registers which that enum applies to are also tagged with the same
10287enum. Synopsys also suggests labeling state vectors, but `verilog-mode'
10288doesn't care.
10289
10290Finally, a AUTOASCIIENUM command is used.
10291
10292 The first parameter is the name of the signal to be decoded.
a3a8b002
DN
10293 If and only if the first parameter width is 2^(number of states
10294 in enum) and does NOT match the width of the enum, the signal
10295 is assumed to be a one hot decode. Otherwise, it's a normal
10296 encoded state vector.
6341f357
DN
10297
10298 The second parameter is the name to store the ASCII code into. For the
10299 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
10300 a signal that is just for simulation, and the magic characters _ascii
10301 tell viewers like Dinotrace to display in ASCII format.
10302
10303 The final optional parameter is a string which will be removed from the
10304 state names.
10305
10306An example:
10307
10308 //== State enumeration
10309 parameter [2:0] // synopsys enum state_info
10310 SM_IDLE = 3'b000,
10311 SM_SEND = 3'b001,
10312 SM_WAIT1 = 3'b010;
10313 //== State variables
a3a8b002
DN
10314 reg [2:0] /* synopsys enum state_info */
10315 state_r; /* synopsys state_vector state_r */
10316 reg [2:0] /* synopsys enum state_info */
10317 state_e1;
6341f357
DN
10318
10319 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
10320
10321Typing \\[verilog-auto] will make this into:
10322
10323 ... same front matter ...
10324
10325 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
10326 // Beginning of automatic ASCII enum decoding
10327 reg [39:0] state_ascii_r; // Decode of state_r
10328 always @(state_r) begin
10329 case ({state_r})
10330 SM_IDLE: state_ascii_r = \"idle \";
10331 SM_SEND: state_ascii_r = \"send \";
10332 SM_WAIT1: state_ascii_r = \"wait1\";
10333 default: state_ascii_r = \"%Erro\";
10334 endcase
10335 end
10336 // End of automatics"
10337 (save-excursion
10338 (let* ((params (verilog-read-auto-params 2 3))
10339 (undecode-name (nth 0 params))
10340 (ascii-name (nth 1 params))
10341 (elim-regexp (nth 2 params))
10342 ;;
10343 (indent-pt (current-indentation))
10344 (modi (verilog-modi-current))
5509c6ad 10345 (moddecls (verilog-modi-get-decls modi))
6341f357 10346 ;;
5509c6ad
DN
10347 (sig-list-consts (append (verilog-decls-get-consts moddecls)
10348 (verilog-decls-get-gparams moddecls)))
10349 (sig-list-all (append (verilog-decls-get-regs moddecls)
10350 (verilog-decls-get-outputs moddecls)
10351 (verilog-decls-get-inouts moddecls)
10352 (verilog-decls-get-inputs moddecls)
10353 (verilog-decls-get-wires moddecls)))
6341f357
DN
10354 ;;
10355 (undecode-sig (or (assoc undecode-name sig-list-all)
10356 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
10357 (undecode-enum (or (verilog-sig-enum undecode-sig)
10358 (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
10359 ;;
a3a8b002
DN
10360 (enum-sigs (verilog-signals-not-in
10361 (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
10362 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum))
10363 nil))
6341f357 10364 ;;
a3a8b002
DN
10365 (one-hot (and ;; width(enum) != width(sig)
10366 (or (not (verilog-sig-bits (car enum-sigs)))
10367 (not (equal (verilog-sig-width (car enum-sigs))
10368 (verilog-sig-width undecode-sig))))
10369 ;; count(enums) == width(sig)
10370 (equal (number-to-string (length enum-sigs))
10371 (verilog-sig-width undecode-sig))))
10372 (enum-chars 0)
6341f357
DN
10373 (ascii-chars 0))
10374 ;;
10375 ;; Find number of ascii chars needed
10376 (let ((tmp-sigs enum-sigs))
10377 (while tmp-sigs
10378 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
10379 ascii-chars (max ascii-chars (length (verilog-enum-ascii
10380 (verilog-sig-name (car tmp-sigs))
10381 elim-regexp)))
10382 tmp-sigs (cdr tmp-sigs))))
10383 ;;
10384 (forward-line 1)
10385 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
10386 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
10387 (concat "Decode of " undecode-name) nil nil))))
10388 (verilog-insert-definition decode-sig-list "reg" indent-pt nil)
10389 (verilog-modi-cache-add-regs modi decode-sig-list))
10390 ;;
10391 (verilog-insert-indent "always @(" undecode-name ") begin\n")
10392 (setq indent-pt (+ indent-pt verilog-indent-level))
10393 (indent-to indent-pt)
10394 (insert "case ({" undecode-name "})\n")
10395 (setq indent-pt (+ indent-pt verilog-case-indent))
10396 ;;
10397 (let ((tmp-sigs enum-sigs)
a3a8b002
DN
10398 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n"
10399 (+ (if one-hot 9 1) (max 8 enum-chars))
6341f357
DN
10400 ascii-name ascii-chars))
10401 (errname (substring "%Error" 0 (min 6 ascii-chars))))
10402 (while tmp-sigs
10403 (verilog-insert-indent
a3a8b002
DN
10404 (concat
10405 (format chrfmt
10406 (concat (if one-hot "(")
10407 (if one-hot (verilog-sig-width undecode-sig))
10408 ;; We use a shift instead of var[index]
10409 ;; so that a non-one hot value will show as error.
10410 (if one-hot "'b1<<")
10411 (verilog-sig-name (car tmp-sigs))
10412 (if one-hot ")") ":")
10413 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
10414 elim-regexp))))
6341f357
DN
10415 (setq tmp-sigs (cdr tmp-sigs)))
10416 (verilog-insert-indent (format chrfmt "default:" errname)))
10417 ;;
10418 (setq indent-pt (- indent-pt verilog-case-indent))
10419 (verilog-insert-indent "endcase\n")
10420 (setq indent-pt (- indent-pt verilog-indent-level))
10421 (verilog-insert-indent "end\n"
60618039 10422 "// End of automatics\n"))))
6341f357
DN
10423
10424(defun verilog-auto-templated-rel ()
10425 "Replace Templated relative line numbers with absolute line numbers.
10426Internal use only. This hacks around the line numbers in AUTOINST Templates
10427being different from the final output's line numbering."
10428 (let ((templateno 0) (template-line (list 0)))
10429 ;; Find line number each template is on
10430 (goto-char (point-min))
10431 (while (search-forward "AUTO_TEMPLATE" nil t)
10432 (setq templateno (1+ templateno))
7ea26faf
DN
10433 (setq template-line
10434 (cons (count-lines (point-min) (point)) template-line)))
6341f357
DN
10435 (setq template-line (nreverse template-line))
10436 ;; Replace T# L# with absolute line number
10437 (goto-char (point-min))
10438 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
7ea26faf
DN
10439 (replace-match
10440 (concat " Templated "
10441 (int-to-string (+ (nth (string-to-number (match-string 1))
10442 template-line)
10443 (string-to-number (match-string 2)))))
10444 t t))))
6341f357
DN
10445
10446\f
10447;;
10448;; Auto top level
10449;;
10450
10451(defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing a arg
10452 "Expand AUTO statements.
10453Look for any /*AUTO...*/ commands in the code, as used in
10454instantiations or argument headers. Update the list of signals
10455following the /*AUTO...*/ command.
10456
10457Use \\[verilog-delete-auto] to remove the AUTOs.
10458
10459Use \\[verilog-inject-auto] to insert AUTOs for the first time.
10460
10461Use \\[verilog-faq] for a pointer to frequently asked questions.
10462
10463The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
10464called before and after this function, respectively.
10465
10466For example:
1dd4b004 10467 module ModuleName (/*AUTOARG*/)
6341f357
DN
10468 /*AUTOINPUT*/
10469 /*AUTOOUTPUT*/
10470 /*AUTOWIRE*/
10471 /*AUTOREG*/
1dd4b004 10472 InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
6341f357
DN
10473
10474You can also update the AUTOs from the shell using:
10475 emacs --batch <filenames.v> -f verilog-batch-auto
10476Or fix indentation with:
10477 emacs --batch <filenames.v> -f verilog-batch-indent
10478Likewise, you can delete or inject AUTOs with:
10479 emacs --batch <filenames.v> -f verilog-batch-delete-auto
10480 emacs --batch <filenames.v> -f verilog-batch-inject-auto
10481
10482Using \\[describe-function], see also:
10483 `verilog-auto-arg' for AUTOARG module instantiations
10484 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
7cb1c4d7 10485 `verilog-auto-inout-comp' for AUTOINOUTCOMP copy complemented i/o
6341f357
DN
10486 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
10487 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
10488 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
a3a8b002 10489 `verilog-auto-insert-lisp' for AUTOINSERTLISP insert code from lisp function
6341f357
DN
10490 `verilog-auto-inst' for AUTOINST instantiation pins
10491 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
10492 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
10493 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
10494 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
10495 `verilog-auto-reg' for AUTOREG registers
10496 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
10497 `verilog-auto-reset' for AUTORESET flop resets
10498 `verilog-auto-sense' for AUTOSENSE always sensitivity lists
10499 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
10500 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
10501 `verilog-auto-wire' for AUTOWIRE instantiation wires
10502
10503 `verilog-read-defines' for reading `define values
10504 `verilog-read-includes' for reading `includes
10505
a3a8b002 10506If you have bugs with these autos, please file an issue at
855b42a2 10507URL `http://www.veripool.org/verilog-mode' or contact the AUTOAUTHOR
a3a8b002 10508Wilson Snyder (wsnyder@wsnyder.org)."
6341f357
DN
10509 (interactive)
10510 (unless noninteractive (message "Updating AUTOs..."))
7ea26faf 10511 (if (fboundp 'dinotrace-unannotate-all)
6341f357
DN
10512 (dinotrace-unannotate-all))
10513 (let ((oldbuf (if (not (buffer-modified-p))
10514 (buffer-string)))
10515 ;; Before version 20, match-string with font-lock returns a
10516 ;; vector that is not equal to the string. IE if on "input"
10517 ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
10518 (fontlocked (when (and (boundp 'font-lock-mode)
10519 font-lock-mode)
7cb1c4d7 10520 (font-lock-mode 0)
5509c6ad
DN
10521 t))
10522 ;; Cache directories; we don't write new files, so can't change
10523 (verilog-dir-cache-preserving t))
6341f357
DN
10524 (unwind-protect
10525 (save-excursion
10526 ;; If we're not in verilog-mode, change syntax table so parsing works right
10527 (unless (eq major-mode `verilog-mode) (verilog-mode))
10528 ;; Allow user to customize
10529 (run-hooks 'verilog-before-auto-hook)
10530 ;; Try to save the user from needing to revert-file to reread file local-variables
10531 (verilog-auto-reeval-locals)
10532 (verilog-read-auto-lisp (point-min) (point-max))
10533 (verilog-getopt-flags)
5509c6ad
DN
10534 ;; From here on out, we can cache anything we read from disk
10535 (verilog-preserve-dir-cache
9c059794
DN
10536 ;; These two may seem obvious to do always, but on large includes it can be way too slow
10537 (when verilog-auto-read-includes
10538 (verilog-read-includes)
10539 (verilog-read-defines nil nil t))
10540 ;; This particular ordering is important
10541 ;; INST: Lower modules correct, no internal dependencies, FIRST
5509c6ad 10542 (verilog-preserve-modi-cache
9c059794
DN
10543 ;; Clear existing autos else we'll be screwed by existing ones
10544 (verilog-delete-auto)
10545 ;; Injection if appropriate
10546 (when inject
10547 (verilog-inject-inst)
10548 (verilog-inject-sense)
10549 (verilog-inject-arg))
10550 ;;
a3a8b002
DN
10551 ;; Do user inserts first, so their code can insert AUTOs
10552 ;; We may provide a AUTOINSERTLISPLAST if another cleanup pass is needed
10553 (verilog-auto-re-search-do "/\\*AUTOINSERTLISP(.*?)\\*/"
10554 'verilog-auto-insert-lisp)
10555 ;; Expand instances before need the signals the instances input/output
5509c6ad
DN
10556 (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
10557 (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
10558 (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
9c059794
DN
10559 ;; Doesn't matter when done, but combine it with a common changer
10560 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
10561 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
10562 ;; Must be done before autoin/out as creates a reg
10563 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
10564 ;;
10565 ;; first in/outs from other files
10566 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
7cb1c4d7 10567 (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP([^)]*)\\*/" 'verilog-auto-inout-comp)
9c059794
DN
10568 ;; next in/outs which need previous sucked inputs first
10569 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((\"[^\"]*\")\\)\\*/"
10570 '(lambda () (verilog-auto-output t)))
10571 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\*/" 'verilog-auto-output)
10572 (verilog-auto-re-search-do "/\\*AUTOINPUT\\((\"[^\"]*\")\\)\\*/"
10573 '(lambda () (verilog-auto-input t)))
10574 (verilog-auto-re-search-do "/\\*AUTOINPUT\\*/" 'verilog-auto-input)
10575 (verilog-auto-re-search-do "/\\*AUTOINOUT\\((\"[^\"]*\")\\)\\*/"
10576 '(lambda () (verilog-auto-inout t)))
10577 (verilog-auto-re-search-do "/\\*AUTOINOUT\\*/" 'verilog-auto-inout)
10578 ;; Then tie off those in/outs
5509c6ad 10579 (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
9c059794 10580 ;; Wires/regs must be after inputs/outputs
5509c6ad
DN
10581 (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
10582 (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
10583 (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
9c059794 10584 ;; outputevery needs AUTOOUTPUTs done first
5509c6ad 10585 (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\*/" 'verilog-auto-output-every)
9c059794 10586 ;; After we've created all new variables
5509c6ad 10587 (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
9c059794 10588 ;; Must be after all inputs outputs are generated
5509c6ad 10589 (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
9c059794 10590 ;; Fix line numbers (comments only)
5509c6ad 10591 (verilog-auto-templated-rel)))
6341f357
DN
10592 ;;
10593 (run-hooks 'verilog-auto-hook)
10594 ;;
10595 (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))
10596 ;;
10597 ;; If end result is same as when started, clear modified flag
10598 (cond ((and oldbuf (equal oldbuf (buffer-string)))
10599 (set-buffer-modified-p nil)
10600 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
7cb1c4d7 10601 (t (unless noninteractive (message "Updating AUTOs...done")))))
6341f357
DN
10602 ;; Unwind forms
10603 (progn
10604 ;; Restore font-lock
7cb1c4d7 10605 (when fontlocked (font-lock-mode t))))))
6341f357
DN
10606\f
10607
10608;;
10609;; Skeleton based code insertion
10610;;
60618039 10611(defvar verilog-template-map
6edb5716
DN
10612 (let ((map (make-sparse-keymap)))
10613 (define-key map "a" 'verilog-sk-always)
10614 (define-key map "b" 'verilog-sk-begin)
10615 (define-key map "c" 'verilog-sk-case)
10616 (define-key map "f" 'verilog-sk-for)
10617 (define-key map "g" 'verilog-sk-generate)
10618 (define-key map "h" 'verilog-sk-header)
10619 (define-key map "i" 'verilog-sk-initial)
10620 (define-key map "j" 'verilog-sk-fork)
10621 (define-key map "m" 'verilog-sk-module)
10622 (define-key map "p" 'verilog-sk-primitive)
10623 (define-key map "r" 'verilog-sk-repeat)
10624 (define-key map "s" 'verilog-sk-specify)
10625 (define-key map "t" 'verilog-sk-task)
10626 (define-key map "w" 'verilog-sk-while)
10627 (define-key map "x" 'verilog-sk-casex)
10628 (define-key map "z" 'verilog-sk-casez)
10629 (define-key map "?" 'verilog-sk-if)
10630 (define-key map ":" 'verilog-sk-else-if)
10631 (define-key map "/" 'verilog-sk-comment)
10632 (define-key map "A" 'verilog-sk-assign)
10633 (define-key map "F" 'verilog-sk-function)
10634 (define-key map "I" 'verilog-sk-input)
10635 (define-key map "O" 'verilog-sk-output)
10636 (define-key map "S" 'verilog-sk-state-machine)
10637 (define-key map "=" 'verilog-sk-inout)
10638 (define-key map "W" 'verilog-sk-wire)
10639 (define-key map "R" 'verilog-sk-reg)
30d48f20
DN
10640 (define-key map "D" 'verilog-sk-define-signal)
10641 map)
6341f357
DN
10642 "Keymap used in Verilog mode for smart template operations.")
10643
6341f357
DN
10644
10645;;
10646;; Place the templates into Verilog Mode. They may be inserted under any key.
10647;; C-c C-t will be the default. If you use templates a lot, you
10648;; may want to consider moving the binding to another key in your .emacs
10649;; file.
10650;;
10651;(define-key verilog-mode-map "\C-ct" verilog-template-map)
10652(define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
10653
10654;;; ---- statement skeletons ------------------------------------------
10655
10656(define-skeleton verilog-sk-prompt-condition
10657 "Prompt for the loop condition."
10658 "[condition]: " str )
10659
10660(define-skeleton verilog-sk-prompt-init
10661 "Prompt for the loop init statement."
10662 "[initial statement]: " str )
10663
10664(define-skeleton verilog-sk-prompt-inc
10665 "Prompt for the loop increment statement."
10666 "[increment statement]: " str )
10667
10668(define-skeleton verilog-sk-prompt-name
10669 "Prompt for the name of something."
10670 "[name]: " str)
10671
10672(define-skeleton verilog-sk-prompt-clock
10673 "Prompt for the name of something."
10674 "name and edge of clock(s): " str)
10675
10676(defvar verilog-sk-reset nil)
10677(defun verilog-sk-prompt-reset ()
10678 "Prompt for the name of a state machine reset."
7ea26faf 10679 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
6341f357
DN
10680
10681
10682(define-skeleton verilog-sk-prompt-state-selector
10683 "Prompt for the name of a state machine selector."
10684 "name of selector (eg {a,b,c,d}): " str )
10685
10686(define-skeleton verilog-sk-prompt-output
10687 "Prompt for the name of something."
10688 "output: " str)
10689
10690(define-skeleton verilog-sk-prompt-msb
10691 "Prompt for least significant bit specification."
f07fe184 10692 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
6341f357
DN
10693
10694(define-skeleton verilog-sk-prompt-lsb
10695 "Prompt for least significant bit specification."
10696 "lsb:" str )
10697
10698(defvar verilog-sk-p nil)
10699(define-skeleton verilog-sk-prompt-width
10700 "Prompt for a width specification."
10701 ()
10702 (progn
10703 (setq verilog-sk-p (point))
10704 (verilog-sk-prompt-msb)
10705 (if (> (point) verilog-sk-p) "] " " ")))
10706
10707(defun verilog-sk-header ()
a3a8b002
DN
10708 "Insert a descriptive header at the top of the file.
10709See also `verilog-header' for an alternative format."
6341f357
DN
10710 (interactive "*")
10711 (save-excursion
10712 (goto-char (point-min))
10713 (verilog-sk-header-tmpl)))
10714
10715(define-skeleton verilog-sk-header-tmpl
10716 "Insert a comment block containing the module title, author, etc."
10717 "[Description]: "
10718 "// -*- Mode: Verilog -*-"
10719 "\n// Filename : " (buffer-name)
10720 "\n// Description : " str
10721 "\n// Author : " (user-full-name)
10722 "\n// Created On : " (current-time-string)
a3a8b002
DN
10723 "\n// Last Modified By: " (user-full-name)
10724 "\n// Last Modified On: " (current-time-string)
6341f357
DN
10725 "\n// Update Count : 0"
10726 "\n// Status : Unknown, Use with caution!"
10727 "\n")
10728
10729(define-skeleton verilog-sk-module
10730 "Insert a module definition."
10731 ()
f07fe184 10732 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
6341f357
DN
10733 > _ \n
10734 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
10735
10736(define-skeleton verilog-sk-primitive
10737 "Insert a task definition."
10738 ()
f07fe184 10739 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
6341f357
DN
10740 > _ \n
10741 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
10742
10743(define-skeleton verilog-sk-task
10744 "Insert a task definition."
10745 ()
f07fe184 10746 > "task " '(verilog-sk-prompt-name) & ?; \n
6341f357
DN
10747 > _ \n
10748 > "begin" \n
10749 > \n
10750 > (- verilog-indent-level-behavioral) "end" \n
10751 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
10752
10753(define-skeleton verilog-sk-function
10754 "Insert a function definition."
10755 ()
f07fe184 10756 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
6341f357
DN
10757 > _ \n
10758 > "begin" \n
10759 > \n
10760 > (- verilog-indent-level-behavioral) "end" \n
10761 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
10762
10763(define-skeleton verilog-sk-always
10764 "Insert always block. Uses the minibuffer to prompt
10765for sensitivity list."
10766 ()
10767 > "always @ ( /*AUTOSENSE*/ ) begin\n"
10768 > _ \n
10769 > (- verilog-indent-level-behavioral) "end" \n >
10770 )
10771
10772(define-skeleton verilog-sk-initial
10773 "Insert an initial block."
10774 ()
10775 > "initial begin\n"
10776 > _ \n
10777 > (- verilog-indent-level-behavioral) "end" \n > )
10778
10779(define-skeleton verilog-sk-specify
10780 "Insert specify block. "
10781 ()
10782 > "specify\n"
10783 > _ \n
10784 > (- verilog-indent-level-behavioral) "endspecify" \n > )
10785
10786(define-skeleton verilog-sk-generate
10787 "Insert generate block. "
10788 ()
10789 > "generate\n"
10790 > _ \n
10791 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
10792
10793(define-skeleton verilog-sk-begin
37ea4b9b 10794 "Insert begin end block. Uses the minibuffer to prompt for name."
6341f357 10795 ()
f07fe184 10796 > "begin" '(verilog-sk-prompt-name) \n
6341f357
DN
10797 > _ \n
10798 > (- verilog-indent-level-behavioral) "end"
10799)
10800
10801(define-skeleton verilog-sk-fork
37ea4b9b 10802 "Insert a fork join block."
6341f357
DN
10803 ()
10804 > "fork\n"
10805 > "begin" \n
10806 > _ \n
10807 > (- verilog-indent-level-behavioral) "end" \n
10808 > "begin" \n
10809 > \n
10810 > (- verilog-indent-level-behavioral) "end" \n
10811 > (- verilog-indent-level-behavioral) "join" \n
10812 > )
10813
10814
10815(define-skeleton verilog-sk-case
10816 "Build skeleton case statement, prompting for the selector expression,
10817and the case items."
10818 "[selector expression]: "
10819 > "case (" str ") " \n
a3a8b002 10820 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
6341f357
DN
10821 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
10822
10823(define-skeleton verilog-sk-casex
10824 "Build skeleton casex statement, prompting for the selector expression,
10825and the case items."
10826 "[selector expression]: "
10827 > "casex (" str ") " \n
a3a8b002 10828 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
6341f357
DN
10829 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
10830
10831(define-skeleton verilog-sk-casez
10832 "Build skeleton casez statement, prompting for the selector expression,
10833and the case items."
10834 "[selector expression]: "
10835 > "casez (" str ") " \n
a3a8b002 10836 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
6341f357
DN
10837 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
10838
10839(define-skeleton verilog-sk-if
10840 "Insert a skeleton if statement."
f07fe184 10841 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
6341f357
DN
10842 > _ \n
10843 > (- verilog-indent-level-behavioral) "end " \n )
10844
10845(define-skeleton verilog-sk-else-if
10846 "Insert a skeleton else if statement."
10847 > (verilog-indent-line) "else if ("
f07fe184 10848 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
6341f357
DN
10849 > _ \n
10850 > "end" (progn (electric-verilog-terminate-line) nil))
10851
10852(define-skeleton verilog-sk-datadef
37ea4b9b 10853 "Common routine to get data definition."
6341f357 10854 ()
f07fe184 10855 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
6341f357
DN
10856
10857(define-skeleton verilog-sk-input
10858 "Insert an input definition."
10859 ()
f07fe184 10860 > "input [" '(verilog-sk-datadef))
6341f357
DN
10861
10862(define-skeleton verilog-sk-output
10863 "Insert an output definition."
10864 ()
f07fe184 10865 > "output [" '(verilog-sk-datadef))
6341f357
DN
10866
10867(define-skeleton verilog-sk-inout
10868 "Insert an inout definition."
10869 ()
f07fe184 10870 > "inout [" '(verilog-sk-datadef))
6341f357
DN
10871
10872(defvar verilog-sk-signal nil)
10873(define-skeleton verilog-sk-def-reg
10874 "Insert a reg definition."
10875 ()
f07fe184 10876 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
6341f357
DN
10877
10878(defun verilog-sk-define-signal ()
10879 "Insert a definition of signal under point at top of module."
10880 (interactive "*")
60618039 10881 (let* ((sig-re "[a-zA-Z0-9_]*")
6341f357
DN
10882 (v1 (buffer-substring
10883 (save-excursion
10884 (skip-chars-backward sig-re)
10885 (point))
10886 (save-excursion
10887 (skip-chars-forward sig-re)
60618039 10888 (point)))))
6341f357
DN
10889 (if (not (member v1 verilog-keywords))
10890 (save-excursion
10891 (setq verilog-sk-signal v1)
10892 (verilog-beg-of-defun)
10893 (verilog-end-of-statement)
10894 (verilog-forward-syntactic-ws)
10895 (verilog-sk-def-reg)
10896 (message "signal at point is %s" v1))
60618039 10897 (message "object at point (%s) is a keyword" v1))))
6341f357
DN
10898
10899(define-skeleton verilog-sk-wire
10900 "Insert a wire definition."
10901 ()
f07fe184 10902 > "wire [" '(verilog-sk-datadef))
6341f357
DN
10903
10904(define-skeleton verilog-sk-reg
10905 "Insert a reg definition."
10906 ()
f07fe184 10907 > "reg [" '(verilog-sk-datadef))
6341f357
DN
10908
10909(define-skeleton verilog-sk-assign
10910 "Insert a skeleton assign statement."
10911 ()
f07fe184 10912 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
6341f357
DN
10913
10914(define-skeleton verilog-sk-while
10915 "Insert a skeleton while loop statement."
10916 ()
f07fe184 10917 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
6341f357
DN
10918 > _ \n
10919 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
10920
10921(define-skeleton verilog-sk-repeat
10922 "Insert a skeleton repeat loop statement."
10923 ()
f07fe184 10924 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
6341f357
DN
10925 > _ \n
10926 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
10927
10928(define-skeleton verilog-sk-for
10929 "Insert a skeleton while loop statement."
10930 ()
10931 > "for ("
f07fe184
DN
10932 '(verilog-sk-prompt-init) "; "
10933 '(verilog-sk-prompt-condition) "; "
10934 '(verilog-sk-prompt-inc)
6341f357
DN
10935 ") begin" \n
10936 > _ \n
10937 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
10938
10939(define-skeleton verilog-sk-comment
10940 "Inserts three comment lines, making a display comment."
10941 ()
10942 > "/*\n"
10943 > "* " _ \n
10944 > "*/")
10945
10946(define-skeleton verilog-sk-state-machine
10947 "Insert a state machine definition."
10948 "Name of state variable: "
10949 '(setq input "state")
10950 > "// State registers for " str | -23 \n
10951 '(setq verilog-sk-state str)
f07fe184 10952 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
6341f357
DN
10953 '(setq input nil)
10954 > \n
10955 > "// State FF for " verilog-sk-state \n
10956 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
10957 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
10958 > verilog-sk-state " = next_" verilog-sk-state ?; \n
10959 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
10960 > \n
10961 > "// Next State Logic for " verilog-sk-state \n
10962 > "always @ ( /*AUTOSENSE*/ ) begin\n"
f07fe184 10963 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
6341f357
DN
10964 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
10965 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
10966 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
6341f357
DN
10967\f
10968
10969;;
10970;; Include file loading with mouse/return event
10971;;
10972;; idea & first impl.: M. Rouat (eldo-mode.el)
10973;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
10974
10975(if (featurep 'xemacs)
10976 (require 'overlay)
10977 (require 'lucid)) ;; what else can we do ??
10978
10979(defconst verilog-include-file-regexp
10980 "^`include\\s-+\"\\([^\n\"]*\\)\""
10981 "Regexp that matches the include file.")
10982
60618039 10983(defvar verilog-mode-mouse-map
6341f357
DN
10984 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
10985 (set-keymap-parent map verilog-mode-map)
10986 ;; mouse button bindings
10987 (define-key map "\r" 'verilog-load-file-at-point)
10988 (if (featurep 'xemacs)
10989 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
10990 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
10991 (if (featurep 'xemacs)
10992 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
30d48f20
DN
10993 (define-key map [S-mouse-2] 'mouse-yank-at-click))
10994 map)
6edb5716
DN
10995 "Map containing mouse bindings for `verilog-mode'.")
10996
6341f357 10997
6341f357
DN
10998(defun verilog-colorize-include-files (beg end old-len)
10999 "This function colorizes included files when the mouse passes over them.
11000Clicking on the middle-mouse button loads them in a buffer (as in dired)."
11001 (save-excursion
11002 (save-match-data
11003 (let (end-point)
11004 (goto-char end)
11005 (setq end-point (verilog-get-end-of-line))
11006 (goto-char beg)
11007 (beginning-of-line) ; scan entire line !
11008 ;; delete overlays existing on this line
11009 (let ((overlays (overlays-in (point) end-point)))
11010 (while overlays
11011 (if (and
11012 (overlay-get (car overlays) 'detachable)
11013 (overlay-get (car overlays) 'verilog-include-file))
11014 (delete-overlay (car overlays)))
11015 (setq overlays (cdr overlays)))) ; let
11016 ;; make new ones, could reuse deleted one ?
11017 (while (search-forward-regexp verilog-include-file-regexp end-point t)
30d48f20 11018 (let (ov)
6341f357 11019 (goto-char (match-beginning 1))
30d48f20
DN
11020 (setq ov (make-overlay (match-beginning 1) (match-end 1)))
11021 (overlay-put ov 'start-closed 't)
11022 (overlay-put ov 'end-closed 't)
11023 (overlay-put ov 'evaporate 't)
11024 (overlay-put ov 'verilog-include-file 't)
11025 (overlay-put ov 'mouse-face 'highlight)
11026 (overlay-put ov 'local-map verilog-mode-mouse-map)))))))
6341f357
DN
11027
11028
11029(defun verilog-colorize-include-files-buffer ()
37ea4b9b 11030 "Colorize an include file."
6341f357
DN
11031 (interactive)
11032 ;; delete overlays
11033 (let ((overlays (overlays-in (point-min) (point-max))))
11034 (while overlays
11035 (if (and
11036 (overlay-get (car overlays) 'detachable)
11037 (overlay-get (car overlays) 'verilog-include-file))
11038 (delete-overlay (car overlays)))
11039 (setq overlays (cdr overlays)))) ; let
11040 ;; remake overlays
11041 (verilog-colorize-include-files (point-min) (point-max) nil))
11042
37ea4b9b 11043;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
6341f357
DN
11044;; so define this function to do more or less the same as ffap-at-mouse
11045;; but first resolve filename...
11046(defun verilog-load-file-at-mouse (event)
11047 "Load file under button 2 click's EVENT.
11048Files are checked based on `verilog-library-directories'."
11049 (interactive "@e")
37ea4b9b 11050 (save-excursion ;; implement a Verilog specific ffap-at-mouse
6341f357
DN
11051 (mouse-set-point event)
11052 (beginning-of-line)
11053 (if (looking-at verilog-include-file-regexp)
11054 (if (and (car (verilog-library-filenames
11055 (match-string 1) (buffer-file-name)))
11056 (file-readable-p (car (verilog-library-filenames
11057 (match-string 1) (buffer-file-name)))))
11058 (find-file (car (verilog-library-filenames
11059 (match-string 1) (buffer-file-name))))
11060 (progn
11061 (message
11062 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
60618039 11063 (match-string 1)))))))
6341f357 11064
37ea4b9b 11065;; ffap isn't useable for Verilog mode. It uses library paths.
6341f357
DN
11066;; so define this function to do more or less the same as ffap
11067;; but first resolve filename...
11068(defun verilog-load-file-at-point ()
11069 "Load file under point.
11070Files are checked based on `verilog-library-directories'."
11071 (interactive)
37ea4b9b 11072 (save-excursion ;; implement a Verilog specific ffap
6341f357
DN
11073 (beginning-of-line)
11074 (if (looking-at verilog-include-file-regexp)
11075 (if (and
11076 (car (verilog-library-filenames
11077 (match-string 1) (buffer-file-name)))
11078 (file-readable-p (car (verilog-library-filenames
11079 (match-string 1) (buffer-file-name)))))
11080 (find-file (car (verilog-library-filenames
60618039 11081 (match-string 1) (buffer-file-name))))))))
6341f357
DN
11082
11083
11084;;
11085;; Bug reporting
11086;;
11087
11088(defun verilog-faq ()
11089 "Tell the user their current version, and where to get the FAQ etc."
11090 (interactive)
11091 (with-output-to-temp-buffer "*verilog-mode help*"
11092 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
11093 (princ "\n")
11094 (princ "For new releases, see http://www.verilog.com\n")
11095 (princ "\n")
7cb1c4d7 11096 (princ "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
6341f357
DN
11097 (princ "\n")
11098 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
11099 (princ "\n")))
11100
7ea26faf 11101(autoload 'reporter-submit-bug-report "reporter")
60618039 11102(defvar reporter-prompt-for-summary-p)
7ea26faf 11103
6341f357
DN
11104(defun verilog-submit-bug-report ()
11105 "Submit via mail a bug report on verilog-mode.el."
11106 (interactive)
11107 (let ((reporter-prompt-for-summary-p t))
11108 (reporter-submit-bug-report
11109 "mac@verilog.com"
11110 (concat "verilog-mode v" verilog-mode-version)
11111 '(
11112 verilog-align-ifelse
11113 verilog-auto-endcomments
11114 verilog-auto-hook
11115 verilog-auto-indent-on-newline
11116 verilog-auto-inst-vector
11117 verilog-auto-inst-template-numbers
11118 verilog-auto-lineup
11119 verilog-auto-newline
11120 verilog-auto-save-policy
11121 verilog-auto-sense-defines-constant
11122 verilog-auto-sense-include-inputs
11123 verilog-before-auto-hook
11124 verilog-case-indent
11125 verilog-cexp-indent
11126 verilog-compiler
11127 verilog-coverage
11128 verilog-highlight-translate-off
11129 verilog-indent-begin-after-if
11130 verilog-indent-declaration-macros
11131 verilog-indent-level
11132 verilog-indent-level-behavioral
11133 verilog-indent-level-declaration
11134 verilog-indent-level-directive
11135 verilog-indent-level-module
11136 verilog-indent-lists
11137 verilog-library-flags
11138 verilog-library-directories
11139 verilog-library-extensions
11140 verilog-library-files
11141 verilog-linter
11142 verilog-minimum-comment-distance
11143 verilog-mode-hook
11144 verilog-simulator
11145 verilog-tab-always-indent
11146 verilog-tab-to-comment
11147 )
11148 nil nil
11149 (concat "Hi Mac,
11150
11151I want to report a bug. I've read the `Bugs' section of `Info' on
11152Emacs, so I know how to make a clear and unambiguous report. To get
11153to that Info section, I typed
11154
11155M-x info RET m " invocation-name " RET m bugs RET
11156
11157Before I go further, I want to say that Verilog mode has changed my life.
11158I save so much time, my files are colored nicely, my co workers respect
11159my coding ability... until now. I'd really appreciate anything you
11160could do to help me out with this minor deficiency in the product.
11161
11162If you have bugs with the AUTO functions, please CC the AUTOAUTHOR Wilson
7cb1c4d7 11163Snyder (wsnyder@wsnyder.org) and/or see http://www.veripool.org.
6341f357 11164You may also want to look at the Verilog-Mode FAQ, see
7cb1c4d7 11165http://www.veripool.org/verilog-mode-faq.html.
6341f357
DN
11166
11167To reproduce the bug, start a fresh Emacs via " invocation-name "
37ea4b9b 11168-no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
6341f357
DN
11169the code included below.
11170
11171Given those lines, I expected [[Fill in here]] to happen;
11172but instead, [[Fill in here]] happens!.
11173
11174== The code: =="))))
11175
6edb5716
DN
11176(provide 'verilog-mode)
11177
6341f357
DN
11178;; Local Variables:
11179;; checkdoc-permit-comma-termination-flag:t
11180;; checkdoc-force-docstrings-flag:nil
11181;; End:
11182
819ee2f4 11183;; arch-tag: 87923725-57b3-41b5-9494-be21118c6a6f
6341f357 11184;;; verilog-mode.el ends here