Initial Commit
[packages] / xemacs-packages / prog-modes / verilog-mode.el
1 ;; verilog-mode.el --- major mode for editing verilog source in Emacs
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008  Free Software Foundation, Inc.
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)
11 ;;      http://www.veripool.org
12 ;; Keywords: languages
13
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
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
25 ;; This file is part of GNU Emacs.
26
27 ;; GNU Emacs is free software: you can redistribute it and/or modify
28 ;; it under the terms of the GNU General Public License as published by
29 ;; the Free Software Foundation, either version 3 of the License, or
30 ;; (at your option) any later version.
31
32 ;; GNU Emacs is distributed in the hope that it will be useful,
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
38 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
39
40 ;;; Commentary:
41
42 ;; This mode borrows heavily from the Pascal-mode and the cc-mode of Emacs
43
44 ;; USAGE
45 ;; =====
46
47 ;; A major mode for editing Verilog HDL source code.  When you have
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
56 ;; under continuous development.  Hence this is beta code, and likely
57 ;; has bugs.  Please report any and all bugs to me at mac@verilog.com.
58 ;; Please use verilog-submit-bug-report to submit a report; type C-c
59 ;; C-b to invoke this and as a result I will have a much easier time
60 ;; of reproducing the bug you find, and hence fixing it.
61
62 ;; INSTALLING THE MODE
63 ;; ===================
64
65 ;; An older version of this mode may be already installed as a part of
66 ;; your environment, and one method of updating would be to update
67 ;; your Emacs environment.  Sometimes this is difficult for local
68 ;; political/control reasons, and hence you can always install a
69 ;; private copy (or even a shared copy) which overrides the system
70 ;; default.
71
72 ;; You can get step by step help in installing this file by going to
73 ;; <http://www.verilog.com/emacs_install.html>
74
75 ;; The short list of installation instructions are: To set up
76 ;; automatic Verilog mode, put this file in your load path, and put
77 ;; the following in code (please un comment it first!) in your
78 ;; .emacs, or in your site's site-load.el
79
80 ; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
81 ; (add-to-list 'auto-mode-alist '("\\.[ds]?vh?\\'" . verilog-mode))
82
83 ;; If you want to customize Verilog mode to fit your needs better,
84 ;; you may add these lines (the values of the variables presented
85 ;; here are the defaults). Note also that if you use an Emacs that
86 ;; supports custom, it's probably better to use the custom menu to
87 ;; edit these.
88 ;;
89 ;; Be sure to examine at the help for verilog-auto, and the other
90 ;; verilog-auto-* functions for some major coding time savers.
91 ;;
92 ; ;; User customization for Verilog mode
93 ; (setq verilog-indent-level             3
94 ;       verilog-indent-level-module      3
95 ;       verilog-indent-level-declaration 3
96 ;       verilog-indent-level-behavioral  3
97 ;       verilog-indent-level-directive   1
98 ;       verilog-case-indent              2
99 ;       verilog-auto-newline             t
100 ;       verilog-auto-indent-on-newline   t
101 ;       verilog-tab-always-indent        t
102 ;       verilog-auto-endcomments         t
103 ;       verilog-minimum-comment-distance 40
104 ;       verilog-indent-begin-after-if    t
105 ;       verilog-auto-lineup              '(all)
106 ;       verilog-highlight-p1800-keywords nil
107 ;       verilog-linter                   "my_lint_shell_command"
108 ;       )
109
110 ;; \f
111
112 ;;; History:
113 ;;
114 ;; See commit history at http://www.veripool.org/verilog-mode.html
115 ;; (This section is required to appease checkdoc.)
116
117 ;;; Code:
118
119 ;; XEmacs additions
120 ;;;###autoload(add-to-list 'auto-mode-alist '("\\.\\(vh?\\|svh?\\|dv\\)\\'" . verilog-mode))
121
122 ;; This variable will always hold the version number of the mode
123 (defconst verilog-mode-version (substring "$$Revision: 463 $$" 12 -3)
124   "Version of this Verilog mode.")
125 (defconst verilog-mode-release-date (substring "$$Date: 2008-11-21 21:16:37 +0000 (Fri, 21 Nov 2008) $$" 8 -3)
126   "Release date of this Verilog mode.")
127 (defconst verilog-mode-release-emacs nil
128   "If non-nil, this version of Verilog mode was released with Emacs itself.")
129
130 ;;;###autoload
131 (defun verilog-version ()
132   "Inform caller of the version of this file."
133   (interactive)
134   (message "Using verilog-mode version %s" verilog-mode-version))
135
136 ;; Insure we have certain packages, and deal with it if we don't
137 ;; Be sure to note which Emacs flavor and version added each feature.
138 (eval-when-compile
139   ;; Provide stuff if we are XEmacs
140   (when (featurep 'xemacs)
141     (condition-case nil
142         (require 'easymenu)
143       (error nil))
144     (condition-case nil
145         (require 'regexp-opt)
146       (error nil))
147     ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
148     (condition-case nil
149         (load "skeleton")
150       (error nil))
151     (condition-case nil
152         (if (fboundp 'when)
153             nil ;; fab
154           (defmacro when (cond &rest body)
155             (list 'if cond (cons 'progn body))))
156       (error nil))
157     (condition-case nil
158         (if (fboundp 'unless)
159             nil ;; fab
160           (defmacro unless (cond &rest body)
161             (cons 'if (cons cond (cons nil body)))))
162       (error nil))
163     (condition-case nil
164         (if (fboundp 'store-match-data)
165             nil ;; fab
166           (defmacro store-match-data (&rest args) nil))
167       (error nil))
168     (condition-case nil
169         (if (fboundp 'char-before)
170             nil ;; great
171           (defmacro char-before (&rest body)
172             (char-after (1- (point)))))
173       (error nil))
174     (condition-case nil
175         (require 'custom)
176       (error nil))
177     (condition-case nil
178         (if (fboundp 'match-string-no-properties)
179             nil ;; great
180           (defsubst match-string-no-properties (num &optional string)
181             "Return string of text matched by last search, without text properties.
182 NUM specifies which parenthesized expression in the last regexp.
183  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
184 Zero means the entire text matched by the whole regexp or whole string.
185 STRING should be given if the last search was by `string-match' on STRING."
186             (if (match-beginning num)
187                 (if string
188                     (let ((result
189                            (substring string
190                                       (match-beginning num) (match-end num))))
191                       (set-text-properties 0 (length result) nil result)
192                       result)
193                   (buffer-substring-no-properties (match-beginning num)
194                                                   (match-end num)
195                                                   (current-buffer)))))
196           )
197       (error nil))
198     (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
199         nil ;; We've got what we needed
200       ;; We have the old custom-library, hack around it!
201       (defmacro defgroup (&rest args)  nil)
202       (defmacro customize (&rest args)
203         (message
204          "Sorry, Customize is not available with this version of Emacs"))
205       (defmacro defcustom (var value doc &rest args)
206         `(defvar ,var ,value ,doc))
207       )
208     (if (fboundp 'defface)
209         nil                             ; great!
210       (defmacro defface (var values doc &rest args)
211         `(make-face ,var))
212       )
213
214     (if (and (featurep 'custom) (fboundp 'customize-group))
215         nil ;; We've got what we needed
216       ;; We have an intermediate custom-library, hack around it!
217       (defmacro customize-group (var &rest args)
218         `(customize ,var))
219       ))
220   ;; OK, do this stuff if we are NOT XEmacs:
221   (unless (featurep 'xemacs)
222     (unless (fboundp 'region-active-p)
223       (defmacro region-active-p ()
224         `(and transient-mark-mode mark-active))))
225   )
226
227 ;; Provide a regular expression optimization routine, using regexp-opt
228 ;; if provided by the user's elisp libraries
229 (eval-and-compile
230   ;; The below were disabled when GNU Emacs 22 was released;
231   ;; perhaps some still need to be there to support Emacs 21.
232   (if (featurep 'xemacs)
233       (if (fboundp 'regexp-opt)
234           ;; regexp-opt is defined, does it take 3 or 2 arguments?
235           (if (fboundp 'function-max-args)
236               (let ((args (function-max-args `regexp-opt)))
237                 (cond
238                  ((eq args 3) ;; It takes 3
239                   (condition-case nil   ; Hide this defun from emacses
240                                         ;with just a two input regexp
241                       (defun verilog-regexp-opt (a b)
242                         "Deal with differing number of required arguments for  `regexp-opt'.
243          Call 'regexp-opt' on A and B."
244                         (regexp-opt a b 't))
245                     (error nil))
246                   )
247                  ((eq args 2) ;; It takes 2
248                   (defun verilog-regexp-opt (a b)
249                     "Call 'regexp-opt' on A and B."
250                     (regexp-opt a b))
251                   )
252                  (t nil)))
253             ;; We can't tell; assume it takes 2
254             (defun verilog-regexp-opt (a b)
255               "Call 'regexp-opt' on A and B."
256               (regexp-opt a b))
257             )
258         ;; There is no regexp-opt, provide our own
259         (defun verilog-regexp-opt (strings &optional paren shy)
260           (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
261             (concat open (mapconcat 'regexp-quote strings "\\|") close)))
262         )
263     ;; Emacs.
264     (defalias 'verilog-regexp-opt 'regexp-opt)))
265
266 (eval-when-compile
267   (defun verilog-regexp-words (a)
268     "Call 'regexp-opt' with word delimiters for the words A."
269     (concat "\\<" (verilog-regexp-opt a t) "\\>")))
270
271 (defun verilog-easy-menu-filter (menu)
272   "Filter a easy-menu-define to support new features."
273   (cond ((not (featurep 'xemacs))
274          menu) ;; GNU Emacs - passthru
275         ;; Xemacs doesn't support :help.  Strip it.
276         ;; Recursively filter the a submenu
277         ((listp menu)
278          (mapcar 'verilog-easy-menu-filter menu))
279         ;; Look for [:help "blah"] and remove
280         ((vectorp menu)
281          (let ((i 0) (out []))
282            (while (< i (length menu))
283              (if (equal `:help (aref menu i))
284                  (setq i (+ 2 i))
285                (setq out (vconcat out (vector (aref menu i)))
286                      i (1+ i))))
287            out))
288         (t menu))) ;; Default - ok
289 ;;(verilog-easy-menu-filter
290 ;;  `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
291 ;;     "----" ["MB" nil :help "Help MB"]))
292
293 ;;;###autoload
294 (defun verilog-customize ()
295   "Customize variables and other settings used by Verilog-Mode."
296   (interactive)
297   (customize-group 'verilog-mode))
298
299 (defun verilog-font-customize ()
300   "Customize fonts used by Verilog-Mode."
301   (interactive)
302   (if (fboundp 'customize-apropos)
303       (customize-apropos "font-lock-*" 'faces)))
304
305 (defun verilog-booleanp (value)
306   "Return t if VALUE is boolean.
307  This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
308  This function may be removed when Emacs 21 is no longer supported."
309   (or (equal value t) (equal value nil)))
310
311 (defalias 'verilog-syntax-ppss
312   (if (fboundp 'syntax-ppss) 'syntax-ppss
313     (lambda (&optional pos) (parse-partial-sexp (point-min) (or pos (point))))))
314
315 (defgroup verilog-mode nil
316   "Facilitates easy editing of Verilog source text."
317   :version "22.2"
318   :group 'languages)
319
320 ; (defgroup verilog-mode-fonts nil
321 ;   "Facilitates easy customization fonts used in Verilog source text"
322 ;   :link '(customize-apropos "font-lock-*" 'faces)
323 ;  :group 'verilog-mode)
324
325 (defgroup verilog-mode-indent nil
326   "Customize indentation and highlighting of Verilog source text."
327   :group 'verilog-mode)
328
329 (defgroup verilog-mode-actions nil
330   "Customize actions on Verilog source text."
331   :group 'verilog-mode)
332
333 (defgroup verilog-mode-auto nil
334   "Customize AUTO actions when expanding Verilog source text."
335   :group 'verilog-mode)
336
337 (defcustom verilog-linter
338   "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
339   "*Unix program and arguments to call to run a lint checker on Verilog source.
340 Depending on the `verilog-set-compile-command', this may be invoked when
341 you type \\[compile].  When the compile completes, \\[next-error] will take
342 you to the next lint error."
343   :type 'string
344   :group 'verilog-mode-actions)
345 ;; We don't mark it safe, as it's used as a shell command
346
347 (defcustom verilog-coverage
348   "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
349   "*Program and arguments to use to annotate for coverage Verilog source.
350 Depending on the `verilog-set-compile-command', this may be invoked when
351 you type \\[compile].  When the compile completes, \\[next-error] will take
352 you to the next lint error."
353   :type 'string
354   :group 'verilog-mode-actions)
355 ;; We don't mark it safe, as it's used as a shell command
356
357 (defcustom verilog-simulator
358   "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
359   "*Program and arguments to use to interpret Verilog source.
360 Depending on the `verilog-set-compile-command', this may be invoked when
361 you type \\[compile].  When the compile completes, \\[next-error] will take
362 you to the next lint error."
363   :type 'string
364   :group 'verilog-mode-actions)
365 ;; We don't mark it safe, as it's used as a shell command
366
367 (defcustom verilog-compiler
368   "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
369   "*Program and arguments to use to compile Verilog source.
370 Depending on the `verilog-set-compile-command', this may be invoked when
371 you type \\[compile].  When the compile completes, \\[next-error] will take
372 you to the next lint error."
373   :type 'string
374   :group 'verilog-mode-actions)
375 ;; We don't mark it safe, as it's used as a shell command
376
377 (defvar verilog-tool 'verilog-linter
378   "Which tool to use for building compiler-command.
379 Either nil, `verilog-linter, `verilog-coverage, `verilog-simulator, or
380 `verilog-compiler.  Alternatively use the \"Choose Compilation Action\"
381 menu.  See `verilog-set-compile-command' for more information.")
382
383 (defcustom verilog-highlight-translate-off nil
384   "*Non-nil means background-highlight code excluded from translation.
385 That is, all code between \"// synopsys translate_off\" and
386 \"// synopsys translate_on\" is highlighted using a different background color
387 \(face `verilog-font-lock-translate-off-face').
388
389 Note: This will slow down on-the-fly fontification (and thus editing).
390
391 Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
392 entry \"Fontify Buffer\").  XEmacs: turn off and on font locking."
393   :type 'boolean
394   :group 'verilog-mode-indent)
395 ;; Note we don't use :safe, as that would break on Emacsen before 22.0.
396 (put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
397
398 (defcustom verilog-indent-level 3
399   "*Indentation of Verilog statements with respect to containing block."
400   :group 'verilog-mode-indent
401   :type 'integer)
402 (put 'verilog-indent-level 'safe-local-variable 'integerp)
403
404 (defcustom verilog-indent-level-module 3
405   "*Indentation of Module level Verilog statements (eg always, initial).
406 Set to 0 to get initial and always statements lined up on the left side of
407 your screen."
408   :group 'verilog-mode-indent
409   :type 'integer)
410 (put 'verilog-indent-level-module 'safe-local-variable 'integerp)
411
412 (defcustom verilog-indent-level-declaration 3
413   "*Indentation of declarations with respect to containing block.
414 Set to 0 to get them list right under containing block."
415   :group 'verilog-mode-indent
416   :type 'integer)
417 (put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
418
419 (defcustom verilog-indent-declaration-macros nil
420   "*How to treat macro expansions in a declaration.
421 If nil, indent as:
422         input [31:0] a;
423         input        `CP;
424         output       c;
425 If non nil, treat as:
426         input [31:0] a;
427         input `CP    ;
428         output       c;"
429   :group 'verilog-mode-indent
430   :type 'boolean)
431 (put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
432
433 (defcustom verilog-indent-lists t
434   "*How to treat indenting items in a list.
435 If t (the default), indent as:
436         always @( posedge a or
437                   reset ) begin
438
439 If nil, treat as:
440         always @( posedge a or
441            reset ) begin"
442   :group 'verilog-mode-indent
443   :type 'boolean)
444 (put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
445
446 (defcustom verilog-indent-level-behavioral 3
447   "*Absolute indentation of first begin in a task or function block.
448 Set to 0 to get such code to start at the left side of the screen."
449   :group 'verilog-mode-indent
450   :type 'integer)
451 (put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
452
453 (defcustom verilog-indent-level-directive 1
454   "*Indentation to add to each level of `ifdef declarations.
455 Set to 0 to have all directives start at the left side of the screen."
456   :group 'verilog-mode-indent
457   :type 'integer)
458 (put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
459
460 (defcustom verilog-cexp-indent 2
461   "*Indentation of Verilog statements split across lines."
462   :group 'verilog-mode-indent
463   :type 'integer)
464 (put 'verilog-cexp-indent 'safe-local-variable 'integerp)
465
466 (defcustom verilog-case-indent 2
467   "*Indentation for case statements."
468   :group 'verilog-mode-indent
469   :type 'integer)
470 (put 'verilog-case-indent 'safe-local-variable 'integerp)
471
472 (defcustom verilog-auto-newline t
473   "*True means automatically newline after semicolons."
474   :group 'verilog-mode-indent
475   :type 'boolean)
476 (put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
477
478 (defcustom verilog-auto-indent-on-newline t
479   "*True means automatically indent line after newline."
480   :group 'verilog-mode-indent
481   :type 'boolean)
482 (put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
483
484 (defcustom verilog-tab-always-indent t
485   "*True means TAB should always re-indent the current line.
486 A nil value means TAB will only reindent when at the beginning of the line."
487   :group 'verilog-mode-indent
488   :type 'boolean)
489 (put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
490
491 (defcustom verilog-tab-to-comment nil
492   "*True means TAB moves to the right hand column in preparation for a comment."
493   :group 'verilog-mode-actions
494   :type 'boolean)
495 (put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
496
497 (defcustom verilog-indent-begin-after-if t
498   "*If true, indent begin statements following if, else, while, for and repeat.
499 Otherwise, line them up."
500   :group 'verilog-mode-indent
501   :type 'boolean)
502 (put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
503
504
505 (defcustom verilog-align-ifelse nil
506   "*If true, align `else' under matching `if'.
507 Otherwise else is lined up with first character on line holding matching if."
508   :group 'verilog-mode-indent
509   :type 'boolean)
510 (put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
511
512 (defcustom verilog-minimum-comment-distance 10
513   "*Minimum distance (in lines) between begin and end required before a comment.
514 Setting this variable to zero results in every end acquiring a comment; the
515 default avoids too many redundant comments in tight quarters."
516   :group 'verilog-mode-indent
517   :type 'integer)
518 (put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
519
520 (defcustom verilog-auto-lineup '(declaration)
521   "*Algorithm for lining up statements on multiple lines.
522
523 If this list contains the symbol 'all', then all line ups described below
524 are done.
525
526 If this list contains the symbol 'declaration', then declarations are lined up
527 with any preceding declarations, taking into account widths and the like, so
528 for example the code:
529         reg [31:0] a;
530         reg b;
531 would become
532         reg [31:0] a;
533         reg        b;
534
535 If this list contains the symbol 'assignment', then assignments are lined up
536 with any preceding assignments, so for example the code
537         a_long_variable = b + c;
538         d = e + f;
539 would become
540         a_long_variable = b + c;
541         d               = e + f;"
542
543 ;; The following is not implemented:
544 ;If this list contains the symbol 'case', then case items are lined up
545 ;with any preceding case items, so for example the code
546 ;       case (a) begin
547 ;        a_long_state : a = 3;
548 ;        b: a = 4;
549 ;       endcase
550 ;would become
551 ;       case (a) begin
552 ;        a_long_state : a = 3;
553 ;        b            : a = 4;
554 ;       endcase
555 ;
556
557   :group 'verilog-mode-indent
558   :type 'list)
559 (put 'verilog-auto-lineup 'safe-local-variable 'listp)
560
561 (defcustom verilog-highlight-p1800-keywords nil
562   "*True means highlight words newly reserved by IEEE-1800.
563 These will appear in `verilog-font-lock-p1800-face' in order to gently
564 suggest changing where these words are used as variables to something else.
565 A nil value means highlight these words as appropriate for the SystemVerilog
566 IEEE-1800 standard.  Note that changing this will require restarting Emacs
567 to see the effect as font color choices are cached by Emacs."
568   :group 'verilog-mode-indent
569   :type 'boolean)
570 (put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
571
572 (defcustom verilog-highlight-grouping-keywords nil
573   "*True means highlight grouping keywords 'begin' and 'end' more dramatically.
574 If false, these words are in the font-lock-type-face; if True then they are in
575 `verilog-font-lock-ams-face'. Some find that special highlighting on these
576 grouping constructs allow the structure of the code to be understood at a glance."
577   :group 'verilog-mode-indent
578   :type 'boolean)
579 (put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
580
581 (defcustom verilog-auto-endcomments t
582   "*True means insert a comment /* ... */ after 'end's.
583 The name of the function or case will be set between the braces."
584   :group 'verilog-mode-actions
585   :type 'boolean)
586 (put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
587
588 (defcustom verilog-auto-read-includes nil
589   "*True means to automatically read includes before AUTOs.
590 This will do a `verilog-read-defines' and `verilog-read-includes' before
591 each AUTO expansion.  This makes it easier to embed defines and includes,
592 but can result in very slow reading times if there are many or large
593 include files."
594   :group 'verilog-mode-actions
595   :type 'boolean)
596 (put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
597
598 (defcustom verilog-auto-save-policy nil
599   "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
600 A value of `force' will always do a \\[verilog-auto] automatically if
601 needed on every save.  A value of `detect' will do \\[verilog-auto]
602 automatically when it thinks necessary.  A value of `ask' will query the
603 user when it thinks updating is needed.
604
605 You should not rely on the 'ask or 'detect policies, they are safeguards
606 only.  They do not detect when AUTOINSTs need to be updated because a
607 sub-module's port list has changed."
608   :group 'verilog-mode-actions
609   :type '(choice (const nil) (const ask) (const detect) (const force)))
610
611 (defcustom verilog-auto-star-expand t
612   "*Non-nil indicates to expand a SystemVerilog .* instance ports.
613 They will be expanded in the same way as if there was a AUTOINST in the
614 instantiation.  See also `verilog-auto-star' and `verilog-auto-star-save'."
615   :group 'verilog-mode-actions
616   :type 'boolean)
617 (put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
618
619 (defcustom verilog-auto-star-save nil
620   "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
621 A nil value indicates direct connections will be removed before saving.
622 Only meaningful to those created due to `verilog-auto-star-expand' being set.
623
624 Instead of setting this, you may want to use /*AUTOINST*/, which will
625 always be saved."
626   :group 'verilog-mode-actions
627   :type 'boolean)
628 (put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
629
630 (defvar verilog-auto-update-tick nil
631   "Modification tick at which autos were last performed.")
632
633 (defvar verilog-auto-last-file-locals nil
634   "Text from file-local-variables during last evaluation.")
635
636 (defvar verilog-error-regexp-add-didit nil)
637 (defvar verilog-error-regexp nil)
638 (setq verilog-error-regexp-add-didit nil
639  verilog-error-regexp
640   '(
641         ; SureLint
642 ;;    ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
643         ; Most SureFire tools
644     ("\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\), \\(line \\|\\)\\([0-9]+\\):" 2 4 )
645     ("\
646 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
647 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
648         ; xsim
649         ; Error! in file /homes/mac/Axis/Xsim/test.v at line 13         [OBJ_NOT_DECLARED]
650     ("\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
651         ; vcs
652     ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
653     ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
654     ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
655     ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
656         ; Verilator
657     ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
658     ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
659        ; vxl
660     ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
661     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 2)               ; vxl
662     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 2)
663         ; nc-verilog
664     (".*\\*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 2)
665        ; Leda
666     ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 2)
667     )
668 ;  "*List of regexps for Verilog compilers, like verilint. See compilation-error-regexp-alist for the formatting."
669 )
670
671 (defvar verilog-error-font-lock-keywords
672   '(
673     ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
674     ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
675
676     ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
677     ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
678
679     ("\
680 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
681 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
682     ("\
683 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
684 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
685
686     ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
687     ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
688
689     ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
690     ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
691
692     ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
693     ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
694
695     ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
696     ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
697
698     ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
699     ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
700        ; vxl
701     ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
702     ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
703
704     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 bold t)
705     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 2 bold t)
706
707     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 bold t)
708     ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 2 bold t)
709         ; nc-verilog
710     (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 bold t)
711     (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
712        ; Leda
713     ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 bold t)
714     ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 2 bold t)
715     )
716   "*Keywords to also highlight in Verilog *compilation* buffers.")
717
718 (defcustom verilog-library-flags '("")
719   "*List of standard Verilog arguments to use for /*AUTOINST*/.
720 These arguments are used to find files for `verilog-auto', and match
721 the flags accepted by a standard Verilog-XL simulator.
722
723     -f filename     Reads more `verilog-library-flags' from the filename.
724     +incdir+dir     Adds the directory to `verilog-library-directories'.
725     -Idir           Adds the directory to `verilog-library-directories'.
726     -y dir          Adds the directory to `verilog-library-directories'.
727     +libext+.v      Adds the extensions to `verilog-library-extensions'.
728     -v filename     Adds the filename to `verilog-library-files'.
729
730     filename        Adds the filename to `verilog-library-files'.
731                     This is not recommended, -v is a better choice.
732
733 You might want these defined in each file; put at the *END* of your file
734 something like:
735
736     // Local Variables:
737     // verilog-library-flags:(\"-y dir -y otherdir\")
738     // End:
739
740 Verilog-mode attempts to detect changes to this local variable, but they
741 are only insured to be correct when the file is first visited.  Thus if you
742 have problems, use \\[find-alternate-file] RET to have these take effect.
743
744 See also the variables mentioned above."
745   :group 'verilog-mode-auto
746   :type '(repeat string))
747 (put 'verilog-library-flags 'safe-local-variable 'listp)
748
749 (defcustom verilog-library-directories '(".")
750   "*List of directories when looking for files for /*AUTOINST*/.
751 The directory may be relative to the current file, or absolute.
752 Environment variables are also expanded in the directory names.
753 Having at least the current directory is a good idea.
754
755 You might want these defined in each file; put at the *END* of your file
756 something like:
757
758     // Local Variables:
759     // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
760     // End:
761
762 Verilog-mode attempts to detect changes to this local variable, but they
763 are only insured to be correct when the file is first visited.  Thus if you
764 have problems, use \\[find-alternate-file] RET to have these take effect.
765
766 See also `verilog-library-flags', `verilog-library-files'
767 and `verilog-library-extensions'."
768   :group 'verilog-mode-auto
769   :type '(repeat file))
770 (put 'verilog-library-directories 'safe-local-variable 'listp)
771
772 (defcustom verilog-library-files '()
773   "*List of files to search for modules.
774 AUTOINST will use this when it needs to resolve a module name.
775 This is a complete path, usually to a technology file with many standard
776 cells defined in it.
777
778 You might want these defined in each file; put at the *END* of your file
779 something like:
780
781     // Local Variables:
782     // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
783     // End:
784
785 Verilog-mode attempts to detect changes to this local variable, but they
786 are only insured to be correct when the file is first visited.  Thus if you
787 have problems, use \\[find-alternate-file] RET to have these take effect.
788
789 See also `verilog-library-flags', `verilog-library-directories'."
790   :group 'verilog-mode-auto
791   :type '(repeat directory))
792 (put 'verilog-library-files 'safe-local-variable 'listp)
793
794 (defcustom verilog-library-extensions '(".v" ".sv")
795   "*List of extensions to use when looking for files for /*AUTOINST*/.
796 See also `verilog-library-flags', `verilog-library-directories'."
797   :type '(repeat string)
798   :group 'verilog-mode-auto)
799 (put 'verilog-library-extensions 'safe-local-variable 'listp)
800
801 (defcustom verilog-active-low-regexp nil
802   "*If set, treat signals matching this regexp as active low.
803 This is used for AUTORESET and AUTOTIEOFF.  For proper behavior,
804 you will probably also need `verilog-auto-reset-widths' set."
805   :group 'verilog-mode-auto
806   :type 'string)
807 (put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
808
809 (defcustom verilog-auto-sense-include-inputs nil
810   "*If true, AUTOSENSE should include all inputs.
811 If nil, only inputs that are NOT output signals in the same block are
812 included."
813   :group 'verilog-mode-auto
814   :type 'boolean)
815 (put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
816
817 (defcustom verilog-auto-sense-defines-constant nil
818   "*If true, AUTOSENSE should assume all defines represent constants.
819 When true, the defines will not be included in sensitivity lists.  To
820 maintain compatibility with other sites, this should be set at the bottom
821 of each Verilog file that requires it, rather than being set globally."
822   :group 'verilog-mode-auto
823   :type 'boolean)
824 (put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
825
826 (defcustom verilog-auto-reset-widths t
827   "*If true, AUTORESET should determine the width of signals.
828 This is then used to set the width of the zero (32'h0 for example).  This
829 is required by some lint tools that aren't smart enough to ignore widths of
830 the constant zero.  This may result in ugly code when parameters determine
831 the MSB or LSB of a signal inside an AUTORESET."
832   :type 'boolean
833   :group 'verilog-mode-auto)
834 (put 'verilog-auto-reset-widths 'safe-local-variable 'verilog-booleanp)
835
836 (defcustom verilog-assignment-delay ""
837   "*Text used for delays in delayed assignments.  Add a trailing space if set."
838   :group 'verilog-mode-auto
839   :type 'string)
840 (put 'verilog-assignment-delay 'safe-local-variable 'stringp)
841
842 (defcustom verilog-auto-inst-param-value nil
843   "*If set, AUTOINST will replace parameters with the parameter value.
844 If nil, leave parameters as symbolic names.
845
846 Parameters must be in Verilog 2001 format #(...), and if a parameter is not
847 listed as such there (as when the default value is acceptable), it will not
848 be replaced, and will remain symbolic.
849
850 For example, imagine a submodule uses parameters to declare the size of its
851 inputs.  This is then used by a upper module:
852
853         module InstModule (o,i)
854            parameter WIDTH;
855            input [WIDTH-1:0] i;
856         endmodule
857
858         module ExampInst;
859            InstModule
860              #(PARAM(10))
861             instName
862              (/*AUTOINST*/
863               .i        (i[PARAM-1:0]));
864
865 Note even though PARAM=10, the AUTOINST has left the parameter as a
866 symbolic name.  If `verilog-auto-inst-param-value' is set, this will
867 instead expand to:
868
869         module ExampInst;
870            InstModule
871              #(PARAM(10))
872             instName
873              (/*AUTOINST*/
874               .i        (i[9:0]));"
875   :group 'verilog-mode-auto
876   :type 'boolean)
877 (put 'verilog-auto-inst-param-value 'safe-local-variable 'verilog-booleanp)
878
879 (defcustom verilog-auto-inst-vector t
880   "*If true, when creating default ports with AUTOINST, use bus subscripts.
881 If nil, skip the subscript when it matches the entire bus as declared in
882 the module (AUTOWIRE signals always are subscripted, you must manually
883 declare the wire to have the subscripts removed.)  Setting this to nil may
884 speed up some simulators, but is less general and harder to read, so avoid."
885   :group 'verilog-mode-auto
886   :type 'boolean)
887 (put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
888
889 (defcustom verilog-auto-inst-template-numbers nil
890   "*If true, when creating templated ports with AUTOINST, add a comment.
891 The comment will add the line number of the template that was used for that
892 port declaration.  Setting this aids in debugging, but nil is suggested for
893 regular use to prevent large numbers of merge conflicts."
894   :group 'verilog-mode-auto
895   :type 'boolean)
896 (put 'verilog-auto-inst-template-numbers 'safe-local-variable 'verilog-booleanp)
897
898 (defcustom verilog-auto-inst-column 40
899   "*Indent-to column number for net name part of AUTOINST created pin."
900   :group 'verilog-mode-indent
901   :type 'integer)
902 (put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
903
904 (defcustom verilog-auto-input-ignore-regexp nil
905   "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
906 See the \\[verilog-faq] for examples on using this."
907   :group 'verilog-mode-auto
908   :type 'string)
909 (put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
910
911 (defcustom verilog-auto-inout-ignore-regexp nil
912   "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
913 See the \\[verilog-faq] for examples on using this."
914   :group 'verilog-mode-auto
915   :type 'string)
916 (put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
917
918 (defcustom verilog-auto-output-ignore-regexp nil
919   "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
920 See the \\[verilog-faq] for examples on using this."
921   :group 'verilog-mode-auto
922   :type 'string)
923 (put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
924
925 (defcustom verilog-auto-unused-ignore-regexp nil
926   "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
927 See the \\[verilog-faq] for examples on using this."
928   :group 'verilog-mode-auto
929   :type 'string)
930 (put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
931
932 (defcustom verilog-typedef-regexp nil
933   "*If non-nil, regular expression that matches Verilog-2001 typedef names.
934 For example, \"_t$\" matches typedefs named with _t, as in the C language."
935   :group 'verilog-mode-auto
936   :type 'string)
937 (put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
938
939 (defcustom verilog-mode-hook   'verilog-set-compile-command
940   "*Hook run after Verilog mode is loaded."
941   :type 'hook
942   :group 'verilog-mode)
943
944 (defcustom verilog-auto-hook nil
945   "*Hook run after `verilog-mode' updates AUTOs."
946   :group 'verilog-mode-auto
947   :type 'hook)
948
949 (defcustom verilog-before-auto-hook nil
950   "*Hook run before `verilog-mode' updates AUTOs."
951   :group 'verilog-mode-auto
952   :type 'hook)
953
954 (defcustom verilog-delete-auto-hook nil
955   "*Hook run after `verilog-mode' deletes AUTOs."
956   :group 'verilog-mode-auto
957   :type 'hook)
958
959 (defcustom verilog-before-delete-auto-hook nil
960   "*Hook run before `verilog-mode' deletes AUTOs."
961   :group 'verilog-mode-auto
962   :type 'hook)
963
964 (defcustom verilog-getopt-flags-hook nil
965   "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
966   :group 'verilog-mode-auto
967   :type 'hook)
968
969 (defcustom verilog-before-getopt-flags-hook nil
970   "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
971   :group 'verilog-mode-auto
972   :type 'hook)
973
974 (defvar verilog-imenu-generic-expression
975   '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
976     ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
977   "Imenu expression for Verilog mode.  See `imenu-generic-expression'.")
978
979 ;;
980 ;; provide a verilog-header function.
981 ;; Customization variables:
982 ;;
983 (defvar verilog-date-scientific-format nil
984   "*If non-nil, dates are written in scientific format (e.g.  1997/09/17).
985 If nil, in European format (e.g.  17.09.1997).  The brain-dead American
986 format (e.g.  09/17/1997) is not supported.")
987
988 (defvar verilog-company nil
989   "*Default name of Company for Verilog header.
990 If set will become buffer local.")
991 (make-variable-buffer-local 'verilog-company)
992
993 (defvar verilog-project nil
994   "*Default name of Project for Verilog header.
995 If set will become buffer local.")
996 (make-variable-buffer-local 'verilog-project)
997
998 (defvar verilog-mode-map
999   (let ((map (make-sparse-keymap)))
1000     (define-key map ";"        'electric-verilog-semi)
1001     (define-key map [(control 59)]    'electric-verilog-semi-with-comment)
1002     (define-key map ":"        'electric-verilog-colon)
1003     ;;(define-key map "="        'electric-verilog-equal)
1004     (define-key map "\`"       'electric-verilog-tick)
1005     (define-key map "\t"       'electric-verilog-tab)
1006     (define-key map "\r"       'electric-verilog-terminate-line)
1007     ;; backspace/delete key bindings
1008     (define-key map [backspace]    'backward-delete-char-untabify)
1009     (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
1010       (define-key map [delete]       'delete-char)
1011       (define-key map [(meta delete)] 'kill-word))
1012     (define-key map "\M-\C-b"  'electric-verilog-backward-sexp)
1013     (define-key map "\M-\C-f"  'electric-verilog-forward-sexp)
1014     (define-key map "\M-\r"    `electric-verilog-terminate-and-indent)
1015     (define-key map "\M-\t"    'verilog-complete-word)
1016     (define-key map "\M-?"     'verilog-show-completions)
1017     (define-key map "\C-c\`"   'verilog-lint-off)
1018     (define-key map "\C-c\*"   'verilog-delete-auto-star-implicit)
1019     (define-key map "\C-c\C-r" 'verilog-label-be)
1020     (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
1021     (define-key map "\C-c="    'verilog-pretty-expr)
1022     (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
1023     (define-key map "\M-*"     'verilog-star-comment)
1024     (define-key map "\C-c\C-c" 'verilog-comment-region)
1025     (define-key map "\C-c\C-u" 'verilog-uncomment-region)
1026     (when (featurep 'xemacs)
1027       (define-key map [(meta control h)] 'verilog-mark-defun)
1028       (define-key map "\M-\C-a"  'verilog-beg-of-defun)
1029       (define-key map "\M-\C-e"  'verilog-end-of-defun))
1030     (define-key map "\C-c\C-d" 'verilog-goto-defun)
1031     (define-key map "\C-c\C-k" 'verilog-delete-auto)
1032     (define-key map "\C-c\C-a" 'verilog-auto)
1033     (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
1034     (define-key map "\C-c\C-z" 'verilog-inject-auto)
1035     (define-key map "\C-c\C-e" 'verilog-expand-vector)
1036     (define-key map "\C-c\C-h" 'verilog-header)
1037     map)
1038   "Keymap used in Verilog mode.")
1039
1040 ;; menus
1041 (easy-menu-define
1042   verilog-menu verilog-mode-map "Menu for Verilog mode"
1043   (verilog-easy-menu-filter
1044    '("Verilog"
1045      ("Choose Compilation Action"
1046       ["None"
1047        (progn
1048          (setq verilog-tool nil)
1049          (verilog-set-compile-command))
1050        :style radio
1051        :selected (equal verilog-tool nil)
1052        :help "When invoking compilation, use compile-command"]
1053       ["Lint"
1054        (progn
1055          (setq verilog-tool 'verilog-linter)
1056          (verilog-set-compile-command))
1057        :style radio
1058        :selected (equal verilog-tool `verilog-linter)
1059        :help "When invoking compilation, use lint checker"]
1060       ["Coverage"
1061        (progn
1062          (setq verilog-tool 'verilog-coverage)
1063          (verilog-set-compile-command))
1064        :style radio
1065        :selected (equal verilog-tool `verilog-coverage)
1066        :help "When invoking compilation, annotate for coverage"]
1067       ["Simulator"
1068        (progn
1069          (setq verilog-tool 'verilog-simulator)
1070          (verilog-set-compile-command))
1071        :style radio
1072        :selected (equal verilog-tool `verilog-simulator)
1073        :help "When invoking compilation, interpret Verilog source"]
1074       ["Compiler"
1075        (progn
1076          (setq verilog-tool 'verilog-compiler)
1077          (verilog-set-compile-command))
1078        :style radio
1079        :selected (equal verilog-tool `verilog-compiler)
1080        :help "When invoking compilation, compile Verilog source"]
1081       )
1082      ("Move"
1083       ["Beginning of function"          verilog-beg-of-defun
1084        :keys "C-M-a"
1085        :help            "Move backward to the beginning of the current function or procedure"]
1086       ["End of function"                verilog-end-of-defun
1087        :keys "C-M-e"
1088        :help            "Move forward to the end of the current function or procedure"]
1089       ["Mark function"                  verilog-mark-defun
1090        :keys "C-M-h"
1091        :help            "Mark the current Verilog function or procedure"]
1092       ["Goto function/module"           verilog-goto-defun
1093        :help            "Move to specified Verilog module/task/function"]
1094       ["Move to beginning of block"     electric-verilog-backward-sexp
1095        :help            "Move backward over one balanced expression"]
1096       ["Move to end of block"           electric-verilog-forward-sexp
1097        :help            "Move forward over one balanced expression"]
1098       )
1099      ("Comments"
1100       ["Comment Region"                 verilog-comment-region
1101        :help            "Put marked area into a comment"]
1102       ["UnComment Region"               verilog-uncomment-region
1103        :help            "Uncomment an area commented with Comment Region"]
1104       ["Multi-line comment insert"      verilog-star-comment
1105        :help            "Insert Verilog /* */ comment at point"]
1106       ["Lint error to comment"          verilog-lint-off
1107        :help            "Convert a Verilog linter warning line into a disable statement"]
1108       )
1109      "----"
1110      ["Compile"                         compile
1111       :help             "Perform compilation-action (above) on the current buffer"]
1112      ["AUTO, Save, Compile"             verilog-auto-save-compile
1113       :help             "Recompute AUTOs, save buffer, and compile"]
1114      ["Next Compile Error"              next-error
1115       :help             "Visit next compilation error message and corresponding source code"]
1116      ["Ignore Lint Warning at point"    verilog-lint-off
1117       :help             "Convert a Verilog linter warning line into a disable statement"]
1118      "----"
1119      ["Line up declarations around point"       verilog-pretty-declarations
1120       :help             "Line up declarations around point"]
1121      ["Line up equations around point"          verilog-pretty-expr
1122       :help             "Line up expressions around point"]
1123      ["Redo/insert comments on every end"       verilog-label-be
1124       :help             "Label matching begin ... end statements"]
1125      ["Expand [x:y] vector line"        verilog-expand-vector
1126       :help             "Take a signal vector on the current line and expand it to multiple lines"]
1127      ["Insert begin-end block"          verilog-insert-block
1128       :help             "Insert begin ... end"]
1129      ["Complete word"                   verilog-complete-word
1130       :help             "Complete word at point"]
1131      "----"
1132      ["Recompute AUTOs"                 verilog-auto
1133       :help             "Expand AUTO meta-comment statements"]
1134      ["Kill AUTOs"                      verilog-delete-auto
1135       :help             "Remove AUTO expansions"]
1136      ["Inject AUTOs"                    verilog-inject-auto
1137       :help             "Inject AUTOs into legacy non-AUTO buffer"]
1138      ("AUTO Help..."
1139       ["AUTO General"                   (describe-function 'verilog-auto)
1140        :help            "Help introduction on AUTOs"]
1141       ["AUTO Library Flags"             (describe-variable 'verilog-library-flags)
1142        :help            "Help on verilog-library-flags"]
1143       ["AUTO Library Path"              (describe-variable 'verilog-library-directories)
1144        :help            "Help on verilog-library-directories"]
1145       ["AUTO Library Files"             (describe-variable 'verilog-library-files)
1146        :help            "Help on verilog-library-files"]
1147       ["AUTO Library Extensions"        (describe-variable 'verilog-library-extensions)
1148        :help            "Help on verilog-library-extensions"]
1149       ["AUTO `define Reading"           (describe-function 'verilog-read-defines)
1150        :help            "Help on reading `defines"]
1151       ["AUTO `include Reading"          (describe-function 'verilog-read-includes)
1152        :help            "Help on parsing `includes"]
1153       ["AUTOARG"                        (describe-function 'verilog-auto-arg)
1154        :help            "Help on AUTOARG - declaring module port list"]
1155       ["AUTOASCIIENUM"                  (describe-function 'verilog-auto-ascii-enum)
1156        :help            "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
1157       ["AUTOINOUTCOMP"                  (describe-function 'verilog-auto-inout-complement)
1158        :help            "Help on AUTOINOUTCOMP - copying complemented i/o from another file"]
1159       ["AUTOINOUTMODULE"                (describe-function 'verilog-auto-inout-module)
1160        :help            "Help on AUTOINOUTMODULE - copying i/o from another file"]
1161       ["AUTOINOUT"                      (describe-function 'verilog-auto-inout)
1162        :help            "Help on AUTOINOUT - adding inouts from cells"]
1163       ["AUTOINPUT"                      (describe-function 'verilog-auto-input)
1164        :help            "Help on AUTOINPUT - adding inputs from cells"]
1165       ["AUTOINST"                       (describe-function 'verilog-auto-inst)
1166        :help            "Help on AUTOINST - adding pins for cells"]
1167       ["AUTOINST (.*)"                  (describe-function 'verilog-auto-star)
1168        :help            "Help on expanding Verilog-2001 .* pins"]
1169       ["AUTOINSTPARAM"                  (describe-function 'verilog-auto-inst-param)
1170        :help            "Help on AUTOINSTPARAM - adding parameter pins to cells"]
1171       ["AUTOOUTPUT"                     (describe-function 'verilog-auto-output)
1172        :help            "Help on AUTOOUTPUT - adding outputs from cells"]
1173       ["AUTOOUTPUTEVERY"                (describe-function 'verilog-auto-output-every)
1174        :help            "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
1175       ["AUTOREG"                        (describe-function 'verilog-auto-reg)
1176        :help            "Help on AUTOREG - declaring registers for non-wires"]
1177       ["AUTOREGINPUT"                   (describe-function 'verilog-auto-reg-input)
1178        :help            "Help on AUTOREGINPUT - declaring inputs for non-wires"]
1179       ["AUTORESET"                      (describe-function 'verilog-auto-reset)
1180        :help            "Help on AUTORESET - resetting always blocks"]
1181       ["AUTOSENSE"                      (describe-function 'verilog-auto-sense)
1182        :help            "Help on AUTOSENSE - sensitivity lists for always blocks"]
1183       ["AUTOTIEOFF"                     (describe-function 'verilog-auto-tieoff)
1184        :help            "Help on AUTOTIEOFF - tieing off unused outputs"]
1185       ["AUTOUNUSED"                     (describe-function 'verilog-auto-unused)
1186        :help            "Help on AUTOUNUSED - terminating unused inputs"]
1187       ["AUTOWIRE"                       (describe-function 'verilog-auto-wire)
1188        :help            "Help on AUTOWIRE - declaring wires for cells"]
1189       )
1190      "----"
1191      ["Submit bug report"               verilog-submit-bug-report
1192       :help             "Submit via mail a bug report on verilog-mode.el"]
1193      ["Version and FAQ"                 verilog-faq
1194       :help             "Show the current version, and where to get the FAQ etc"]
1195      ["Customize Verilog Mode..."       verilog-customize
1196       :help             "Customize variables and other settings used by Verilog-Mode"]
1197      ["Customize Verilog Fonts & Colors"        verilog-font-customize
1198       :help             "Customize fonts used by Verilog-Mode."])))
1199
1200 (easy-menu-define
1201   verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
1202   (verilog-easy-menu-filter
1203    '("Statements"
1204      ["Header"          verilog-sk-header
1205       :help             "Insert a header block at the top of file"]
1206      ["Comment"         verilog-sk-comment
1207       :help             "Insert a comment block"]
1208      "----"
1209      ["Module"          verilog-sk-module
1210       :help             "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
1211      ["Primitive"       verilog-sk-primitive
1212       :help             "Insert a primitive .. (.. );.. endprimitive block"]
1213      "----"
1214      ["Input"           verilog-sk-input
1215       :help             "Insert an input declaration"]
1216      ["Output"          verilog-sk-output
1217       :help             "Insert an output declaration"]
1218      ["Inout"           verilog-sk-inout
1219       :help             "Insert an inout declaration"]
1220      ["Wire"            verilog-sk-wire
1221       :help             "Insert a wire declaration"]
1222      ["Reg"             verilog-sk-reg
1223       :help             "Insert a register declaration"]
1224      ["Define thing under point as a register" verilog-sk-define-signal
1225       :help             "Define signal under point as a register at the top of the module"]
1226      "----"
1227      ["Initial"         verilog-sk-initial
1228       :help             "Insert an initial begin .. end block"]
1229      ["Always"          verilog-sk-always
1230       :help             "Insert an always @(AS) begin .. end block"]
1231      ["Function"        verilog-sk-function
1232       :help             "Insert a function .. begin .. end endfunction block"]
1233      ["Task"            verilog-sk-task
1234       :help             "Insert a task .. begin .. end endtask block"]
1235      ["Specify"         verilog-sk-specify
1236       :help             "Insert a specify .. endspecify block"]
1237      ["Generate"        verilog-sk-generate
1238       :help             "Insert a generate .. endgenerate block"]
1239      "----"
1240      ["Begin"           verilog-sk-begin
1241       :help             "Insert a begin .. end block"]
1242      ["If"              verilog-sk-if
1243       :help             "Insert an if (..) begin .. end block"]
1244      ["(if) else"       verilog-sk-else-if
1245       :help             "Insert an else if (..) begin .. end block"]
1246      ["For"             verilog-sk-for
1247       :help             "Insert a for (...) begin .. end block"]
1248      ["While"           verilog-sk-while
1249       :help             "Insert a while (...) begin .. end block"]
1250      ["Fork"            verilog-sk-fork
1251       :help             "Insert a fork begin .. end .. join block"]
1252      ["Repeat"          verilog-sk-repeat
1253       :help             "Insert a repeat (..) begin .. end block"]
1254      ["Case"            verilog-sk-case
1255       :help             "Insert a case block, prompting for details"]
1256      ["Casex"           verilog-sk-casex
1257       :help             "Insert a casex (...) item: begin.. end endcase block"]
1258      ["Casez"           verilog-sk-casez
1259       :help             "Insert a casez (...) item: begin.. end endcase block"])))
1260
1261 (defvar verilog-mode-abbrev-table nil
1262   "Abbrev table in use in Verilog-mode buffers.")
1263
1264 (define-abbrev-table 'verilog-mode-abbrev-table ())
1265
1266 ;;
1267 ;;  Macros
1268 ;;
1269
1270 (defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1271   "Replace occurrences of FROM-STRING with TO-STRING.
1272 FIXEDCASE and LITERAL as in `replace-match`.  STRING is what to replace.
1273 The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1274 will break, as the o's continuously replace.  xa -> x works ok though."
1275   ;; Hopefully soon to a emacs built-in
1276   (let ((start 0))
1277     (while (string-match from-string string start)
1278       (setq string (replace-match to-string fixedcase literal string)
1279             start (min (length string) (+ (match-beginning 0) (length to-string)))))
1280     string))
1281
1282 (defsubst verilog-string-remove-spaces (string)
1283   "Remove spaces surrounding STRING."
1284   (save-match-data
1285     (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1286     (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1287     string))
1288
1289 (defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1290   ; checkdoc-params: (REGEXP BOUND NOERROR)
1291   "Like `re-search-forward', but skips over match in comments or strings."
1292   (let ((mdata '(nil nil)))  ;; So match-end will return nil if no matches found
1293     (while (and
1294             (re-search-forward REGEXP BOUND NOERROR)
1295             (setq mdata (match-data))
1296             (and (verilog-skip-forward-comment-or-string)
1297                  (progn
1298                    (setq mdata '(nil nil))
1299                    (if BOUND
1300                        (< (point) BOUND)
1301                      t)))))
1302     (store-match-data mdata)
1303     (match-end 0)))
1304
1305 (defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1306   ; checkdoc-params: (REGEXP BOUND NOERROR)
1307   "Like `re-search-backward', but skips over match in comments or strings."
1308   (let ((mdata '(nil nil)))  ;; So match-end will return nil if no matches found
1309     (while (and
1310             (re-search-backward REGEXP BOUND NOERROR)
1311             (setq mdata (match-data))
1312             (and (verilog-skip-backward-comment-or-string)
1313                  (progn
1314                    (setq mdata '(nil nil))
1315                    (if BOUND
1316                        (> (point) BOUND)
1317                      t)))))
1318     (store-match-data mdata)
1319     (match-end 0)))
1320
1321 (defsubst verilog-re-search-forward-quick (regexp bound noerror)
1322   "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1323 but trashes match data and is faster for REGEXP that doesn't match often.
1324 This may at some point use text properties to ignore comments,
1325 so there may be a large up front penalty for the first search."
1326   (let (pt)
1327     (while (and (not pt)
1328                 (re-search-forward regexp bound noerror))
1329       (if (not (verilog-inside-comment-p))
1330           (setq pt (match-end 0))))
1331     pt))
1332
1333 (defsubst verilog-re-search-backward-quick (regexp bound noerror)
1334   ; checkdoc-params: (REGEXP BOUND NOERROR)
1335   "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1336 but trashes match data and is faster for REGEXP that doesn't match often.
1337 This may at some point use text properties to ignore comments,
1338 so there may be a large up front penalty for the first search."
1339   (let (pt)
1340     (while (and (not pt)
1341                 (re-search-backward regexp bound noerror))
1342       (if (not (verilog-inside-comment-p))
1343           (setq pt (match-end 0))))
1344     pt))
1345
1346 (defsubst verilog-get-beg-of-line (&optional arg)
1347   (save-excursion
1348     (beginning-of-line arg)
1349     (point)))
1350
1351 (defsubst verilog-get-end-of-line (&optional arg)
1352   (save-excursion
1353     (end-of-line arg)
1354     (point)))
1355
1356 (defsubst verilog-within-string ()
1357   (save-excursion
1358     (nth 3 (parse-partial-sexp (verilog-get-beg-of-line) (point)))))
1359
1360 (defvar compile-command)
1361
1362 ;; compilation program
1363 (defun verilog-set-compile-command ()
1364   "Function to compute shell command to compile Verilog.
1365
1366 This reads `verilog-tool' and sets `compile-command'.  This specifies the
1367 program that executes when you type \\[compile] or
1368 \\[verilog-auto-save-compile].
1369
1370 By default `verilog-tool' uses a Makefile if one exists in the current
1371 directory.  If not, it is set to the `verilog-linter', `verilog-coverage',
1372 `verilog-simulator', or `verilog-compiler' variables, as selected with the
1373 Verilog -> \"Choose Compilation Action\" menu.
1374
1375 You should set `verilog-tool' or the other variables to the path and
1376 arguments for your Verilog simulator.  For example:
1377     \"vcs -p123 -O\"
1378 or a string like:
1379     \"(cd /tmp; surecov %s)\".
1380
1381 In the former case, the path to the current buffer is concat'ed to the
1382 value of `verilog-tool'; in the later, the path to the current buffer is
1383 substituted for the %s.
1384
1385 Where __FILE__ appears in the string, the `buffer-file-name' of the
1386 current buffer, without the directory portion, will be substituted."
1387   (interactive)
1388   (cond
1389    ((or (file-exists-p "makefile")      ;If there is a makefile, use it
1390         (file-exists-p "Makefile"))
1391     (make-local-variable 'compile-command)
1392     (setq compile-command "make "))
1393    (t
1394     (make-local-variable 'compile-command)
1395     (setq compile-command
1396           (if verilog-tool
1397               (if (string-match "%s" (eval verilog-tool))
1398                   (format (eval verilog-tool) (or buffer-file-name ""))
1399                 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1400             ""))))
1401   (verilog-modify-compile-command))
1402
1403 (defun verilog-modify-compile-command ()
1404   "Replace meta-information in `compile-command'.
1405 Where __FILE__ appears in the string, the current buffer's file-name,
1406 without the directory portion, will be substituted."
1407   (when (and
1408          (stringp compile-command)
1409          (string-match "\\b__FILE__\\b" compile-command))
1410     (make-local-variable 'compile-command)
1411     (setq compile-command
1412           (verilog-string-replace-matches
1413            "\\b__FILE__\\b" (file-name-nondirectory (buffer-file-name))
1414            t t compile-command))))
1415
1416 ;; Following code only gets called from compilation-mode-hook.
1417 (defvar compilation-error-regexp-alist)
1418
1419 (defun verilog-error-regexp-add ()
1420   "Add the messages to the `compilation-error-regexp-alist'.
1421 Called by `compilation-mode-hook'.  This allows \\[next-error] to
1422 find the errors."
1423   (if (not verilog-error-regexp-add-didit)
1424       (progn
1425         (setq verilog-error-regexp-add-didit t)
1426         (setq-default compilation-error-regexp-alist
1427                       (append verilog-error-regexp
1428                               (default-value 'compilation-error-regexp-alist)))
1429         ;; Could be buffer local at this point; maybe also in let; change all three
1430         (setq compilation-error-regexp-alist
1431               (default-value 'compilation-error-regexp-alist))
1432         (set (make-local-variable 'compilation-error-regexp-alist)
1433              (default-value 'compilation-error-regexp-alist)))))
1434
1435 (add-hook 'compilation-mode-hook 'verilog-error-regexp-add)
1436
1437 (defconst verilog-directive-re
1438   ;; "`case" "`default" "`define" "`define" "`else" "`endfor" "`endif"
1439   ;; "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1440   ;; "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1441   ;; "`time_scale" "`undef" "`while"
1442   "\\<`\\(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\\)\\>")
1443
1444 (defconst verilog-directive-re-1
1445   (concat "[ \t]*"  verilog-directive-re))
1446
1447 (defconst verilog-directive-begin
1448   "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1449
1450 (defconst verilog-directive-middle
1451   "\\<`\\(else\\|default\\|case\\)\\>")
1452
1453 (defconst verilog-directive-end
1454   "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1455
1456 (defconst verilog-ovm-begin-re
1457   (eval-when-compile
1458     (verilog-regexp-opt 
1459      '(
1460        "`ovm_component_utils_begin"
1461        "`ovm_field_utils_begin"
1462        "`ovm_object_utils_begin"
1463        "`ovm_sequence_utils_begin"
1464        "`ovm_sequencer_utils_begin" 
1465        ) nil )))
1466
1467 (defconst verilog-ovm-end-re
1468   (eval-when-compile
1469     (verilog-regexp-opt 
1470      '(
1471        "`ovm_component_utils_end"
1472        "`ovm_field_utils_end"
1473        "`ovm_object_utils_end"
1474        "`ovm_sequence_utils_end"
1475        "`ovm_sequencer_utils_end"
1476        ) nil )))
1477   
1478 (defconst verilog-ovm-statement-re
1479   (eval-when-compile
1480     (verilog-regexp-opt 
1481      '(
1482        ;; Statements
1483        "`DUT_ERROR"
1484        "`MESSAGE"
1485        "`dut_error"
1486        "`message"
1487        "`ovm_analysis_imp_decl"
1488        "`ovm_blocking_get_imp_decl"
1489        "`ovm_blocking_get_peek_imp_decl"
1490        "`ovm_blocking_master_imp_decl"
1491        "`ovm_blocking_peek_imp_decl"
1492        "`ovm_blocking_put_imp_decl"
1493        "`ovm_blocking_slave_imp_decl"
1494        "`ovm_blocking_transport_imp_decl"
1495        "`ovm_component_registry"
1496        "`ovm_component_registry_param"
1497        "`ovm_component_utils"
1498        "`ovm_create"
1499        "`ovm_create_seq"
1500        "`ovm_declare_sequence_lib"
1501        "`ovm_do"
1502        "`ovm_do_seq"
1503        "`ovm_do_seq_with"
1504        "`ovm_do_with"
1505        "`ovm_error"
1506        "`ovm_fatal"
1507        "`ovm_field_aa_int_byte"
1508        "`ovm_field_aa_int_byte_unsigned"
1509        "`ovm_field_aa_int_int"
1510        "`ovm_field_aa_int_int_unsigned"
1511        "`ovm_field_aa_int_integer"
1512        "`ovm_field_aa_int_integer_unsigned"
1513        "`ovm_field_aa_int_key"
1514        "`ovm_field_aa_int_longint"
1515        "`ovm_field_aa_int_longint_unsigned"
1516        "`ovm_field_aa_int_shortint"
1517        "`ovm_field_aa_int_shortint_unsigned"
1518        "`ovm_field_aa_int_string"
1519        "`ovm_field_aa_object_int"
1520        "`ovm_field_aa_object_string"
1521        "`ovm_field_aa_string_int"
1522        "`ovm_field_aa_string_string"
1523        "`ovm_field_array_int"
1524        "`ovm_field_array_object"
1525        "`ovm_field_array_string"
1526        "`ovm_field_enum"
1527        "`ovm_field_event"
1528        "`ovm_field_int"
1529        "`ovm_field_object"
1530        "`ovm_field_queue_int"
1531        "`ovm_field_queue_object"
1532        "`ovm_field_queue_string"
1533        "`ovm_field_sarray_int"
1534        "`ovm_field_string"
1535        "`ovm_field_utils"
1536        "`ovm_file"
1537        "`ovm_get_imp_decl"
1538        "`ovm_get_peek_imp_decl"
1539        "`ovm_info"
1540        "`ovm_info1"
1541        "`ovm_info2"
1542        "`ovm_info3"
1543        "`ovm_info4"
1544        "`ovm_line"
1545        "`ovm_master_imp_decl"
1546        "`ovm_msg_detail"
1547        "`ovm_non_blocking_transport_imp_decl"
1548        "`ovm_nonblocking_get_imp_decl"
1549        "`ovm_nonblocking_get_peek_imp_decl"
1550        "`ovm_nonblocking_master_imp_decl"
1551        "`ovm_nonblocking_peek_imp_decl"
1552        "`ovm_nonblocking_put_imp_decl"
1553        "`ovm_nonblocking_slave_imp_decl"
1554        "`ovm_object_registry"
1555        "`ovm_object_registry_param"
1556        "`ovm_object_utils"
1557        "`ovm_peek_imp_decl"
1558        "`ovm_phase_func_decl"
1559        "`ovm_phase_task_decl"
1560        "`ovm_print_aa_int_object"
1561        "`ovm_print_aa_string_int"
1562        "`ovm_print_aa_string_object"
1563        "`ovm_print_aa_string_string"
1564        "`ovm_print_array_int"
1565        "`ovm_print_array_object"
1566        "`ovm_print_array_string"
1567        "`ovm_print_object_queue"
1568        "`ovm_print_queue_int"
1569        "`ovm_print_string_queue"
1570        "`ovm_put_imp_decl"
1571        "`ovm_rand_send"
1572        "`ovm_rand_send_with"
1573        "`ovm_send"
1574        "`ovm_sequence_utils"
1575        "`ovm_slave_imp_decl"
1576        "`ovm_transport_imp_decl"
1577        "`ovm_update_sequence_lib"
1578        "`ovm_update_sequence_lib_and_item"
1579        "`ovm_warning"
1580        "`static_dut_error"
1581        "`static_message") nil )))
1582
1583
1584 ;;
1585 ;; Regular expressions used to calculate indent, etc.
1586 ;;
1587 (defconst verilog-symbol-re      "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
1588 (defconst verilog-case-re        "\\(\\<case[xz]?\\>\\|\\<randcase\\>\\)")
1589 ;; Want to match
1590 ;; aa :
1591 ;; aa,bb :
1592 ;; a[34:32] :
1593 ;; a,
1594 ;;   b :
1595
1596 (defconst verilog-no-indent-begin-re
1597   "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
1598
1599 (defconst verilog-ends-re
1600   ;; Parenthesis indicate type of keyword found
1601   (concat
1602    "\\(\\<else\\>\\)\\|"                ; 1
1603    "\\(\\<if\\>\\)\\|"                  ; 2
1604    "\\(\\<end\\>\\)\\|"                 ; 3
1605    "\\(\\<endcase\\>\\)\\|"             ; 4
1606    "\\(\\<endfunction\\>\\)\\|"         ; 5
1607    "\\(\\<endtask\\>\\)\\|"             ; 6
1608    "\\(\\<endspecify\\>\\)\\|"          ; 7
1609    "\\(\\<endtable\\>\\)\\|"            ; 8
1610    "\\(\\<endgenerate\\>\\)\\|"         ; 9
1611    "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
1612    "\\(\\<endclass\\>\\)\\|"            ; 11
1613    "\\(\\<endgroup\\>\\)\\|"            ; 12
1614    ;; OVM
1615    "\\(\\<`ovm_component_utils_end\\>\\)\\|"
1616    "\\(\\<`ovm_field_utils_end\\>\\)\\|"
1617    "\\(\\<`ovm_object_utils_end\\>\\)\\|"
1618    "\\(\\<`ovm_sequence_utils_end\\>\\)\\|"
1619    "\\(\\<`ovm_sequencer_utils_end\\>\\)"
1620
1621    ))
1622
1623 (defconst verilog-auto-end-comment-lines-re
1624   ;; Matches to names in this list cause auto-end-commentation
1625   (concat "\\("
1626           verilog-directive-re "\\)\\|\\("
1627           (eval-when-compile
1628             (verilog-regexp-words
1629              `( "begin"
1630                 "else"
1631                 "end"
1632                 "endcase"
1633                 "endclass"
1634                 "endclocking"
1635                 "endgroup"
1636                 "endfunction"
1637                 "endmodule"
1638                 "endprogram"
1639                 "endprimitive"
1640                 "endinterface"
1641                 "endpackage"
1642                 "endsequence"
1643                 "endspecify"
1644                 "endtable"
1645                 "endtask"
1646                 "join"
1647                 "join_any"
1648                 "join_none"
1649                 "module"
1650                 "macromodule"
1651                 "primitive"
1652                 "interface"
1653                 "package")))
1654           "\\)"))
1655
1656 ;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
1657 ;;; verilog-end-block-ordered-re matches exactly the same strings.
1658 (defconst verilog-end-block-ordered-re
1659   ;; Parenthesis indicate type of keyword found
1660   (concat "\\(\\<endcase\\>\\)\\|" ; 1
1661           "\\(\\<end\\>\\)\\|"     ; 2
1662           "\\(\\<end"              ; 3, but not used
1663           "\\("                    ; 4, but not used
1664           "\\(function\\)\\|"      ; 5
1665           "\\(task\\)\\|"          ; 6
1666           "\\(module\\)\\|"        ; 7
1667           "\\(primitive\\)\\|"     ; 8
1668           "\\(interface\\)\\|"     ; 9
1669           "\\(package\\)\\|"       ; 10
1670           "\\(class\\)\\|"         ; 11
1671           "\\(group\\)\\|"         ; 12
1672           "\\(program\\)\\|"       ; 13
1673           "\\(sequence\\)\\|"      ; 14
1674           "\\(clocking\\)\\|"      ; 15
1675           "\\)\\>\\)"))
1676 (defconst verilog-end-block-re
1677   (eval-when-compile
1678     (verilog-regexp-words
1679
1680      `("end"  ;; closes begin
1681        "endcase" ;; closes any of case, casex casez or randcase
1682        "join" "join_any" "join_none" ;; closes fork
1683        "endclass"
1684        "endtable"
1685        "endspecify"
1686        "endfunction"
1687        "endgenerate"
1688        "endtask"
1689        "endgroup"
1690        "endproperty"
1691        "endinterface"
1692        "endpackage"
1693        "endprogram"
1694        "endsequence"
1695        "endclocking"
1696        ;; OVM
1697        "`ovm_component_utils_end"
1698        "`ovm_field_utils_end"
1699        "`ovm_object_utils_end"
1700        "`ovm_sequence_utils_end"
1701        "`ovm_sequencer_utils_end"
1702
1703        ))))
1704
1705
1706 (defconst verilog-endcomment-reason-re
1707   ;; Parenthesis indicate type of keyword found
1708   (concat
1709    "\\(\\<fork\\>\\)\\|"
1710    "\\(\\<begin\\>\\)\\|"
1711    "\\(\\<if\\>\\)\\|"
1712    "\\(\\<clocking\\>\\)\\|"
1713    "\\(\\<else\\>\\)\\|"
1714    "\\(\\<end\\>.*\\<else\\>\\)\\|"
1715    "\\(\\<task\\>\\)\\|"
1716    "\\(\\<function\\>\\)\\|"
1717    "\\(\\<initial\\>\\)\\|"
1718    "\\(\\<interface\\>\\)\\|"
1719    "\\(\\<package\\>\\)\\|"
1720    "\\(\\<final\\>\\)\\|"
1721    "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
1722    "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|"
1723    "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|"
1724    "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|"
1725    "\\(@\\)\\|"
1726    "\\(\\<while\\>\\)\\|"
1727    "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
1728    "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
1729    "#"))
1730
1731 (defconst verilog-named-block-re  "begin[ \t]*:")
1732
1733 ;; These words begin a block which can occur inside a module which should be indented,
1734 ;; and closed with the respective word from the end-block list
1735
1736 (defconst verilog-beg-block-re
1737   (eval-when-compile
1738     (verilog-regexp-words
1739      `("begin"
1740        "case" "casex" "casez" "randcase"
1741        "clocking"
1742        "generate"
1743        "fork"
1744        "function"
1745        "property"
1746        "specify"
1747        "table"
1748        "task"
1749        ;;; OVM 
1750        "`ovm_component_utils_begin"
1751        "`ovm_field_utils_begin"
1752        "`ovm_object_utils_begin"
1753        "`ovm_sequence_utils_begin"
1754        "`ovm_sequencer_utils_begin"
1755
1756        ))))
1757 ;; These are the same words, in a specific order in the regular
1758 ;; expression so that matching will work nicely for
1759 ;; verilog-forward-sexp and verilog-calc-indent
1760 (defconst verilog-beg-block-re-ordered
1761   ( concat "\\(\\<begin\\>\\)"          ;1
1762            "\\|\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
1763            "\\|\\(\\(\\<disable\\>\\s-+\\)?fork\\>\\)" ;4,5
1764            "\\|\\(\\<class\\>\\)"               ;6
1765            "\\|\\(\\<table\\>\\)"               ;7
1766            "\\|\\(\\<specify\\>\\)"             ;8
1767            "\\|\\(\\<function\\>\\)"            ;9
1768            "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<function\\>\\)"        ;10
1769            "\\|\\(\\<task\\>\\)"                ;14
1770            "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)"    ;15
1771            "\\|\\(\\<generate\\>\\)"            ;18
1772            "\\|\\(\\<covergroup\\>\\)"  ;16 20
1773            "\\|\\(\\(\\(\\<cover\\>\\s-+\\)\\|\\(\\<assert\\>\\s-+\\)\\)*\\<property\\>\\)"     ;17 21
1774            "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;21 25
1775            "\\|\\(\\<clocking\\>\\)"          ;22 27
1776            "\\|\\(\\<`ovm_[a-z_]+_begin\\>\\)" ;28
1777            ;;
1778            
1779            ))
1780
1781 (defconst verilog-end-block-ordered-rry
1782   [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1783     "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
1784     "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1785     "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
1786     "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
1787     "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
1788     "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
1789     "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
1790     "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
1791     "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
1792     "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
1793     "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
1794     "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
1795     ] )
1796
1797 (defconst verilog-nameable-item-re
1798   (eval-when-compile
1799     (verilog-regexp-words
1800      `("begin"
1801        "fork"
1802        "join" "join_any" "join_none"
1803        "end"
1804        "endcase"
1805        "endconfig"
1806        "endclass"
1807        "endclocking"
1808        "endfunction"
1809        "endgenerate"
1810        "endmodule"
1811        "endprimative"
1812        "endinterface"
1813        "endpackage"
1814        "endspecify"
1815        "endtable"
1816        "endtask" )
1817      )))
1818
1819 (defconst verilog-declaration-opener
1820   (eval-when-compile
1821     (verilog-regexp-words
1822      `("module" "begin" "task" "function"))))
1823
1824 (defconst verilog-declaration-prefix-re
1825   (eval-when-compile
1826     (verilog-regexp-words
1827      `(
1828        ;; port direction
1829        "inout" "input" "output" "ref"
1830        ;; changeableness
1831        "const" "static" "protected" "local"
1832        ;; parameters
1833        "localparam" "parameter" "var"
1834        ;; type creation
1835        "typedef"
1836        ))))
1837 (defconst verilog-declaration-core-re
1838   (eval-when-compile
1839     (verilog-regexp-words
1840      `(
1841        ;; port direction (by themselves)
1842        "inout" "input" "output"
1843        ;; integer_atom_type
1844        "byte" "shortint" "int" "longint" "integer" "time"
1845        ;; integer_vector_type
1846        "bit" "logic" "reg"
1847        ;; non_integer_type
1848        "shortreal" "real" "realtime"
1849        ;; net_type
1850        "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
1851        ;; misc
1852        "string" "event" "chandle" "virtual" "enum" "genvar"
1853        "struct" "union"
1854        ;; builtin classes
1855        "mailbox" "semaphore"
1856        ))))
1857 (defconst verilog-declaration-re
1858   (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
1859 (defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
1860 (defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
1861 (defconst verilog-optional-signed-range-re
1862   (concat
1863    "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
1864 (defconst verilog-macroexp-re "`\\sw+")
1865
1866 (defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
1867 (defconst verilog-declaration-re-2-no-macro
1868   (concat "\\s-*" verilog-declaration-re
1869           "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1870           "\\)?"))
1871 (defconst verilog-declaration-re-2-macro
1872   (concat "\\s-*" verilog-declaration-re
1873           "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1874           "\\|\\(" verilog-macroexp-re "\\)"
1875           "\\)?"))
1876 (defconst verilog-declaration-re-1-macro
1877   (concat "^" verilog-declaration-re-2-macro))
1878
1879 (defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
1880
1881 (defconst verilog-defun-re
1882   (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
1883 (defconst verilog-end-defun-re
1884   (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
1885 (defconst verilog-zero-indent-re
1886   (concat verilog-defun-re "\\|" verilog-end-defun-re))
1887 (defconst verilog-directive-re
1888   ;; "`case" "`default" "`define" "`define" "`else" "`endfor" "`endif"
1889   ;; "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1890   ;; "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1891   ;; "`time_scale" "`undef" "`while"
1892   "\\<`\\(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\\)\\>")
1893
1894 (defconst verilog-directive-begin
1895   "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1896
1897 (defconst verilog-directive-middle
1898   "\\<`\\(else\\|default\\|case\\)\\>")
1899
1900 (defconst verilog-directive-end
1901   "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1902
1903 (defconst verilog-directive-re-1
1904   (concat "[ \t]*"  verilog-directive-re))
1905
1906 (defconst verilog-autoindent-lines-re
1907   ;; "macromodule" "module" "primitive" "end" "endcase" "endfunction"
1908   ;; "endtask" "endmodule" "endprimitive" "endspecify" "endtable" "join"
1909   ;; "begin" "else" "`else" "`ifdef" "`endif" "`define" "`undef" "`include"
1910   (concat "\\("
1911           verilog-directive-re
1912           "\\|\\(\\<begin\\>\\|e\\(lse\\>\\|nd\\(\\>\\|case\\>\\|function\\>\\|module\\>\\|primitive\\>\\|specify\\>\\|ta\\(ble\\>\\|sk\\>\\)\\)\\)\\|join\\>\\|m\\(acromodule\\>\\|odule\\>\\)\\|primitive\\>\\)\\)" ))
1913
1914 (defconst verilog-behavioral-block-beg-re
1915   (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
1916                                              "function" "task"))))
1917 (defconst verilog-coverpoint-re "\\w+\\s*:\\s*\\(coverpoint\\|cross\\constraint\\)"  )
1918 (defconst verilog-indent-re
1919   (eval-when-compile
1920     (verilog-regexp-words
1921      `(
1922        "{"
1923        "always" "always_latch" "always_ff" "always_comb"
1924        "begin" "end"
1925 ;       "unique" "priority"
1926        "case" "casex" "casez" "randcase" "endcase"
1927        "class" "endclass"
1928        "clocking" "endclocking"
1929        "config" "endconfig"
1930        "covergroup" "endgroup"
1931        "fork" "join" "join_any" "join_none"
1932        "function" "endfunction"
1933        "final"
1934        "generate" "endgenerate"
1935        "initial"
1936        "interface" "endinterface"
1937        "module" "macromodule" "endmodule"
1938        "package" "endpackage"
1939        "primitive" "endprimative"
1940        "program" "endprogram"
1941        "property" "endproperty"
1942        "sequence" "randsequence" "endsequence"
1943        "specify" "endspecify"
1944        "table" "endtable"
1945        "task" "endtask"
1946        "virtual"
1947        "`case"
1948        "`default"
1949        "`define" "`undef"
1950        "`if" "`ifdef" "`ifndef" "`else" "`endif"
1951        "`while" "`endwhile"
1952        "`for" "`endfor"
1953        "`format"
1954        "`include"
1955        "`let"
1956        "`protect" "`endprotect"
1957        "`switch" "`endswitch"
1958        "`timescale"
1959        "`time_scale"
1960        ;; OVM Begin tokens
1961        "`ovm_component_utils_begin"
1962        "`ovm_field_utils_begin"
1963        "`ovm_object_utils_begin"
1964        "`ovm_sequence_utils_begin"
1965        "`ovm_sequencer_utils_begin" 
1966        ;; OVM End tokens
1967        "`ovm_component_utils_end"
1968        "`ovm_field_utils_end"
1969        "`ovm_object_utils_end"
1970        "`ovm_sequence_utils_end"
1971        "`ovm_sequencer_utils_end"
1972        ))))
1973
1974 (defconst verilog-defun-level-not-generate-re
1975   (eval-when-compile
1976     (verilog-regexp-words 
1977      `( "module" "macromodule" "primitive" "class" "program"
1978         "interface" "package" "config"))))
1979
1980 (defconst verilog-defun-level-re
1981   (eval-when-compile
1982     (verilog-regexp-words 
1983      (append 
1984       `( "module" "macromodule" "primitive" "class" "program"
1985          "interface" "package" "config")
1986       `( "initial" "final" "always" "always_comb" "always_ff"
1987          "always_latch" "endtask" "endfunction" )))))
1988
1989 (defconst verilog-defun-level-generate-only-re
1990   (eval-when-compile
1991     (verilog-regexp-words 
1992      `( "initial" "final" "always" "always_comb" "always_ff"
1993         "always_latch" "endtask" "endfunction" ))))
1994
1995 (defconst verilog-cpp-level-re
1996   (eval-when-compile
1997     (verilog-regexp-words
1998      `(
1999        "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
2000        ))))
2001 (defconst verilog-disable-fork-re "disable\\s-+fork")
2002 (defconst verilog-extended-case-re "\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?")
2003 (defconst verilog-extended-complete-re
2004   (concat "\\(\\<extern\\s-+\\|\\<virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)"
2005           "\\|\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)"
2006           "\\|" verilog-extended-case-re ))
2007 (defconst verilog-basic-complete-re
2008   (eval-when-compile
2009     (verilog-regexp-words
2010      `(
2011        "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
2012        "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
2013        "if" "for" "forever" "foreach" "else" "parameter" "do"
2014        ))))
2015 (defconst verilog-complete-reg
2016   (concat
2017    verilog-extended-complete-re
2018    "\\|"
2019    verilog-basic-complete-re))
2020
2021 (defconst verilog-end-statement-re
2022   (concat "\\(" verilog-beg-block-re "\\)\\|\\("
2023           verilog-end-block-re "\\)"))
2024
2025 (defconst verilog-endcase-re
2026   (concat verilog-case-re "\\|"
2027           "\\(endcase\\)\\|"
2028           verilog-defun-re
2029           ))
2030
2031 (defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
2032   "String used to mark beginning of excluded text.")
2033 (defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
2034   "String used to mark end of excluded text.")
2035 (defconst verilog-preprocessor-re
2036   (eval-when-compile
2037     (verilog-regexp-words
2038      `(
2039        "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
2040        ))))
2041
2042 (defconst verilog-keywords
2043   '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
2044      "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
2045      "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
2046      "`time_scale" "`undef" "`while"
2047
2048      "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
2049      "assert" "assign" "assume" "automatic" "before" "begin" "bind"
2050      "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
2051      "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
2052      "config" "const" "constraint" "context" "continue" "cover"
2053      "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
2054      "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
2055      "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
2056      "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
2057      "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
2058      "endtask" "enum" "event" "expect" "export" "extends" "extern"
2059      "final" "first_match" "for" "force" "foreach" "forever" "fork"
2060      "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
2061      "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
2062      "include" "initial" "inout" "input" "inside" "instance" "int"
2063      "integer" "interface" "intersect" "join" "join_any" "join_none"
2064      "large" "liblist" "library" "local" "localparam" "logic"
2065      "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
2066      "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
2067      "notif0" "notif1" "null" "or" "output" "package" "packed"
2068      "parameter" "pmos" "posedge" "primitive" "priority" "program"
2069      "property" "protected" "pull0" "pull1" "pulldown" "pullup"
2070      "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2071      "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
2072      "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
2073      "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
2074      "showcancelled" "signed" "small" "solve" "specify" "specparam"
2075      "static" "string" "strong0" "strong1" "struct" "super" "supply0"
2076      "supply1" "table" "tagged" "task" "this" "throughout" "time"
2077      "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
2078      "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
2079      "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
2080      "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
2081      "wire" "with" "within" "wor" "xnor" "xor"
2082  )
2083  "List of Verilog keywords.")
2084
2085 (defconst verilog-comment-start-regexp "//\\|/\\*"
2086   "Dual comment value for `comment-start-regexp'.")
2087
2088 (defvar verilog-mode-syntax-table
2089   (let ((table (make-syntax-table)))
2090     ;; Populate the syntax TABLE.
2091     (modify-syntax-entry ?\\ "\\" table)
2092     (modify-syntax-entry ?+ "." table)
2093     (modify-syntax-entry ?- "." table)
2094     (modify-syntax-entry ?= "." table)
2095     (modify-syntax-entry ?% "." table)
2096     (modify-syntax-entry ?< "." table)
2097     (modify-syntax-entry ?> "." table)
2098     (modify-syntax-entry ?& "." table)
2099     (modify-syntax-entry ?| "." table)
2100     (modify-syntax-entry ?` "w" table)
2101     (modify-syntax-entry ?_ "w" table)
2102     (modify-syntax-entry ?\' "." table)
2103
2104     ;; Set up TABLE to handle block and line style comments.
2105     (if (featurep 'xemacs)
2106         (progn
2107           ;; XEmacs (formerly Lucid) has the best implementation
2108           (modify-syntax-entry ?/  ". 1456" table)
2109           (modify-syntax-entry ?*  ". 23"   table)
2110           (modify-syntax-entry ?\n "> b"    table))
2111       ;; Emacs does things differently, but we can work with it
2112       (modify-syntax-entry ?/  ". 124b" table)
2113       (modify-syntax-entry ?*  ". 23"   table)
2114       (modify-syntax-entry ?\n "> b"    table))
2115     table)
2116   "Syntax table used in Verilog mode buffers.")
2117
2118 (defvar verilog-font-lock-keywords nil
2119   "Default highlighting for Verilog mode.")
2120
2121 (defvar verilog-font-lock-keywords-1 nil
2122   "Subdued level highlighting for Verilog mode.")
2123
2124 (defvar verilog-font-lock-keywords-2 nil
2125   "Medium level highlighting for Verilog mode.
2126 See also `verilog-font-lock-extra-types'.")
2127
2128 (defvar verilog-font-lock-keywords-3 nil
2129   "Gaudy level highlighting for Verilog mode.
2130 See also `verilog-font-lock-extra-types'.")
2131 (defvar  verilog-font-lock-translate-off-face
2132   'verilog-font-lock-translate-off-face
2133   "Font to use for translated off regions.")
2134 (defface verilog-font-lock-translate-off-face
2135   '((((class color)
2136       (background light))
2137      (:background "gray90" :italic t ))
2138     (((class color)
2139       (background dark))
2140      (:background "gray10" :italic t ))
2141     (((class grayscale) (background light))
2142      (:foreground "DimGray" :italic t))
2143     (((class grayscale) (background dark))
2144      (:foreground "LightGray" :italic t))
2145     (t (:italis t)))
2146   "Font lock mode face used to background highlight translate-off regions."
2147   :group 'font-lock-highlighting-faces)
2148
2149 (defvar verilog-font-lock-p1800-face
2150   'verilog-font-lock-p1800-face
2151   "Font to use for p1800 keywords.")
2152 (defface verilog-font-lock-p1800-face
2153   '((((class color)
2154       (background light))
2155      (:foreground "DarkOrange3" :bold t ))
2156     (((class color)
2157       (background dark))
2158      (:foreground "orange1" :bold t ))
2159     (t (:italic t)))
2160   "Font lock mode face used to highlight P1800 keywords."
2161   :group 'font-lock-highlighting-faces)
2162
2163 (defvar verilog-font-lock-ams-face
2164   'verilog-font-lock-ams-face
2165   "Font to use for Analog/Mixed Signal keywords.")
2166 (defface verilog-font-lock-ams-face
2167   '((((class color)
2168       (background light))
2169      (:foreground "Purple" :bold t ))
2170     (((class color)
2171       (background dark))
2172      (:foreground "orange1" :bold t ))
2173     (t (:italic t)))
2174   "Font lock mode face used to highlight AMS keywords."
2175   :group 'font-lock-highlighting-faces)
2176
2177 (defvar verilog-font-grouping-keywords-face
2178   'verilog-font-lock-grouping-keywords-face
2179   "Font to use for Verilog Grouping Keywords (such as begin..end).")
2180 (defface verilog-font-lock-grouping-keywords-face
2181   '((((class color)
2182       (background light))
2183      (:foreground "red4" :bold t ))
2184     (((class color)
2185       (background dark))
2186      (:foreground "red4" :bold t ))
2187     (t (:italic t)))
2188   "Font lock mode face used to highlight verilog grouping keywords."
2189   :group 'font-lock-highlighting-faces)
2190
2191 (let* ((verilog-type-font-keywords
2192         (eval-when-compile
2193           (verilog-regexp-opt
2194            '(
2195              "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
2196              "event" "genvar" "inout" "input" "integer" "localparam"
2197              "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
2198              "output" "parameter" "pmos" "pull0" "pull1" "pullup"
2199              "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
2200              "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
2201              "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
2202              "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
2203              "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
2204              ) nil  )))
2205
2206        (verilog-pragma-keywords
2207         (eval-when-compile
2208           (verilog-regexp-opt
2209            '("surefire" "synopsys" "rtl_synthesis" "verilint" "leda" "0in") nil
2210             )))
2211
2212        (verilog-p1800-keywords
2213         (eval-when-compile
2214           (verilog-regexp-opt
2215            '("alias" "assert" "assume" "automatic" "before" "bind"
2216              "bins" "binsof" "break" "byte" "cell" "chandle" "class"
2217              "clocking" "config" "const" "constraint" "context" "continue"
2218              "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
2219              "dist" "do" "edge" "endclass" "endclocking" "endconfig"
2220              "endgroup" "endprogram" "endproperty" "endsequence" "enum"
2221              "expect" "export" "extends" "extern" "first_match" "foreach"
2222              "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
2223              "illegal_bins" "import" "incdir" "include" "inside" "instance"
2224              "int" "intersect" "large" "liblist" "library" "local" "longint"
2225              "matches" "medium" "modport" "new" "noshowcancelled" "null"
2226              "packed" "program" "property" "protected" "pull0" "pull1"
2227              "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2228              "randcase" "randsequence" "ref" "release" "return" "scalared"
2229              "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
2230              "specparam" "static" "string" "strong0" "strong1" "struct"
2231              "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
2232              "type" "union" "unsigned" "use" "var" "virtual" "void"
2233              "wait_order" "weak0" "weak1" "wildcard" "with" "within"
2234              ) nil )))
2235
2236        (verilog-ams-keywords
2237         (eval-when-compile
2238           (verilog-regexp-opt
2239            '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
2240              "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
2241              "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
2242              "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
2243              "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
2244              "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
2245              "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
2246              "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
2247              "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
2248              "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
2249              "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
2250
2251        (verilog-font-keywords
2252         (eval-when-compile
2253           (verilog-regexp-opt
2254            '(
2255              "assign" "case" "casex" "casez" "randcase" "deassign"
2256              "default" "disable" "else" "endcase" "endfunction"
2257              "endgenerate" "endinterface" "endmodule" "endprimitive"
2258              "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
2259              "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
2260              "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
2261              "package" "endpackage" "always" "always_comb" "always_ff"
2262              "always_latch" "posedge" "primitive" "priority" "release"
2263              "repeat" "specify" "table" "task" "unique" "wait" "while"
2264              "class" "program" "endclass" "endprogram"
2265              ) nil  )))
2266
2267        (verilog-font-grouping-keywords
2268         (eval-when-compile
2269           (verilog-regexp-opt
2270            '( "begin" "end" ) nil  ))))
2271
2272   (setq verilog-font-lock-keywords
2273         (list
2274          ;; Fontify all builtin keywords
2275          (concat "\\<\\(" verilog-font-keywords "\\|"
2276                        ;; And user/system tasks and functions
2277               "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
2278               "\\)\\>")
2279          ;; Fontify all types
2280          (if verilog-highlight-grouping-keywords
2281              (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2282                    'verilog-font-lock-ams-face)
2283            (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2284                  'font-lock-type-face))
2285          (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
2286           'font-lock-type-face)
2287          ;; Fontify IEEE-P1800 keywords appropriately
2288          (if verilog-highlight-p1800-keywords
2289              (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
2290                    'verilog-font-lock-p1800-face)
2291            (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
2292                  'font-lock-type-face))
2293          ;; Fontify Verilog-AMS keywords
2294          (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
2295                'verilog-font-lock-ams-face)))
2296
2297   (setq verilog-font-lock-keywords-1
2298         (append verilog-font-lock-keywords
2299                 (list
2300                  ;; Fontify module definitions
2301                  (list
2302                   "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
2303                   '(1 font-lock-keyword-face)
2304                   '(3 font-lock-function-name-face 'prepend))
2305                  ;; Fontify function definitions
2306                  (list
2307                   (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
2308                        '(1 font-lock-keyword-face)
2309                        '(3 font-lock-reference-face prepend))
2310                  '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
2311                    (1 font-lock-keyword-face)
2312                    (2 font-lock-reference-face append))
2313                  '("\\<function\\>\\s-+\\(\\sw+\\)"
2314                    1 'font-lock-reference-face append))))
2315
2316   (setq verilog-font-lock-keywords-2
2317         (append verilog-font-lock-keywords-1
2318                 (list
2319                  ;; Fontify pragmas
2320                  (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
2321                  ;; Fontify escaped names
2322                  '("\\(\\\\\\S-*\\s-\\)"  0 font-lock-function-name-face)
2323                  ;; Fontify macro definitions/ uses
2324                  '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
2325                                                        'font-lock-preprocessor-face
2326                                                      'font-lock-type-face))
2327                  ;; Fontify delays/numbers
2328                  '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
2329                    0 font-lock-type-face append)
2330                  ;; Fontify instantiation names
2331                  '("\\([A-Za-z][A-Za-z0-9_]+\\)\\s-*(" 1 font-lock-function-name-face)
2332                  )))
2333
2334   (setq verilog-font-lock-keywords-3
2335         (append verilog-font-lock-keywords-2
2336                 (when verilog-highlight-translate-off
2337                   (list
2338                    ;; Fontify things in translate off regions
2339                    '(verilog-match-translate-off
2340                      (0 'verilog-font-lock-translate-off-face prepend))
2341                    )))))
2342
2343
2344 (defun verilog-inside-comment-p ()
2345   "Check if point inside a nested comment."
2346   (save-excursion
2347     (let ((st-point (point)) hitbeg)
2348       (or (search-backward "//" (verilog-get-beg-of-line) t)
2349           (if (progn
2350                 ;; This is for tricky case //*, we keep searching if /*
2351                 ;; is proceeded by // on same line.
2352                 (while
2353                     (and (setq hitbeg (search-backward "/*" nil t))
2354                          (progn
2355                            (forward-char 1)
2356                            (search-backward "//" (verilog-get-beg-of-line) t))))
2357                 hitbeg)
2358               (not (search-forward "*/" st-point t)))))))
2359
2360 (defun verilog-declaration-end ()
2361   (search-forward ";"))
2362
2363 (defun verilog-point-text (&optional pointnum)
2364   "Return text describing where POINTNUM or current point is (for errors).
2365 Use filename, if current buffer being edited shorten to just buffer name."
2366   (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
2367                    (buffer-name))
2368               buffer-file-name
2369               (buffer-name))
2370           ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
2371
2372 (defun electric-verilog-backward-sexp ()
2373   "Move backward over one balanced expression."
2374   (interactive)
2375   ;; before that see if we are in a comment
2376   (verilog-backward-sexp))
2377
2378 (defun electric-verilog-forward-sexp ()
2379   "Move forward over one balanced expression."
2380   (interactive)
2381   ;; before that see if we are in a comment
2382   (verilog-forward-sexp))
2383
2384 ;;;used by hs-minor-mode
2385 (defun verilog-forward-sexp-function (arg)
2386   (if (< arg 0)
2387       (verilog-backward-sexp)
2388     (verilog-forward-sexp)))
2389
2390
2391 (defun verilog-backward-sexp ()
2392   (let ((reg)
2393         (elsec 1)
2394         (found nil)
2395         (st (point)))
2396     (if (not (looking-at "\\<"))
2397         (forward-word -1))
2398     (cond
2399      ((verilog-skip-backward-comment-or-string))
2400      ((looking-at "\\<else\\>")
2401       (setq reg (concat
2402                  verilog-end-block-re
2403                  "\\|\\(\\<else\\>\\)"
2404                  "\\|\\(\\<if\\>\\)"))
2405       (while (and (not found)
2406                   (verilog-re-search-backward reg nil 'move))
2407         (cond
2408          ((match-end 1) ; matched verilog-end-block-re
2409         ; try to leap back to matching outward block by striding across
2410         ; indent level changing tokens then immediately
2411         ; previous line governs indentation.
2412           (verilog-leap-to-head))
2413          ((match-end 2) ; else, we're in deep
2414           (setq elsec (1+ elsec)))
2415          ((match-end 3) ; found it
2416           (setq elsec (1- elsec))
2417           (if (= 0 elsec)
2418               ;; Now previous line describes syntax
2419               (setq found 't))))))
2420      ((looking-at verilog-end-block-re)
2421       (verilog-leap-to-head))
2422      ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
2423       (cond
2424        ((match-end 1)
2425         (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
2426        ((match-end 2)
2427         (verilog-re-search-backward "\\<primitive\\>" nil 'move))
2428        ((match-end 3)
2429         (verilog-re-search-backward "\\<class\\>" nil 'move))
2430        ((match-end 4)
2431         (verilog-re-search-backward "\\<program\\>" nil 'move))
2432        ((match-end 5)
2433         (verilog-re-search-backward "\\<interface\\>" nil 'move))
2434        ((match-end 6)
2435         (verilog-re-search-backward "\\<package\\>" nil 'move))
2436        (t
2437         (goto-char st)
2438         (backward-sexp 1))))
2439      (t
2440       (goto-char st)
2441       (backward-sexp)))))
2442
2443 (defun verilog-forward-sexp ()
2444   (let ((reg)
2445         (md 2)
2446         (st (point))
2447         (nest 'yes))
2448     (if (not (looking-at "\\<"))
2449         (forward-word -1))
2450     (cond
2451      ((verilog-skip-forward-comment-or-string)
2452       (verilog-forward-syntactic-ws))
2453      ((looking-at verilog-beg-block-re-ordered)
2454       (cond
2455        ((match-end 1);
2456         ;; Search forward for matching end
2457         (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
2458        ((match-end 2)
2459         ;; Search forward for matching endcase
2460         (setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2461         (setq md 3) ;; ender is third item in regexp
2462         )
2463        ((match-end 4)
2464         ;; might be "disable fork"
2465         (if (or 
2466              (looking-at verilog-disable-fork-re)
2467              (and (looking-at "fork")
2468                   (progn
2469                     (forward-word -1)
2470                     (looking-at verilog-disable-fork-re))))
2471             (progn
2472               (goto-char (match-end 0))
2473               (forward-word 1)
2474               (setq reg nil))
2475           (progn
2476             ;; Search forward for matching join
2477             (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))))
2478        ((match-end 6)
2479         ;; Search forward for matching endclass
2480         (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
2481        
2482        ((match-end 7)
2483         ;; Search forward for matching endtable
2484         (setq reg "\\<endtable\\>" )
2485         (setq nest 'no))
2486       ((match-end 8)
2487        ;; Search forward for matching endspecify
2488        (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
2489       ((match-end 9)
2490        ;; Search forward for matching endfunction
2491        (setq reg "\\<endfunction\\>" )
2492        (setq nest 'no))
2493       ((match-end 10)
2494        ;; Search forward for matching endfunction
2495        (setq reg "\\<endfunction\\>" )
2496        (setq nest 'no))
2497       ((match-end 14)
2498        ;; Search forward for matching endtask
2499        (setq reg "\\<endtask\\>" )
2500        (setq nest 'no))
2501       ((match-end 15)
2502        ;; Search forward for matching endtask
2503        (setq reg "\\<endtask\\>" )
2504        (setq nest 'no))
2505       ((match-end 19)
2506        ;; Search forward for matching endgenerate
2507        (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
2508       ((match-end 20)
2509        ;; Search forward for matching endgroup
2510        (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
2511       ((match-end 21)
2512        ;; Search forward for matching endproperty
2513        (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
2514       ((match-end 25)
2515        ;; Search forward for matching endsequence
2516        (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
2517        (setq md 3)) ; 3 to get to endsequence in the reg above
2518       ((match-end 27)
2519        ;; Search forward for matching endclocking
2520        (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
2521       (if (and reg
2522                (forward-word 1))
2523           (catch 'skip
2524             (if (eq nest 'yes) 
2525                 (let ((depth 1))
2526                   (while (verilog-re-search-forward reg nil 'move)
2527                     (cond
2528                      ((match-end md) ; the closer in reg, so we are climbing out
2529                       (setq depth (1- depth))
2530                       (if (= 0 depth) ; we are out!
2531                           (throw 'skip 1)))
2532                      ((match-end 1) ; the opener in reg, so we are deeper now
2533                       (setq depth (1+ depth))))))
2534               (if (verilog-re-search-forward reg nil 'move)
2535                   (throw 'skip 1))))))
2536     
2537      ((looking-at (concat
2538                    "\\(\\<\\(macro\\)?module\\>\\)\\|"
2539                    "\\(\\<primitive\\>\\)\\|"
2540                    "\\(\\<class\\>\\)\\|"
2541                    "\\(\\<program\\>\\)\\|"
2542                    "\\(\\<interface\\>\\)\\|"
2543                    "\\(\\<package\\>\\)"))
2544       (cond
2545        ((match-end 1)
2546         (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
2547        ((match-end 2)
2548         (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
2549        ((match-end 3)
2550         (verilog-re-search-forward "\\<endclass\\>" nil 'move))
2551        ((match-end 4)
2552         (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
2553        ((match-end 5)
2554         (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
2555        ((match-end 6)
2556         (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
2557        (t
2558         (goto-char st)
2559         (if (= (following-char) ?\) )
2560             (forward-char 1)
2561           (forward-sexp 1)))))
2562      (t
2563       (goto-char st)
2564       (if (= (following-char) ?\) )
2565           (forward-char 1)
2566         (forward-sexp 1))))))
2567
2568 (defun verilog-declaration-beg ()
2569   (verilog-re-search-backward verilog-declaration-re (bobp) t))
2570
2571 ;;
2572 ;;
2573 ;;  Mode
2574 ;;
2575 (defvar verilog-which-tool 1)
2576 ;;;###autoload
2577 (defun verilog-mode ()
2578   "Major mode for editing Verilog code.
2579 \\<verilog-mode-map>
2580 See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
2581 AUTOs can improve coding efficiency.
2582
2583 Use \\[verilog-faq] for a pointer to frequently asked questions.
2584
2585 NEWLINE, TAB indents for Verilog code.
2586 Delete converts tabs to spaces as it moves back.
2587
2588 Supports highlighting.
2589
2590 Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
2591 with no args, if that value is non-nil.
2592
2593 Variables controlling indentation/edit style:
2594
2595  variable `verilog-indent-level'      (default 3)
2596    Indentation of Verilog statements with respect to containing block.
2597  `verilog-indent-level-module'        (default 3)
2598    Absolute indentation of Module level Verilog statements.
2599    Set to 0 to get initial and always statements lined up
2600    on the left side of your screen.
2601  `verilog-indent-level-declaration'   (default 3)
2602    Indentation of declarations with respect to containing block.
2603    Set to 0 to get them list right under containing block.
2604  `verilog-indent-level-behavioral'    (default 3)
2605    Indentation of first begin in a task or function block
2606    Set to 0 to get such code to lined up underneath the task or
2607    function keyword.
2608  `verilog-indent-level-directive'     (default 1)
2609    Indentation of `ifdef/`endif blocks.
2610  `verilog-cexp-indent'              (default 1)
2611    Indentation of Verilog statements broken across lines i.e.:
2612       if (a)
2613         begin
2614  `verilog-case-indent'              (default 2)
2615    Indentation for case statements.
2616  `verilog-auto-newline'             (default nil)
2617    Non-nil means automatically newline after semicolons and the punctuation
2618    mark after an end.
2619  `verilog-auto-indent-on-newline'   (default t)
2620    Non-nil means automatically indent line after newline.
2621  `verilog-tab-always-indent'        (default t)
2622    Non-nil means TAB in Verilog mode should always reindent the current line,
2623    regardless of where in the line point is when the TAB command is used.
2624  `verilog-indent-begin-after-if'    (default t)
2625    Non-nil means to indent begin statements following a preceding
2626    if, else, while, for and repeat statements, if any.  Otherwise,
2627    the begin is lined up with the preceding token.  If t, you get:
2628       if (a)
2629          begin // amount of indent based on `verilog-cexp-indent'
2630    otherwise you get:
2631       if (a)
2632       begin
2633  `verilog-auto-endcomments'         (default t)
2634    Non-nil means a comment /* ... */ is set after the ends which ends
2635    cases, tasks, functions and modules.
2636    The type and name of the object will be set between the braces.
2637  `verilog-minimum-comment-distance' (default 10)
2638    Minimum distance (in lines) between begin and end required before a comment
2639    will be inserted.  Setting this variable to zero results in every
2640    end acquiring a comment; the default avoids too many redundant
2641    comments in tight quarters.
2642  `verilog-auto-lineup'              (default `(all))
2643    List of contexts where auto lineup of code should be done.
2644
2645 Variables controlling other actions:
2646
2647  `verilog-linter'                   (default surelint)
2648    Unix program to call to run the lint checker.  This is the default
2649    command for \\[compile-command] and \\[verilog-auto-save-compile].
2650
2651 See \\[customize] for the complete list of variables.
2652
2653 AUTO expansion functions are, in part:
2654
2655     \\[verilog-auto]  Expand AUTO statements.
2656     \\[verilog-delete-auto]  Remove the AUTOs.
2657     \\[verilog-inject-auto]  Insert AUTOs for the first time.
2658
2659 Some other functions are:
2660
2661     \\[verilog-complete-word]    Complete word with appropriate possibilities.
2662     \\[verilog-mark-defun]  Mark function.
2663     \\[verilog-beg-of-defun]  Move to beginning of current function.
2664     \\[verilog-end-of-defun]  Move to end of current function.
2665     \\[verilog-label-be]  Label matching begin ... end, fork ... join, etc statements.
2666
2667     \\[verilog-comment-region]  Put marked area in a comment.
2668     \\[verilog-uncomment-region]  Uncomment an area commented with \\[verilog-comment-region].
2669     \\[verilog-insert-block]  Insert begin ... end.
2670     \\[verilog-star-comment]    Insert /* ... */.
2671
2672     \\[verilog-sk-always]  Insert an always @(AS) begin .. end block.
2673     \\[verilog-sk-begin]  Insert a begin .. end block.
2674     \\[verilog-sk-case]  Insert a case block, prompting for details.
2675     \\[verilog-sk-for]  Insert a for (...) begin .. end block, prompting for details.
2676     \\[verilog-sk-generate]  Insert a generate .. endgenerate block.
2677     \\[verilog-sk-header]  Insert a header block at the top of file.
2678     \\[verilog-sk-initial]  Insert an initial begin .. end block.
2679     \\[verilog-sk-fork]  Insert a fork begin .. end .. join block.
2680     \\[verilog-sk-module]  Insert a module .. (/*AUTOARG*/);.. endmodule block.
2681     \\[verilog-sk-primitive]  Insert a primitive .. (.. );.. endprimitive block.
2682     \\[verilog-sk-repeat]  Insert a repeat (..) begin .. end block.
2683     \\[verilog-sk-specify]  Insert a specify .. endspecify block.
2684     \\[verilog-sk-task]  Insert a task .. begin .. end endtask block.
2685     \\[verilog-sk-while]  Insert a while (...) begin .. end block, prompting for details.
2686     \\[verilog-sk-casex]  Insert a casex (...) item: begin.. end endcase block, prompting for details.
2687     \\[verilog-sk-casez]  Insert a casez (...) item: begin.. end endcase block, prompting for details.
2688     \\[verilog-sk-if]  Insert an if (..) begin .. end block.
2689     \\[verilog-sk-else-if]  Insert an else if (..) begin .. end block.
2690     \\[verilog-sk-comment]  Insert a comment block.
2691     \\[verilog-sk-assign]  Insert an assign .. = ..; statement.
2692     \\[verilog-sk-function]  Insert a function .. begin .. end endfunction block.
2693     \\[verilog-sk-input]  Insert an input declaration, prompting for details.
2694     \\[verilog-sk-output]  Insert an output declaration, prompting for details.
2695     \\[verilog-sk-state-machine]  Insert a state machine definition, prompting for details.
2696     \\[verilog-sk-inout]  Insert an inout declaration, prompting for details.
2697     \\[verilog-sk-wire]  Insert a wire declaration, prompting for details.
2698     \\[verilog-sk-reg]  Insert a register declaration, prompting for details.
2699     \\[verilog-sk-define-signal]  Define signal under point as a register at the top of the module.
2700
2701 All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
2702 Key bindings specific to `verilog-mode-map' are:
2703
2704 \\{verilog-mode-map}"
2705   (interactive)
2706   (kill-all-local-variables)
2707   (use-local-map verilog-mode-map)
2708   (setq major-mode 'verilog-mode)
2709   (setq mode-name "Verilog")
2710   (setq local-abbrev-table verilog-mode-abbrev-table)
2711   (set (make-local-variable 'beginning-of-defun-function)
2712        'verilog-beg-of-defun)
2713   (set (make-local-variable 'end-of-defun-function)
2714        'verilog-end-of-defun)
2715   (set-syntax-table verilog-mode-syntax-table)
2716   (make-local-variable 'indent-line-function)
2717   (setq indent-line-function 'verilog-indent-line-relative)
2718   (setq comment-indent-function 'verilog-comment-indent)
2719   (make-local-variable 'parse-sexp-ignore-comments)
2720   (setq parse-sexp-ignore-comments nil)
2721   (make-local-variable 'comment-start)
2722   (make-local-variable 'comment-end)
2723   (make-local-variable 'comment-multi-line)
2724   (make-local-variable 'comment-start-skip)
2725   (setq comment-start "// "
2726         comment-end ""
2727         comment-start-skip "/\\*+ *\\|// *"
2728         comment-multi-line nil)
2729   ;; Set up for compilation
2730   (setq verilog-which-tool 1)
2731   (setq verilog-tool 'verilog-linter)
2732   (verilog-set-compile-command)
2733   (when (boundp 'hack-local-variables-hook)  ;; Also modify any file-local-variables
2734     (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
2735
2736   ;; Setting up menus
2737   (when (featurep 'xemacs)
2738     (easy-menu-add verilog-stmt-menu)
2739     (easy-menu-add verilog-menu)
2740     (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
2741
2742   ;; Stuff for GNU Emacs
2743   (set (make-local-variable 'font-lock-defaults)
2744        `((verilog-font-lock-keywords verilog-font-lock-keywords-1
2745                                      verilog-font-lock-keywords-2
2746                                      verilog-font-lock-keywords-3)
2747          nil nil nil 
2748          ,(if (functionp 'syntax-ppss) 
2749               ;; verilog-beg-of-defun uses syntax-ppss, and syntax-ppss uses
2750               ;; font-lock-beginning-of-syntax-function, so
2751               ;; font-lock-beginning-of-syntax-function, can't use
2752               ;; verilog-beg-of-defun.
2753               nil
2754             'verilog-beg-of-defun)))
2755   ;;------------------------------------------------------------
2756   ;; now hook in 'verilog-colorize-include-files (eldo-mode.el&spice-mode.el)
2757   ;; all buffer local:
2758   (when (featurep 'xemacs)
2759     (make-local-hook 'font-lock-mode-hook)
2760     (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
2761     (make-local-hook 'after-change-functions))
2762   (add-hook 'font-lock-mode-hook 'verilog-colorize-include-files-buffer t t)
2763   (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-colorize-include-files-buffer t t) ; not in Emacs
2764   (add-hook 'after-change-functions 'verilog-colorize-include-files t t)
2765
2766   ;; Tell imenu how to handle Verilog.
2767   (make-local-variable 'imenu-generic-expression)
2768   (setq imenu-generic-expression verilog-imenu-generic-expression)
2769   ;; Tell which-func-modes that imenu knows about verilog
2770   (when (boundp 'which-function-modes)
2771     (add-to-list 'which-func-modes 'verilog-mode))
2772   ;; hideshow support
2773   (when (boundp 'hs-special-modes-alist)
2774     (unless (assq 'verilog-mode hs-special-modes-alist)
2775       (setq hs-special-modes-alist
2776             (cons '(verilog-mode-mode  "\\<begin\\>" "\\<end\\>" nil
2777                                        verilog-forward-sexp-function)
2778                   hs-special-modes-alist))))
2779
2780   ;; Stuff for autos
2781   (add-hook 'write-contents-hooks 'verilog-auto-save-check) ; already local
2782   (run-hooks 'verilog-mode-hook))
2783 \f
2784
2785 ;;
2786 ;;  Electric functions
2787 ;;
2788 (defun electric-verilog-terminate-line (&optional arg)
2789   "Terminate line and indent next line.
2790 With optional ARG, remove existing end of line comments."
2791   (interactive)
2792   ;; before that see if we are in a comment
2793   (let ((state (save-excursion (verilog-syntax-ppss))))
2794     (cond
2795      ((nth 7 state)                     ; Inside // comment
2796       (if (eolp)
2797           (progn
2798             (delete-horizontal-space)
2799             (newline))
2800         (progn
2801           (newline)
2802           (insert "// ")
2803           (beginning-of-line)))
2804       (verilog-indent-line))
2805      ((nth 4 state)                     ; Inside any comment (hence /**/)
2806       (newline)
2807       (verilog-more-comment))
2808      ((eolp)
2809        ;; First, check if current line should be indented
2810        (if (save-excursion
2811              (delete-horizontal-space)
2812              (beginning-of-line)
2813              (skip-chars-forward " \t")
2814              (if (looking-at verilog-auto-end-comment-lines-re)
2815                  (let ((indent-str (verilog-indent-line)))
2816                    ;; Maybe we should set some endcomments
2817                    (if verilog-auto-endcomments
2818                        (verilog-set-auto-endcomments indent-str arg))
2819                    (end-of-line)
2820                    (delete-horizontal-space)
2821                    (if arg
2822                        ()
2823                      (newline))
2824                    nil)
2825                (progn
2826                  (end-of-line)
2827                  (delete-horizontal-space)
2828                  't)))
2829            ;; see if we should line up assignments
2830            (progn
2831              (if (or (memq 'all verilog-auto-lineup)
2832                      (memq 'assignments verilog-auto-lineup))
2833                  (verilog-pretty-expr))
2834              (newline))
2835          (forward-line 1))
2836        ;; Indent next line
2837        (if verilog-auto-indent-on-newline
2838            (verilog-indent-line)))
2839      (t
2840       (newline)))))
2841
2842 (defun electric-verilog-terminate-and-indent ()
2843   "Insert a newline and indent for the next statement."
2844   (interactive)
2845   (electric-verilog-terminate-line 1))
2846
2847 (defun electric-verilog-semi ()
2848   "Insert `;' character and reindent the line."
2849   (interactive)
2850   (insert last-command-char)
2851
2852   (if (or (verilog-in-comment-or-string-p)
2853           (verilog-in-escaped-name-p))
2854       ()
2855     (save-excursion
2856       (beginning-of-line)
2857       (verilog-forward-ws&directives)
2858       (verilog-indent-line))
2859     (if (and verilog-auto-newline
2860              (not (verilog-parenthesis-depth)))
2861         (electric-verilog-terminate-line))))
2862
2863 (defun electric-verilog-semi-with-comment ()
2864   "Insert `;' character, reindent the line and indent for comment."
2865   (interactive)
2866   (insert "\;")
2867   (save-excursion
2868     (beginning-of-line)
2869     (verilog-indent-line))
2870   (indent-for-comment))
2871
2872 (defun electric-verilog-colon ()
2873   "Insert `:' and do all indentations except line indent on this line."
2874   (interactive)
2875   (insert last-command-char)
2876   ;; Do nothing if within string.
2877   (if (or
2878        (verilog-within-string)
2879        (not (verilog-in-case-region-p)))
2880       ()
2881     (save-excursion
2882       (let ((p (point))
2883             (lim (progn (verilog-beg-of-statement) (point))))
2884         (goto-char p)
2885         (verilog-backward-case-item lim)
2886         (verilog-indent-line)))
2887 ;;    (let ((verilog-tab-always-indent nil))
2888 ;;      (verilog-indent-line))
2889     ))
2890
2891 ;;(defun electric-verilog-equal ()
2892 ;;  "Insert `=', and do indentation if within block."
2893 ;;  (interactive)
2894 ;;  (insert last-command-char)
2895 ;; Could auto line up expressions, but not yet
2896 ;;  (if (eq (car (verilog-calculate-indent)) 'block)
2897 ;;      (let ((verilog-tab-always-indent nil))
2898 ;;      (verilog-indent-command)))
2899 ;;  )
2900
2901 (defun electric-verilog-tick ()
2902   "Insert back-tick, and indent to column 0 if this is a CPP directive."
2903   (interactive)
2904   (insert last-command-char)
2905   (save-excursion
2906     (if (progn
2907           (beginning-of-line)
2908           (looking-at verilog-directive-re-1))
2909         (verilog-indent-line))))
2910
2911 (defun electric-verilog-tab ()
2912   "Function called when TAB is pressed in Verilog mode."
2913   (interactive)
2914   ;; If verilog-tab-always-indent, indent the beginning of the line.
2915   (cond
2916    ;; The region is active, indent it.
2917    ((and (region-active-p)
2918          (not (eq (region-beginning) (region-end))))
2919     (indent-region (region-beginning) (region-end) nil))
2920    ((or verilog-tab-always-indent
2921         (save-excursion
2922           (skip-chars-backward " \t")
2923           (bolp)))
2924     (let* ((oldpnt (point))
2925            (boi-point
2926             (save-excursion
2927               (beginning-of-line)
2928               (skip-chars-forward " \t")
2929               (verilog-indent-line)
2930               (back-to-indentation)
2931               (point))))
2932       (if (< (point) boi-point)
2933           (back-to-indentation)
2934         (cond ((not verilog-tab-to-comment))
2935               ((not (eolp))
2936                (end-of-line))
2937               (t
2938                (indent-for-comment)
2939                (when (and (eolp) (= oldpnt (point)))
2940                                         ; kill existing comment
2941                  (beginning-of-line)
2942                  (re-search-forward comment-start-skip oldpnt 'move)
2943                  (goto-char (match-beginning 0))
2944                  (skip-chars-backward " \t")
2945                  (kill-region (point) oldpnt)))))))
2946    (t (progn (insert "\t")))))
2947   
2948 \f
2949
2950 ;;
2951 ;; Interactive functions
2952 ;;
2953
2954 (defun verilog-indent-buffer ()
2955   "Indent-region the entire buffer as Verilog code.
2956 To call this from the command line, see \\[verilog-batch-indent]."
2957   (interactive)
2958   (verilog-mode)
2959   (indent-region (point-min) (point-max) nil))
2960
2961 (defun verilog-insert-block ()
2962   "Insert Verilog begin ... end; block in the code with right indentation."
2963   (interactive)
2964   (verilog-indent-line)
2965   (insert "begin")
2966   (electric-verilog-terminate-line)
2967   (save-excursion
2968     (electric-verilog-terminate-line)
2969     (insert "end")
2970     (beginning-of-line)
2971     (verilog-indent-line)))
2972
2973 (defun verilog-star-comment ()
2974   "Insert Verilog star comment at point."
2975   (interactive)
2976   (verilog-indent-line)
2977   (insert "/*")
2978   (save-excursion
2979     (newline)
2980     (insert " */"))
2981   (newline)
2982   (insert " * "))
2983
2984 (defun verilog-insert-1 (fmt max)
2985   "Use format string FMT to insert integers 0 to MAX - 1.
2986 Inserts one integer per line, at the current column.  Stops early
2987 if it reaches the end of the buffer."
2988   (let ((col (current-column))
2989         (n 0))
2990     (save-excursion
2991       (while (< n max)
2992         (insert (format fmt n))
2993         (forward-line 1)
2994         ;; Note that this function does not bother to check for lines
2995         ;; shorter than col.
2996         (if (eobp)
2997             (setq n max)
2998           (setq n (1+ n))
2999           (move-to-column col))))))
3000
3001 (defun verilog-insert-indices (max)
3002   "Insert a set of indices into a rectangle.
3003 The upper left corner is defined by point.  Indices begin with 0
3004 and extend to the MAX - 1.  If no prefix arg is given, the user
3005 is prompted for a value.  The indices are surrounded by square
3006 brackets \[].  For example, the following code with the point
3007 located after the first 'a' gives:
3008
3009     a = b                           a[  0] = b
3010     a = b                           a[  1] = b
3011     a = b                           a[  2] = b
3012     a = b                           a[  3] = b
3013     a = b   ==> insert-indices ==>  a[  4] = b
3014     a = b                           a[  5] = b
3015     a = b                           a[  6] = b
3016     a = b                           a[  7] = b
3017     a = b                           a[  8] = b"
3018
3019   (interactive "NMAX: ")
3020   (verilog-insert-1 "[%3d]" max))
3021
3022 (defun verilog-generate-numbers (max)
3023   "Insert a set of generated numbers into a rectangle.
3024 The upper left corner is defined by point.  The numbers are padded to three
3025 digits, starting with 000 and extending to (MAX - 1).  If no prefix argument
3026 is supplied, then the user is prompted for the MAX number.  Consider the
3027 following code fragment:
3028
3029     buf buf                             buf buf000
3030     buf buf                             buf buf001
3031     buf buf                             buf buf002
3032     buf buf                             buf buf003
3033     buf buf   ==> generate-numbers ==>  buf buf004
3034     buf buf                             buf buf005
3035     buf buf                             buf buf006
3036     buf buf                             buf buf007
3037     buf buf                             buf buf008"
3038
3039   (interactive "NMAX: ")
3040   (verilog-insert-1 "%3.3d" max))
3041
3042 (defun verilog-mark-defun ()
3043   "Mark the current Verilog function (or procedure).
3044 This puts the mark at the end, and point at the beginning."
3045   (interactive)
3046   (if (featurep 'xemacs)
3047       (progn
3048         (push-mark (point))
3049         (verilog-end-of-defun)
3050         (push-mark (point))
3051         (verilog-beg-of-defun)
3052         (if (fboundp 'zmacs-activate-region)
3053             (zmacs-activate-region)))
3054     (mark-defun)))
3055
3056 (defun verilog-comment-region (start end)
3057   ; checkdoc-params: (start end)
3058   "Put the region into a Verilog comment.
3059 The comments that are in this area are \"deformed\":
3060 `*)' becomes `!(*' and `}' becomes `!{'.
3061 These deformed comments are returned to normal if you use
3062 \\[verilog-uncomment-region] to undo the commenting.
3063
3064 The commented area starts with `verilog-exclude-str-start', and ends with
3065 `verilog-exclude-str-end'.  But if you change these variables,
3066 \\[verilog-uncomment-region] won't recognize the comments."
3067   (interactive "r")
3068   (save-excursion
3069     ;; Insert start and endcomments
3070     (goto-char end)
3071     (if (and (save-excursion (skip-chars-forward " \t") (eolp))
3072              (not (save-excursion (skip-chars-backward " \t") (bolp))))
3073         (forward-line 1)
3074       (beginning-of-line))
3075     (insert verilog-exclude-str-end)
3076     (setq end (point))
3077     (newline)
3078     (goto-char start)
3079     (beginning-of-line)
3080     (insert verilog-exclude-str-start)
3081     (newline)
3082     ;; Replace end-comments within commented area
3083     (goto-char end)
3084     (save-excursion
3085       (while (re-search-backward "\\*/" start t)
3086         (replace-match "*-/" t t)))
3087     (save-excursion
3088       (let ((s+1 (1+ start)))
3089         (while (re-search-backward "/\\*" s+1 t)
3090           (replace-match "/-*" t t))))))
3091
3092 (defun verilog-uncomment-region ()
3093   "Uncomment a commented area; change deformed comments back to normal.
3094 This command does nothing if the pointer is not in a commented
3095 area.  See also `verilog-comment-region'."
3096   (interactive)
3097   (save-excursion
3098     (let ((start (point))
3099           (end (point)))
3100       ;; Find the boundaries of the comment
3101       (save-excursion
3102         (setq start (progn (search-backward verilog-exclude-str-start nil t)
3103                            (point)))
3104         (setq end (progn (search-forward verilog-exclude-str-end nil t)
3105                          (point))))
3106       ;; Check if we're really inside a comment
3107       (if (or (equal start (point)) (<= end (point)))
3108           (message "Not standing within commented area.")
3109         (progn
3110           ;; Remove endcomment
3111           (goto-char end)
3112           (beginning-of-line)
3113           (let ((pos (point)))
3114             (end-of-line)
3115             (delete-region pos (1+ (point))))
3116           ;; Change comments back to normal
3117           (save-excursion
3118             (while (re-search-backward "\\*-/" start t)
3119               (replace-match "*/" t t)))
3120           (save-excursion
3121             (while (re-search-backward "/-\\*" start t)
3122               (replace-match "/*" t t)))
3123           ;; Remove start comment
3124           (goto-char start)
3125           (beginning-of-line)
3126           (let ((pos (point)))
3127             (end-of-line)
3128             (delete-region pos (1+ (point)))))))))
3129
3130 (defun verilog-beg-of-defun ()
3131   "Move backward to the beginning of the current function or procedure."
3132   (interactive)
3133   (verilog-re-search-backward verilog-defun-re nil 'move))
3134
3135 (defun verilog-end-of-defun ()
3136   "Move forward to the end of the current function or procedure."
3137   (interactive)
3138   (verilog-re-search-forward verilog-end-defun-re nil 'move))
3139
3140 (defun verilog-get-beg-of-defun (&optional warn)
3141   (save-excursion
3142     (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
3143            (point))
3144           (t
3145            (error "%s: Can't find module beginning" (verilog-point-text))
3146            (point-max)))))
3147 (defun verilog-get-end-of-defun (&optional warn)
3148   (save-excursion
3149     (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
3150            (point))
3151           (t
3152            (error "%s: Can't find endmodule" (verilog-point-text))
3153            (point-max)))))
3154
3155 (defun verilog-label-be (&optional arg)
3156   "Label matching begin ... end, fork ... join and case ... endcase statements.
3157 With ARG, first kill any existing labels."
3158   (interactive)
3159   (let ((cnt 0)
3160         (oldpos (point))
3161         (b (progn
3162              (verilog-beg-of-defun)
3163              (point-marker)))
3164         (e (progn
3165              (verilog-end-of-defun)
3166              (point-marker))))
3167     (goto-char (marker-position b))
3168     (if (> (- e b) 200)
3169         (message  "Relabeling module..."))
3170     (while (and
3171             (> (marker-position e) (point))
3172             (verilog-re-search-forward
3173              (concat
3174               "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
3175               "\\|\\(`endif\\)\\|\\(`else\\)")
3176              nil 'move))
3177       (goto-char (match-beginning 0))
3178       (let ((indent-str (verilog-indent-line)))
3179         (verilog-set-auto-endcomments indent-str 't)
3180         (end-of-line)
3181         (delete-horizontal-space))
3182       (setq cnt (1+ cnt))
3183       (if (= 9 (% cnt 10))
3184           (message "%d..." cnt)))
3185     (goto-char oldpos)
3186     (if (or
3187          (> (- e b) 200)
3188          (> cnt 20))
3189         (message  "%d lines auto commented" cnt))))
3190
3191 (defun verilog-beg-of-statement ()
3192   "Move backward to beginning of statement."
3193   (interactive)
3194   ;; Move back token by token until we see the end
3195   ;; of some ealier line.
3196   (while
3197       ;; If the current point does not begin a new
3198       ;; statement, as in the character ahead of us is a ';', or SOF
3199       ;; or the string after us unambiguosly starts a statement,
3200       ;; or the token before us unambiguously ends a statement,
3201       ;; then move back a token and test again.
3202       (not (or
3203             (bolp)
3204             (= (preceding-char) ?\;)
3205             (looking-at "\\w+\\W*:\\W*\\(coverpoint\\|cross\\|constraint\\)")
3206             (not (or
3207                   (looking-at "\\<")
3208                   (forward-word -1)))
3209             (and
3210              (looking-at verilog-extended-complete-re)
3211              (not (save-excursion
3212                     (verilog-backward-token)
3213                     (looking-at verilog-extended-complete-re))))
3214             (looking-at verilog-basic-complete-re)
3215             (save-excursion
3216               (verilog-backward-token)
3217               (or
3218                (looking-at verilog-end-block-re)
3219                (looking-at verilog-preprocessor-re)))))
3220     (verilog-backward-syntactic-ws)
3221     (verilog-backward-token))
3222   ;; Now point is where the previous line ended.
3223   (verilog-forward-syntactic-ws))
3224
3225 (defun verilog-beg-of-statement-1 ()
3226   "Move backward to beginning of statement."
3227   (interactive)
3228   (let ((pt (point)))
3229
3230     (while (and (not (looking-at verilog-complete-reg))
3231                 (setq pt (point))
3232                 (verilog-backward-token)
3233                 (not (looking-at verilog-complete-reg))
3234                 (verilog-backward-syntactic-ws)
3235                 (setq pt (point))
3236                 (not (bolp))
3237                 (not (= (preceding-char) ?\;))))
3238     (goto-char pt)
3239     (verilog-forward-ws&directives)))
3240
3241 (defun verilog-end-of-statement ()
3242   "Move forward to end of current statement."
3243   (interactive)
3244   (let ((nest 0) pos)
3245     (or (looking-at verilog-beg-block-re)
3246         ;; Skip to end of statement
3247         (setq pos (catch 'found
3248                     (while t
3249                       (forward-sexp 1)
3250                       (verilog-skip-forward-comment-or-string)
3251                       (cond ((looking-at "[ \t]*;")
3252                              (skip-chars-forward "^;")
3253                              (forward-char 1)
3254                              (throw 'found (point)))
3255                             ((save-excursion
3256                                (forward-sexp -1)
3257                                (looking-at verilog-beg-block-re))
3258                              (goto-char (match-beginning 0))
3259                              (throw 'found nil))
3260                             ((looking-at "[ \t]*)")
3261                              (throw 'found (point)))
3262                             ((eobp)
3263                              (throw 'found (point))))))))
3264     (if (not pos)
3265         ;; Skip a whole block
3266         (catch 'found
3267           (while t
3268             (verilog-re-search-forward verilog-end-statement-re nil 'move)
3269             (setq nest (if (match-end 1)
3270                            (1+ nest)
3271                          (1- nest)))
3272             (cond ((eobp)
3273                    (throw 'found (point)))
3274                   ((= 0 nest)
3275                    (throw 'found (verilog-end-of-statement))))))
3276       pos)))
3277
3278 (defun verilog-in-case-region-p ()
3279   "Return true if in a case region.
3280 More specifically, point @ in the line foo : @ begin"
3281   (interactive)
3282   (save-excursion
3283     (if (and
3284          (progn (verilog-forward-syntactic-ws)
3285                 (looking-at "\\<begin\\>"))
3286          (progn (verilog-backward-syntactic-ws)
3287                 (= (preceding-char) ?\:)))
3288         (catch 'found
3289           (let ((nest 1))
3290             (while t
3291               (verilog-re-search-backward
3292                (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
3293                        "\\(\\<endcase\\>\\)\\>")
3294                nil 'move)
3295               (cond
3296                ((match-end 3)
3297                 (setq nest (1+ nest)))
3298                ((match-end 2)
3299                 (if (= nest 1)
3300                 (throw 'found 1))
3301                 (setq nest (1- nest)))
3302                (t
3303                 (throw 'found (= nest 0)))))))
3304       nil)))
3305 (defun verilog-in-struct-region-p ()
3306   "Return true if in a struct region.
3307 More specifically, in a list after a struct|union keyword."
3308   (interactive)
3309   (save-excursion
3310     (let* ((state (verilog-syntax-ppss))
3311            (depth (nth 0 state)))
3312       (if depth
3313           (progn (backward-up-list depth)
3314                  (verilog-beg-of-statement)
3315                  (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>"))))))
3316
3317 (defun verilog-in-generate-region-p ()
3318   "Return true if in a generate region.
3319 More specifically, after a generate and before an endgenerate."
3320   (interactive)
3321   (let ((nest 1))
3322     (save-excursion
3323       (catch 'done
3324         (while (and
3325                 (/= nest 0)
3326                 (verilog-re-search-backward 
3327                  "\\<\\(module\\)\\|\\(generate\\)\\|\\(endgenerate\\)\\>" nil 'move)
3328                 (cond
3329                  ((match-end 1) ; module - we have crawled out
3330                   (throw 'done 1))
3331                  ((match-end 2) ; generate
3332                   (setq nest (1- nest)))
3333                  ((match-end 3) ; endgenerate
3334                   (setq nest (1+ nest))))))))
3335     (= nest 0) )) ; return nest
3336
3337 (defun verilog-in-fork-region-p ()
3338   "Return true if between a fork and join."
3339   (interactive)
3340   (let ((lim (save-excursion (verilog-beg-of-defun)  (point)))
3341         (nest 1))
3342     (save-excursion
3343       (while (and
3344               (/= nest 0)
3345               (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
3346               (cond
3347                ((match-end 1) ; fork
3348                 (setq nest (1- nest)))
3349                ((match-end 2) ; join
3350                 (setq nest (1+ nest)))))))
3351     (= nest 0) )) ; return nest
3352
3353 (defun verilog-backward-case-item (lim)
3354   "Skip backward to nearest enclosing case item.
3355 Limit search to point LIM."
3356   (interactive)
3357   (let ((str 'nil)
3358         (lim1
3359          (progn
3360            (save-excursion
3361              (verilog-re-search-backward verilog-endcomment-reason-re
3362                                          lim 'move)
3363              (point)))))
3364     ;; Try to find the real :
3365     (if (save-excursion (search-backward ":" lim1 t))
3366         (let ((colon 0)
3367               b e )
3368           (while
3369               (and
3370                (< colon 1)
3371                (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
3372                                            lim1 'move))
3373             (cond
3374              ((match-end 1) ;; [
3375               (setq colon (1+ colon))
3376               (if (>= colon 0)
3377                   (error "%s: unbalanced [" (verilog-point-text))))
3378              ((match-end 2) ;; ]
3379               (setq colon (1- colon)))
3380
3381              ((match-end 3) ;; :
3382               (setq colon (1+ colon)))))
3383           ;; Skip back to beginning of case item
3384           (skip-chars-backward "\t ")
3385           (verilog-skip-backward-comment-or-string)
3386           (setq e (point))
3387           (setq b
3388                 (progn
3389                   (if
3390                       (verilog-re-search-backward
3391                        "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
3392                       (progn
3393                         (cond
3394                          ((match-end 1)
3395                           (goto-char (match-end 1))
3396                           (verilog-forward-ws&directives)
3397                           (if (looking-at "(")
3398                               (progn
3399                                 (forward-sexp)
3400                                 (verilog-forward-ws&directives)))
3401                           (point))
3402                          (t
3403                           (goto-char (match-end 0))
3404                           (verilog-forward-ws&directives)
3405                           (point))))
3406                     (error "Malformed case item"))))
3407           (setq str (buffer-substring b e))
3408           (if
3409               (setq e
3410                     (string-match
3411                      "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3412               (setq str (concat (substring str 0 e) "...")))
3413           str)
3414       'nil)))
3415 \f
3416
3417 ;;
3418 ;; Other functions
3419 ;;
3420
3421 (defun verilog-kill-existing-comment ()
3422   "Kill auto comment on this line."
3423   (save-excursion
3424     (let* (
3425            (e (progn
3426                 (end-of-line)
3427                 (point)))
3428            (b (progn
3429                 (beginning-of-line)
3430                 (search-forward "//" e t))))
3431       (if b
3432           (delete-region (- b 2) e)))))
3433
3434 (defconst verilog-directive-nest-re
3435   (concat "\\(`else\\>\\)\\|"
3436           "\\(`endif\\>\\)\\|"
3437           "\\(`if\\>\\)\\|"
3438           "\\(`ifdef\\>\\)\\|"
3439           "\\(`ifndef\\>\\)"))
3440 (defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
3441   "Add ending comment with given INDENT-STR.
3442 With KILL-EXISTING-COMMENT, remove what was there before.
3443 Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
3444 Insert `// case expr ' if this line ends a case block.
3445 Insert `// ifdef FOO ' if this line ends code conditional on FOO.
3446 Insert `// NAME ' if this line ends a function, task, module,
3447 primitive or interface named NAME."
3448   (save-excursion
3449     (cond
3450      (; Comment close preprocessor directives
3451       (and
3452        (looking-at "\\(`endif\\)\\|\\(`else\\)")
3453        (or  kill-existing-comment
3454             (not (save-excursion
3455                    (end-of-line)
3456                    (search-backward "//" (verilog-get-beg-of-line) t)))))
3457       (let ((nest 1) b e
3458             m
3459             (else (if (match-end 2) "!" " ")))
3460         (end-of-line)
3461         (if kill-existing-comment
3462             (verilog-kill-existing-comment))
3463         (delete-horizontal-space)
3464         (save-excursion
3465           (backward-sexp 1)
3466           (while (and (/= nest 0)
3467                       (verilog-re-search-backward verilog-directive-nest-re nil 'move))
3468             (cond
3469              ((match-end 1) ; `else
3470               (if (= nest 1)
3471                   (setq else "!")))
3472              ((match-end 2) ; `endif
3473               (setq nest (1+ nest)))
3474              ((match-end 3) ; `if
3475               (setq nest (1- nest)))
3476              ((match-end 4) ; `ifdef
3477               (setq nest (1- nest)))
3478              ((match-end 5) ; `ifndef
3479               (setq nest (1- nest)))))
3480           (if (match-end 0)
3481               (setq
3482                m (buffer-substring
3483                   (match-beginning 0)
3484                   (match-end 0))
3485                b (progn
3486                    (skip-chars-forward "^ \t")
3487                    (verilog-forward-syntactic-ws)
3488                    (point))
3489                e (progn
3490                    (skip-chars-forward "a-zA-Z0-9_")
3491                    (point)))))
3492         (if b
3493             (if (> (count-lines (point) b) verilog-minimum-comment-distance)
3494                 (insert (concat " // " else m " " (buffer-substring b e))))
3495           (progn
3496             (insert " // unmatched `else or `endif")
3497             (ding 't)))))
3498
3499      (; Comment close case/class/function/task/module and named block
3500       (and (looking-at "\\<end")
3501            (or kill-existing-comment
3502                (not (save-excursion
3503                       (end-of-line)
3504                       (search-backward "//" (verilog-get-beg-of-line) t)))))
3505       (let ((type (car indent-str)))
3506         (unless (eq type 'declaration)
3507           (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
3508             (if (looking-at verilog-end-block-ordered-re)
3509               (cond
3510                (;- This is a case block; search back for the start of this case
3511                 (match-end 1) ;; of verilog-end-block-ordered-re
3512
3513                 (let ((err 't)
3514                       (str "UNMATCHED!!"))
3515                   (save-excursion
3516                     (verilog-leap-to-head)
3517                     (cond
3518                      ((looking-at "\\<randcase\\>")
3519                       (setq str "randcase")
3520                       (setq err nil))
3521                      ((match-end 0)
3522                       (goto-char (match-end 1))
3523                       (if nil
3524                           (let (s f)
3525                             (setq s (match-beginning 1))
3526                             (setq f (progn (end-of-line)
3527                                            (point)))
3528                             (setq str  (buffer-substring s f)))
3529                         (setq err nil))
3530                       (setq str (concat (buffer-substring (match-beginning 1) (match-end 1))
3531                                         " "
3532                                         (verilog-get-expr))))))
3533                   (end-of-line)
3534                   (if kill-existing-comment
3535                       (verilog-kill-existing-comment))
3536                   (delete-horizontal-space)
3537                   (insert (concat " // " str ))
3538                   (if err (ding 't))))
3539
3540                (;- This is a begin..end block
3541                 (match-end 2) ;; of verilog-end-block-ordered-re
3542                 (let ((str " // UNMATCHED !!")
3543                       (err 't)
3544                       (here (point))
3545                       there
3546                       cntx)
3547                   (save-excursion
3548                     (verilog-leap-to-head)
3549                     (setq there (point))
3550                     (if (not (match-end 0))
3551                         (progn
3552                           (goto-char here)
3553                           (end-of-line)
3554                           (if kill-existing-comment
3555                               (verilog-kill-existing-comment))
3556                           (delete-horizontal-space)
3557                           (insert str)
3558                           (ding 't))
3559                       (let ((lim
3560                              (save-excursion (verilog-beg-of-defun) (point)))
3561                             (here (point)))
3562                         (cond
3563                          (;-- handle named block differently
3564                           (looking-at verilog-named-block-re)
3565                           (search-forward ":")
3566                           (setq there (point))
3567                           (setq str (verilog-get-expr))
3568                           (setq err nil)
3569                           (setq str (concat " // block: " str )))
3570
3571                          ((verilog-in-case-region-p) ;-- handle case item differently
3572                           (goto-char here)
3573                           (setq str (verilog-backward-case-item lim))
3574                           (setq there (point))
3575                           (setq err nil)
3576                           (setq str (concat " // case: " str )))
3577
3578                          (;- try to find "reason" for this begin
3579                           (cond
3580                            (;
3581                             (eq here (progn
3582                                        (verilog-backward-token)
3583                                        (verilog-beg-of-statement-1)
3584                                        (point)))
3585                             (setq err nil)
3586                             (setq str ""))
3587                            ((looking-at verilog-endcomment-reason-re)
3588                             (setq there (match-end 0))
3589                             (setq cntx (concat
3590                                         (buffer-substring (match-beginning 0) (match-end 0)) " "))
3591                             (cond
3592                              (;- begin
3593                               (match-end 2)
3594                               (setq err nil)
3595                               (save-excursion
3596                                 (if (and (verilog-continued-line)
3597                                          (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
3598                                     (progn
3599                                       (goto-char (match-end 0))
3600                                       (setq there (point))
3601                                       (setq str
3602                                             (concat " // "
3603                                                     (buffer-substring (match-beginning 0) (match-end 0)) " "
3604                                                     (verilog-get-expr))))
3605                                   (setq str ""))))
3606
3607                              (;- else
3608                               (match-end 4)
3609                               (let ((nest 0)
3610                                     ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
3611                                 (catch 'skip
3612                                   (while (verilog-re-search-backward reg nil 'move)
3613                                     (cond
3614                                      ((match-end 1) ; begin
3615                                       (setq nest (1- nest)))
3616                                      ((match-end 2)                       ; end
3617                                       (setq nest (1+ nest)))
3618                                      ((match-end 3)
3619                                       (if (= 0 nest)
3620                                           (progn
3621                                             (goto-char (match-end 0))
3622                                             (setq there (point))
3623                                             (setq err nil)
3624                                             (setq str (verilog-get-expr))
3625                                             (setq str (concat " // else: !if" str ))
3626                                             (throw 'skip 1)))))))))
3627
3628                              (;- end else
3629                               (match-end 5)
3630                               (goto-char there)
3631                               (let ((nest 0)
3632                                     (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
3633                                 (catch 'skip
3634                                   (while (verilog-re-search-backward reg nil 'move)
3635                                     (cond
3636                                      ((match-end 1) ; begin
3637                                       (setq nest (1- nest)))
3638                                      ((match-end 2)                       ; end
3639                                       (setq nest (1+ nest)))
3640                                      ((match-end 3)
3641                                       (if (= 0 nest)
3642                                           (progn
3643                                             (goto-char (match-end 0))
3644                                             (setq there (point))
3645                                             (setq err nil)
3646                                             (setq str (verilog-get-expr))
3647                                             (setq str (concat " // else: !if" str ))
3648                                             (throw 'skip 1)))))))))
3649
3650                              (;- task/function/initial et cetera
3651                               t
3652                               (match-end 0)
3653                               (goto-char (match-end 0))
3654                               (setq there (point))
3655                               (setq err nil)
3656                               (setq str (verilog-get-expr))
3657                               (setq str (concat " // " cntx str )))
3658
3659                              (;-- otherwise...
3660                               (setq str " // auto-endcomment confused "))))
3661
3662                            ((and
3663                              (verilog-in-case-region-p) ;-- handle case item differently
3664                              (progn
3665                                (setq there (point))
3666                                (goto-char here)
3667                                (setq str (verilog-backward-case-item lim))))
3668                             (setq err nil)
3669                             (setq str (concat " // case: " str )))
3670
3671                            ((verilog-in-fork-region-p)
3672                             (setq err nil)
3673                             (setq str " // fork branch" ))
3674
3675                            ((looking-at "\\<end\\>")
3676                             ;; HERE
3677                             (forward-word 1)
3678                             (verilog-forward-syntactic-ws)
3679                             (setq err nil)
3680                             (setq str (verilog-get-expr))
3681                             (setq str (concat " // " cntx str )))
3682
3683                            ))))
3684                       (goto-char here)
3685                       (end-of-line)
3686                       (if kill-existing-comment
3687                           (verilog-kill-existing-comment))
3688                       (delete-horizontal-space)
3689                       (if (or err
3690                               (> (count-lines here there) verilog-minimum-comment-distance))
3691                           (insert str))
3692                       (if err (ding 't))
3693                       ))))
3694                (;- this is endclass, which can be nested
3695                 (match-end 11) ;; of verilog-end-block-ordered-re
3696                 ;;(goto-char there)
3697                 (let ((nest 0)
3698                       (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
3699                       string)
3700                   (save-excursion
3701                     (catch 'skip
3702                       (while (verilog-re-search-backward reg nil 'move)
3703                         (cond
3704                          ((match-end 3) ; endclass
3705                           (ding 't)
3706                           (setq string "unmatched endclass")
3707                           (throw 'skip 1))
3708
3709                          ((match-end 2) ; endclass
3710                           (setq nest (1+ nest)))
3711
3712                          ((match-end 1) ; class
3713                           (setq nest (1- nest))
3714                           (if (< nest 0)
3715                               (progn
3716                                 (goto-char (match-end 0))
3717                                 (let (b e)
3718                                   (setq b (progn
3719                                             (skip-chars-forward "^ \t")
3720                                             (verilog-forward-ws&directives)
3721                                             (point))
3722                                         e (progn
3723                                             (skip-chars-forward "a-zA-Z0-9_")
3724                                             (point)))
3725                                   (setq string (buffer-substring b e)))
3726                                 (throw 'skip 1))))
3727                          ))))
3728                   (end-of-line)
3729                   (insert (concat " // " string ))))
3730
3731                (;- this is end{function,generate,task,module,primitive,table,generate}
3732                 ;- which can not be nested.
3733                 t
3734                 (let (string reg (name-re nil))
3735                   (end-of-line)
3736                   (if kill-existing-comment
3737                       (save-match-data
3738                        (verilog-kill-existing-comment)))
3739                   (delete-horizontal-space)
3740                   (backward-sexp)
3741                   (cond
3742                    ((match-end 5) ;; of verilog-end-block-ordered-re
3743                     (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
3744                     (setq name-re "\\w+\\s-*(")
3745                     )
3746                    ((match-end 6) ;; of verilog-end-block-ordered-re
3747                     (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
3748                    ((match-end 7) ;; of verilog-end-block-ordered-re
3749                     (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
3750                    ((match-end 8) ;; of verilog-end-block-ordered-re
3751                     (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3752                    ((match-end 9) ;; of verilog-end-block-ordered-re
3753                     (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
3754                    ((match-end 10) ;; of verilog-end-block-ordered-re
3755                     (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3756                    ((match-end 11) ;; of verilog-end-block-ordered-re
3757                     (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3758                    ((match-end 12) ;; of verilog-end-block-ordered-re
3759                     (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3760                    ((match-end 13) ;; of verilog-end-block-ordered-re
3761                     (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3762                    ((match-end 14) ;; of verilog-end-block-ordered-re
3763                     (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3764                    ((match-end 15) ;; of verilog-end-block-ordered-re
3765                     (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
3766
3767                    (t (error "Problem in verilog-set-auto-endcomments")))
3768                   (let (b e)
3769                     (save-excursion
3770                       (verilog-re-search-backward reg nil 'move)
3771                       (cond
3772                        ((match-end 1)
3773                         (setq b (progn
3774                                   (skip-chars-forward "^ \t")
3775                                   (verilog-forward-ws&directives)
3776                                   (if (and name-re (verilog-re-search-forward name-re nil 'move))
3777                                       (progn
3778                                         (goto-char (match-beginning 0))
3779                                         (verilog-forward-ws&directives)))
3780                                   (point))
3781                               e (progn
3782                                   (skip-chars-forward "a-zA-Z0-9_")
3783                                   (point)))
3784                         (setq string (buffer-substring b e)))
3785                        (t
3786                         (ding 't)
3787                         (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
3788                   (end-of-line)
3789                   (insert (concat " // " string )))
3790                 ))))))))))
3791
3792 (defun verilog-get-expr()
3793   "Grab expression at point, e.g, case ( a | b & (c ^d))."
3794   (let* ((b (progn
3795               (verilog-forward-syntactic-ws)
3796               (skip-chars-forward " \t")
3797               (point)))
3798          (e (let ((par 1))
3799               (cond
3800                ((looking-at "@")
3801                 (forward-char 1)
3802                 (verilog-forward-syntactic-ws)
3803                 (if (looking-at "(")
3804                     (progn
3805                       (forward-char 1)
3806                       (while (and (/= par 0)
3807                                   (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3808                         (cond
3809                          ((match-end 1)
3810                           (setq par (1+ par)))
3811                          ((match-end 2)
3812                           (setq par (1- par)))))))
3813                 (point))
3814                ((looking-at "(")
3815                 (forward-char 1)
3816                 (while (and (/= par 0)
3817                             (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3818                   (cond
3819                    ((match-end 1)
3820                     (setq par (1+ par)))
3821                    ((match-end 2)
3822                     (setq par (1- par)))))
3823                 (point))
3824                ((looking-at "\\[")
3825                 (forward-char 1)
3826                 (while (and (/= par 0)
3827                             (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
3828                   (cond
3829                    ((match-end 1)
3830                     (setq par (1+ par)))
3831                    ((match-end 2)
3832                     (setq par (1- par)))))
3833                 (verilog-forward-syntactic-ws)
3834                 (skip-chars-forward "^ \t\n\f")
3835                 (point))
3836                ((looking-at "/[/\\*]")
3837                 b)
3838                ('t
3839                 (skip-chars-forward "^: \t\n\f")
3840                 (point)))))
3841          (str (buffer-substring b e)))
3842     (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3843         (setq str (concat (substring str 0 e) "...")))
3844     str))
3845
3846 (defun verilog-expand-vector ()
3847   "Take a signal vector on the current line and expand it to multiple lines.
3848 Useful for creating tri's and other expanded fields."
3849   (interactive)
3850   (verilog-expand-vector-internal "[" "]"))
3851
3852 (defun verilog-expand-vector-internal (bra ket)
3853   "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
3854   (save-excursion
3855     (forward-line 0)
3856     (let ((signal-string (buffer-substring (point)
3857                                            (progn
3858                                              (end-of-line) (point)))))
3859       (if (string-match
3860            (concat "\\(.*\\)"
3861                    (regexp-quote bra)
3862                    "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
3863                    (regexp-quote ket)
3864                    "\\(.*\\)$") signal-string)
3865           (let* ((sig-head (match-string 1 signal-string))
3866                  (vec-start (string-to-number (match-string 2 signal-string)))
3867                  (vec-end (if (= (match-beginning 3) (match-end 3))
3868                               vec-start
3869                             (string-to-number
3870                              (substring signal-string (1+ (match-beginning 3))
3871                                         (match-end 3)))))
3872                  (vec-range
3873                   (if (= (match-beginning 4) (match-end 4))
3874                       1
3875                     (string-to-number
3876                      (substring signal-string (+ 2 (match-beginning 4))
3877                                 (match-end 4)))))
3878                  (sig-tail (match-string 5 signal-string))
3879                  vec)
3880             ;; Decode vectors
3881             (setq vec nil)
3882             (if (< vec-range 0)
3883                 (let ((tmp vec-start))
3884                   (setq vec-start vec-end
3885                         vec-end tmp
3886                         vec-range (- vec-range))))
3887             (if (< vec-end vec-start)
3888                 (while (<= vec-end vec-start)
3889                   (setq vec (append vec (list vec-start)))
3890                   (setq vec-start (- vec-start vec-range)))
3891               (while (<= vec-start vec-end)
3892                 (setq vec (append vec (list vec-start)))
3893                 (setq vec-start (+ vec-start vec-range))))
3894             ;;
3895             ;; Delete current line
3896             (delete-region (point) (progn (forward-line 0) (point)))
3897             ;;
3898             ;; Expand vector
3899             (while vec
3900               (insert (concat sig-head bra
3901                               (int-to-string (car vec)) ket sig-tail "\n"))
3902               (setq vec (cdr vec)))
3903             (delete-char -1)
3904             ;;
3905             )))))
3906
3907 (defun verilog-strip-comments ()
3908   "Strip all comments from the Verilog code."
3909   (interactive)
3910   (goto-char (point-min))
3911   (while (re-search-forward "//" nil t)
3912     (if (verilog-within-string)
3913         (re-search-forward "\"" nil t)
3914       (if (verilog-in-star-comment-p)
3915           (re-search-forward "\*/" nil t)
3916         (let ((bpt (- (point) 2)))
3917           (end-of-line)
3918           (delete-region bpt (point))))))
3919     ;;
3920   (goto-char (point-min))
3921   (while (re-search-forward "/\\*" nil t)
3922     (if (verilog-within-string)
3923         (re-search-forward "\"" nil t)
3924       (let ((bpt (- (point) 2)))
3925         (re-search-forward "\\*/")
3926         (delete-region bpt (point))))))
3927
3928 (defun verilog-one-line ()
3929   "Convert structural Verilog instances to occupy one line."
3930   (interactive)
3931   (goto-char (point-min))
3932   (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
3933         (replace-match "\\1 " nil nil)))
3934
3935 (defun verilog-linter-name ()
3936   "Return name of linter, either surelint or verilint."
3937   (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
3938                                                        compile-command))
3939         (lint-word1    (verilog-string-replace-matches "\\s .*$" "" nil nil
3940                                                        verilog-linter)))
3941     (cond ((equal compile-word1 "surelint") `surelint)
3942           ((equal compile-word1 "verilint") `verilint)
3943           ((equal lint-word1 "surelint")    `surelint)
3944           ((equal lint-word1 "verilint")    `verilint)
3945           (t `surelint))))  ;; back compatibility
3946
3947 (defun verilog-lint-off ()
3948   "Convert a Verilog linter warning line into a disable statement.
3949 For example:
3950         pci_bfm_null.v, line  46: Unused input: pci_rst_
3951 becomes a comment for the appropriate tool.
3952
3953 The first word of the `compile-command' or `verilog-linter'
3954 variables is used to determine which product is being used.
3955
3956 See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
3957   (interactive)
3958   (let ((linter (verilog-linter-name)))
3959     (cond ((equal linter `surelint)
3960            (verilog-surelint-off))
3961           ((equal linter `verilint)
3962            (verilog-verilint-off))
3963           (t (error "Linter name not set")))))
3964
3965 (defvar compilation-last-buffer)
3966
3967 (defun verilog-surelint-off ()
3968   "Convert a SureLint warning line into a disable statement.
3969 Run from Verilog source window; assumes there is a *compile* buffer
3970 with point set appropriately.
3971
3972 For example:
3973         WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
3974 becomes:
3975         // surefire lint_line_off UDDONX"
3976   (interactive)
3977   (let ((buff (if (boundp 'next-error-last-buffer)
3978                   next-error-last-buffer
3979                 compilation-last-buffer)))
3980     (when (buffer-live-p buff)
3981       ;; FIXME with-current-buffer?
3982       (save-excursion
3983         (switch-to-buffer buff)
3984         (beginning-of-line)
3985         (when
3986             (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
3987           (let* ((code (match-string 2))
3988                  (file (match-string 3))
3989                  (line (match-string 4))
3990                  (buffer (get-file-buffer file))
3991                  dir filename)
3992             (unless buffer
3993               (progn
3994                 (setq buffer
3995                       (and (file-exists-p file)
3996                            (find-file-noselect file)))
3997                 (or buffer
3998                     (let* ((pop-up-windows t))
3999                       (let ((name (expand-file-name
4000                                    (read-file-name
4001                                     (format "Find this error in: (default %s) "
4002                                             file)
4003                                     dir file t))))
4004                         (if (file-directory-p name)
4005                             (setq name (expand-file-name filename name)))
4006                         (setq buffer
4007                               (and (file-exists-p name)
4008                                    (find-file-noselect name))))))))
4009             (switch-to-buffer buffer)
4010             (goto-line (string-to-number line))
4011             (end-of-line)
4012             (catch 'already
4013               (cond
4014                ((verilog-in-slash-comment-p)
4015                 (re-search-backward "//")
4016                 (cond
4017                  ((looking-at "// surefire lint_off_line ")
4018                   (goto-char (match-end 0))
4019                   (let ((lim (save-excursion (end-of-line) (point))))
4020                     (if (re-search-forward code lim 'move)
4021                         (throw 'already t)
4022                       (insert (concat " " code)))))
4023                  (t
4024                   )))
4025                ((verilog-in-star-comment-p)
4026                 (re-search-backward "/\*")
4027                 (insert (format " // surefire lint_off_line %6s" code )))
4028                (t
4029                 (insert (format " // surefire lint_off_line %6s" code ))
4030                 )))))))))
4031
4032 (defun verilog-verilint-off ()
4033   "Convert a Verilint warning line into a disable statement.
4034
4035 For example:
4036         (W240)  pci_bfm_null.v, line  46: Unused input: pci_rst_
4037 becomes:
4038         //Verilint 240 off // WARNING: Unused input"
4039   (interactive)
4040   (save-excursion
4041     (beginning-of-line)
4042     (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
4043       (replace-match (format
4044                       ;; %3s makes numbers 1-999 line up nicely
4045                       "\\1//Verilint %3s off // WARNING: \\3"
4046                       (match-string 2)))
4047       (beginning-of-line)
4048       (verilog-indent-line))))
4049
4050 (defun verilog-auto-save-compile ()
4051   "Update automatics with \\[verilog-auto], save the buffer, and compile."
4052   (interactive)
4053   (verilog-auto)        ; Always do it for safety
4054   (save-buffer)
4055   (compile compile-command))
4056
4057 \f
4058
4059 ;;
4060 ;; Batch
4061 ;;
4062
4063 (defmacro verilog-batch-error-wrapper (&rest body)
4064   "Execute BODY and add error prefix to any errors found.
4065 This lets programs calling batch mode to easily extract error messages."
4066   `(condition-case err
4067        (progn ,@body)
4068      (error
4069       (error "%%Error: %s%s" (error-message-string err)
4070              (if (featurep 'xemacs) "\n" "")))))  ;; XEmacs forgets to add a newline
4071
4072 (defun verilog-batch-execute-func (funref)
4073   "Internal processing of a batch command, running FUNREF on all command arguments."
4074   (verilog-batch-error-wrapper
4075    ;; General globals needed
4076    (setq make-backup-files nil)
4077    (setq-default make-backup-files nil)
4078    (setq enable-local-variables t)
4079    (setq enable-local-eval t)
4080    ;; Make sure any sub-files we read get proper mode
4081    (setq default-major-mode `verilog-mode)
4082    ;; Ditto files already read in
4083    (mapc (lambda (buf)
4084            (when (buffer-file-name buf)
4085              (save-excursion
4086                (set-buffer buf)
4087                (verilog-mode))))
4088          (buffer-list))
4089    ;; Process the files
4090    (mapcar '(lambda (buf)
4091               (when (buffer-file-name buf)
4092                 (save-excursion
4093                   (if (not (file-exists-p (buffer-file-name buf)))
4094                       (error
4095                        (concat "File not found: " (buffer-file-name buf))))
4096                   (message (concat "Processing " (buffer-file-name buf)))
4097                   (set-buffer buf)
4098                   (funcall funref)
4099                   (save-buffer))))
4100            (buffer-list))))
4101
4102 (defun verilog-batch-auto ()
4103   "For use with --batch, perform automatic expansions as a stand-alone tool.
4104 This sets up the appropriate Verilog mode environment, updates automatics
4105 with \\[verilog-auto] on all command-line files, and saves the buffers.
4106 For proper results, multiple filenames need to be passed on the command
4107 line in bottom-up order."
4108   (unless noninteractive
4109     (error "Use verilog-batch-auto only with --batch"))  ;; Otherwise we'd mess up buffer modes
4110   (verilog-batch-execute-func `verilog-auto))
4111
4112 (defun verilog-batch-delete-auto ()
4113   "For use with --batch, perform automatic deletion as a stand-alone tool.
4114 This sets up the appropriate Verilog mode environment, deletes automatics
4115 with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
4116   (unless noninteractive
4117     (error "Use verilog-batch-delete-auto only with --batch"))  ;; Otherwise we'd mess up buffer modes
4118   (verilog-batch-execute-func `verilog-delete-auto))
4119
4120 (defun verilog-batch-inject-auto ()
4121   "For use with --batch, perform automatic injection as a stand-alone tool.
4122 This sets up the appropriate Verilog mode environment, injects new automatics
4123 with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
4124 For proper results, multiple filenames need to be passed on the command
4125 line in bottom-up order."
4126   (unless noninteractive
4127     (error "Use verilog-batch-inject-auto only with --batch"))  ;; Otherwise we'd mess up buffer modes
4128   (verilog-batch-execute-func `verilog-inject-auto))
4129
4130 (defun verilog-batch-indent ()
4131   "For use with --batch, reindent an a entire file as a stand-alone tool.
4132 This sets up the appropriate Verilog mode environment, calls
4133 \\[verilog-indent-buffer] on all command-line files, and saves the buffers."
4134   (unless noninteractive
4135     (error "Use verilog-batch-indent only with --batch"))  ;; Otherwise we'd mess up buffer modes
4136   (verilog-batch-execute-func `verilog-indent-buffer))
4137 \f
4138
4139 ;;
4140 ;; Indentation
4141 ;;
4142 (defconst verilog-indent-alist
4143   '((block       . (+ ind verilog-indent-level))
4144     (case        . (+ ind verilog-case-indent))
4145     (cparenexp   . (+ ind verilog-indent-level))
4146     (cexp        . (+ ind verilog-cexp-indent))
4147     (defun       . verilog-indent-level-module)
4148     (declaration . verilog-indent-level-declaration)
4149     (directive   . (verilog-calculate-indent-directive))
4150     (tf          . verilog-indent-level)
4151     (behavioral  . (+ verilog-indent-level-behavioral verilog-indent-level-module))
4152     (statement   . ind)
4153     (cpp         . 0)
4154     (comment     . (verilog-comment-indent))
4155     (unknown     . 3)
4156     (string      . 0)))
4157
4158 (defun verilog-continued-line-1 (lim)
4159   "Return true if this is a continued line.
4160 Set point to where line starts.  Limit search to point LIM."
4161   (let ((continued 't))
4162     (if (eq 0 (forward-line -1))
4163         (progn
4164           (end-of-line)
4165           (verilog-backward-ws&directives lim)
4166           (if (bobp)
4167               (setq continued nil)
4168             (setq continued (verilog-backward-token))))
4169       (setq continued nil))
4170     continued))
4171
4172 (defun verilog-calculate-indent ()
4173   "Calculate the indent of the current Verilog line.
4174 Examine previous lines.  Once a line is found that is definitive as to the
4175 type of the current line, return that lines' indent level and its type.
4176 Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
4177   (save-excursion
4178     (let* ((starting_position (point))
4179            (par 0)
4180            (begin (looking-at "[ \t]*begin\\>"))
4181            (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
4182            (type (catch 'nesting
4183                    ;; Keep working backwards until we can figure out
4184                    ;; what type of statement this is.
4185                    ;; Basically we need to figure out
4186                    ;; 1) if this is a continuation of the previous line;
4187                    ;; 2) are we in a block scope (begin..end)
4188
4189                    ;; if we are in a comment, done.
4190                    (if (verilog-in-star-comment-p)
4191                        (throw 'nesting 'comment))
4192
4193                    ;; if we have a directive, done.
4194                    (if (save-excursion (beginning-of-line) 
4195                                        (and (looking-at verilog-directive-re-1)
4196                                             (not (looking-at "[ \t]*`ovm_"))))
4197                        (throw 'nesting 'directive))
4198
4199                    ;; unless we are in the newfangled coverpoint or constraint blocks
4200                    ;; if we are in a parenthesized list, and the user likes to indent these, return.
4201                    (if (and
4202                         verilog-indent-lists
4203                         (not (verilog-in-coverage))
4204                         (verilog-in-paren))
4205                        (progn (setq par 1)
4206                               (throw 'nesting 'block)))
4207
4208                    ;; See if we are continuing a previous line
4209                    (while t
4210                      ;; trap out if we crawl off the top of the buffer
4211                      (if (bobp) (throw 'nesting 'cpp))
4212
4213                      (if (verilog-continued-line-1 lim)
4214                          (let ((sp (point)))
4215                            (if (and
4216                                 (not (looking-at verilog-complete-reg))
4217                                 (verilog-continued-line-1 lim))
4218                                (progn (goto-char sp)
4219                                       (throw 'nesting 'cexp))
4220
4221                              (goto-char sp))
4222
4223                            (if (and begin
4224                                     (not verilog-indent-begin-after-if)
4225                                     (looking-at verilog-no-indent-begin-re))
4226                                (progn
4227                                  (beginning-of-line)
4228                                  (skip-chars-forward " \t")
4229                                  (throw 'nesting 'statement))
4230                              (progn
4231                                (throw 'nesting 'cexp))))
4232                        ;; not a continued line
4233                        (goto-char starting_position))
4234
4235                      (if (looking-at "\\<else\\>")
4236                          ;; search back for governing if, striding across begin..end pairs
4237                          ;; appropriately
4238                          (let ((elsec 1))
4239                            (while (verilog-re-search-backward verilog-ends-re nil 'move)
4240                              (cond
4241                               ((match-end 1) ; else, we're in deep
4242                                (setq elsec (1+ elsec)))
4243                               ((match-end 2) ; if
4244                                (setq elsec (1- elsec))
4245                                (if (= 0 elsec)
4246                                    (if verilog-align-ifelse
4247                                        (throw 'nesting 'statement)
4248                                      (progn ;; back up to first word on this line
4249                                        (beginning-of-line)
4250                                        (verilog-forward-syntactic-ws)
4251                                        (throw 'nesting 'statement)))))
4252                               (t ; endblock
4253                                 ; try to leap back to matching outward block by striding across
4254                                 ; indent level changing tokens then immediately
4255                                 ; previous line governs indentation.
4256                                (let (( reg) (nest 1))
4257 ;;       verilog-ends =>  else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
4258                                  (cond
4259                                   ((match-end 3) ; end
4260                                    ;; Search back for matching begin
4261                                    (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
4262                                   ((match-end 4) ; endcase
4263                                    ;; Search back for matching case
4264                                    (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4265                                   ((match-end 5) ; endfunction
4266                                    ;; Search back for matching function
4267                                    (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4268                                   ((match-end 6) ; endtask
4269                                    ;; Search back for matching task
4270                                    (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
4271                                   ((match-end 7) ; endspecify
4272                                    ;; Search back for matching specify
4273                                    (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4274                                   ((match-end 8) ; endtable
4275                                    ;; Search back for matching table
4276                                    (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4277                                   ((match-end 9) ; endgenerate
4278                                    ;; Search back for matching generate
4279                                    (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4280                                   ((match-end 10) ; joins
4281                                    ;; Search back for matching fork
4282                                    (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
4283                                   ((match-end 11) ; class
4284                                    ;; Search back for matching class
4285                                    (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4286                                   ((match-end 12) ; covergroup
4287                                    ;; Search back for matching covergroup
4288                                    (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
4289                                  (catch 'skip
4290                                    (while (verilog-re-search-backward reg nil 'move)
4291                                      (cond
4292                                       ((match-end 1) ; begin
4293                                        (setq nest (1- nest))
4294                                        (if (= 0 nest)
4295                                            (throw 'skip 1)))
4296                                       ((match-end 2) ; end
4297                                        (setq nest (1+ nest)))))
4298                                    )))))))
4299                      (throw 'nesting (verilog-calc-1)))
4300                    );; catch nesting
4301                  );; type
4302            )
4303       ;; Return type of block and indent level.
4304       (if (not type)
4305           (setq type 'cpp))
4306       (if (> par 0)                     ; Unclosed Parenthesis
4307           (list 'cparenexp par)
4308         (cond
4309           ((eq type 'case)
4310            (list type (verilog-case-indent-level)))
4311           ((eq type 'statement)
4312            (list type (current-column)))
4313           ((eq type 'defun)
4314            (list type 0))
4315           (t
4316            (list type (verilog-current-indent-level))))))))
4317
4318 (defun verilog-wai ()
4319   "Show matching nesting block for debugging."
4320   (interactive)
4321   (save-excursion
4322     (let* ((type (verilog-calc-1))
4323            depth)
4324       ;; Return type of block and indent level.
4325       (if (not type)
4326           (setq type 'cpp))
4327       (if (and
4328            verilog-indent-lists
4329            (not (verilog-in-coverage))
4330            (verilog-in-paren))
4331           (setq depth 1)
4332         (cond
4333           ((eq type 'case)
4334            (setq depth (verilog-case-indent-level)))
4335           ((eq type 'statement)
4336            (setq depth (current-column)))
4337           ((eq type 'defun)
4338            (setq depth 0))
4339           (t
4340            (setq depth (verilog-current-indent-level)))))
4341       (message "You are at nesting %s depth %d" type depth))))
4342
4343 (defun verilog-calc-1 ()
4344   (catch 'nesting
4345     (let ((re (concat "\\({\\|}\\|" verilog-indent-re "\\)")))
4346       (while (verilog-re-search-backward re nil 'move)
4347         (catch 'continue
4348           (cond
4349            ((equal (char-after) ?\{)
4350             (if (verilog-at-constraint-p)
4351                 (throw 'nesting 'block)))
4352
4353            ((equal (char-after) ?\})
4354             (let ((there (verilog-at-close-constraint-p)))
4355               (if there ;; we are at the } that closes a constraing.  Find the { that opens it
4356                   (progn
4357                     (forward-char 1)
4358                     (backward-list 1)
4359                     (verilog-beg-of-statement)))))
4360            
4361            ((looking-at verilog-beg-block-re-ordered)
4362             (cond
4363              ((match-end 2)  ; *sigh* could be "unique case" or "priority casex"
4364               (let ((here (point)))
4365                 (verilog-beg-of-statement)
4366                 (if (looking-at verilog-extended-case-re)
4367                     (throw 'nesting 'case)
4368                   (goto-char here)))
4369               (throw 'nesting 'case))
4370              
4371              ((match-end 4)  ; *sigh* could be "disable fork"
4372               (let ((here (point)))
4373                 (verilog-beg-of-statement)
4374                 (if (looking-at verilog-disable-fork-re)
4375                     t ; is disable fork, this is a normal statement
4376                   (progn ; or is fork, starts a new block
4377                     (goto-char here)
4378                     (throw 'nesting 'block)))))
4379              
4380              
4381              ;; need to consider typedef struct here...
4382              ((looking-at "\\<class\\|struct\\|function\\|task\\>")
4383                                         ; *sigh* These words have an optional prefix:
4384                                         ; extern {virtual|protected}? function a();
4385                                         ; typedef class foo;
4386                                         ; and we don't want to confuse this with
4387                                         ; function a();
4388                                         ; property
4389                                         ; ...
4390                                         ; endfunction
4391               (verilog-beg-of-statement)
4392               (if (looking-at verilog-beg-block-re-ordered)
4393                   (throw 'nesting 'block)
4394                 (throw 'nesting 'defun)))
4395              
4396              ((looking-at "\\<property\\>")
4397                                         ; *sigh* 
4398                                         ;    {assert|assume|cover} property (); are complete
4399                                         ; but
4400                                         ;    property ID () ... needs end_property
4401               (verilog-beg-of-statement)
4402               (if (looking-at "\\(assert\\|assume\\|cover\\)\\s-+property\\>")
4403                   (throw 'nesting 'statement) ; We don't need an endproperty for these
4404                 (throw 'nesting 'block) ;We still need a endproperty
4405                 ))
4406              
4407              (t              (throw 'nesting 'block))))
4408            
4409            ((looking-at verilog-end-block-re)
4410             (verilog-leap-to-head)
4411             (if (verilog-in-case-region-p)
4412                 (progn
4413                   (verilog-leap-to-case-head)
4414                   (if (looking-at verilog-case-re)
4415                       (throw 'nesting 'case)))))
4416            
4417            ((looking-at verilog-defun-level-re)
4418             (if (looking-at verilog-defun-level-generate-only-re)
4419                 (if (verilog-in-generate-region-p)
4420                     (throw 'continue 'foo)  ; always block in a generate
4421                   (throw 'nesting 'defun))
4422               (throw 'nesting 'defun)))
4423            
4424            ((looking-at verilog-cpp-level-re)
4425             (throw 'nesting 'cpp))
4426            
4427            ((bobp)
4428             (throw 'nesting 'cpp)))))
4429
4430       (throw 'nesting 'cpp))))
4431
4432 (defun verilog-calculate-indent-directive ()
4433   "Return indentation level for directive.
4434 For speed, the searcher looks at the last directive, not the indent
4435 of the appropriate enclosing block."
4436   (let ((base -1)       ;; Indent of the line that determines our indentation
4437         (ind 0))        ;; Relative offset caused by other directives (like `endif on same line as `else)
4438     ;; Start at current location, scan back for another directive
4439
4440     (save-excursion
4441       (beginning-of-line)
4442       (while (and (< base 0)
4443                   (verilog-re-search-backward verilog-directive-re nil t))
4444         (cond ((save-excursion (skip-chars-backward " \t") (bolp))
4445                (setq base (current-indentation))))
4446         (cond ((and (looking-at verilog-directive-end) (< base 0))  ;; Only matters when not at BOL
4447                (setq ind (- ind verilog-indent-level-directive)))
4448               ((and (looking-at verilog-directive-middle) (>= base 0))  ;; Only matters when at BOL
4449                (setq ind (+ ind verilog-indent-level-directive)))
4450               ((looking-at verilog-directive-begin)
4451                (setq ind (+ ind verilog-indent-level-directive)))))
4452       ;; Adjust indent to starting indent of critical line
4453       (setq ind (max 0 (+ ind base))))
4454
4455     (save-excursion
4456       (beginning-of-line)
4457       (skip-chars-forward " \t")
4458       (cond ((or (looking-at verilog-directive-middle)
4459                  (looking-at verilog-directive-end))
4460              (setq ind (max 0 (- ind verilog-indent-level-directive))))))
4461    ind))
4462
4463 (defun verilog-leap-to-case-head ()
4464   (let ((nest 1))
4465     (while (/= 0 nest)
4466       (verilog-re-search-backward "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" nil 'move)
4467       (cond
4468        ((match-end 1)
4469         (setq nest (1- nest)))
4470        ((match-end 2)
4471         (setq nest (1+ nest)))
4472        ((bobp)
4473         (ding 't)
4474         (setq nest 0))))))
4475
4476 (defun verilog-leap-to-head ()
4477   "Move point to the head of this block.
4478 Jump from end to matching begin, from endcase to matching case, and so on."
4479   (let ((reg nil)
4480         snest
4481         (nesting 'yes)
4482         (nest 1))
4483     (cond
4484      ((looking-at "\\<end\\>")
4485       ;; 1: Search back for matching begin
4486       (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
4487                         "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
4488      ((looking-at "\\<endtask\\>")
4489       ;; 2: Search back for matching task
4490       (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
4491       (setq nesting 'no))
4492      ((looking-at "\\<endcase\\>")
4493       ;; 3: Search back for matching case
4494       (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)" ))
4495      ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
4496       ;; 4: Search back for matching fork
4497       (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4498      ((looking-at "\\<endclass\\>")
4499       ;; 5: Search back for matching class
4500       (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4501      ((looking-at "\\<endtable\\>")
4502       ;; 6: Search back for matching table
4503       (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4504      ((looking-at "\\<endspecify\\>")
4505       ;; 7: Search back for matching specify
4506       (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4507      ((looking-at "\\<endfunction\\>")
4508       ;; 8: Search back for matching function
4509       (setq reg "\\(\\<function\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<function\\>\\)")
4510       (setq nesting 'no))
4511       ;;(setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4512      ((looking-at "\\<endgenerate\\>")
4513       ;; 8: Search back for matching generate
4514       (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4515      ((looking-at "\\<endgroup\\>")
4516       ;; 10: Search back for matching covergroup
4517       (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
4518      ((looking-at "\\<endproperty\\>")
4519       ;; 11: Search back for matching property
4520       (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
4521      ((looking-at verilog-ovm-end-re)
4522       ;; 12: Search back for matching sequence
4523       (setq reg (concat "\\(" verilog-ovm-begin-re "\\|" verilog-ovm-end-re "\\)")))
4524      ((looking-at "\\<endinterface\\>")
4525       ;; 12: Search back for matching interface
4526       (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
4527      ((looking-at "\\<endsequence\\>")
4528       ;; 12: Search back for matching sequence
4529       (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
4530      ((looking-at "\\<endclocking\\>")
4531       ;; 12: Search back for matching clocking
4532       (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
4533     (if reg
4534         (catch 'skip
4535           (if (eq nesting 'yes)
4536               (let (sreg)
4537                 (while (verilog-re-search-backward reg nil 'move)
4538                   (cond
4539                    ((match-end 1) ; begin
4540                     (setq nest (1- nest))
4541                     (if (= 0 nest)
4542                         ;; Now previous line describes syntax
4543                         (throw 'skip 1))
4544                     (if (and snest
4545                              (= snest nest))
4546                         (setq reg sreg)))
4547                    ((match-end 2) ; end
4548                     (setq nest (1+ nest)))
4549                    ((match-end 3)
4550                     ;; endcase, jump to case
4551                     (setq snest nest)
4552                     (setq nest (1+ nest))
4553                     (setq sreg reg)
4554                     (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4555                    ((match-end 4)
4556                     ;; join, jump to fork
4557                     (setq snest nest)
4558                     (setq nest (1+ nest))
4559                     (setq sreg reg)
4560                     (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4561                    )))
4562             ;no nesting
4563             (if (and
4564                  (verilog-re-search-backward reg nil 'move)         
4565                  (match-end 1)) ; task -> could be virtual and/or protected
4566                 (progn
4567                   (verilog-beg-of-statement)
4568                   (throw 'skip 1))
4569               (throw 'skip 1)))))))
4570
4571 (defun verilog-continued-line ()
4572   "Return true if this is a continued line.
4573 Set point to where line starts."
4574   (let ((continued 't))
4575     (if (eq 0 (forward-line -1))
4576         (progn
4577           (end-of-line)
4578           (verilog-backward-ws&directives)
4579           (if (bobp)
4580               (setq continued nil)
4581             (while (and continued
4582                         (save-excursion
4583                           (skip-chars-backward " \t")
4584                           (not (bolp))))
4585             (setq continued (verilog-backward-token)))))
4586       (setq continued nil))
4587     continued))
4588
4589 (defun verilog-backward-token ()
4590   "Step backward token, returning true if we are now at an end of line token."
4591   (interactive)
4592   (verilog-backward-syntactic-ws)
4593   (cond
4594    ((bolp)
4595     nil)
4596    (;-- Anything ending in a ; is complete
4597     (= (preceding-char) ?\;)
4598     nil)
4599    (; If a "}" is prefixed by a ";", then this is a complete statement
4600     ; i.e.: constraint foo { a = b; }
4601     (= (preceding-char) ?\})
4602     (progn
4603       (backward-char)
4604       (not(verilog-at-close-constraint-p))))
4605    (;-- constraint foo { a = b }
4606     ;   is a complete statement. *sigh*
4607     (= (preceding-char) ?\{)
4608     (progn
4609       (backward-char)
4610       (not (verilog-at-constraint-p))))
4611    (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
4612     ;   also could be simply '@(foo)'
4613     ;   or foo u1 #(a=8)
4614     ;            (b, ... which ISN'T complete
4615     ;;;; Do we need this???
4616     (= (preceding-char) ?\))
4617     (progn
4618       (backward-char)
4619       (backward-up-list 1)
4620       (verilog-backward-syntactic-ws)
4621       (let ((back (point)))
4622         (forward-word -1)
4623         (cond
4624          ;;XX
4625          ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
4626           (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
4627          ((looking-at verilog-ovm-statement-re)
4628           nil)
4629          ((looking-at verilog-ovm-begin-re)
4630           t)
4631          ((looking-at verilog-ovm-end-re)
4632           t)
4633          (t
4634           (goto-char back)
4635           (cond
4636            ((= (preceding-char) ?\@)
4637             (backward-char)
4638             (save-excursion
4639               (verilog-backward-token)
4640               (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
4641            ((= (preceding-char) ?\#)
4642             (backward-char))
4643            (t t)))))))
4644
4645    (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
4646     t
4647     (forward-word -1)
4648     (cond
4649      ((looking-at "\\<else\\>")
4650       t)
4651      ((looking-at verilog-behavioral-block-beg-re)
4652       t)
4653      ((looking-at verilog-indent-re)
4654       nil)
4655      (t
4656       (let
4657           ((back (point)))
4658         (verilog-backward-syntactic-ws)
4659         (cond
4660          ((= (preceding-char) ?\:)
4661           (backward-char)
4662           (verilog-backward-syntactic-ws)
4663           (backward-sexp)
4664           (if (looking-at verilog-nameable-item-re )
4665               nil
4666             t))
4667          ((= (preceding-char) ?\#)
4668           (backward-char)
4669           t)
4670          ((= (preceding-char) ?\`)
4671           (backward-char)
4672           t)
4673
4674          (t
4675           (goto-char back)
4676           t))))))))
4677
4678 (defun verilog-backward-syntactic-ws (&optional bound)
4679   "Backward skip over syntactic whitespace for Emacs 19.
4680 Optional BOUND limits search."
4681   (save-restriction
4682     (let* ((bound (or bound (point-min))) (here bound) )
4683       (if (< bound (point))
4684           (progn
4685             (narrow-to-region bound (point))
4686             (while (/= here (point))
4687               (setq here (point))
4688               (verilog-skip-backward-comments))))))
4689   t)
4690
4691 (defun verilog-forward-syntactic-ws (&optional bound)
4692   "Forward skip over syntactic whitespace for Emacs 19.
4693 Optional BOUND limits search."
4694   (save-restriction
4695     (let* ((bound (or bound (point-max)))
4696            (here bound))
4697       (if (> bound (point))
4698           (progn
4699             (narrow-to-region (point) bound)
4700             (while (/= here (point))
4701               (setq here (point))
4702               (forward-comment (buffer-size))))))))
4703
4704 (defun verilog-backward-ws&directives (&optional bound)
4705   "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
4706 Optional BOUND limits search."
4707   (save-restriction
4708     (let* ((bound (or bound (point-min)))
4709            (here bound)
4710            (p nil) )
4711       (if (< bound (point))
4712           (progn
4713             (let ((state (save-excursion (verilog-syntax-ppss))))
4714               (cond
4715                ((nth 7 state) ;; in // comment
4716                 (verilog-re-search-backward "//" nil 'move)
4717                 (skip-chars-backward "/"))
4718                ((nth 4 state) ;; in /* */ comment
4719                 (verilog-re-search-backward "/\*" nil 'move))))
4720             (narrow-to-region bound (point))
4721             (while (/= here (point))
4722               (setq here (point))
4723               (verilog-skip-backward-comments)
4724               (setq p
4725                     (save-excursion
4726                       (beginning-of-line)
4727                       (cond
4728                        ((and verilog-highlight-translate-off
4729                              (verilog-within-translate-off))
4730                         (verilog-back-to-start-translate-off (point-min)))
4731                        ((looking-at verilog-directive-re-1)
4732                         (point))
4733                        (t
4734                         nil))))
4735               (if p (goto-char p))))))))
4736
4737 (defun verilog-forward-ws&directives (&optional bound)
4738   "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
4739 Optional BOUND limits search."
4740   (save-restriction
4741     (let* ((bound (or bound (point-max)))
4742            (here bound)
4743            jump)
4744       (if (> bound (point))
4745           (progn
4746             (let ((state (save-excursion (verilog-syntax-ppss))))
4747               (cond
4748                ((nth 7 state) ;; in // comment
4749                 (verilog-re-search-forward "//" nil 'move))
4750                ((nth 4 state) ;; in /* */ comment
4751                 (verilog-re-search-forward "/\*" nil 'move))))
4752             (narrow-to-region (point) bound)
4753             (while (/= here (point))
4754               (setq here (point)
4755                     jump nil)
4756               (forward-comment (buffer-size))
4757               (save-excursion
4758                 (beginning-of-line)
4759                 (if (looking-at verilog-directive-re-1)
4760                     (setq jump t)))
4761               (if jump
4762                   (beginning-of-line 2))))))))
4763
4764 (defun verilog-in-comment-p ()
4765  "Return true if in a star or // comment."
4766  (let ((state (save-excursion (verilog-syntax-ppss))))
4767    (or (nth 4 state) (nth 7 state))))
4768
4769 (defun verilog-in-star-comment-p ()
4770  "Return true if in a star comment."
4771  (let ((state (save-excursion (verilog-syntax-ppss))))
4772    (and
4773     (nth 4 state)                       ; t if in a comment of style a // or b /**/
4774         (not
4775          (nth 7 state)                  ; t if in a comment of style b /**/
4776          ))))
4777
4778 (defun verilog-in-slash-comment-p ()
4779  "Return true if in a slash comment."
4780  (let ((state (save-excursion (verilog-syntax-ppss))))
4781    (nth 7 state)))
4782
4783 (defun verilog-in-comment-or-string-p ()
4784  "Return true if in a string or comment."
4785  (let ((state (save-excursion (verilog-syntax-ppss))))
4786    (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
4787
4788 (defun verilog-in-escaped-name-p ()
4789  "Return true if in an escaped name."
4790  (save-excursion
4791    (backward-char)
4792    (skip-chars-backward "^ \t\n\f")
4793    (if (equal (char-after (point) ) ?\\ )
4794        t
4795      nil)))
4796
4797 (defun verilog-in-paren ()
4798  "Return true if in a parenthetical expression."
4799  (let ((state (save-excursion (verilog-syntax-ppss))))
4800    (> (nth 0 state) 0 )))
4801
4802 (defun verilog-in-coverage ()
4803  "Return true if in a constraint or coverpoint expression."
4804  (interactive)
4805  (save-excursion
4806    (if (verilog-in-paren)
4807        (progn
4808          (backward-up-list 1)
4809          (verilog-at-constraint-p)
4810          )
4811      nil)))
4812 (defun verilog-at-close-constraint-p ()
4813   "If at the } that closes a constraint or covergroup, return true."
4814   (if (and
4815        (equal (char-after) ?\})
4816        (verilog-in-paren))
4817
4818       (save-excursion
4819         (verilog-backward-ws&directives)
4820         (if (equal (char-before) ?\;)
4821             (point)
4822           nil))))
4823
4824 (defun verilog-at-constraint-p ()
4825   "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
4826   (if (save-excursion
4827         (and
4828          (equal (char-after) ?\{)
4829          (forward-list)
4830          (progn (backward-char 1)
4831                 (verilog-backward-ws&directives)
4832                 (equal (char-before) ?\;))))
4833       ;; maybe
4834       (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
4835     ;; not
4836     nil))
4837
4838 (defun verilog-parenthesis-depth ()
4839  "Return non zero if in parenthetical-expression."
4840  (save-excursion (nth 1 (verilog-syntax-ppss))))
4841
4842
4843 (defun verilog-skip-forward-comment-or-string ()
4844  "Return true if in a string or comment."
4845  (let ((state (save-excursion (verilog-syntax-ppss))))
4846    (cond
4847     ((nth 3 state)                      ;Inside string
4848      (search-forward "\"")
4849      t)
4850     ((nth 7 state)                      ;Inside // comment
4851      (forward-line 1)
4852      t)
4853     ((nth 4 state)                      ;Inside any comment (hence /**/)
4854      (search-forward "*/"))
4855     (t
4856      nil))))
4857
4858 (defun verilog-skip-backward-comment-or-string ()
4859  "Return true if in a string or comment."
4860  (let ((state (save-excursion (verilog-syntax-ppss))))
4861    (cond
4862     ((nth 3 state)                      ;Inside string
4863      (search-backward "\"")
4864      t)
4865     ((nth 7 state)                      ;Inside // comment
4866      (search-backward "//")
4867      (skip-chars-backward "/")
4868      t)
4869     ((nth 4 state)                      ;Inside /* */ comment
4870      (search-backward "/*")
4871      t)
4872     (t
4873      nil))))
4874
4875 (defun verilog-skip-backward-comments ()
4876  "Return true if a comment was skipped."
4877  (let ((more t))
4878    (while more
4879      (setq more
4880            (let ((state (save-excursion (verilog-syntax-ppss))))
4881              (cond
4882               ((nth 7 state)                    ;Inside // comment
4883                (search-backward "//")
4884                (skip-chars-backward "/")
4885                (skip-chars-backward " \t\n\f")
4886                t)
4887               ((nth 4 state)                    ;Inside /* */ comment
4888                (search-backward "/*")
4889                (skip-chars-backward " \t\n\f")
4890                t)
4891               ((and (not (bobp))
4892                     (= (char-before) ?\/)
4893                     (= (char-before (1- (point))) ?\*))
4894                (goto-char (- (point) 2))
4895                t)
4896               (t
4897                (skip-chars-backward " \t\n\f")
4898                nil)))))))
4899
4900 (defun verilog-skip-forward-comment-p ()
4901   "If in comment, move to end and return true."
4902   (let (state)
4903     (progn
4904       (setq state (save-excursion (verilog-syntax-ppss)))
4905       (cond
4906        ((nth 3 state)
4907         t)
4908        ((nth 7 state)                   ;Inside // comment
4909         (end-of-line)
4910         (forward-char 1)
4911         t)
4912        ((nth 4 state)                   ;Inside any comment
4913         t)
4914        (t
4915         nil)))))
4916
4917 (defun verilog-indent-line-relative ()
4918   "Cheap version of indent line.
4919 Only look at a few lines to determine indent level."
4920   (interactive)
4921   (let ((indent-str)
4922         (sp (point)))
4923     (if (looking-at "^[ \t]*$")
4924         (cond  ;- A blank line; No need to be too smart.
4925          ((bobp)
4926           (setq indent-str (list 'cpp 0)))
4927          ((verilog-continued-line)
4928           (let ((sp1 (point)))
4929             (if (verilog-continued-line)
4930                 (progn
4931                   (goto-char sp)
4932                   (setq indent-str
4933                         (list 'statement (verilog-current-indent-level))))
4934               (goto-char sp1)
4935               (setq indent-str (list 'block (verilog-current-indent-level)))))
4936           (goto-char sp))
4937          ((goto-char sp)
4938           (setq indent-str (verilog-calculate-indent))))
4939       (progn (skip-chars-forward " \t")
4940              (setq indent-str (verilog-calculate-indent))))
4941     (verilog-do-indent indent-str)))
4942
4943 (defun verilog-indent-line ()
4944   "Indent for special part of code."
4945   (verilog-do-indent (verilog-calculate-indent)))
4946
4947 (defun verilog-do-indent (indent-str)
4948   (let ((type (car indent-str))
4949         (ind (car (cdr indent-str))))
4950     (cond
4951      (; handle continued exp
4952       (eq type 'cexp)
4953       (let ((here (point)))
4954         (verilog-backward-syntactic-ws)
4955         (cond
4956          ((or
4957            (= (preceding-char) ?\,)
4958            (= (preceding-char) ?\])
4959            (save-excursion
4960              (verilog-beg-of-statement-1)
4961              (looking-at verilog-declaration-re)))
4962           (let* ( fst
4963                   (val
4964                    (save-excursion
4965                      (backward-char 1)
4966                      (verilog-beg-of-statement-1)
4967                      (setq fst (point))
4968                      (if (looking-at verilog-declaration-re)
4969                          (progn ;; we have multiple words
4970                            (goto-char (match-end 0))
4971                            (skip-chars-forward " \t")
4972                            (cond
4973                             ((and verilog-indent-declaration-macros
4974                                   (= (following-char) ?\`))
4975                              (progn
4976                                (forward-char 1)
4977                                (forward-word 1)
4978                                (skip-chars-forward " \t")))
4979                             ((= (following-char) ?\[)
4980                              (progn
4981                                (forward-char 1)
4982                                (backward-up-list -1)
4983                                (skip-chars-forward " \t"))))
4984                            (current-column))
4985                        (progn
4986                          (goto-char fst)
4987                          (+ (current-column) verilog-cexp-indent))))))
4988             (goto-char here)
4989             (indent-line-to val)))
4990          ((= (preceding-char) ?\) )
4991           (goto-char here)
4992           (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4993             (indent-line-to val)))
4994          (t
4995           (goto-char here)
4996           (let ((val))
4997             (verilog-beg-of-statement-1)
4998             (if (and (< (point) here)
4999                      (verilog-re-search-forward "=[ \\t]*" here 'move))
5000                 (setq val (current-column))
5001               (setq val (eval (cdr (assoc type verilog-indent-alist)))))
5002             (goto-char here)
5003             (indent-line-to val))))))
5004
5005      (; handle inside parenthetical expressions
5006       (eq type 'cparenexp)
5007       (let ((val (save-excursion
5008                    (backward-up-list 1)
5009                    (forward-char 1)
5010                    (skip-chars-forward " \t")
5011                    (current-column))))
5012         (indent-line-to val)
5013       ))
5014      
5015      (;-- Handle the ends
5016       (or
5017        (looking-at verilog-end-block-re )
5018        (verilog-at-close-constraint-p))
5019       (let ((val (if (eq type 'statement)
5020                      (- ind verilog-indent-level)
5021                    ind)))
5022         (indent-line-to val)))
5023
5024      (;-- Case -- maybe line 'em up
5025       (and (eq type 'case) (not (looking-at "^[ \t]*$")))
5026       (progn
5027         (cond
5028          ((looking-at "\\<endcase\\>")
5029           (indent-line-to ind))
5030          (t
5031           (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5032             (indent-line-to val))))))
5033
5034      (;-- defun
5035       (and (eq type 'defun)
5036            (looking-at verilog-zero-indent-re))
5037       (indent-line-to 0))
5038
5039      (;-- declaration
5040       (and (or
5041             (eq type 'defun)
5042             (eq type 'block))
5043            (looking-at verilog-declaration-re))
5044       (verilog-indent-declaration ind))
5045
5046      (;-- Everything else
5047       t
5048       (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5049         (indent-line-to val))))
5050
5051     (if (looking-at "[ \t]+$")
5052         (skip-chars-forward " \t"))
5053     indent-str                          ; Return indent data
5054     ))
5055
5056 (defun verilog-current-indent-level ()
5057   "Return the indent-level of the current statement."
5058   (save-excursion
5059     (let (par-pos)
5060       (beginning-of-line)
5061       (setq par-pos (verilog-parenthesis-depth))
5062       (while par-pos
5063         (goto-char par-pos)
5064         (beginning-of-line)
5065         (setq par-pos (verilog-parenthesis-depth)))
5066       (skip-chars-forward " \t")
5067       (current-column))))
5068
5069 (defun verilog-case-indent-level ()
5070   "Return the indent-level of the current statement.
5071 Do not count named blocks or case-statements."
5072   (save-excursion
5073     (skip-chars-forward " \t")
5074     (cond
5075      ((looking-at verilog-named-block-re)
5076       (current-column))
5077      ((and (not (looking-at verilog-case-re))
5078            (looking-at "^[^:;]+[ \t]*:"))
5079       (verilog-re-search-forward ":" nil t)
5080       (skip-chars-forward " \t")
5081       (current-column))
5082      (t
5083       (current-column)))))
5084
5085 (defun verilog-indent-comment ()
5086   "Indent current line as comment."
5087   (let* ((stcol
5088           (cond
5089            ((verilog-in-star-comment-p)
5090             (save-excursion
5091               (re-search-backward "/\\*" nil t)
5092               (1+(current-column))))
5093            (comment-column
5094              comment-column )
5095            (t
5096             (save-excursion
5097               (re-search-backward "//" nil t)
5098               (current-column))))))
5099     (indent-line-to stcol)
5100     stcol))
5101
5102 (defun verilog-more-comment ()
5103   "Make more comment lines like the previous."
5104   (let* ((star 0)
5105          (stcol
5106           (cond
5107            ((verilog-in-star-comment-p)
5108             (save-excursion
5109               (setq star 1)
5110               (re-search-backward "/\\*" nil t)
5111               (1+(current-column))))
5112            (comment-column
5113             comment-column )
5114            (t
5115             (save-excursion
5116               (re-search-backward "//" nil t)
5117               (current-column))))))
5118     (progn
5119       (indent-to stcol)
5120       (if (and star
5121                (save-excursion
5122                  (forward-line -1)
5123                  (skip-chars-forward " \t")
5124                  (looking-at "\*")))
5125           (insert "* ")))))
5126
5127 (defun verilog-comment-indent (&optional arg)
5128   "Return the column number the line should be indented to.
5129 ARG is ignored, for `comment-indent-function' compatibility."
5130   (cond
5131    ((verilog-in-star-comment-p)
5132     (save-excursion
5133       (re-search-backward "/\\*" nil t)
5134       (1+(current-column))))
5135    ( comment-column
5136      comment-column )
5137    (t
5138     (save-excursion
5139       (re-search-backward "//" nil t)
5140       (current-column)))))
5141
5142 ;;
5143
5144 (defun verilog-pretty-declarations (&optional quiet)
5145   "Line up declarations around point."
5146   (interactive)
5147   (save-excursion
5148     (if (progn
5149           (verilog-beg-of-statement-1)
5150           (looking-at verilog-declaration-re))
5151         (let* ((m1 (make-marker))
5152                (e) (r)
5153                (here (point))
5154                ;; Start of declaration range
5155                (start
5156                 (progn
5157                   (verilog-beg-of-statement-1)
5158                   (while (looking-at verilog-declaration-re)
5159                     (beginning-of-line)
5160                     (setq e (point))
5161                     (verilog-backward-syntactic-ws)
5162                     (backward-char)
5163                     (verilog-beg-of-statement-1)) ;Ack, need to grok `define
5164                   e))
5165                ;; End of declaration range
5166                (end
5167                 (progn
5168                   (goto-char here)
5169                   (verilog-end-of-statement)
5170                   (setq e (point))      ;Might be on last line
5171                   (verilog-forward-syntactic-ws)
5172                   (while (looking-at verilog-declaration-re)
5173                     (beginning-of-line)
5174                     (verilog-end-of-statement)
5175                     (setq e (point))
5176                     (verilog-forward-syntactic-ws))
5177                   e))
5178                (edpos (set-marker (make-marker) end))
5179                (ind)
5180                (base-ind
5181                 (progn
5182                   (goto-char start)
5183                   (verilog-do-indent (verilog-calculate-indent))
5184                   (verilog-forward-ws&directives)
5185                   (current-column))))
5186           (goto-char end)
5187           (goto-char start)
5188           (if (and (not quiet)
5189                    (> (- end start) 100))
5190               (message "Lining up declarations..(please stand by)"))
5191           ;; Get the beginning of line indent first
5192           (while (progn (setq e (marker-position edpos))
5193                         (< (point) e))
5194             (cond
5195              ( (save-excursion (skip-chars-backward " \t")
5196                                (bolp))
5197                (verilog-forward-ws&directives)
5198                (indent-line-to base-ind)
5199                (verilog-forward-ws&directives)
5200                (verilog-re-search-forward "[ \t\n\f]" e 'move))
5201              (t
5202               (just-one-space)
5203               (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5204             ;;(forward-line)
5205             )
5206           ;; Now find biggest prefix
5207           (setq ind (verilog-get-lineup-indent start edpos))
5208           ;; Now indent each line.
5209           (goto-char start)
5210           (while (progn (setq e (marker-position edpos))
5211                         (setq r (- e (point)))
5212                         (> r 0))
5213             (setq e (point))
5214             (unless quiet (message "%d" r))
5215             (cond
5216              ((or (and verilog-indent-declaration-macros
5217                        (looking-at verilog-declaration-re-1-macro))
5218                   (looking-at verilog-declaration-re-1-no-macro))
5219               (let ((p (match-end 0)))
5220                 (set-marker m1 p)
5221                 (if (verilog-re-search-forward "[[#`]" p 'move)
5222                     (progn
5223                       (forward-char -1)
5224                       (just-one-space)
5225                       (goto-char (marker-position m1))
5226                       (just-one-space)
5227                       (indent-to ind))
5228                   (progn
5229                     (just-one-space)
5230                     (indent-to ind)))))
5231              ((verilog-continued-line-1 start)
5232               (goto-char e)
5233               (indent-line-to ind))
5234              (t         ; Must be comment or white space
5235               (goto-char e)
5236               (verilog-forward-ws&directives)
5237               (forward-line -1)))
5238             (forward-line 1))
5239           (unless quiet (message ""))))))
5240
5241 (defun verilog-pretty-expr (&optional quiet myre)
5242   "Line up expressions around point, or optional regexp MYRE."
5243   (interactive "sRegular Expression: ((<|:)?=) ")
5244   (save-excursion
5245     (if (or (eq myre nil)
5246             (string-equal myre ""))
5247         (setq myre "\\(<\\|:\\)?="))
5248     (setq myre (concat "\\(^[^;#<=>]*\\)\\(" myre "\\)"))
5249     (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
5250       (beginning-of-line)
5251       (if (and (not (looking-at rexp ))
5252                (looking-at myre))
5253           (let* ((here (point))
5254                  (e) (r)
5255                  (start
5256                   (progn
5257                     (beginning-of-line)
5258                     (setq e (point))
5259                     (verilog-backward-syntactic-ws)
5260                     (beginning-of-line)
5261                     (while (and (not (looking-at rexp ))
5262                                 (looking-at myre)
5263                                 (not (bobp))
5264                                 )
5265                       (setq e (point))
5266                       (verilog-backward-syntactic-ws)
5267                       (beginning-of-line)
5268                       ) ;Ack, need to grok `define
5269                     e))
5270                  (end
5271                   (progn
5272                     (goto-char here)
5273                     (end-of-line)
5274                     (setq e (point))    ;Might be on last line
5275                     (verilog-forward-syntactic-ws)
5276                     (beginning-of-line)
5277                     (while (and (not (looking-at rexp ))
5278                                 (looking-at myre))
5279                       (end-of-line)
5280                       (setq e (point))
5281                       (verilog-forward-syntactic-ws)
5282                       (beginning-of-line)
5283                       )
5284                     e))
5285                  (edpos (set-marker (make-marker) end))
5286                  (ind)
5287                  )
5288             (goto-char start)
5289             (verilog-do-indent (verilog-calculate-indent))
5290             (if (and (not quiet)
5291                      (> (- end start) 100))
5292                 (message "Lining up expressions..(please stand by)"))
5293
5294             ;; Set indent to minimum throughout region
5295             (while (< (point) (marker-position edpos))
5296               (beginning-of-line)
5297               (verilog-just-one-space myre)
5298               (end-of-line)
5299               (verilog-forward-syntactic-ws)
5300               )
5301
5302             ;; Now find biggest prefix
5303             (setq ind (verilog-get-lineup-indent-2 myre start edpos))
5304
5305             ;; Now indent each line.
5306             (goto-char start)
5307             (while (progn (setq e (marker-position edpos))
5308                           (setq r (- e (point)))
5309                           (> r 0))
5310               (setq e (point))
5311               (if (not quiet) (message "%d" r))
5312               (cond
5313                ((looking-at myre)
5314                 (goto-char (match-end 1))
5315                 (if (not (verilog-parenthesis-depth)) ;; ignore parenthsized exprs
5316                     (if (eq (char-after) ?=)
5317                         (indent-to (1+ ind))    ; line up the = of the <= with surrounding =
5318                       (indent-to ind)
5319                       )))
5320                ((verilog-continued-line-1 start)
5321                 (goto-char e)
5322                 (indent-line-to ind))
5323                (t               ; Must be comment or white space
5324                 (goto-char e)
5325                 (verilog-forward-ws&directives)
5326                 (forward-line -1))
5327                )
5328               (forward-line 1))
5329             (unless quiet (message ""))
5330             )))))
5331
5332 (defun verilog-just-one-space (myre)
5333   "Remove extra spaces around regular expression MYRE."
5334   (interactive)
5335   (if (and (not(looking-at verilog-complete-reg))
5336            (looking-at myre))
5337       (let ((p1 (match-end 1))
5338             (p2 (match-end 2)))
5339         (progn
5340           (goto-char p2)
5341           (if (looking-at "\\s-") (just-one-space))
5342           (goto-char p1)
5343           (forward-char -1)
5344           (if (looking-at "\\s-") (just-one-space))
5345           ))))
5346
5347 (defun verilog-indent-declaration (baseind)
5348   "Indent current lines as declaration.
5349 Line up the variable names based on previous declaration's indentation.
5350 BASEIND is the base indent to offset everything."
5351   (interactive)
5352   (let ((pos (point-marker))
5353         (lim (save-excursion
5354                ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
5355                (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
5356                (point)))
5357         (ind)
5358         (val)
5359         (m1 (make-marker)))
5360     (setq val
5361           (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
5362     (indent-line-to val)
5363
5364     ;; Use previous declaration (in this module) as template.
5365     (if (or (memq 'all verilog-auto-lineup)
5366             (memq 'declaration verilog-auto-lineup))
5367         (if (verilog-re-search-backward
5368              (or (and verilog-indent-declaration-macros
5369                       verilog-declaration-re-1-macro)
5370                  verilog-declaration-re-1-no-macro) lim t)
5371             (progn
5372               (goto-char (match-end 0))
5373               (skip-chars-forward " \t")
5374               (setq ind (current-column))
5375               (goto-char pos)
5376               (setq val
5377                     (+ baseind
5378                        (eval (cdr (assoc 'declaration verilog-indent-alist)))))
5379               (indent-line-to val)
5380               (if (and verilog-indent-declaration-macros
5381                        (looking-at verilog-declaration-re-2-macro))
5382                   (let ((p (match-end 0)))
5383                     (set-marker m1 p)
5384                     (if (verilog-re-search-forward "[[#`]" p 'move)
5385                         (progn
5386                           (forward-char -1)
5387                           (just-one-space)
5388                           (goto-char (marker-position m1))
5389                           (just-one-space)
5390                           (indent-to ind))
5391                       (if (/= (current-column) ind)
5392                           (progn
5393                             (just-one-space)
5394                             (indent-to ind)))))
5395                 (if (looking-at verilog-declaration-re-2-no-macro)
5396                     (let ((p (match-end 0)))
5397                       (set-marker m1 p)
5398                       (if (verilog-re-search-forward "[[`#]" p 'move)
5399                           (progn
5400                             (forward-char -1)
5401                             (just-one-space)
5402                             (goto-char (marker-position m1))
5403                             (just-one-space)
5404                             (indent-to ind))
5405                         (if (/= (current-column) ind)
5406                             (progn
5407                               (just-one-space)
5408                               (indent-to ind))))))))))
5409     (goto-char pos)))
5410
5411 (defun verilog-get-lineup-indent (b edpos)
5412   "Return the indent level that will line up several lines within the region.
5413 Region is defined by B and EDPOS."
5414   (save-excursion
5415     (let ((ind 0) e)
5416       (goto-char b)
5417       ;; Get rightmost position
5418       (while (progn (setq e (marker-position edpos))
5419                     (< (point) e))
5420         (if (verilog-re-search-forward
5421              (or (and verilog-indent-declaration-macros
5422                       verilog-declaration-re-1-macro)
5423                  verilog-declaration-re-1-no-macro) e 'move)
5424             (progn
5425               (goto-char (match-end 0))
5426               (verilog-backward-syntactic-ws)
5427               (if (> (current-column) ind)
5428                   (setq ind (current-column)))
5429               (goto-char (match-end 0)))))
5430       (if (> ind 0)
5431           (1+ ind)
5432         ;; No lineup-string found
5433         (goto-char b)
5434         (end-of-line)
5435         (skip-chars-backward " \t")
5436         (1+ (current-column))))))
5437
5438 (defun verilog-get-lineup-indent-2 (myre b edpos)
5439   "Return the indent level that will line up several lines within the region."
5440   (save-excursion
5441     (let ((ind 0) e)
5442       (goto-char b)
5443       ;; Get rightmost position
5444       (while (progn (setq e (marker-position edpos))
5445                     (< (point) e))
5446         (if (and (verilog-re-search-forward myre e 'move)
5447                  (not (verilog-parenthesis-depth))) ;; skip parenthsized exprs
5448             (progn
5449               (goto-char (match-beginning 2))
5450               (verilog-backward-syntactic-ws)
5451               (if (> (current-column) ind)
5452                   (setq ind (current-column)))
5453               (goto-char (match-end 0)))
5454           ))
5455       (if (> ind 0)
5456           (1+ ind)
5457         ;; No lineup-string found
5458         (goto-char b)
5459         (end-of-line)
5460         (skip-chars-backward " \t")
5461         (1+ (current-column))))))
5462
5463 (defun verilog-comment-depth (type val)
5464   "A useful mode debugging aide.  TYPE and VAL are comments for insertion."
5465   (save-excursion
5466     (let
5467         ((b (prog2
5468                 (beginning-of-line)
5469                 (point-marker)
5470               (end-of-line)))
5471          (e (point-marker)))
5472       (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
5473           (progn
5474             (replace-match " /* -#  ## */")
5475             (end-of-line))
5476         (progn
5477           (end-of-line)
5478           (insert " /* ##  ## */"))))
5479     (backward-char 6)
5480     (insert
5481      (format "%s %d" type val))))
5482
5483 ;; \f
5484 ;;
5485 ;; Completion
5486 ;;
5487 (defvar verilog-str nil)
5488 (defvar verilog-all nil)
5489 (defvar verilog-pred nil)
5490 (defvar verilog-buffer-to-use nil)
5491 (defvar verilog-flag nil)
5492 (defvar verilog-toggle-completions nil
5493   "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
5494 Repeated use of \\[verilog-complete-word] will show you all of them.
5495 Normally, when there is more than one possible completion,
5496 it displays a list of all possible completions.")
5497
5498
5499 (defvar verilog-type-keywords
5500   '(
5501     "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
5502     "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
5503     "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pullup"
5504     "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
5505     "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
5506     "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
5507     )
5508   "*Keywords for types used when completing a word in a declaration or parmlist.
5509 \(Eg. integer, real, reg...)")
5510
5511 (defvar verilog-cpp-keywords
5512   '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
5513     "endif")
5514   "*Keywords to complete when at first word of a line in declarative scope.
5515 \(Eg. initial, always, begin, assign.)
5516 The procedures and variables defined within the Verilog program
5517 will be completed at runtime and should not be added to this list.")
5518
5519 (defvar verilog-defun-keywords
5520   (append
5521    '(
5522      "always" "always_comb" "always_ff" "always_latch" "assign"
5523      "begin" "end" "generate" "endgenerate" "module" "endmodule"
5524      "specify" "endspecify" "function" "endfunction" "initial" "final"
5525      "task" "endtask" "primitive" "endprimitive"
5526      )
5527    verilog-type-keywords)
5528   "*Keywords to complete when at first word of a line in declarative scope.
5529 \(Eg. initial, always, begin, assign.)
5530 The procedures and variables defined within the Verilog program
5531 will be completed at runtime and should not be added to this list.")
5532
5533 (defvar verilog-block-keywords
5534   '(
5535     "begin" "break" "case" "continue" "else" "end" "endfunction"
5536     "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
5537     "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
5538     "while")
5539   "*Keywords to complete when at first word of a line in behavioral scope.
5540 \(Eg. begin, if, then, else, for, fork.)
5541 The procedures and variables defined within the Verilog program
5542 will be completed at runtime and should not be added to this list.")
5543
5544 (defvar verilog-tf-keywords
5545   '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
5546   "*Keywords to complete when at first word of a line in a task or function.
5547 \(Eg. begin, if, then, else, for, fork.)
5548 The procedures and variables defined within the Verilog program
5549 will be completed at runtime and should not be added to this list.")
5550
5551 (defvar verilog-case-keywords
5552   '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
5553   "*Keywords to complete when at first word of a line in case scope.
5554 \(Eg. begin, if, then, else, for, fork.)
5555 The procedures and variables defined within the Verilog program
5556 will be completed at runtime and should not be added to this list.")
5557
5558 (defvar verilog-separator-keywords
5559   '("else" "then" "begin")
5560   "*Keywords to complete when NOT standing at the first word of a statement.
5561 \(Eg. else, then.)
5562 Variables and function names defined within the Verilog program
5563 will be completed at runtime and should not be added to this list.")
5564
5565 (defun verilog-string-diff (str1 str2)
5566   "Return index of first letter where STR1 and STR2 differs."
5567   (catch 'done
5568     (let ((diff 0))
5569       (while t
5570         (if (or (> (1+ diff) (length str1))
5571                 (> (1+ diff) (length str2)))
5572             (throw 'done diff))
5573         (or (equal (aref str1 diff) (aref str2 diff))
5574             (throw 'done diff))
5575         (setq diff (1+ diff))))))
5576
5577 ;; Calculate all possible completions for functions if argument is `function',
5578 ;; completions for procedures if argument is `procedure' or both functions and
5579 ;; procedures otherwise.
5580
5581 (defun verilog-func-completion (type)
5582   "Build regular expression for module/task/function names.
5583 TYPE is 'module, 'tf for task or function, or t if unknown."
5584   (if (string= verilog-str "")
5585       (setq verilog-str "[a-zA-Z_]"))
5586   (let ((verilog-str (concat (cond
5587                              ((eq type 'module) "\\<\\(module\\)\\s +")
5588                              ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
5589                              (t "\\<\\(task\\|function\\|module\\)\\s +"))
5590                             "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
5591         match)
5592
5593     (if (not (looking-at verilog-defun-re))
5594         (verilog-re-search-backward verilog-defun-re nil t))
5595     (forward-char 1)
5596
5597     ;; Search through all reachable functions
5598     (goto-char (point-min))
5599     (while (verilog-re-search-forward verilog-str (point-max) t)
5600       (progn (setq match (buffer-substring (match-beginning 2)
5601                                            (match-end 2)))
5602              (if (or (null verilog-pred)
5603                      (funcall verilog-pred match))
5604                  (setq verilog-all (cons match verilog-all)))))
5605     (if (match-beginning 0)
5606         (goto-char (match-beginning 0)))))
5607
5608 (defun verilog-get-completion-decl (end)
5609   "Macro for searching through current declaration (var, type or const)
5610 for matches of `str' and adding the occurrence tp `all' through point END."
5611   (let ((re (or (and verilog-indent-declaration-macros
5612                      verilog-declaration-re-2-macro)
5613                 verilog-declaration-re-2-no-macro))
5614         decl-end match)
5615     ;; Traverse lines
5616     (while (and (< (point) end)
5617                 (verilog-re-search-forward re end t))
5618       ;; Traverse current line
5619       (setq decl-end (save-excursion (verilog-declaration-end)))
5620       (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
5621                   (not (match-end 1)))
5622         (setq match (buffer-substring (match-beginning 0) (match-end 0)))
5623         (if (string-match (concat "\\<" verilog-str) match)
5624             (if (or (null verilog-pred)
5625                     (funcall verilog-pred match))
5626                 (setq verilog-all (cons match verilog-all)))))
5627       (forward-line 1)))
5628   verilog-all)
5629
5630 (defun verilog-type-completion ()
5631   "Calculate all possible completions for types."
5632   (let ((start (point))
5633         goon)
5634     ;; Search for all reachable type declarations
5635     (while (or (verilog-beg-of-defun)
5636                (setq goon (not goon)))
5637       (save-excursion
5638         (if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
5639                                                  (point))
5640                             (forward-char 1)))
5641                  (verilog-re-search-forward
5642                   "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
5643                   start t)
5644                  (not (match-end 1)))
5645             ;; Check current type declaration
5646             (verilog-get-completion-decl start))))))
5647
5648 (defun verilog-var-completion ()
5649   "Calculate all possible completions for variables (or constants)."
5650   (let ((start (point)))
5651     ;; Search for all reachable var declarations
5652     (verilog-beg-of-defun)
5653     (save-excursion
5654       ;; Check var declarations
5655       (verilog-get-completion-decl start))))
5656
5657 (defun verilog-keyword-completion (keyword-list)
5658   "Give list of all possible completions of keywords in KEYWORD-LIST."
5659   (mapcar '(lambda (s)
5660              (if (string-match (concat "\\<" verilog-str) s)
5661                  (if (or (null verilog-pred)
5662                          (funcall verilog-pred s))
5663                      (setq verilog-all (cons s verilog-all)))))
5664           keyword-list))
5665
5666
5667 (defun verilog-completion (verilog-str verilog-pred verilog-flag)
5668   "Function passed to `completing-read', `try-completion' or `all-completions'.
5669 Called to get completion on VERILOG-STR.  If VERILOG-PRED is non-nil, it
5670 must be a function to be called for every match to check if this should
5671 really be a match.  If VERILOG-FLAG is t, the function returns a list of
5672 all possible completions.  If VERILOG-FLAG is nil it returns a string,
5673 the longest possible completion, or t if VERILOG-STR is an exact match.
5674 If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
5675 exact match, nil otherwise."
5676   (save-excursion
5677     (let ((verilog-all nil))
5678       ;; Set buffer to use for searching labels. This should be set
5679       ;; within functions which use verilog-completions
5680       (set-buffer verilog-buffer-to-use)
5681
5682       ;; Determine what should be completed
5683       (let ((state (car (verilog-calculate-indent))))
5684         (cond ((eq state 'defun)
5685                (save-excursion (verilog-var-completion))
5686                (verilog-func-completion 'module)
5687                (verilog-keyword-completion verilog-defun-keywords))
5688
5689               ((eq state 'behavioral)
5690                (save-excursion (verilog-var-completion))
5691                (verilog-func-completion 'module)
5692                (verilog-keyword-completion verilog-defun-keywords))
5693
5694               ((eq state 'block)
5695                (save-excursion (verilog-var-completion))
5696                (verilog-func-completion 'tf)
5697                (verilog-keyword-completion verilog-block-keywords))
5698
5699               ((eq state 'case)
5700                (save-excursion (verilog-var-completion))
5701                (verilog-func-completion 'tf)
5702                (verilog-keyword-completion verilog-case-keywords))
5703
5704               ((eq state 'tf)
5705                (save-excursion (verilog-var-completion))
5706                (verilog-func-completion 'tf)
5707                (verilog-keyword-completion verilog-tf-keywords))
5708
5709               ((eq state 'cpp)
5710                (save-excursion (verilog-var-completion))
5711                (verilog-keyword-completion verilog-cpp-keywords))
5712
5713               ((eq state 'cparenexp)
5714                (save-excursion (verilog-var-completion)))
5715
5716               (t;--Anywhere else
5717                (save-excursion (verilog-var-completion))
5718                (verilog-func-completion 'both)
5719                (verilog-keyword-completion verilog-separator-keywords))))
5720
5721       ;; Now we have built a list of all matches. Give response to caller
5722       (verilog-completion-response))))
5723
5724 (defun verilog-completion-response ()
5725   (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
5726          ;; This was not called by all-completions
5727          (if (null verilog-all)
5728              ;; Return nil if there was no matching label
5729              nil
5730            ;; Get longest string common in the labels
5731            (let* ((elm (cdr verilog-all))
5732                   (match (car verilog-all))
5733                   (min (length match))
5734                   tmp)
5735              (if (string= match verilog-str)
5736                  ;; Return t if first match was an exact match
5737                  (setq match t)
5738                (while (not (null elm))
5739                  ;; Find longest common string
5740                  (if (< (setq tmp (verilog-string-diff match (car elm))) min)
5741                      (progn
5742                        (setq min tmp)
5743                        (setq match (substring match 0 min))))
5744                  ;; Terminate with match=t if this is an exact match
5745                  (if (string= (car elm) verilog-str)
5746                      (progn
5747                        (setq match t)
5748                        (setq elm nil))
5749                    (setq elm (cdr elm)))))
5750              ;; If this is a test just for exact match, return nil ot t
5751              (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
5752                  nil
5753                match))))
5754         ;; If flag is t, this was called by all-completions. Return
5755         ;; list of all possible completions
5756         (verilog-flag
5757          verilog-all)))
5758
5759 (defvar verilog-last-word-numb 0)
5760 (defvar verilog-last-word-shown nil)
5761 (defvar verilog-last-completions nil)
5762
5763 (defun verilog-complete-word ()
5764   "Complete word at current point.
5765 \(See also `verilog-toggle-completions', `verilog-type-keywords',
5766 and `verilog-separator-keywords'.)"
5767   (interactive)
5768   (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5769          (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5770          (verilog-str (buffer-substring b e))
5771          ;; The following variable is used in verilog-completion
5772          (verilog-buffer-to-use (current-buffer))
5773          (allcomp (if (and verilog-toggle-completions
5774                            (string= verilog-last-word-shown verilog-str))
5775                       verilog-last-completions
5776                     (all-completions verilog-str 'verilog-completion)))
5777          (match (if verilog-toggle-completions
5778                     "" (try-completion
5779                         verilog-str (mapcar '(lambda (elm)
5780                                               (cons elm 0)) allcomp)))))
5781     ;; Delete old string
5782     (delete-region b e)
5783
5784     ;; Toggle-completions inserts whole labels
5785     (if verilog-toggle-completions
5786         (progn
5787           ;; Update entry number in list
5788           (setq verilog-last-completions allcomp
5789                 verilog-last-word-numb
5790                 (if (>= verilog-last-word-numb (1- (length allcomp)))
5791                     0
5792                   (1+ verilog-last-word-numb)))
5793           (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
5794           ;; Display next match or same string if no match was found
5795           (if (not (null allcomp))
5796               (insert "" verilog-last-word-shown)
5797             (insert "" verilog-str)
5798             (message "(No match)")))
5799       ;; The other form of completion does not necessarily do that.
5800
5801       ;; Insert match if found, or the original string if no match
5802       (if (or (null match) (equal match 't))
5803           (progn (insert "" verilog-str)
5804                  (message "(No match)"))
5805         (insert "" match))
5806       ;; Give message about current status of completion
5807       (cond ((equal match 't)
5808              (if (not (null (cdr allcomp)))
5809                  (message "(Complete but not unique)")
5810                (message "(Sole completion)")))
5811             ;; Display buffer if the current completion didn't help
5812             ;; on completing the label.
5813             ((and (not (null (cdr allcomp))) (= (length verilog-str)
5814                                                 (length match)))
5815              (with-output-to-temp-buffer "*Completions*"
5816                (display-completion-list allcomp))
5817              ;; Wait for a key press. Then delete *Completion*  window
5818              (momentary-string-display "" (point))
5819              (delete-window (get-buffer-window (get-buffer "*Completions*")))
5820              )))))
5821
5822 (defun verilog-show-completions ()
5823   "Show all possible completions at current point."
5824   (interactive)
5825   (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5826          (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5827          (verilog-str (buffer-substring b e))
5828          ;; The following variable is used in verilog-completion
5829          (verilog-buffer-to-use (current-buffer))
5830          (allcomp (if (and verilog-toggle-completions
5831                            (string= verilog-last-word-shown verilog-str))
5832                       verilog-last-completions
5833                     (all-completions verilog-str 'verilog-completion))))
5834     ;; Show possible completions in a temporary buffer.
5835     (with-output-to-temp-buffer "*Completions*"
5836       (display-completion-list allcomp))
5837     ;; Wait for a key press. Then delete *Completion*  window
5838     (momentary-string-display "" (point))
5839     (delete-window (get-buffer-window (get-buffer "*Completions*")))))
5840
5841
5842 (defun verilog-get-default-symbol ()
5843   "Return symbol around current point as a string."
5844   (save-excursion
5845     (buffer-substring (progn
5846                         (skip-chars-backward " \t")
5847                         (skip-chars-backward "a-zA-Z0-9_")
5848                         (point))
5849                       (progn
5850                         (skip-chars-forward "a-zA-Z0-9_")
5851                         (point)))))
5852
5853 (defun verilog-build-defun-re (str &optional arg)
5854   "Return function/task/module starting with STR as regular expression.
5855 With optional second ARG non-nil, STR is the complete name of the instruction."
5856   (if arg
5857       (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
5858     (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
5859
5860 (defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
5861   "Function passed to `completing-read', `try-completion' or `all-completions'.
5862 Returns a completion on any function name based on VERILOG-STR prefix.  If
5863 VERILOG-PRED is non-nil, it must be a function to be called for every match
5864 to check if this should really be a match.  If VERILOG-FLAG is t, the
5865 function returns a list of all possible completions.  If it is nil it
5866 returns a string, the longest possible completion, or t if VERILOG-STR is
5867 an exact match.  If VERILOG-FLAG is 'lambda, the function returns t if
5868 VERILOG-STR is an exact match, nil otherwise."
5869   (save-excursion
5870     (let ((verilog-all nil)
5871           match)
5872
5873       ;; Set buffer to use for searching labels. This should be set
5874       ;; within functions which use verilog-completions
5875       (set-buffer verilog-buffer-to-use)
5876
5877       (let ((verilog-str verilog-str))
5878         ;; Build regular expression for functions
5879         (if (string= verilog-str "")
5880             (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
5881           (setq verilog-str (verilog-build-defun-re verilog-str)))
5882         (goto-char (point-min))
5883
5884         ;; Build a list of all possible completions
5885         (while (verilog-re-search-forward verilog-str nil t)
5886           (setq match (buffer-substring (match-beginning 2) (match-end 2)))
5887           (if (or (null verilog-pred)
5888                   (funcall verilog-pred match))
5889               (setq verilog-all (cons match verilog-all)))))
5890
5891       ;; Now we have built a list of all matches. Give response to caller
5892       (verilog-completion-response))))
5893
5894 (defun verilog-goto-defun ()
5895   "Move to specified Verilog module/task/function.
5896 The default is a name found in the buffer around point.
5897 If search fails, other files are checked based on
5898 `verilog-library-flags'."
5899   (interactive)
5900   (let* ((default (verilog-get-default-symbol))
5901          ;; The following variable is used in verilog-comp-function
5902          (verilog-buffer-to-use (current-buffer))
5903          (label (if (not (string= default ""))
5904                     ;; Do completion with default
5905                     (completing-read (concat "Goto-Label: (default "
5906                                              default ") ")
5907                                      'verilog-comp-defun nil nil "")
5908                   ;; There is no default value. Complete without it
5909                   (completing-read "Goto-Label: "
5910                                    'verilog-comp-defun nil nil "")))
5911          pt)
5912     ;; Make sure library paths are correct, in case need to resolve module
5913     (verilog-auto-reeval-locals)
5914     (verilog-getopt-flags)
5915     ;; If there was no response on prompt, use default value
5916     (if (string= label "")
5917         (setq label default))
5918     ;; Goto right place in buffer if label is not an empty string
5919     (or (string= label "")
5920         (progn
5921           (save-excursion
5922             (goto-char (point-min))
5923             (setq pt
5924                   (re-search-forward (verilog-build-defun-re label t) nil t)))
5925           (when pt
5926             (goto-char pt)
5927             (beginning-of-line))
5928           pt)
5929         (verilog-goto-defun-file label))))
5930
5931 ;; Eliminate compile warning
5932 (defvar occur-pos-list)
5933
5934 (defun verilog-showscopes ()
5935   "List all scopes in this module."
5936   (interactive)
5937   (let ((buffer (current-buffer))
5938         (linenum 1)
5939         (nlines 0)
5940         (first 1)
5941         (prevpos (point-min))
5942         (final-context-start (make-marker))
5943         (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
5944     (with-output-to-temp-buffer "*Occur*"
5945       (save-excursion
5946         (message (format "Searching for %s ..." regexp))
5947         ;; Find next match, but give up if prev match was at end of buffer.
5948         (while (and (not (= prevpos (point-max)))
5949                     (verilog-re-search-forward regexp nil t))
5950           (goto-char (match-beginning 0))
5951           (beginning-of-line)
5952           (save-match-data
5953             (setq linenum (+ linenum (count-lines prevpos (point)))))
5954           (setq prevpos (point))
5955           (goto-char (match-end 0))
5956           (let* ((start (save-excursion
5957                           (goto-char (match-beginning 0))
5958                           (forward-line (if (< nlines 0) nlines (- nlines)))
5959                           (point)))
5960                  (end (save-excursion
5961                         (goto-char (match-end 0))
5962                         (if (> nlines 0)
5963                             (forward-line (1+ nlines))
5964                             (forward-line 1))
5965                         (point)))
5966                  (tag (format "%3d" linenum))
5967                  (empty (make-string (length tag) ?\ ))
5968                  tem)
5969             (save-excursion
5970               (setq tem (make-marker))
5971               (set-marker tem (point))
5972               (set-buffer standard-output)
5973               (setq occur-pos-list (cons tem occur-pos-list))
5974               (or first (zerop nlines)
5975                   (insert "--------\n"))
5976               (setq first nil)
5977               (insert-buffer-substring buffer start end)
5978               (backward-char (- end start))
5979               (setq tem (if (< nlines 0) (- nlines) nlines))
5980               (while (> tem 0)
5981                 (insert empty ?:)
5982                 (forward-line 1)
5983                 (setq tem (1- tem)))
5984               (let ((this-linenum linenum))
5985                 (set-marker final-context-start
5986                             (+ (point) (- (match-end 0) (match-beginning 0))))
5987                 (while (< (point) final-context-start)
5988                   (if (null tag)
5989                       (setq tag (format "%3d" this-linenum)))
5990                   (insert tag ?:)))))))
5991       (set-buffer-modified-p nil))))
5992
5993
5994 ;; Highlight helper functions
5995 (defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
5996 (defun verilog-within-translate-off ()
5997   "Return point if within translate-off region, else nil."
5998   (and (save-excursion
5999          (re-search-backward
6000           (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
6001           nil t))
6002        (equal "off" (match-string 2))
6003        (point)))
6004
6005 (defun verilog-start-translate-off (limit)
6006   "Return point before translate-off directive if before LIMIT, else nil."
6007   (when (re-search-forward
6008           (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6009           limit t)
6010     (match-beginning 0)))
6011
6012 (defun verilog-back-to-start-translate-off (limit)
6013   "Return point before translate-off directive if before LIMIT, else nil."
6014   (when (re-search-backward
6015           (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6016           limit t)
6017     (match-beginning 0)))
6018
6019 (defun verilog-end-translate-off (limit)
6020   "Return point after translate-on directive if before LIMIT, else nil."
6021
6022   (re-search-forward (concat
6023                       "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
6024
6025 (defun verilog-match-translate-off (limit)
6026   "Match a translate-off block, setting `match-data' and returning t, else nil.
6027 Bound search by LIMIT."
6028   (when (< (point) limit)
6029     (let ((start (or (verilog-within-translate-off)
6030                      (verilog-start-translate-off limit)))
6031           (case-fold-search t))
6032       (when start
6033         (let ((end (or (verilog-end-translate-off limit) limit)))
6034           (set-match-data (list start end))
6035           (goto-char end))))))
6036
6037 (defun verilog-font-lock-match-item (limit)
6038   "Match, and move over, any declaration item after point.
6039 Bound search by LIMIT.  Adapted from
6040 `font-lock-match-c-style-declaration-item-and-skip-to-next'."
6041   (condition-case nil
6042       (save-restriction
6043         (narrow-to-region (point-min) limit)
6044         ;; match item
6045         (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
6046           (save-match-data
6047             (goto-char (match-end 1))
6048             ;; move to next item
6049             (if (looking-at "\\(\\s-*,\\)")
6050                 (goto-char (match-end 1))
6051               (end-of-line) t))))
6052     (error nil)))
6053
6054
6055 ;; Added by Subbu Meiyappan for Header
6056
6057 (defun verilog-header ()
6058   "Insert a standard Verilog file header."
6059   (interactive)
6060   (let ((start (point)))
6061   (insert "\
6062 //-----------------------------------------------------------------------------
6063 // Title         : <title>
6064 // Project       : <project>
6065 //-----------------------------------------------------------------------------
6066 // File          : <filename>
6067 // Author        : <author>
6068 // Created       : <credate>
6069 // Last modified : <moddate>
6070 //-----------------------------------------------------------------------------
6071 // Description :
6072 // <description>
6073 //-----------------------------------------------------------------------------
6074 // Copyright (c) <copydate> by <company> This model is the confidential and
6075 // proprietary property of <company> and the possession or use of this
6076 // file requires a written license from <company>.
6077 //------------------------------------------------------------------------------
6078 // Modification history :
6079 // <modhist>
6080 //-----------------------------------------------------------------------------
6081
6082 ")
6083     (goto-char start)
6084     (search-forward "<filename>")
6085     (replace-match (buffer-name) t t)
6086     (search-forward "<author>") (replace-match "" t t)
6087     (insert (user-full-name))
6088     (insert "  <" (user-login-name) "@" (system-name) ">")
6089     (search-forward "<credate>") (replace-match "" t t)
6090     (verilog-insert-date)
6091     (search-forward "<moddate>") (replace-match "" t t)
6092     (verilog-insert-date)
6093     (search-forward "<copydate>") (replace-match "" t t)
6094     (verilog-insert-year)
6095     (search-forward "<modhist>") (replace-match "" t t)
6096     (verilog-insert-date)
6097     (insert " : created")
6098     (goto-char start)
6099     (let (string)
6100       (setq string (read-string "title: "))
6101       (search-forward "<title>")
6102       (replace-match string t t)
6103       (setq string (read-string "project: " verilog-project))
6104       (setq verilog-project string)
6105       (search-forward "<project>")
6106       (replace-match string t t)
6107       (setq string (read-string "Company: " verilog-company))
6108       (setq verilog-company string)
6109       (search-forward "<company>")
6110       (replace-match string t t)
6111       (search-forward "<company>")
6112       (replace-match string t t)
6113       (search-forward "<company>")
6114       (replace-match string t t)
6115       (search-backward "<description>")
6116       (replace-match "" t t))))
6117
6118 ;; verilog-header Uses the verilog-insert-date function
6119
6120 (defun verilog-insert-date ()
6121   "Insert date from the system."
6122   (interactive)
6123   (let ((timpos))
6124     (setq timpos (point))
6125     (if verilog-date-scientific-format
6126         (shell-command  "date \"+@%Y/%m/%d\"" t)
6127       (shell-command  "date \"+@%d.%m.%Y\"" t))
6128     (search-forward "@")
6129     (delete-region timpos (point))
6130     (end-of-line))
6131     (delete-char 1))
6132
6133 (defun verilog-insert-year ()
6134   "Insert year from the system."
6135   (interactive)
6136   (let ((timpos))
6137     (setq timpos (point))
6138     (shell-command  "date \"+@%Y\"" t)
6139     (search-forward "@")
6140     (delete-region timpos (point))
6141     (end-of-line))
6142   (delete-char 1))
6143
6144 \f
6145 ;;
6146 ;; Signal list parsing
6147 ;;
6148
6149 ;; Elements of a signal list
6150 (defsubst verilog-sig-name (sig)
6151   (car sig))
6152 (defsubst verilog-sig-bits (sig)
6153   (nth 1 sig))
6154 (defsubst verilog-sig-comment (sig)
6155   (nth 2 sig))
6156 (defsubst verilog-sig-memory (sig)
6157   (nth 3 sig))
6158 (defsubst verilog-sig-enum (sig)
6159   (nth 4 sig))
6160 (defsubst verilog-sig-signed (sig)
6161   (nth 5 sig))
6162 (defsubst verilog-sig-type (sig)
6163   (nth 6 sig))
6164 (defsubst verilog-sig-multidim (sig)
6165   (nth 7 sig))
6166 (defsubst verilog-sig-multidim-string (sig)
6167   (if (verilog-sig-multidim sig)
6168       (let ((str "") (args (verilog-sig-multidim sig)))
6169         (while args
6170           (setq str (concat str (car args)))
6171           (setq args (cdr args)))
6172         str)))
6173 (defsubst verilog-sig-width (sig)
6174   (verilog-make-width-expression (verilog-sig-bits sig)))
6175
6176 (defsubst verilog-alw-get-inputs (sigs)
6177   (nth 2 sigs))
6178 (defsubst verilog-alw-get-outputs (sigs)
6179   (nth 0 sigs))
6180 (defsubst verilog-alw-get-uses-delayed (sigs)
6181   (nth 3 sigs))
6182
6183 (defun verilog-signals-not-in (in-list not-list)
6184   "Return list of signals in IN-LIST that aren't also in NOT-LIST.
6185 Also remove any duplicates in IN-LIST.
6186 Signals must be in standard (base vector) form."
6187   (let (out-list)
6188     (while in-list
6189       (if (not (or (assoc (car (car in-list)) not-list)
6190                    (assoc (car (car in-list)) out-list)))
6191           (setq out-list (cons (car in-list) out-list)))
6192       (setq in-list (cdr in-list)))
6193     (nreverse out-list)))
6194 ;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
6195
6196 (defun verilog-signals-in (in-list other-list)
6197   "Return list of signals in IN-LIST that are also in OTHER-LIST.
6198 Signals must be in standard (base vector) form."
6199   (let (out-list)
6200     (while in-list
6201       (if (assoc (car (car in-list)) other-list)
6202           (setq out-list (cons (car in-list) out-list)))
6203       (setq in-list (cdr in-list)))
6204     (nreverse out-list)))
6205 ;;(verilog-signals-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
6206
6207 (defun verilog-signals-memory (in-list)
6208   "Return list of signals in IN-LIST that are memoried (multidimensional)."
6209   (let (out-list)
6210     (while in-list
6211       (if (nth 3 (car in-list))
6212           (setq out-list (cons (car in-list) out-list)))
6213       (setq in-list (cdr in-list)))
6214     out-list))
6215 ;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
6216
6217 (defun verilog-signals-sort-compare (a b)
6218   "Compare signal A and B for sorting."
6219   (string< (car a) (car b)))
6220
6221 (defun verilog-signals-not-params (in-list)
6222   "Return list of signals in IN-LIST that aren't parameters or numeric constants."
6223   (let (out-list)
6224     (while in-list
6225       (unless (boundp (intern (concat "vh-" (car (car in-list)))))
6226         (setq out-list (cons (car in-list) out-list)))
6227       (setq in-list (cdr in-list)))
6228     (nreverse out-list)))
6229
6230 (defun verilog-signals-combine-bus (in-list)
6231   "Return a list of signals in IN-LIST, with busses combined.
6232 Duplicate signals are also removed.  For example A[2] and A[1] become A[2:1]."
6233   (let (combo buswarn
6234         out-list
6235         sig highbit lowbit              ; Temp information about current signal
6236         sv-name sv-highbit sv-lowbit    ; Details about signal we are forming
6237         sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
6238         bus)
6239     ;; Shove signals so duplicated signals will be adjacent
6240     (setq in-list (sort in-list `verilog-signals-sort-compare))
6241     (while in-list
6242       (setq sig (car in-list))
6243       ;; No current signal; form from existing details
6244       (unless sv-name
6245         (setq sv-name    (verilog-sig-name sig)
6246               sv-highbit nil
6247               sv-busstring nil
6248               sv-comment (verilog-sig-comment sig)
6249               sv-memory  (verilog-sig-memory sig)
6250               sv-enum    (verilog-sig-enum sig)
6251               sv-signed  (verilog-sig-signed sig)
6252               sv-type    (verilog-sig-type sig)
6253               sv-multidim (verilog-sig-multidim sig)
6254               combo ""
6255               buswarn ""))
6256       ;; Extract bus details
6257       (setq bus (verilog-sig-bits sig))
6258       (cond ((and bus
6259                   (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
6260                            (setq highbit (string-to-number (match-string 1 bus))
6261                                  lowbit  (string-to-number
6262                                           (match-string 2 bus))))
6263                       (and (string-match "\\[\\([0-9]+\\)\\]" bus)
6264                            (setq highbit (string-to-number (match-string 1 bus))
6265                                  lowbit  highbit))))
6266              ;; Combine bits in bus
6267              (if sv-highbit
6268                  (setq sv-highbit (max highbit sv-highbit)
6269                        sv-lowbit  (min lowbit  sv-lowbit))
6270                (setq sv-highbit highbit
6271                      sv-lowbit  lowbit)))
6272             (bus
6273              ;; String, probably something like `preproc:0
6274              (setq sv-busstring bus)))
6275       ;; Peek ahead to next signal
6276       (setq in-list (cdr in-list))
6277       (setq sig (car in-list))
6278       (cond ((and sig (equal sv-name (verilog-sig-name sig)))
6279              ;; Combine with this signal
6280              (when (and sv-busstring
6281                         (not (equal sv-busstring (verilog-sig-bits sig))))
6282                (when nil  ;; Debugging
6283                  (message (concat "Warning, can't merge into single bus "
6284                                   sv-name bus
6285                                   ", the AUTOs may be wrong")))
6286                (setq buswarn ", Couldn't Merge"))
6287              (if (verilog-sig-comment sig) (setq combo ", ..."))
6288              (setq sv-memory (or sv-memory (verilog-sig-memory sig))
6289                    sv-enum   (or sv-enum   (verilog-sig-enum sig))
6290                    sv-signed (or sv-signed (verilog-sig-signed sig))
6291                    sv-type   (or sv-type   (verilog-sig-type sig))
6292                    sv-multidim (or sv-multidim (verilog-sig-multidim sig))))
6293             ;; Doesn't match next signal, add to queue, zero in prep for next
6294             ;; Note sig may also be nil for the last signal in the list
6295             (t
6296              (setq out-list
6297                    (cons
6298                     (list sv-name
6299                           (or sv-busstring
6300                               (if sv-highbit
6301                                   (concat "[" (int-to-string sv-highbit) ":"
6302                                           (int-to-string sv-lowbit) "]")))
6303                           (concat sv-comment combo buswarn)
6304                           sv-memory sv-enum sv-signed sv-type sv-multidim)
6305                     out-list)
6306                    sv-name nil))))
6307     ;;
6308     out-list))
6309
6310 (defun verilog-sig-tieoff (sig &optional no-width)
6311   "Return tieoff expression for given SIG, with appropriate width.
6312 Ignore width if optional NO-WIDTH is set."
6313   (let* ((width (if no-width nil (verilog-sig-width sig))))
6314     (concat
6315      (if (and verilog-active-low-regexp
6316               (string-match verilog-active-low-regexp (verilog-sig-name sig)))
6317          "~" "")
6318      (cond ((not width)
6319             "0")
6320            ((string-match "^[0-9]+$" width)
6321             (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
6322            (t
6323             (concat "{" width "{1'b0}}"))))))
6324
6325 ;;
6326 ;; Port/Wire/Etc Reading
6327 ;;
6328
6329 (defun verilog-read-inst-backward-name ()
6330   "Internal.  Move point back to beginning of inst-name."
6331     (verilog-backward-open-paren)
6332     (let (done)
6333       (while (not done)
6334         (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil)  ; ] isn't word boundary
6335         (cond ((looking-at ")")
6336                (verilog-backward-open-paren))
6337               (t (setq done t)))))
6338     (while (looking-at "\\]")
6339       (verilog-backward-open-bracket)
6340       (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
6341     (skip-chars-backward "a-zA-Z0-9`_$"))
6342
6343 (defun verilog-read-inst-module ()
6344   "Return module_name when point is inside instantiation."
6345   (save-excursion
6346     (verilog-read-inst-backward-name)
6347     ;; Skip over instantiation name
6348     (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil)  ; ) isn't word boundary
6349     ;; Check for parameterized instantiations
6350     (when (looking-at ")")
6351       (verilog-backward-open-paren)
6352       (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
6353     (skip-chars-backward "a-zA-Z0-9'_$")
6354     (looking-at "[a-zA-Z0-9`_\$]+")
6355     ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6356     (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
6357
6358 (defun verilog-read-inst-name ()
6359   "Return instance_name when point is inside instantiation."
6360   (save-excursion
6361     (verilog-read-inst-backward-name)
6362     (looking-at "[a-zA-Z0-9`_\$]+")
6363     ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6364     (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
6365
6366 (defun verilog-read-module-name ()
6367   "Return module name when after its ( or ;."
6368   (save-excursion
6369     (re-search-backward "[(;]")
6370     (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
6371     (skip-chars-backward "a-zA-Z0-9`_$")
6372     (looking-at "[a-zA-Z0-9`_\$]+")
6373     ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6374     (verilog-symbol-detick
6375      (buffer-substring-no-properties (match-beginning 0) (match-end 0)) t)))
6376
6377 (defun verilog-read-inst-param-value ()
6378   "Return list of parameters and values when point is inside instantiation."
6379   (save-excursion
6380     (verilog-read-inst-backward-name)
6381     ;; Skip over instantiation name
6382     (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil)  ; ) isn't word boundary
6383     ;; If there are parameterized instantiations
6384     (when (looking-at ")")
6385       (let ((end-pt (point))
6386             params
6387             param-name paren-beg-pt param-value)
6388         (verilog-backward-open-paren)
6389         (while (verilog-re-search-forward-quick "\\." end-pt t)
6390           (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
6391           (skip-chars-backward "a-zA-Z0-9'_$")
6392           (looking-at "[a-zA-Z0-9`_\$]+")
6393           (setq param-name (buffer-substring-no-properties
6394                             (match-beginning 0) (match-end 0)))
6395           (verilog-re-search-forward-quick "(" nil nil)
6396           (setq paren-beg-pt (point))
6397           (verilog-forward-close-paren)
6398           (setq param-value (verilog-string-remove-spaces
6399                              (buffer-substring-no-properties
6400                               paren-beg-pt (1- (point)))))
6401           (setq params (cons (list param-name param-value) params)))
6402         params))))
6403
6404 (defun verilog-read-auto-params (num-param &optional max-param)
6405   "Return parameter list inside auto.
6406 Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
6407   (let ((olist))
6408     (save-excursion
6409       ;; /*AUTOPUNT("parameter", "parameter")*/
6410       (search-backward "(")
6411       (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
6412         (setq olist (cons (match-string 1) olist))
6413         (goto-char (match-end 0))))
6414     (or (eq nil num-param)
6415         (<= num-param (length olist))
6416         (error "%s: Expected %d parameters" (verilog-point-text) num-param))
6417     (if (eq max-param nil) (setq max-param num-param))
6418     (or (eq nil max-param)
6419         (>= max-param (length olist))
6420         (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
6421     (nreverse olist)))
6422
6423 (defun verilog-read-decls ()
6424   "Compute signal declaration information for the current module at point.
6425 Return a array of [outputs inouts inputs wire reg assign const]."
6426   (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
6427         (functask 0) (paren 0) (sig-paren 0)
6428         sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const sigs-gparam
6429         vec expect-signal keywd newsig rvalue enum io signed typedefed multidim)
6430     (save-excursion
6431       (verilog-beg-of-defun)
6432       (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
6433       (while (< (point) end-mod-point)
6434         ;;(if dbg (setq dbg (cons (format "Pt %s  Vec %s   Kwd'%s'\n" (point) vec keywd) dbg)))
6435         (cond
6436          ((looking-at "//")
6437           (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6438               (setq enum (match-string 1)))
6439           (search-forward "\n"))
6440          ((looking-at "/\\*")
6441           (forward-char 2)
6442           (if (looking-at "[^*]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6443               (setq enum (match-string 1)))
6444           (or (search-forward "*/")
6445               (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6446          ((looking-at "(\\*")
6447           (forward-char 2)
6448           (or (looking-at "\\s-*)")   ; It's an "always @ (*)"
6449               (search-forward "*)")
6450               (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
6451          ((eq ?\" (following-char))
6452           (or (re-search-forward "[^\\]\"" nil t)       ;; don't forward-char first, since we look for a non backslash first
6453               (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
6454          ((eq ?\; (following-char))
6455           (setq vec nil  io nil  expect-signal nil  newsig nil  paren 0  rvalue nil)
6456           (forward-char 1))
6457          ((eq ?= (following-char))
6458           (setq rvalue t  newsig nil)
6459           (forward-char 1))
6460          ((and (or rvalue sig-paren)
6461                (cond ((and (eq ?, (following-char))
6462                            (eq paren sig-paren))
6463                       (setq rvalue nil)
6464                       (forward-char 1)
6465                       t)
6466                      ;; ,'s can occur inside {} & funcs
6467                      ((looking-at "[{(]")
6468                       (setq paren (1+ paren))
6469                       (forward-char 1)
6470                       t)
6471                      ((looking-at "[})]")
6472                       (setq paren (1- paren))
6473                       (forward-char 1)
6474                       (when (< paren sig-paren)
6475                         (setq expect-signal nil))   ; ) that ends variables inside v2k arg list
6476                       t))))
6477          ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
6478           (goto-char (match-end 0))
6479           (cond (newsig ; Memory, not just width.  Patch last signal added's memory (nth 3)
6480                  (setcar (cdr (cdr (cdr newsig))) (match-string 1)))
6481                 (vec ;; Multidimensional
6482                  (setq multidim (cons vec multidim))
6483                  (setq vec (verilog-string-replace-matches
6484                             "\\s-+" "" nil nil (match-string 1))))
6485                 (t ;; Bit width
6486                  (setq vec (verilog-string-replace-matches
6487                             "\\s-+" "" nil nil (match-string 1))))))
6488          ;; Normal or escaped identifier -- note we remember the \ if escaped
6489          ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
6490           (goto-char (match-end 0))
6491           (setq keywd (match-string 1))
6492           (when (string-match "^\\\\" keywd)
6493             (setq keywd (concat keywd " ")))  ;; Escaped ID needs space at end
6494           (cond ((equal keywd "input")
6495                  (setq vec nil enum nil  rvalue nil  newsig nil  signed nil  typedefed nil  multidim nil  sig-paren paren
6496                        expect-signal 'sigs-in  io t))
6497                 ((equal keywd "output")
6498                  (setq vec nil enum nil  rvalue nil  newsig nil  signed nil  typedefed nil  multidim nil  sig-paren paren
6499                        expect-signal 'sigs-out  io t))
6500                 ((equal keywd "inout")
6501                  (setq vec nil enum nil  rvalue nil  newsig nil  signed nil  typedefed nil  multidim nil  sig-paren paren
6502                        expect-signal 'sigs-inout  io t))
6503                 ((equal keywd "parameter")
6504                  (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
6505                        expect-signal 'sigs-gparam  io t))
6506                 ((or (equal keywd "wire")
6507                      (equal keywd "tri")
6508                      (equal keywd "tri0")
6509                      (equal keywd "tri1"))
6510                  (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
6511                                   expect-signal 'sigs-wire)))
6512                 ((member keywd (list "reg" "trireg"
6513                                      "byte" "shortint" "int" "longint" "integer" "time"
6514                                      "bit" "logic"))
6515                  (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
6516                                   expect-signal 'sigs-reg)))
6517                 ((equal keywd "assign")
6518                  (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
6519                        expect-signal 'sigs-assign))
6520                 ((or (equal keywd "supply0")
6521                      (equal keywd "supply1")
6522                      (equal keywd "supply")
6523                      (equal keywd "localparam")
6524                      (equal keywd "genvar"))
6525                  (unless io (setq vec nil  enum nil  rvalue nil  signed nil  typedefed nil  multidim nil  sig-paren paren
6526                                   expect-signal 'sigs-const)))
6527                 ((equal keywd "signed")
6528                  (setq signed "signed"))
6529                 ((or (equal keywd "function")
6530                      (equal keywd "task"))
6531                  (setq functask (1+ functask)))
6532                 ((or (equal keywd "endfunction")
6533                      (equal keywd "endtask"))
6534                  (setq functask (1- functask)))
6535                 ((or (equal keywd "`ifdef")
6536                      (equal keywd "`ifndef"))
6537                  (setq rvalue t))
6538                 ((verilog-typedef-name-p keywd)
6539                  (setq typedefed keywd))
6540                 ((and expect-signal
6541                       (eq functask 0)
6542                       (not rvalue)
6543                       (eq paren sig-paren)
6544                       (not (member keywd verilog-keywords)))
6545                  ;; Add new signal to expect-signal's variable
6546                  (setq newsig (list keywd vec nil nil enum signed typedefed multidim))
6547                  (set expect-signal (cons newsig
6548                                           (symbol-value expect-signal))))))
6549          (t
6550           (forward-char 1)))
6551         (skip-syntax-forward " "))
6552       ;; Return arguments
6553       (vector (nreverse sigs-out)
6554               (nreverse sigs-inout)
6555               (nreverse sigs-in)
6556               (nreverse sigs-wire)
6557               (nreverse sigs-reg)
6558               (nreverse sigs-assign)
6559               (nreverse sigs-const)
6560               (nreverse sigs-gparam)))))
6561
6562 (eval-when-compile
6563   ;; Prevent compile warnings; these are let's, not globals
6564   ;; Do not remove the eval-when-compile
6565   ;; - we want a error when we are debugging this code if they are refed.
6566   (defvar sigs-in)
6567   (defvar sigs-inout)
6568   (defvar sigs-out))
6569
6570
6571 (defsubst verilog-modi-get-decls (modi)
6572   (verilog-modi-cache-results modi 'verilog-read-decls))
6573
6574 (defsubst verilog-modi-get-sub-decls (modi)
6575   (verilog-modi-cache-results modi 'verilog-read-sub-decls))
6576
6577
6578 ;; Signal reading for given module
6579 ;; Note these all take modi's - as returned from the
6580 ;; verilog-modi-current function.
6581 (defsubst verilog-decls-get-outputs (decls)
6582   (aref decls 0))
6583 (defsubst verilog-decls-get-inouts (decls)
6584   (aref decls 1))
6585 (defsubst verilog-decls-get-inputs (decls)
6586   (aref decls 2))
6587 (defsubst verilog-decls-get-wires (decls)
6588   (aref decls 3))
6589 (defsubst verilog-decls-get-regs (decls)
6590   (aref decls 4))
6591 (defsubst verilog-decls-get-assigns (decls)
6592   (aref decls 5))
6593 (defsubst verilog-decls-get-consts (decls)
6594   (aref decls 6))
6595 (defsubst verilog-decls-get-gparams (decls)
6596   (aref decls 7))
6597 (defsubst verilog-subdecls-get-outputs (subdecls)
6598   (aref subdecls 0))
6599 (defsubst verilog-subdecls-get-inouts (subdecls)
6600   (aref subdecls 1))
6601 (defsubst verilog-subdecls-get-inputs (subdecls)
6602   (aref subdecls 2))
6603
6604
6605 (defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
6606   "For `verilog-read-sub-decls-line', add a signal."
6607   (let (portdata)
6608     (when sig
6609       (setq port (verilog-symbol-detick-denumber port))
6610       (setq sig  (verilog-symbol-detick-denumber sig))
6611       (if sig (setq sig  (verilog-string-replace-matches "^[---+~!|&]+" "" nil nil sig)))
6612       (if vec (setq vec  (verilog-symbol-detick-denumber vec)))
6613       (if multidim (setq multidim  (mapcar `verilog-symbol-detick-denumber multidim)))
6614       (unless (or (not sig)
6615                   (equal sig ""))  ;; Ignore .foo(1'b1) assignments
6616         (cond ((setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
6617                (setq sigs-inout (cons (list sig vec (concat "To/From " comment) nil nil
6618                                             (verilog-sig-signed portdata)
6619                                             (verilog-sig-type portdata)
6620                                             multidim)
6621                                       sigs-inout)))
6622               ((setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
6623                (setq sigs-out   (cons (list sig vec (concat "From " comment) nil nil
6624                                             (verilog-sig-signed portdata)
6625                                             (verilog-sig-type portdata)
6626                                             multidim)
6627                                       sigs-out)))
6628               ((setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
6629                (setq sigs-in    (cons (list sig vec (concat "To " comment) nil nil
6630                                             (verilog-sig-signed portdata)
6631                                             (verilog-sig-type portdata)
6632                                             multidim)
6633                                       sigs-in)))
6634               ;; (t  -- warning pin isn't defined.)   ; Leave for lint tool
6635               )))))
6636
6637 (defun verilog-read-sub-decls-line (submoddecls comment)
6638   "For `verilog-read-sub-decls', read lines of port defs until none match anymore.
6639 Return the list of signals found, using submodi to look up each port."
6640   (let (done port sig vec multidim)
6641     (save-excursion
6642       (forward-line 1)
6643       (while (not done)
6644         ;; Get port name
6645         (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
6646                (setq port (match-string 1))
6647                (goto-char (match-end 0)))
6648               ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
6649                (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
6650                (goto-char (match-end 0)))
6651               ((looking-at "\\s-*\\.[^(]*(")
6652                (setq port nil) ;; skip this line
6653                (goto-char (match-end 0)))
6654               (t
6655                (setq port nil  done t))) ;; Unknown, ignore rest of line
6656         ;; Get signal name
6657         (when port
6658           (setq multidim nil)
6659           (cond ((looking-at "\\(\\\\[^ \t\n\f]*\\)\\s-*)")
6660                  (setq sig (concat (match-string 1) " ") ;; escaped id's need trailing space
6661                        vec nil))
6662                 ; We intentionally ignore (non-escaped) signals with .s in them
6663                 ; this prevents AUTOWIRE etc from noticing hierarchical sigs.
6664                 ((looking-at "\\([^[({).]*\\)\\s-*)")
6665                  (setq sig (verilog-string-remove-spaces (match-string 1))
6666                        vec nil))
6667                 ((looking-at "\\([^[({).]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
6668                  (setq sig (verilog-string-remove-spaces (match-string 1))
6669                        vec (match-string 2)))
6670                 ((looking-at "\\([^[({).]*\\)\\s-*/\\*\\(\\[[^*]+\\]\\)\\*/\\s-*)")
6671                  (setq sig (verilog-string-remove-spaces (match-string 1))
6672                        vec nil)
6673                  (let ((parse (match-string 2)))
6674                    (while (string-match "^\\(\\[[^]]+\\]\\)\\(.*\\)$" parse)
6675                      (when vec (setq multidim (cons vec multidim)))
6676                      (setq vec (match-string 1 parse))
6677                      (setq parse (match-string 2 parse)))))
6678                 ((looking-at "{\\(.*\\)}.*\\s-*)")
6679                  (let ((mlst (split-string (match-string 1) ","))
6680                        mstr)
6681                    (while (setq mstr (pop mlst))
6682                      ;;(unless noninteractive (message "sig: %s " mstr))
6683                      (cond
6684                       ((string-match "\\(['`a-zA-Z0-9_$]+\\)\\s-*$" mstr)
6685                        (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
6686                              vec nil)
6687                        ;;(unless noninteractive (message "concat sig1: %s %s" mstr (match-string 1 mstr)))
6688                        )
6689                       ((string-match "\\([^[({).]+\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*" mstr)
6690                        (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
6691                              vec (match-string 2 mstr))
6692                        ;;(unless noninteractive (message "concat sig2: '%s' '%s' '%s'" mstr (match-string 1 mstr) (match-string 2 mstr)))
6693                        )
6694                       (t
6695                        (setq sig nil)))
6696                      ;; Process signals
6697                      (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))
6698                 (t
6699                  (setq sig nil)))
6700           ;; Process signals
6701           (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))
6702         ;;
6703         (forward-line 1)))))
6704
6705 (defun verilog-read-sub-decls ()
6706   "Internally parse signals going to modules under this module.
6707 Return a array of [ outputs inouts inputs ] signals for modules that are
6708 instantiated in this module.  For example if declare A A (.B(SIG)) and SIG
6709 is a output, then SIG will be included in the list.
6710
6711 This only works on instantiations created with /*AUTOINST*/ converted by
6712 \\[verilog-auto-inst].  Otherwise, it would have to read in the whole
6713 component library to determine connectivity of the design.
6714
6715 One work around for this problem is to manually create // Inputs and //
6716 Outputs comments above subcell signals, for example:
6717
6718         module ModuleName (
6719             // Outputs
6720             .out (out),
6721             // Inputs
6722             .in  (in));"
6723   (save-excursion
6724     (let ((end-mod-point (verilog-get-end-of-defun t))
6725           st-point end-inst-point
6726           ;; below 3 modified by verilog-read-sub-decls-line
6727           sigs-out sigs-inout sigs-in)
6728       (verilog-beg-of-defun)
6729       (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
6730         (save-excursion
6731           (goto-char (match-beginning 0))
6732           (unless (verilog-inside-comment-p)
6733             ;; Attempt to snarf a comment
6734             (let* ((submod (verilog-read-inst-module))
6735                    (inst (verilog-read-inst-name))
6736                    (comment (concat inst " of " submod ".v"))
6737                    submodi submoddecls)
6738               (when (setq submodi (verilog-modi-lookup submod t))
6739                 (setq submoddecls (verilog-modi-get-decls submodi))
6740                 ;; This could have used a list created by verilog-auto-inst
6741                 ;; However I want it to be runnable even on user's manually added signals
6742                 (verilog-backward-open-paren)
6743                 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
6744                       st-point (point))
6745                 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
6746                   (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
6747                 (goto-char st-point)
6748                 (while (re-search-forward "\\s *// Inouts" end-inst-point t)
6749                   (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
6750                 (goto-char st-point)
6751                 (while (re-search-forward "\\s *// Inputs" end-inst-point t)
6752                   (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
6753                 )))))
6754       ;; Combine duplicate bits
6755       ;;(setq rr (vector sigs-out sigs-inout sigs-in))
6756       (vector (verilog-signals-combine-bus (nreverse sigs-out))
6757               (verilog-signals-combine-bus (nreverse sigs-inout))
6758               (verilog-signals-combine-bus (nreverse sigs-in))))))
6759
6760 (defun verilog-read-inst-pins ()
6761   "Return an array of [ pins ] for the current instantiation at point.
6762 For example if declare A A (.B(SIG)) then B will be included in the list."
6763   (save-excursion
6764     (let ((end-mod-point (point))       ;; presume at /*AUTOINST*/ point
6765           pins pin)
6766       (verilog-backward-open-paren)
6767       (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
6768         (setq pin (match-string 1))
6769         (unless (verilog-inside-comment-p)
6770           (setq pins (cons (list pin) pins))
6771           (when (looking-at "(")
6772             (forward-sexp 1))))
6773       (vector pins))))
6774
6775 (defun verilog-read-arg-pins ()
6776   "Return an array of [ pins ] for the current argument declaration at point."
6777   (save-excursion
6778     (let ((end-mod-point (point))       ;; presume at /*AUTOARG*/ point
6779           pins pin)
6780       (verilog-backward-open-paren)
6781       (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
6782         (setq pin (match-string 1))
6783         (unless (verilog-inside-comment-p)
6784           (setq pins (cons (list pin) pins))))
6785       (vector pins))))
6786
6787 (defun verilog-read-auto-constants (beg end-mod-point)
6788   "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
6789   ;; Insert new
6790   (save-excursion
6791     (let (sig-list tpl-end-pt)
6792       (goto-char beg)
6793       (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
6794         (if (not (looking-at "\\s *("))
6795             (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
6796         (search-forward "(" end-mod-point)
6797         (setq tpl-end-pt (save-excursion
6798                            (backward-char 1)
6799                            (forward-sexp 1)   ;; Moves to paren that closes argdecl's
6800                            (backward-char 1)
6801                            (point)))
6802         (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
6803           (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
6804       sig-list)))
6805
6806 (defun verilog-read-auto-lisp (start end)
6807   "Look for and evaluate a AUTO_LISP between START and END."
6808   (save-excursion
6809     (goto-char start)
6810     (while (re-search-forward "\\<AUTO_LISP(" end t)
6811       (backward-char)
6812       (let* ((beg-pt (prog1 (point)
6813                        (forward-sexp 1)))       ;; Closing paren
6814              (end-pt (point)))
6815         (eval-region beg-pt end-pt nil)))))
6816
6817 (eval-when-compile
6818   ;; Prevent compile warnings; these are let's, not globals
6819   ;; Do not remove the eval-when-compile
6820   ;; - we want a error when we are debugging this code if they are refed.
6821   (defvar sigs-in)
6822   (defvar sigs-out)
6823   (defvar got-sig)
6824   (defvar got-rvalue)
6825   (defvar uses-delayed)
6826   (defvar vector-skip-list))
6827
6828 (defun verilog-read-always-signals-recurse
6829   (exit-keywd rvalue ignore-next)
6830   "Recursive routine for parentheses/bracket matching.
6831 EXIT-KEYWD is expression to stop at, nil if top level.
6832 RVALUE is true if at right hand side of equal.
6833 IGNORE-NEXT is true to ignore next token, fake from inside case statement."
6834   (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
6835          keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-rvalue end-else-check)
6836     ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue ignore-next))))
6837     (while (not (or (eobp) gotend))
6838       (cond
6839        ((looking-at "//")
6840         (search-forward "\n"))
6841        ((looking-at "/\\*")
6842         (or (search-forward "*/")
6843             (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6844        ((looking-at "(\\*")
6845         (or (looking-at "(\\*\\s-*)")   ; It's a "always @ (*)"
6846             (search-forward "*)")
6847             (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
6848        (t (setq keywd (buffer-substring-no-properties
6849                        (point)
6850                        (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
6851                                          (forward-char 1))
6852                                        (point)))
6853                 sig-last-tolk sig-tolk
6854                 sig-tolk nil)
6855           ;;(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))))
6856           (cond
6857            ((equal keywd "\"")
6858             (or (re-search-forward "[^\\]\"" nil t)
6859                 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
6860            ;; else at top level loop, keep parsing
6861            ((and end-else-check (equal keywd "else"))
6862             ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
6863             ;; no forward movement, want to see else in lower loop
6864             (setq end-else-check nil))
6865            ;; End at top level loop
6866            ((and end-else-check (looking-at "[^ \t\n\f]"))
6867             ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
6868             (setq gotend t))
6869            ;; Final statement?
6870            ((and exit-keywd (equal keywd exit-keywd))
6871             (setq gotend t)
6872             (forward-char (length keywd)))
6873            ;; Standard tokens...
6874            ((equal keywd ";")
6875             (setq ignore-next nil  rvalue semi-rvalue)
6876             ;; Final statement at top level loop?
6877             (when (not exit-keywd)
6878               ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
6879               (setq end-else-check t))
6880             (forward-char 1))
6881            ((equal keywd "'")
6882             (if (looking-at "'s?[hdxbo][0-9a-fA-F_xz? \t]*")
6883                 (goto-char (match-end 0))
6884               (forward-char 1)))
6885            ((equal keywd ":")   ;; Case statement, begin/end label, x?y:z
6886             (cond ((equal "endcase" exit-keywd)  ;; case x: y=z; statement next
6887                    (setq ignore-next nil rvalue nil))
6888                   ((equal "?" exit-keywd)  ;; x?y:z rvalue
6889                    ) ;; NOP
6890                   (got-sig      ;; label: statement
6891                    (setq ignore-next nil rvalue semi-rvalue got-sig nil))
6892                   ((not rvalue) ;; begin label
6893                    (setq ignore-next t rvalue nil)))
6894             (forward-char 1))
6895            ((equal keywd "=")
6896             (if (eq (char-before) ?< )
6897                 (setq uses-delayed 1))
6898             (setq ignore-next nil rvalue t)
6899             (forward-char 1))
6900            ((equal keywd "?")
6901             (forward-char 1)
6902             (verilog-read-always-signals-recurse ":" rvalue nil))
6903            ((equal keywd "[")
6904             (forward-char 1)
6905             (verilog-read-always-signals-recurse "]" t nil))
6906            ((equal keywd "(")
6907             (forward-char 1)
6908             (cond (sig-last-tolk        ;; Function call; zap last signal
6909                    (setq got-sig nil)))
6910             (cond ((equal last-keywd "for")
6911                    (verilog-read-always-signals-recurse ";" nil nil)
6912                    (verilog-read-always-signals-recurse ";" t nil)
6913                    (verilog-read-always-signals-recurse ")" nil nil))
6914                   (t (verilog-read-always-signals-recurse ")" t nil))))
6915            ((equal keywd "begin")
6916             (skip-syntax-forward "w_")
6917             (verilog-read-always-signals-recurse "end" nil nil)
6918             ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
6919             (setq ignore-next nil  rvalue semi-rvalue)
6920             (if (not exit-keywd) (setq end-else-check t)))
6921            ((or (equal keywd "case")
6922                 (equal keywd "casex")
6923                 (equal keywd "casez"))
6924             (skip-syntax-forward "w_")
6925             (verilog-read-always-signals-recurse "endcase" t nil)
6926             (setq ignore-next nil  rvalue semi-rvalue)
6927             (if (not exit-keywd) (setq gotend t)))      ;; top level begin/end
6928            ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
6929             (cond ((or (equal keywd "`ifdef")
6930                        (equal keywd "`ifndef"))
6931                    (setq ignore-next t))
6932                   ((or ignore-next
6933                        (member keywd verilog-keywords)
6934                        (string-match "^\\$" keywd))     ;; PLI task
6935                    (setq ignore-next nil))
6936                   (t
6937                    (setq keywd (verilog-symbol-detick-denumber keywd))
6938                    (when got-sig
6939                      (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
6940                        (setq sigs-out (cons got-sig sigs-out)))
6941                      ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
6942                      )
6943                    (setq got-rvalue rvalue
6944                          got-sig (if (or (not keywd)
6945                                          (assoc keywd (if got-rvalue sigs-in sigs-out)))
6946                                      nil (list keywd nil nil))
6947                          sig-tolk t)))
6948             (skip-chars-forward "a-zA-Z0-9$_.%`"))
6949            (t
6950             (forward-char 1)))
6951           ;; End of non-comment token
6952           (setq last-keywd keywd)))
6953       (skip-syntax-forward " "))
6954     ;; Append the final pending signal
6955     (when got-sig
6956       (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
6957         (setq sigs-out (cons got-sig sigs-out)))
6958       ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
6959       (setq got-sig nil))
6960     ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
6961     ))
6962
6963 (defun verilog-read-always-signals ()
6964   "Parse always block at point and return list of (outputs inout inputs)."
6965   ;; Insert new
6966   (save-excursion
6967     (let* (;;(dbg "")
6968            sigs-in sigs-out
6969            uses-delayed)        ;; Found signal/rvalue; push if not function
6970       (search-forward ")")
6971       (verilog-read-always-signals-recurse nil nil nil)
6972       ;;(if dbg (save-excursion (set-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg "")))
6973       ;; Return what was found
6974       (list sigs-out nil sigs-in uses-delayed))))
6975
6976 (defun verilog-read-instants ()
6977   "Parse module at point and return list of ( ( file instance ) ... )."
6978   (verilog-beg-of-defun)
6979   (let* ((end-mod-point (verilog-get-end-of-defun t))
6980          (state nil)
6981          (instants-list nil))
6982     (save-excursion
6983       (while (< (point) end-mod-point)
6984         ;; Stay at level 0, no comments
6985         (while (progn
6986                  (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
6987                  (or (> (car state) 0)  ; in parens
6988                      (nth 5 state)              ; comment
6989                      ))
6990           (forward-line 1))
6991         (beginning-of-line)
6992         (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
6993             ;;(if (looking-at "^\\(.+\\)$")
6994             (let ((module (match-string 1))
6995                   (instant (match-string 2)))
6996               (if (not (member module verilog-keywords))
6997                   (setq instants-list (cons (list module instant) instants-list)))))
6998         (forward-line 1)))
6999     instants-list))
7000
7001
7002 (defun verilog-read-auto-template (module)
7003   "Look for a auto_template for the instantiation of the given MODULE.
7004 If found returns the signal name connections.  Return REGEXP and
7005 list of ( (signal_name connection_name)... )."
7006   (save-excursion
7007     ;; Find beginning
7008     (let ((tpl-regexp "\\([0-9]+\\)")
7009           (lineno 0)
7010           (templateno 0)
7011           tpl-sig-list tpl-wild-list tpl-end-pt rep)
7012       (cond ((or
7013                (re-search-backward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
7014                (progn
7015                  (goto-char (point-min))
7016                  (re-search-forward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
7017              (goto-char (match-end 0))
7018              ;; Parse "REGEXP"
7019              ;; We reserve @"..." for future lisp expressions that evaluate once-per-AUTOINST
7020              (when (looking-at "\\s-*\"\\([^\"]*)\\)\"")
7021                (setq tpl-regexp (match-string 1))
7022                (goto-char (match-end 0)))
7023              (search-forward "(")
7024              ;; Parse lines in the template
7025              (when verilog-auto-inst-template-numbers
7026                (save-excursion
7027                  (goto-char (point-min))
7028                  (while (search-forward "AUTO_TEMPLATE" nil t)
7029                    (setq templateno (1+ templateno)))))
7030              (setq tpl-end-pt (save-excursion
7031                                 (backward-char 1)
7032                                 (forward-sexp 1)   ;; Moves to paren that closes argdecl's
7033                                 (backward-char 1)
7034                                 (point)))
7035              ;;
7036              (while (< (point) tpl-end-pt)
7037                (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7038                       (setq tpl-sig-list (cons (list
7039                                                 (match-string-no-properties 1)
7040                                                 (match-string-no-properties 2)
7041                                                 templateno lineno)
7042                                                tpl-sig-list))
7043                       (goto-char (match-end 0)))
7044                      ;; Regexp form??
7045                      ((looking-at
7046                        ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
7047                        "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7048                       (setq rep (match-string-no-properties 3))
7049                       (goto-char (match-end 0))
7050                       (setq tpl-wild-list
7051                             (cons (list
7052                                    (concat "^"
7053                                            (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
7054                                                                            (match-string 1))
7055                                            "$")
7056                                    rep
7057                                    templateno lineno)
7058                                   tpl-wild-list)))
7059                      ((looking-at "[ \t\f]+")
7060                       (goto-char (match-end 0)))
7061                      ((looking-at "\n")
7062                       (setq lineno (1+ lineno))
7063                       (goto-char (match-end 0)))
7064                      ((looking-at "//")
7065                       (search-forward "\n"))
7066                      ((looking-at "/\\*")
7067                       (forward-char 2)
7068                       (or (search-forward "*/")
7069                           (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7070                      (t
7071                       (error "%s: AUTO_TEMPLATE parsing error: %s"
7072                              (verilog-point-text)
7073                              (progn (looking-at ".*$") (match-string 0))))))
7074              ;; Return
7075              (vector tpl-regexp
7076                      (list tpl-sig-list tpl-wild-list)))
7077             ;; If no template found
7078             (t (vector tpl-regexp nil))))))
7079 ;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
7080
7081 (defun verilog-set-define (defname defvalue &optional buffer enumname)
7082   "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
7083 Optionally associate it with the specified enumeration ENUMNAME."
7084   (save-excursion
7085     (set-buffer (or buffer (current-buffer)))
7086     (let ((mac (intern (concat "vh-" defname))))
7087       ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
7088       ;; Need to define to a constant if no value given
7089       (set (make-variable-buffer-local mac)
7090            (if (equal defvalue "") "1" defvalue)))
7091     (if enumname
7092         (let ((enumvar (intern (concat "venum-" enumname))))
7093           ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
7094           (unless (boundp enumvar) (set enumvar nil))
7095           (make-variable-buffer-local enumvar)
7096           (add-to-list enumvar defname)))))
7097
7098 (defun verilog-read-defines (&optional filename recurse subcall)
7099   "Read `defines and parameters for the current file, or optional FILENAME.
7100 If the filename is provided, `verilog-library-flags' will be used to
7101 resolve it.  If optional RECURSE is non-nil, recurse through `includes.
7102
7103 Parameters must be simple assignments to constants, or have their own
7104 \"parameter\" label rather than a list of parameters.  Thus:
7105
7106     parameter X = 5, Y = 10;    // Ok
7107     parameter X = {1'b1, 2'h2}; // Ok
7108     parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
7109
7110 Defines must be simple text substitutions, one on a line, starting
7111 at the beginning of the line.  Any ifdefs or multiline comments around the
7112 define are ignored.
7113
7114 Defines are stored inside Emacs variables using the name vh-{definename}.
7115
7116 This function is useful for setting vh-* variables.  The file variables
7117 feature can be used to set defines that `verilog-mode' can see; put at the
7118 *END* of your file something like:
7119
7120     // Local Variables:
7121     // vh-macro:\"macro_definition\"
7122     // End:
7123
7124 If macros are defined earlier in the same file and you want their values,
7125 you can read them automatically (provided `enable-local-eval' is on):
7126
7127     // Local Variables:
7128     // eval:(verilog-read-defines)
7129     // eval:(verilog-read-defines \"group_standard_includes.v\")
7130     // End:
7131
7132 Note these are only read when the file is first visited, you must use
7133 \\[find-alternate-file] RET  to have these take effect after editing them!
7134
7135 If you want to disable the \"Process `eval' or hook local variables\"
7136 warning message, you need to add to your .emacs file:
7137
7138     (setq enable-local-eval t)"
7139   (let ((origbuf (current-buffer)))
7140     (save-excursion
7141       (unless subcall (verilog-getopt-flags))
7142       (when filename
7143         (let ((fns (verilog-library-filenames filename (buffer-file-name))))
7144           (if fns
7145               (set-buffer (find-file-noselect (car fns)))
7146             (error (concat (verilog-point-text)
7147                            ": Can't find verilog-read-defines file: " filename)))))
7148       (when recurse
7149         (goto-char (point-min))
7150         (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
7151           (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string-no-properties 1))))
7152             (unless (verilog-inside-comment-p)
7153               (verilog-read-defines inc recurse t)))))
7154       ;; Read `defines
7155       ;; note we don't use verilog-re... it's faster this way, and that
7156       ;; function has problems when comments are at the end of the define
7157       (goto-char (point-min))
7158       (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
7159         (let ((defname (match-string-no-properties 1))
7160               (defvalue (match-string-no-properties 2)))
7161           (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
7162           (verilog-set-define defname defvalue origbuf)))
7163       ;; Hack: Read parameters
7164       (goto-char (point-min))
7165       (while (re-search-forward
7166               "^\\s-*\\(parameter\\|localparam\\)\\(\\s-*\\[[^]]*\\]\\)?\\s-+" nil t)
7167         (let (enumname)
7168           ;; The primary way of getting defines is verilog-read-decls
7169           ;; However, that isn't called yet for included files, so we'll add another scheme
7170           (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
7171               (setq enumname (match-string-no-properties 1)))
7172           (forward-comment 999)
7173           (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
7174             (verilog-set-define (match-string-no-properties 1) (match-string-no-properties 2) origbuf enumname)
7175             (goto-char (match-end 0))
7176             (forward-comment 999)))))))
7177
7178 (defun verilog-read-includes ()
7179   "Read `includes for the current file.
7180 This will find all of the `includes which are at the beginning of lines,
7181 ignoring any ifdefs or multiline comments around them.
7182 `verilog-read-defines' is then performed on the current and each included
7183 file.
7184
7185 It is often useful put at the *END* of your file something like:
7186
7187     // Local Variables:
7188     // eval:(verilog-read-defines)
7189     // eval:(verilog-read-includes)
7190     // End:
7191
7192 Note includes are only read when the file is first visited, you must use
7193 \\[find-alternate-file] RET  to have these take effect after editing them!
7194
7195 It is good to get in the habit of including all needed files in each .v
7196 file that needs it, rather than waiting for compile time.  This will aid
7197 this process, Verilint, and readability.  To prevent defining the same
7198 variable over and over when many modules are compiled together, put a test
7199 around the inside each include file:
7200
7201 foo.v (a include):
7202         `ifdef _FOO_V   // include if not already included
7203         `else
7204         `define _FOO_V
7205         ... contents of file
7206         `endif // _FOO_V"
7207 ;;slow:  (verilog-read-defines nil t))
7208   (save-excursion
7209     (verilog-getopt-flags)
7210     (goto-char (point-min))
7211     (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
7212       (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
7213         (verilog-read-defines inc nil t)))))
7214
7215 (defun verilog-read-signals (&optional start end)
7216   "Return a simple list of all possible signals in the file.
7217 Bounded by optional region from START to END.  Overly aggressive but fast.
7218 Some macros and such are also found and included.  For dinotrace.el."
7219   (let (sigs-all keywd)
7220     (progn;save-excursion
7221       (goto-char (or start (point-min)))
7222       (setq end (or end (point-max)))
7223       (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
7224         (forward-char -1)
7225         (cond
7226          ((looking-at "//")
7227           (search-forward "\n"))
7228          ((looking-at "/\\*")
7229           (search-forward "*/"))
7230          ((looking-at "(\\*")
7231           (or (looking-at "(\\*\\s-*)")   ; It's a "always @ (*)"
7232               (search-forward "*)")))
7233          ((eq ?\" (following-char))
7234           (re-search-forward "[^\\]\""))        ;; don't forward-char first, since we look for a non backslash first
7235          ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
7236           (goto-char (match-end 0))
7237           (setq keywd (match-string-no-properties 1))
7238           (or (member keywd verilog-keywords)
7239               (member keywd sigs-all)
7240               (setq sigs-all (cons keywd sigs-all))))
7241          (t (forward-char 1))))
7242       ;; Return list
7243       sigs-all)))
7244
7245 ;;
7246 ;; Argument file parsing
7247 ;;
7248
7249 (defun verilog-getopt (arglist)
7250   "Parse -f, -v etc arguments in ARGLIST list or string."
7251   (unless (listp arglist) (setq arglist (list arglist)))
7252   (let ((space-args '())
7253         arg next-param)
7254     ;; Split on spaces, so users can pass whole command lines
7255     (while arglist
7256       (setq arg (car arglist)
7257             arglist (cdr arglist))
7258       (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
7259         (setq space-args (append space-args
7260                                  (list (match-string-no-properties 1 arg))))
7261         (setq arg (match-string 2 arg))))
7262     ;; Parse arguments
7263     (while space-args
7264       (setq arg (car space-args)
7265             space-args (cdr space-args))
7266       (cond
7267        ;; Need another arg
7268        ((equal arg "-f")
7269         (setq next-param arg))
7270        ((equal arg "-v")
7271         (setq next-param arg))
7272        ((equal arg "-y")
7273         (setq next-param arg))
7274        ;; +libext+(ext1)+(ext2)...
7275        ((string-match "^\\+libext\\+\\(.*\\)" arg)
7276         (setq arg (match-string 1 arg))
7277         (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
7278           (verilog-add-list-unique `verilog-library-extensions
7279                                    (match-string 1 arg))
7280           (setq arg (match-string 2 arg))))
7281        ;;
7282        ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg)    ;; -Ddefine=val
7283             (string-match "^-D\\([^+=]*\\)\\(\\)" arg)  ;; -Ddefine
7284             (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg)     ;; +define+val
7285             (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg))          ;; +define+define
7286         (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
7287        ;;
7288        ((or (string-match "^\\+incdir\\+\\(.*\\)" arg)  ;; +incdir+dir
7289             (string-match "^-I\\(.*\\)" arg))   ;; -Idir
7290         (verilog-add-list-unique `verilog-library-directories
7291                                  (match-string 1 (substitute-in-file-name arg))))
7292        ;; Ignore
7293        ((equal "+librescan" arg))
7294        ((string-match "^-U\\(.*\\)" arg))       ;; -Udefine
7295        ;; Second parameters
7296        ((equal next-param "-f")
7297         (setq next-param nil)
7298         (verilog-getopt-file (substitute-in-file-name arg)))
7299        ((equal next-param "-v")
7300         (setq next-param nil)
7301         (verilog-add-list-unique `verilog-library-files
7302                                  (substitute-in-file-name arg)))
7303        ((equal next-param "-y")
7304         (setq next-param nil)
7305         (verilog-add-list-unique `verilog-library-directories 
7306                                  (substitute-in-file-name arg)))
7307        ;; Filename
7308        ((string-match "^[^-+]" arg)
7309         (verilog-add-list-unique `verilog-library-files 
7310                                  (substitute-in-file-name arg)))
7311        ;; Default - ignore; no warning
7312        ))))
7313 ;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
7314
7315 (defun verilog-getopt-file (filename)
7316   "Read Verilog options from the specified FILENAME."
7317   (save-excursion
7318     (let ((fns (verilog-library-filenames filename (buffer-file-name)))
7319           (orig-buffer (current-buffer))
7320           line)
7321       (if fns
7322           (set-buffer (find-file-noselect (car fns)))
7323         (error (concat (verilog-point-text)
7324                        ": Can't find verilog-getopt-file -f file: " filename)))
7325       (goto-char (point-min))
7326       (while (not (eobp))
7327         (setq line (buffer-substring (point)
7328                                      (save-excursion (end-of-line) (point))))
7329         (forward-line 1)
7330         (when (string-match "//" line)
7331           (setq line (substring line 0 (match-beginning 0))))
7332         (save-excursion
7333           (set-buffer orig-buffer)  ; Variables are buffer-local, so need right context.
7334           (verilog-getopt line))))))
7335
7336 (defun verilog-getopt-flags ()
7337   "Convert `verilog-library-flags' into standard library variables."
7338   ;; If the flags are local, then all the outputs should be local also
7339   (when (local-variable-p `verilog-library-flags (current-buffer))
7340     (mapc 'make-local-variable '(verilog-library-extensions
7341                                  verilog-library-directories
7342                                  verilog-library-files
7343                                  verilog-library-flags)))
7344   ;; Allow user to customize
7345   (run-hooks 'verilog-before-getopt-flags-hook)
7346   ;; Process arguments
7347   (verilog-getopt verilog-library-flags)
7348   ;; Allow user to customize
7349   (run-hooks 'verilog-getopt-flags-hook))
7350
7351 (defun verilog-add-list-unique (varref object)
7352   "Append to VARREF list the given OBJECT,
7353 unless it is already a member of the variable's list."
7354   (unless (member object (symbol-value varref))
7355     (set varref (append (symbol-value varref) (list object))))
7356   varref)
7357 ;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
7358
7359 \f
7360 ;;
7361 ;; Cached directory support
7362 ;;
7363
7364 (defvar verilog-dir-cache-preserving nil
7365   "If set, the directory cache is enabled, and file system changes are ignored.
7366 See `verilog-dir-exists-p' and `verilog-dir-files'.")
7367
7368 ;; If adding new cached variable, add also to verilog-preserve-dir-cache
7369 (defvar verilog-dir-cache-list nil
7370   "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
7371 (defvar verilog-dir-cache-lib-filenames nil
7372   "Cached data for `verilog-library-filenames'.")
7373
7374 (defmacro verilog-preserve-dir-cache (&rest body)
7375   "Execute the BODY forms, allowing directory cache preservation within BODY.
7376 This means that changes inside BODY made to the file system will not be
7377 seen by the `verilog-dir-files' and related functions."
7378   `(let ((verilog-dir-cache-preserving t)
7379          verilog-dir-cache-list
7380          verilog-dir-cache-lib-filenames)
7381      (progn ,@body)))
7382
7383 (defun verilog-dir-files (dirname)
7384   "Return all filenames in the DIRNAME directory.
7385 Relative paths depend on the `default-directory'.
7386 Results are cached if inside `verilog-preserve-dir-cache'."
7387   (unless verilog-dir-cache-preserving
7388     (setq verilog-dir-cache-list nil)) ;; Cache disabled
7389   ;; We don't use expand-file-name on the dirname to make key, as it's slow
7390   (let* ((cache-key (list dirname default-directory))
7391          (fass (assoc cache-key verilog-dir-cache-list))
7392          exp-dirname data)
7393     (cond (fass  ;; Return data from cache hit
7394            (nth 1 fass))
7395           (t
7396            (setq exp-dirname (expand-file-name dirname)
7397                  data (and (file-directory-p exp-dirname)
7398                            (directory-files exp-dirname nil nil nil)))
7399            ;; Note we also encache nil for non-existing dirs.
7400            (setq verilog-dir-cache-list (cons (list cache-key data)
7401                                               verilog-dir-cache-list))
7402            data))))
7403 ;; Miss-and-hit test:
7404 ;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
7405 ;; (prin1 (verilog-dir-files ".")) nil)
7406
7407 (defun verilog-dir-file-exists-p (filename)
7408   "Return true if FILENAME exists.
7409 Like `file-exists-p' but results are cached if inside
7410 `verilog-preserve-dir-cache'."
7411   (let* ((dirname (file-name-directory filename))
7412          ;; Correct for file-name-nondirectory returning same if no slash.
7413          (dirnamed (if (or (not dirname) (equal dirname filename))
7414                        default-directory dirname))
7415          (flist (verilog-dir-files dirnamed)))
7416     (and flist
7417          (member (file-name-nondirectory filename) flist)
7418          t)))
7419 ;;(verilog-dir-file-exists-p "verilog-mode.el")
7420 ;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
7421
7422 \f
7423 ;;
7424 ;; Module name lookup
7425 ;;
7426
7427 (defun verilog-module-inside-filename-p (module filename)
7428   "Return point if MODULE is specified inside FILENAME, else nil.
7429 Allows version control to check out the file if need be."
7430   (and (or (file-exists-p filename)
7431            (and (fboundp 'vc-backend)
7432                 (vc-backend filename)))
7433        (let (pt)
7434          (save-excursion
7435            (set-buffer (find-file-noselect filename))
7436            (goto-char (point-min))
7437            (while (and
7438                    ;; It may be tempting to look for verilog-defun-re, don't, it slows things down a lot!
7439                    (verilog-re-search-forward-quick "\\<module\\>" nil t)
7440                    (verilog-re-search-forward-quick "[(;]" nil t))
7441              (if (equal module (verilog-read-module-name))
7442                  (setq pt (point))))
7443            pt))))
7444
7445 (defun verilog-is-number (symbol)
7446   "Return true if SYMBOL is number-like."
7447   (or (string-match "^[0-9 \t:]+$" symbol)
7448       (string-match "^[---]*[0-9]+$" symbol)
7449       (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
7450
7451 (defun verilog-symbol-detick (symbol wing-it)
7452   "Return an expanded SYMBOL name without any defines.
7453 If the variable vh-{symbol} is defined, return that value.
7454 If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
7455   (while (and symbol (string-match "^`" symbol))
7456     (setq symbol (substring symbol 1))
7457     (setq symbol
7458           (if (boundp (intern (concat "vh-" symbol)))
7459               ;; Emacs has a bug where boundp on a buffer-local
7460               ;; variable in only one buffer returns t in another.
7461               ;; This can confuse, so check for nil.
7462               (let ((val (eval (intern (concat "vh-" symbol)))))
7463                 (if (eq val nil)
7464                     (if wing-it symbol nil)
7465                   val))
7466             (if wing-it symbol nil))))
7467   symbol)
7468 ;;(verilog-symbol-detick "`mod" nil)
7469
7470 (defun verilog-symbol-detick-denumber (symbol)
7471   "Return SYMBOL with defines converted and any numbers dropped to nil."
7472   (when (string-match "^`" symbol)
7473     ;; This only will work if the define is a simple signal, not
7474     ;; something like a[b].  Sorry, it should be substituted into the parser
7475     (setq symbol
7476           (verilog-string-replace-matches
7477            "\[[^0-9: \t]+\]" "" nil nil
7478            (or (verilog-symbol-detick symbol nil)
7479                (if verilog-auto-sense-defines-constant
7480                    "0"
7481                  symbol)))))
7482   (if (verilog-is-number symbol)
7483       nil
7484     symbol))
7485
7486 (defun verilog-symbol-detick-text (text)
7487   "Return TEXT without any known defines.
7488 If the variable vh-{symbol} is defined, substitute that value."
7489   (let ((ok t) symbol val)
7490     (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
7491       (setq symbol (match-string 1 text))
7492       (message symbol)
7493       (cond ((and
7494               (boundp (intern (concat "vh-" symbol)))
7495               ;; Emacs has a bug where boundp on a buffer-local
7496               ;; variable in only one buffer returns t in another.
7497               ;; This can confuse, so check for nil.
7498               (setq val (eval (intern (concat "vh-" symbol)))))
7499              (setq text (replace-match val nil nil text)))
7500             (t (setq ok nil)))))
7501   text)
7502 ;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
7503
7504 (defun verilog-expand-dirnames (&optional dirnames)
7505   "Return a list of existing directories given a list of wildcarded DIRNAMES.
7506 Or, just the existing dirnames themselves if there are no wildcards."
7507   ;; Note this function is performance critical.
7508   ;; Do not call anything that requires disk access that cannot be cached.
7509   (interactive)
7510   (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
7511   (setq dirnames (reverse dirnames))    ; not nreverse
7512   (let ((dirlist nil)
7513         pattern dirfile dirfiles dirname root filename rest basefile)
7514     (while dirnames
7515       (setq dirname (substitute-in-file-name (car dirnames))
7516             dirnames (cdr dirnames))
7517       (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)"  ;; root
7518                                    "\\([^/\\]*[*?][^/\\]*\\)"     ;; filename with *?
7519                                    "\\(.*\\)")                    ;; rest
7520                            dirname)
7521              (setq root (match-string 1 dirname)
7522                    filename (match-string 2 dirname)
7523                    rest (match-string 3 dirname)
7524                    pattern filename)
7525              ;; now replace those * and ? with .+ and .
7526              ;; use ^ and /> to get only whole file names
7527              (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
7528                    pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
7529                    pattern (concat "^" pattern "$")
7530                    dirfiles (verilog-dir-files root))
7531              (while dirfiles
7532                (setq basefile (car dirfiles)
7533                      dirfile (expand-file-name (concat root basefile rest))
7534                      dirfiles (cdr dirfiles))
7535                (if (and (string-match pattern basefile)
7536                         ;; Don't allow abc/*/rtl to match abc/rtl via ..
7537                         (not (equal basefile "."))
7538                         (not (equal basefile ".."))
7539                         (file-directory-p dirfile))
7540                    (setq dirlist (cons dirfile dirlist)))))
7541             ;; Defaults
7542             (t
7543              (if (file-directory-p dirname)
7544                  (setq dirlist (cons dirname dirlist))))))
7545     dirlist))
7546 ;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
7547
7548 (defun verilog-library-filenames (filename current &optional check-ext)
7549   "Return a search path to find the given FILENAME or module name.
7550 Uses the CURRENT filename, `verilog-library-directories' and
7551 `verilog-library-extensions' variables to build the path.
7552 With optional CHECK-EXT also check `verilog-library-extensions'."
7553   (unless verilog-dir-cache-preserving
7554     (setq verilog-dir-cache-lib-filenames nil))
7555   (let* ((cache-key (list filename current check-ext))
7556          (fass (assoc cache-key verilog-dir-cache-lib-filenames))
7557          chkdirs chkdir chkexts fn outlist)
7558     (cond (fass  ;; Return data from cache hit
7559            (nth 1 fass))
7560           (t
7561            ;; Note this expand can't be easily cached, as we need to
7562            ;; pick up buffer-local variables for newly read sub-module files
7563            (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
7564            (while chkdirs
7565              (setq chkdir (expand-file-name (car chkdirs)
7566                                             (file-name-directory current))
7567                    chkexts (if check-ext verilog-library-extensions `("")))
7568              (while chkexts
7569                (setq fn (expand-file-name (concat filename (car chkexts))
7570                                           chkdir))
7571                ;;(message "Check for %s" fn)
7572                (if (verilog-dir-file-exists-p fn)
7573                    (setq outlist (cons (expand-file-name
7574                                         fn (file-name-directory current))
7575                                        outlist)))
7576                  (setq chkexts (cdr chkexts)))
7577              (setq chkdirs (cdr chkdirs)))
7578            (setq outlist (nreverse outlist))
7579            (setq verilog-dir-cache-lib-filenames
7580                  (cons (list cache-key outlist)
7581                        verilog-dir-cache-lib-filenames))
7582            outlist))))
7583
7584 (defun verilog-module-filenames (module current)
7585   "Return a search path to find the given MODULE name.
7586 Uses the CURRENT filename, `verilog-library-extensions',
7587 `verilog-library-directories' and `verilog-library-files'
7588 variables to build the path."
7589   ;; Return search locations for it
7590   (append (list current)                ; first, current buffer
7591           (verilog-library-filenames module current t)
7592           verilog-library-files))       ; finally, any libraries
7593
7594 ;;
7595 ;; Module Information
7596 ;;
7597 ;; Many of these functions work on "modi" a module information structure
7598 ;; A modi is:  [module-name-string file-name begin-point]
7599
7600 (defvar verilog-cache-enabled t
7601   "If true, enable caching of signals, etc.  Set to nil for debugging to make things SLOW!")
7602
7603 (defvar verilog-modi-cache-list nil
7604   "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
7605 For speeding up verilog-modi-get-* commands.
7606 Buffer-local.")
7607
7608 (make-variable-buffer-local 'verilog-modi-cache-list)
7609
7610 (defvar verilog-modi-cache-preserve-tick nil
7611   "Modification tick after which the cache is still considered valid.
7612 Use `verilog-preserve-modi-cache' to set it.")
7613 (defvar verilog-modi-cache-preserve-buffer nil
7614   "Modification tick after which the cache is still considered valid.
7615 Use `verilog-preserve-modi-cache' to set it.")
7616
7617 (defun verilog-modi-current ()
7618   "Return the modi structure for the module currently at point."
7619   (let* (name pt)
7620     ;; read current module's name
7621     (save-excursion
7622       (verilog-re-search-backward-quick verilog-defun-re nil nil)
7623       (verilog-re-search-forward-quick "(" nil nil)
7624       (setq name (verilog-read-module-name))
7625       (setq pt (point)))
7626     ;; return
7627     (vector name (or (buffer-file-name) (current-buffer)) pt)))
7628
7629 (defvar verilog-modi-lookup-last-mod nil "Cache of last module looked up.")
7630 (defvar verilog-modi-lookup-last-modi nil "Cache of last modi returned.")
7631 (defvar verilog-modi-lookup-last-current nil "Cache of last `current-buffer' looked up.")
7632 (defvar verilog-modi-lookup-last-tick nil "Cache of last `buffer-modified-tick' looked up.")
7633
7634 (defun verilog-modi-lookup (module allow-cache &optional ignore-error)
7635   "Find the file and point at which MODULE is defined.
7636 If ALLOW-CACHE is set, check and remember cache of previous lookups.
7637 Return modi if successful, else print message unless IGNORE-ERROR is true."
7638   (let* ((current (or (buffer-file-name) (current-buffer))))
7639     (cond ((and verilog-modi-lookup-last-modi
7640                 verilog-cache-enabled
7641                 allow-cache
7642                 (equal verilog-modi-lookup-last-mod module)
7643                 (equal verilog-modi-lookup-last-current current)
7644                 (equal verilog-modi-lookup-last-tick (buffer-modified-tick)))
7645            ;; ok as is
7646            )
7647           (t (let* ((realmod (verilog-symbol-detick module t))
7648                     (orig-filenames (verilog-module-filenames realmod current))
7649                     (filenames orig-filenames)
7650                     pt)
7651                (while (and filenames (not pt))
7652                  (if (not (setq pt (verilog-module-inside-filename-p realmod (car filenames))))
7653                      (setq filenames (cdr filenames))))
7654                (cond (pt (setq verilog-modi-lookup-last-modi
7655                                (vector realmod (car filenames) pt)))
7656                      (t (setq verilog-modi-lookup-last-modi nil)
7657                         (or ignore-error
7658                             (error (concat (verilog-point-text)
7659                                            ": Can't locate " module " module definition"
7660                                            (if (not (equal module realmod))
7661                                                (concat " (Expanded macro to " realmod ")")
7662                                              "")
7663                                            "\n    Check the verilog-library-directories variable."
7664                                            "\n    I looked in (if not listed, doesn't exist):\n\t"
7665                                            (mapconcat 'concat orig-filenames "\n\t"))))))
7666                (setq verilog-modi-lookup-last-mod module
7667                      verilog-modi-lookup-last-current current
7668                      verilog-modi-lookup-last-tick (buffer-modified-tick)))))
7669     verilog-modi-lookup-last-modi))
7670
7671 (defsubst verilog-modi-name (modi)
7672   (aref modi 0))
7673 (defsubst verilog-modi-file-or-buffer (modi)
7674   (aref modi 1))
7675 (defsubst verilog-modi-point (modi)
7676   (aref modi 2))
7677
7678 (defun verilog-modi-filename (modi)
7679   "Filename of MODI, or name of buffer if it's never been saved."
7680   (if (bufferp (verilog-modi-file-or-buffer modi))
7681       (or (buffer-file-name (verilog-modi-file-or-buffer modi))
7682           (buffer-name (verilog-modi-file-or-buffer modi)))
7683     (verilog-modi-file-or-buffer modi)))
7684
7685 (defun verilog-modi-goto (modi)
7686   "Move point/buffer to specified MODI."
7687   (or modi (error "Passed unfound modi to goto, check earlier"))
7688   (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
7689                   (verilog-modi-file-or-buffer modi)
7690                 (find-file-noselect (verilog-modi-file-or-buffer modi))))
7691   (or (equal major-mode `verilog-mode)  ;; Put into Verilog mode to get syntax
7692       (verilog-mode))
7693   (goto-char (verilog-modi-point modi)))
7694
7695 (defun verilog-goto-defun-file (module)
7696   "Move point to the file at which a given MODULE is defined."
7697   (interactive "sGoto File for Module: ")
7698   (let* ((modi (verilog-modi-lookup module nil)))
7699     (when modi
7700       (verilog-modi-goto modi)
7701       (switch-to-buffer (current-buffer)))))
7702
7703 (defun verilog-modi-cache-results (modi function)
7704   "Run on MODI the given FUNCTION.  Locate the module in a file.
7705 Cache the output of function so next call may have faster access."
7706   (let (fass)
7707     (save-excursion  ;; Cache is buffer-local so can't avoid this.
7708       (verilog-modi-goto modi)
7709       (if (and (setq fass (assoc (list modi function)
7710                                  verilog-modi-cache-list))
7711                ;; Destroy caching when incorrect; Modified or file changed
7712                (not (and verilog-cache-enabled
7713                          (or (equal (buffer-modified-tick) (nth 1 fass))
7714                              (and verilog-modi-cache-preserve-tick
7715                                   (<= verilog-modi-cache-preserve-tick  (nth 1 fass))
7716                                   (equal  verilog-modi-cache-preserve-buffer (current-buffer))))
7717                          (equal (visited-file-modtime) (nth 2 fass)))))
7718           (setq verilog-modi-cache-list nil
7719                 fass nil))
7720       (cond (fass
7721              ;; Return data from cache hit
7722              (nth 3 fass))
7723             (t
7724              ;; Read from file
7725              ;; Clear then restore any hilighting to make emacs19 happy
7726              (let ((fontlocked (when (and (boundp 'font-lock-mode)
7727                                           font-lock-mode)
7728                                  (font-lock-mode 0)
7729                                  t))
7730                    func-returns)
7731                (setq func-returns (funcall function))
7732                (when fontlocked (font-lock-mode t))
7733                ;; Cache for next time
7734                (setq verilog-modi-cache-list
7735                      (cons (list (list modi function)
7736                                  (buffer-modified-tick)
7737                                  (visited-file-modtime)
7738                                  func-returns)
7739                            verilog-modi-cache-list))
7740                func-returns))))))
7741
7742 (defun verilog-modi-cache-add (modi function element sig-list)
7743   "Add function return results to the module cache.
7744 Update MODI's cache for given FUNCTION so that the return ELEMENT of that
7745 function now contains the additional SIG-LIST parameters."
7746   (let (fass)
7747     (save-excursion
7748       (verilog-modi-goto modi)
7749       (if (setq fass (assoc (list modi function)
7750                             verilog-modi-cache-list))
7751           (let ((func-returns (nth 3 fass)))
7752             (aset func-returns element
7753                   (append sig-list (aref func-returns element))))))))
7754
7755 (defmacro verilog-preserve-modi-cache (&rest body)
7756   "Execute the BODY forms, allowing cache preservation within BODY.
7757 This means that changes to the buffer will not result in the cache being
7758 flushed.  If the changes affect the modsig state, they must call the
7759 modsig-cache-add-* function, else the results of later calls may be
7760 incorrect.  Without this, changes are assumed to be adding/removing signals
7761 and invalidating the cache."
7762   `(let ((verilog-modi-cache-preserve-tick (buffer-modified-tick))
7763          (verilog-modi-cache-preserve-buffer (current-buffer)))
7764      (progn ,@body)))
7765
7766
7767 (defun verilog-signals-matching-enum (in-list enum)
7768   "Return all signals in IN-LIST matching the given ENUM."
7769   (let (out-list)
7770     (while in-list
7771       (if (equal (verilog-sig-enum (car in-list)) enum)
7772           (setq out-list (cons (car in-list) out-list)))
7773       (setq in-list (cdr in-list)))
7774     ;; New scheme
7775     (let* ((enumvar (intern (concat "venum-" enum)))
7776            (enumlist (and (boundp enumvar) (eval enumvar))))
7777       (while enumlist
7778         (add-to-list 'out-list (list (car enumlist)))
7779         (setq enumlist (cdr enumlist))))
7780     (nreverse out-list)))
7781
7782 (defun verilog-signals-matching-regexp (in-list regexp)
7783   "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
7784   (if (not regexp)
7785       in-list
7786     (let (out-list)
7787       (while in-list
7788         (if (string-match regexp (verilog-sig-name (car in-list)))
7789             (setq out-list (cons (car in-list) out-list)))
7790         (setq in-list (cdr in-list)))
7791       (nreverse out-list))))
7792
7793 (defun verilog-signals-not-matching-regexp (in-list regexp)
7794   "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
7795   (if (not regexp)
7796       in-list
7797     (let (out-list)
7798       (while in-list
7799         (if (not (string-match regexp (verilog-sig-name (car in-list))))
7800             (setq out-list (cons (car in-list) out-list)))
7801         (setq in-list (cdr in-list)))
7802       (nreverse out-list))))
7803
7804 ;; Combined
7805 (defun verilog-decls-get-signals (decls)
7806   (append
7807    (verilog-decls-get-outputs decls)
7808    (verilog-decls-get-inouts decls)
7809    (verilog-decls-get-inputs decls)
7810    (verilog-decls-get-wires decls)
7811    (verilog-decls-get-regs decls)
7812    (verilog-decls-get-assigns decls)
7813    (verilog-decls-get-consts decls)
7814    (verilog-decls-get-gparams decls)))
7815
7816 (defun verilog-decls-get-ports (decls)
7817   (append
7818    (verilog-decls-get-outputs decls)
7819    (verilog-decls-get-inouts decls)
7820    (verilog-decls-get-inputs decls)))
7821
7822 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
7823   (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
7824 (defsubst verilog-modi-cache-add-inouts (modi sig-list)
7825   (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
7826 (defsubst verilog-modi-cache-add-inputs (modi sig-list)
7827   (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
7828 (defsubst verilog-modi-cache-add-wires (modi sig-list)
7829   (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
7830 (defsubst verilog-modi-cache-add-regs (modi sig-list)
7831   (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
7832
7833 (defun verilog-signals-from-signame (signame-list)
7834   "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
7835   (mapcar (function (lambda (name) (list name nil nil)))
7836           signame-list))
7837 \f
7838 ;;
7839 ;; Auto creation utilities
7840 ;;
7841
7842 (defun verilog-auto-re-search-do (search-for func)
7843   "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
7844   (goto-char (point-min))
7845   (while (verilog-re-search-forward search-for nil t)
7846     (funcall func)))
7847
7848 (defun verilog-insert-one-definition (sig type indent-pt)
7849   "Print out a definition for SIG of the given TYPE,
7850 with appropriate INDENT-PT indentation."
7851   (indent-to indent-pt)
7852   (insert type)
7853   (when (verilog-sig-signed sig)
7854     (insert " " (verilog-sig-signed sig)))
7855   (when (verilog-sig-multidim sig)
7856     (insert " " (verilog-sig-multidim-string sig)))
7857   (when (verilog-sig-bits sig)
7858     (insert " " (verilog-sig-bits sig)))
7859   (indent-to (max 24 (+ indent-pt 16)))
7860   (unless (= (char-syntax (preceding-char)) ?\  )
7861     (insert " "))  ; Need space between "]name" if indent-to did nothing
7862   (insert (verilog-sig-name sig)))
7863
7864 (defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
7865   "Print out a definition for a list of SIGS of the given DIRECTION,
7866 with appropriate INDENT-PT indentation.  If V2K, use Verilog 2001 I/O
7867 format.  Sort unless DONT-SORT.  DIRECTION is normally wire/reg/output."
7868   (or dont-sort
7869       (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
7870   (while sigs
7871     (let ((sig (car sigs)))
7872       (verilog-insert-one-definition
7873        sig
7874        ;; Want "type x" or "output type x", not "wire type x"
7875        (cond ((verilog-sig-type sig)
7876               (concat
7877                (if (not (equal direction "wire"))
7878                    (concat direction " "))
7879                (verilog-sig-type sig)))
7880              (t direction))
7881        indent-pt)
7882       (insert (if v2k "," ";"))
7883       (if (or (not (verilog-sig-comment sig))
7884               (equal "" (verilog-sig-comment sig)))
7885           (insert "\n")
7886         (indent-to (max 48 (+ indent-pt 40)))
7887         (insert (concat "// " (verilog-sig-comment sig) "\n")))
7888       (setq sigs (cdr sigs)))))
7889
7890 (eval-when-compile
7891   (if (not (boundp 'indent-pt))
7892       (defvar indent-pt nil "Local used by insert-indent")))
7893
7894 (defun verilog-insert-indent (&rest stuff)
7895   "Indent to position stored in local `indent-pt' variable, then insert STUFF.
7896 Presumes that any newlines end a list element."
7897   (let ((need-indent t))
7898     (while stuff
7899       (if need-indent (indent-to indent-pt))
7900       (setq need-indent nil)
7901       (insert (car stuff))
7902       (setq need-indent (string-match "\n$" (car stuff))
7903             stuff (cdr stuff)))))
7904 ;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
7905
7906 (defun verilog-repair-open-comma ()
7907   "If backwards-from-point is other than a open parenthesis insert comma."
7908   (save-excursion
7909     (verilog-backward-syntactic-ws)
7910     (when (save-excursion
7911             (backward-char 1)
7912             (and (not (looking-at "[(,]"))
7913                  (progn
7914                    (verilog-re-search-backward "[(`]" nil t)
7915                    (looking-at "("))))
7916     (insert ","))))
7917
7918 (defun verilog-repair-close-comma ()
7919   "If point is at a comma followed by a close parenthesis, fix it.
7920 This repairs those mis-inserted by a AUTOARG."
7921   ;; It would be much nicer if Verilog allowed extra commas like Perl does!
7922   (save-excursion
7923     (verilog-forward-close-paren)
7924     (backward-char 1)
7925     (verilog-backward-syntactic-ws)
7926     (backward-char 1)
7927     (when (looking-at ",")
7928       (delete-char 1))))
7929
7930 (defun verilog-get-list (start end)
7931   "Return the elements of a comma separated list between START and END."
7932   (interactive)
7933   (let ((my-list (list))
7934         my-string)
7935     (save-excursion
7936       (while (< (point) end)
7937         (when (re-search-forward "\\([^,{]+\\)" end t)
7938           (setq my-string (verilog-string-remove-spaces (match-string 1)))
7939           (setq my-list (nconc my-list (list my-string) ))
7940           (goto-char (match-end 0))))
7941       my-list)))
7942
7943 (defun verilog-make-width-expression (range-exp)
7944   "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
7945   ;; strip off the []
7946   (cond ((not range-exp)
7947          "1")
7948         (t
7949          (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
7950              (setq range-exp (match-string 1 range-exp)))
7951          (cond ((not range-exp)
7952                 "1")
7953                ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
7954                               range-exp)
7955                 (int-to-string
7956                  (1+ (abs (- (string-to-number (match-string 1 range-exp))
7957                              (string-to-number (match-string 2 range-exp)))))))
7958                ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
7959                 (concat "(1+(" (match-string 1 range-exp) ")"
7960                         (if (equal "0" (match-string 2 range-exp))
7961                             ""  ;; Don't bother with -(0)
7962                           (concat "-(" (match-string 2 range-exp) ")"))
7963                         ")"))
7964                (t nil)))))
7965 ;;(verilog-make-width-expression "`A:`B")
7966
7967 (defun verilog-simplify-range-expression (range-exp)
7968   "Return a simplified range expression with constants eliminated from RANGE-EXP."
7969   (let ((out range-exp)
7970         (last-pass ""))
7971     (while (not (equal last-pass out))
7972       (setq last-pass out)
7973       (while (string-match "(\\<\\([0-9A-Z-az_]+\\)\\>)" out)
7974         (setq out (replace-match "\\1" nil nil out)))
7975       (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\+\\s *\\<\\([0-9]+\\)\\>" out)
7976         (setq out (replace-match 
7977                    (int-to-string (+ (string-to-number (match-string 1 out))
7978                                      (string-to-number (match-string 2 out))))
7979                    nil nil out)))
7980       (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\-\\s *\\<\\([0-9]+\\)\\>" out)
7981         (setq out (replace-match 
7982                    (int-to-string (- (string-to-number (match-string 1 out))
7983                                      (string-to-number (match-string 2 out))))
7984                    nil nil out))))
7985     out))
7986 ;;(verilog-simplify-range-expression "1")
7987 ;;(verilog-simplify-range-expression "(((16)+1)-3)")
7988
7989 (defun verilog-typedef-name-p (variable-name)
7990   "Return true if the VARIABLE-NAME is a type definition."
7991   (when verilog-typedef-regexp
7992     (string-match verilog-typedef-regexp variable-name)))
7993 \f
7994 ;;
7995 ;; Auto deletion
7996 ;;
7997
7998 (defun verilog-delete-autos-lined ()
7999   "Delete autos that occupy multiple lines, between begin and end comments."
8000   (let ((pt (point)))
8001     (forward-line 1)
8002     (when (and
8003            (looking-at "\\s-*// Beginning")
8004            (search-forward "// End of automatic" nil t))
8005       ;; End exists
8006       (end-of-line)
8007       (delete-region pt (point))
8008       (forward-line 1))))
8009
8010 (defun verilog-forward-close-paren ()
8011   "Find the close parenthesis that match the current point.
8012 Ignore other close parenthesis with matching open parens."
8013   (let ((parens 1))
8014     (while (> parens 0)
8015       (unless (verilog-re-search-forward-quick "[()]" nil t)
8016         (error "%s: Mismatching ()" (verilog-point-text)))
8017       (cond ((= (preceding-char) ?\( )
8018              (setq parens (1+ parens)))
8019             ((= (preceding-char) ?\) )
8020              (setq parens (1- parens)))))))
8021
8022 (defun verilog-backward-open-paren ()
8023   "Find the open parenthesis that match the current point.
8024 Ignore other open parenthesis with matching close parens."
8025   (let ((parens 1))
8026     (while (> parens 0)
8027       (unless (verilog-re-search-backward-quick "[()]" nil t)
8028         (error "%s: Mismatching ()" (verilog-point-text)))
8029       (cond ((= (following-char) ?\) )
8030              (setq parens (1+ parens)))
8031             ((= (following-char) ?\( )
8032              (setq parens (1- parens)))))))
8033
8034 (defun verilog-backward-open-bracket ()
8035   "Find the open bracket that match the current point.
8036 Ignore other open bracket with matching close bracket."
8037   (let ((parens 1))
8038     (while (> parens 0)
8039       (unless (verilog-re-search-backward-quick "[][]" nil t)
8040         (error "%s: Mismatching []" (verilog-point-text)))
8041       (cond ((= (following-char) ?\] )
8042              (setq parens (1+ parens)))
8043             ((= (following-char) ?\[ )
8044              (setq parens (1- parens)))))))
8045
8046 (defun verilog-delete-to-paren ()
8047   "Delete the automatic inst/sense/arg created by autos.
8048 Deletion stops at the matching end parenthesis."
8049   (delete-region (point)
8050                  (save-excursion
8051                    (verilog-backward-open-paren)
8052                    (forward-sexp 1)   ;; Moves to paren that closes argdecl's
8053                    (backward-char 1)
8054                    (point))))
8055
8056 (defun verilog-auto-star-safe ()
8057   "Return if a .* AUTOINST is safe to delete or expand.
8058 It was created by the AUTOS themselves, or by the user."
8059   (and verilog-auto-star-expand
8060        (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\)\\)")))
8061
8062 (defun verilog-delete-auto-star-all ()
8063   "Delete a .* AUTOINST, if it is safe."
8064   (when (verilog-auto-star-safe)
8065     (verilog-delete-to-paren)))
8066
8067 (defun verilog-delete-auto-star-implicit ()
8068   "Delete all .* implicit connections created by `verilog-auto-star'.
8069 This function will be called automatically at save unless
8070 `verilog-auto-star-save' is set, any non-templated expanded pins will be
8071 removed."
8072   (interactive)
8073   (let (paren-pt indent have-close-paren)
8074     (save-excursion
8075       (goto-char (point-min))
8076       ;; We need to match these even outside of comments.
8077       ;; For reasonable performance, we don't check if inside comments, sorry.
8078       (while (re-search-forward "// Implicit \\.\\*" nil t)
8079         (setq paren-pt (point))
8080         (beginning-of-line)
8081         (setq have-close-paren
8082               (save-excursion
8083                 (when (search-forward ");" paren-pt t)
8084                   (setq indent (current-indentation))
8085                   t)))
8086         (delete-region (point) (+ 1 paren-pt))  ; Nuke line incl CR
8087         (when have-close-paren
8088           ;; Delete extra commentary
8089           (save-excursion
8090             (while (progn
8091                      (forward-line -1)
8092                      (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\)\n"))
8093               (delete-region (match-beginning 0) (match-end 0))))
8094           ;; If it is simple, we can put the ); on the same line as the last text
8095           (let ((rtn-pt (point)))
8096             (save-excursion
8097               (while (progn (backward-char 1)
8098                             (looking-at "[ \t\n\f]")))
8099               (when (looking-at ",")
8100                 (delete-region (+ 1 (point)) rtn-pt))))
8101           (when (bolp)
8102             (indent-to indent))
8103           (insert ");\n")
8104           ;; Still need to kill final comma - always is one as we put one after the .*
8105           (re-search-backward ",")
8106           (delete-char 1))))))
8107
8108 (defun verilog-delete-auto ()
8109   "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
8110 Use \\[verilog-auto] to re-insert the updated AUTOs.
8111
8112 The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
8113 called before and after this function, respectively."
8114   (interactive)
8115   (save-excursion
8116     (if (buffer-file-name)
8117         (find-file-noselect (buffer-file-name)))        ;; To check we have latest version
8118     ;; Allow user to customize
8119     (run-hooks 'verilog-before-delete-auto-hook)
8120
8121     ;; Remove those that have multi-line insertions, possibly with parameters
8122     (verilog-auto-re-search-do
8123      (concat "/\\*"
8124              (eval-when-compile
8125                (verilog-regexp-words
8126                 `("AUTOASCIIENUM" "AUTOCONCATCOMMENT" "AUTODEFINEVALUE"
8127                   "AUTOINOUT" "AUTOINOUTCOMP" "AUTOINOUTMODULE"
8128                   "AUTOINPUT" "AUTOOUTPUT" "AUTOOUTPUTEVERY"
8129                   "AUTOREG" "AUTOREGINPUT" "AUTORESET" "AUTOTIEOFF"
8130                   "AUTOUNUSED" "AUTOWIRE")))
8131              "\\(\\|([^)]*)\\|(\"[^\"]*\")\\)" ; Optional parens or quoted parameter
8132              "\\*/")
8133      'verilog-delete-autos-lined)
8134     ;; Remove those that are in parenthesis
8135     (verilog-auto-re-search-do
8136      (concat "/\\*"
8137              (eval-when-compile
8138                (verilog-regexp-words
8139                 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
8140                   "AUTOSENSE")))
8141              "\\*/")
8142      'verilog-delete-to-paren)
8143     ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
8144     (verilog-auto-re-search-do "\\.\\*"
8145                                'verilog-delete-auto-star-all)
8146     ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
8147     (goto-char (point-min))
8148     (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
8149       (replace-match ""))
8150
8151     ;; Final customize
8152     (run-hooks 'verilog-delete-auto-hook)))
8153 \f
8154 ;;
8155 ;; Auto inject
8156 ;;
8157
8158 (defun verilog-inject-auto ()
8159   "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
8160
8161 Any always @ blocks with sensitivity lists that match computed lists will
8162 be replaced with /*AS*/ comments.
8163
8164 Any cells will get /*AUTOINST*/ added to the end of the pin list.
8165 Pins with have identical names will be deleted.
8166
8167 Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
8168 support adding new ports.  You may wish to delete older ports yourself.
8169
8170 For example:
8171
8172         module ExampInject (i, o);
8173           input i;
8174           input j;
8175           output o;
8176           always @ (i or j)
8177              o = i | j;
8178           InstModule instName
8179             (.foobar(baz),
8180              j(j));
8181         endmodule
8182
8183 Typing \\[verilog-inject-auto] will make this into:
8184
8185         module ExampInject (i, o/*AUTOARG*/
8186           // Inputs
8187           j);
8188           input i;
8189           output o;
8190           always @ (/*AS*/i or j)
8191              o = i | j;
8192           InstModule instName
8193             (.foobar(baz),
8194              /*AUTOINST*/
8195              // Outputs
8196              j(j));
8197         endmodule"
8198   (interactive)
8199   (verilog-auto t))
8200
8201 (defun verilog-inject-arg ()
8202   "Inject AUTOARG into new code.  See `verilog-inject-auto'."
8203   ;; Presume one module per file.
8204   (save-excursion
8205     (goto-char (point-min))
8206     (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
8207       (let ((endmodp (save-excursion
8208                        (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
8209                        (point))))
8210         ;; See if there's already a comment .. inside a comment so not verilog-re-search
8211         (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
8212           (verilog-re-search-forward-quick ";" nil t)
8213           (backward-char 1)
8214           (verilog-backward-syntactic-ws)
8215           (backward-char 1) ; Moves to paren that closes argdecl's
8216           (when (looking-at ")")
8217             (insert "/*AUTOARG*/")))))))
8218
8219 (defun verilog-inject-sense ()
8220   "Inject AUTOSENSE into new code.  See `verilog-inject-auto'."
8221   (save-excursion
8222     (goto-char (point-min))
8223     (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
8224       (let* ((start-pt (point))
8225              (modi (verilog-modi-current))
8226              (moddecls (verilog-modi-get-decls modi))
8227              pre-sigs
8228              got-sigs)
8229         (backward-char 1)
8230         (forward-sexp 1)
8231         (backward-char 1) ;; End )
8232         (when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
8233           (setq pre-sigs (verilog-signals-from-signame
8234                           (verilog-read-signals start-pt (point)))
8235                 got-sigs (verilog-auto-sense-sigs moddecls nil))
8236           (when (not (or (verilog-signals-not-in pre-sigs got-sigs)  ; Both are equal?
8237                          (verilog-signals-not-in got-sigs pre-sigs)))
8238             (delete-region start-pt (point))
8239             (insert "/*AS*/")))))))
8240
8241 (defun verilog-inject-inst ()
8242   "Inject AUTOINST into new code.  See `verilog-inject-auto'."
8243   (save-excursion
8244     (goto-char (point-min))
8245     ;; It's hard to distinguish modules; we'll instead search for pins.
8246     (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
8247       (verilog-backward-open-paren) ;; Inst start
8248       (cond
8249        ((= (preceding-char) ?\#)  ;; #(...) parameter section, not pin.  Skip.
8250         (forward-char 1)
8251         (verilog-forward-close-paren)) ;; Parameters done
8252        (t
8253         (forward-char 1)
8254         (let ((indent-pt (+ (current-column)))
8255               (end-pt (save-excursion (verilog-forward-close-paren) (point))))
8256           (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
8257                  (goto-char end-pt)) ;; Already there, continue search with next instance
8258                 (t
8259                  ;; Delete identical interconnect
8260                  (let ((case-fold-search nil))  ;; So we don't convert upper-to-lower, etc
8261                    (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
8262                      (delete-region (match-beginning 0) (match-end 0))
8263                      (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
8264                      (while (or (looking-at "[ \t\n\f,]+")
8265                                 (looking-at "//[^\n]*"))
8266                        (delete-region (match-beginning 0) (match-end 0))
8267                        (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
8268                  (verilog-forward-close-paren)
8269                  (backward-char 1)
8270                  ;; Not verilog-re-search, as we don't want to strip comments
8271                  (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
8272                    (delete-region (match-beginning 0) (match-end 0)))
8273                  (insert "\n")
8274                  (indent-to indent-pt)
8275                  (insert "/*AUTOINST*/")))))))))
8276 \f
8277 ;;
8278 ;; Auto save
8279 ;;
8280
8281 (defun verilog-auto-save-check ()
8282   "On saving see if we need auto update."
8283   (cond ((not verilog-auto-save-policy)) ; disabled
8284         ((not (save-excursion
8285                 (save-match-data
8286                   (let ((case-fold-search nil))
8287                     (goto-char (point-min))
8288                     (re-search-forward "AUTO" nil t))))))
8289         ((eq verilog-auto-save-policy 'force)
8290          (verilog-auto))
8291         ((not (buffer-modified-p)))
8292         ((eq verilog-auto-update-tick (buffer-modified-tick))) ; up-to-date
8293         ((eq verilog-auto-save-policy 'detect)
8294          (verilog-auto))
8295         (t
8296          (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
8297            (verilog-auto))
8298          ;; Don't ask again if didn't update
8299          (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))))
8300   (when (not verilog-auto-star-save)
8301     (verilog-delete-auto-star-implicit))
8302   nil)  ;; Always return nil -- we don't write the file ourselves
8303
8304 (defun verilog-auto-read-locals ()
8305   "Return file local variable segment at bottom of file."
8306   (save-excursion
8307     (goto-char (point-max))
8308     (if (re-search-backward "Local Variables:" nil t)
8309         (buffer-substring-no-properties (point) (point-max))
8310       "")))
8311
8312 (defun verilog-auto-reeval-locals (&optional force)
8313   "Read file local variable segment at bottom of file if it has changed.
8314 If FORCE, always reread it."
8315   (make-local-variable 'verilog-auto-last-file-locals)
8316   (let ((curlocal (verilog-auto-read-locals)))
8317     (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
8318       (setq verilog-auto-last-file-locals curlocal)
8319       ;; Note this may cause this function to be recursively invoked,
8320       ;; because hack-local-variables may call (verilog-mode)
8321       ;; The above when statement will prevent it from recursing forever.
8322       (hack-local-variables)
8323       t)))
8324 \f
8325 ;;
8326 ;; Auto creation
8327 ;;
8328
8329 (defun verilog-auto-arg-ports (sigs message indent-pt)
8330   "Print a list of ports for a AUTOINST.
8331 Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
8332   (when sigs
8333     (insert "\n")
8334     (indent-to indent-pt)
8335     (insert message)
8336     (insert "\n")
8337     (let ((space ""))
8338       (indent-to indent-pt)
8339       (while sigs
8340         (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
8341                (insert "\n")
8342                (indent-to indent-pt))
8343               (t (insert space)))
8344         (insert (verilog-sig-name (car sigs)) ",")
8345         (setq sigs (cdr sigs)
8346               space " ")))))
8347
8348 (defun verilog-auto-arg ()
8349   "Expand AUTOARG statements.
8350 Replace the argument declarations at the beginning of the
8351 module with ones automatically derived from input and output
8352 statements.  This can be dangerous if the module is instantiated
8353 using position-based connections, so use only name-based when
8354 instantiating the resulting module.  Long lines are split based
8355 on the `fill-column', see \\[set-fill-column].
8356
8357 Limitations:
8358   Concatenation and outputting partial busses is not supported.
8359
8360   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8361
8362 For example:
8363
8364         module ExampArg (/*AUTOARG*/);
8365           input i;
8366           output o;
8367         endmodule
8368
8369 Typing \\[verilog-auto] will make this into:
8370
8371         module ExampArg (/*AUTOARG*/
8372           // Outputs
8373           o,
8374           // Inputs
8375           i
8376         );
8377           input i;
8378           output o;
8379         endmodule
8380
8381 Any ports declared between the ( and /*AUTOARG*/ are presumed to be
8382 predeclared and are not redeclared by AUTOARG.  AUTOARG will make a
8383 conservative guess on adding a comma for the first signal, if you have
8384 any ifdefs or complicated expressions before the AUTOARG you will need
8385 to choose the comma yourself.
8386
8387 Avoid declaring ports manually, as it makes code harder to maintain."
8388   (save-excursion
8389     (let* ((modi (verilog-modi-current))
8390            (moddecls (verilog-modi-get-decls modi))
8391            (skip-pins (aref (verilog-read-arg-pins) 0)))
8392       (verilog-repair-open-comma)
8393       (verilog-auto-arg-ports (verilog-signals-not-in
8394                                (verilog-decls-get-outputs moddecls)
8395                                skip-pins)
8396                               "// Outputs"
8397                               verilog-indent-level-declaration)
8398       (verilog-auto-arg-ports (verilog-signals-not-in
8399                                (verilog-decls-get-inouts moddecls)
8400                                skip-pins)
8401                               "// Inouts"
8402                               verilog-indent-level-declaration)
8403       (verilog-auto-arg-ports (verilog-signals-not-in
8404                                (verilog-decls-get-inputs moddecls)
8405                                skip-pins)
8406                               "// Inputs"
8407                               verilog-indent-level-declaration)
8408       (verilog-repair-close-comma)
8409       (unless (eq (char-before) ?/ )
8410         (insert "\n"))
8411       (indent-to verilog-indent-level-declaration))))
8412
8413 (defun verilog-auto-inst-port-map (port-st)
8414   nil)
8415
8416 (defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
8417 (defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
8418 (defvar vl-name  nil "See `verilog-auto-inst'.") ; Prevent compile warning
8419 (defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
8420 (defvar vl-dir   nil "See `verilog-auto-inst'.") ; Prevent compile warning
8421
8422 (defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
8423   "Print out a instantiation connection for this PORT-ST.
8424 Insert to INDENT-PT, use template TPL-LIST.
8425 @ are instantiation numbers, replaced with TPL-NUM.
8426 @\"(expression @)\" are evaluated, with @ as a variable.
8427 If FOR-STAR add comment it is a .* expansion.
8428 If PAR-VALUES replace final strings with these parameter values."
8429   (let* ((port (verilog-sig-name port-st))
8430          (tpl-ass (or (assoc port (car tpl-list))
8431                       (verilog-auto-inst-port-map port-st)))
8432          ;; vl-* are documented for user use
8433          (vl-name (verilog-sig-name port-st))
8434          (vl-width (verilog-sig-width port-st))
8435          (vl-bits (if (or verilog-auto-inst-vector
8436                           (not (assoc port vector-skip-list))
8437                           (not (equal (verilog-sig-bits port-st)
8438                                       (verilog-sig-bits (assoc port vector-skip-list)))))
8439                       (or (verilog-sig-bits port-st) "")
8440                     ""))
8441          (case-fold-search nil)
8442          (check-values par-values)
8443          tpl-net)
8444     ;; Replace parameters in bit-width
8445     (when (and check-values
8446                (not (equal vl-bits "")))
8447       (while check-values
8448         (setq vl-bits (verilog-string-replace-matches
8449                        (concat "\\<" (nth 0 (car check-values)) "\\>")
8450                        (concat "(" (nth 1 (car check-values)) ")")
8451                        t t vl-bits)
8452               check-values (cdr check-values)))
8453       (setq vl-bits (verilog-simplify-range-expression vl-bits))) ; Not in the loop for speed
8454     ;; Default net value if not found
8455     (setq tpl-net (if (verilog-sig-multidim port-st)
8456                       (concat port "/*" (verilog-sig-multidim-string port-st)
8457                               vl-bits "*/")
8458                     (concat port vl-bits)))
8459     ;; Find template
8460     (cond (tpl-ass          ; Template of exact port name
8461            (setq tpl-net (nth 1 tpl-ass)))
8462           ((nth 1 tpl-list) ; Wildcards in template, search them
8463            (let ((wildcards (nth 1 tpl-list)))
8464              (while wildcards
8465                (when (string-match (nth 0 (car wildcards)) port)
8466                  (setq tpl-ass (car wildcards)  ; so allow @ parsing
8467                        tpl-net (replace-match (nth 1 (car wildcards))
8468                                               t nil port)))
8469                (setq wildcards (cdr wildcards))))))
8470     ;; Parse Templated variable
8471     (when tpl-ass
8472       ;; Evaluate @"(lispcode)"
8473       (when (string-match "@\".*[^\\]\"" tpl-net)
8474         (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
8475           (setq tpl-net
8476                 (concat
8477                  (substring tpl-net 0 (match-beginning 0))
8478                  (save-match-data
8479                    (let* ((expr (match-string 1 tpl-net))
8480                           (value
8481                            (progn
8482                              (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
8483                              (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
8484                              (prin1 (eval (car (read-from-string expr)))
8485                                     (lambda (ch) ())))))
8486                      (if (numberp value) (setq value (number-to-string value)))
8487                      value))
8488                  (substring tpl-net (match-end 0))))))
8489       ;; Replace @ and [] magic variables in final output
8490       (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
8491       (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
8492     ;; Insert it
8493     (indent-to indent-pt)
8494     (insert "." port)
8495     (indent-to verilog-auto-inst-column)
8496     (insert "(" tpl-net "),")
8497     (cond (tpl-ass
8498            (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
8499                          verilog-auto-inst-column))
8500            (insert " // Templated")
8501            (when verilog-auto-inst-template-numbers
8502              (insert " T" (int-to-string (nth 2 tpl-ass))
8503                      " L" (int-to-string (nth 3 tpl-ass)))))
8504           (for-star
8505            (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
8506                          verilog-auto-inst-column))
8507            (insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
8508     (insert "\n")))
8509 ;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
8510 ;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
8511 ;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
8512
8513 (defun verilog-auto-inst-first ()
8514   "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
8515   ;; Do we need a trailing comma?
8516   ;; There maybe a ifdef or something similar before us.  What a mess.  Thus
8517   ;; to avoid trouble we only insert on preceeding ) or *.
8518   ;; Insert first port on new line
8519   (insert "\n")  ;; Must insert before search, so point will move forward if insert comma
8520   (save-excursion
8521     (verilog-re-search-backward "[^ \t\n\f]" nil nil)
8522     (when (looking-at ")\\|\\*")  ;; Generally don't insert, unless we are fairly sure
8523       (forward-char 1)
8524       (insert ","))))
8525
8526 (defun verilog-auto-star ()
8527   "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
8528
8529 If `verilog-auto-star-expand' is set, .* pins are treated if they were
8530 AUTOINST statements, otherwise they are ignored.  For safety, Verilog mode
8531 will also ignore any .* that are not last in your pin list (this prevents
8532 it from deleting pins following the .* when it expands the AUTOINST.)
8533
8534 On writing your file, unless `verilog-auto-star-save' is set, any
8535 non-templated expanded pins will be removed.  You may do this at any time
8536 with \\[verilog-delete-auto-star-implicit].
8537
8538 If you are converting a module to use .* for the first time, you may wish
8539 to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
8540
8541 See `verilog-auto-inst' for examples, templates, and more information."
8542   (when (verilog-auto-star-safe)
8543     (verilog-auto-inst)))
8544
8545 (defun verilog-auto-inst ()
8546   "Expand AUTOINST statements, as part of \\[verilog-auto].
8547 Replace the pin connections to an instantiation with ones
8548 automatically derived from the module header of the instantiated netlist.
8549
8550 If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
8551 and delete them before saving unless `verilog-auto-star-save' is set.
8552 See `verilog-auto-star' for more information.
8553
8554 Limitations:
8555   Module names must be resolvable to filenames by adding a
8556   `verilog-library-extensions', and being found in the same directory, or
8557   by changing the variable `verilog-library-flags' or
8558   `verilog-library-directories'.  Macros `modname are translated through the
8559   vh-{name} Emacs variable, if that is not found, it just ignores the `.
8560
8561   In templates you must have one signal per line, ending in a ), or ));,
8562   and have proper () nesting, including a final ); to end the template.
8563
8564   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8565
8566   SystemVerilog multidimensional input/output has only experimental support.
8567
8568   Parameters referenced by the instantiation will remain symbolic, unless
8569   `verilog-auto-inst-param-value' is set.
8570
8571 For example, first take the submodule InstModule.v:
8572
8573         module InstModule (o,i)
8574            output [31:0] o;
8575            input i;
8576            wire [31:0] o = {32{i}};
8577         endmodule
8578
8579 This is then used in a upper level module:
8580
8581         module ExampInst (o,i)
8582            output o;
8583            input i;
8584            InstModule instName
8585              (/*AUTOINST*/);
8586         endmodule
8587
8588 Typing \\[verilog-auto] will make this into:
8589
8590         module ExampInst (o,i)
8591            output o;
8592            input i;
8593            InstModule instName
8594              (/*AUTOINST*/
8595               // Outputs
8596               .ov       (ov[31:0]),
8597               // Inputs
8598               .i        (i));
8599         endmodule
8600
8601 Where the list of inputs and outputs came from the inst module.
8602 \f
8603 Exceptions:
8604
8605   Unless you are instantiating a module multiple times, or the module is
8606   something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
8607   It just makes for unmaintainable code.  To sanitize signal names, try
8608   vrename from http://www.veripool.org.
8609
8610   When you need to violate this suggestion there are two ways to list
8611   exceptions, placing them before the AUTOINST, or using templates.
8612
8613   Any ports defined before the /*AUTOINST*/ are not included in the list of
8614   automatics.  This is similar to making a template as described below, but
8615   is restricted to simple connections just like you normally make.  Also note
8616   that any signals before the AUTOINST will only be picked up by AUTOWIRE if
8617   you have the appropriate // Input or // Output comment, and exactly the
8618   same line formatting as AUTOINST itself uses.
8619
8620         InstModule instName
8621           (// Inputs
8622            .i           (my_i_dont_mess_with_it),
8623            /*AUTOINST*/
8624            // Outputs
8625            .ov          (ov[31:0]));
8626
8627 \f
8628 Templates:
8629
8630   For multiple instantiations based upon a single template, create a
8631   commented out template:
8632
8633         /* InstModule AUTO_TEMPLATE (
8634                 .sig3   (sigz[]),
8635                 );
8636         */
8637
8638   Templates go ABOVE the instantiation(s).  When an instantiation is
8639   expanded `verilog-mode' simply searches up for the closest template.
8640   Thus you can have multiple templates for the same module, just alternate
8641   between the template for an instantiation and the instantiation itself.
8642
8643   The module name must be the same as the name of the module in the
8644   instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
8645   words and capitalized.  Only signals that must be different for each
8646   instantiation need to be listed.
8647
8648   Inside a template, a [] in a connection name (with nothing else inside
8649   the brackets) will be replaced by the same bus subscript as it is being
8650   connected to, or the [] will be removed if it is a single bit signal.
8651   Generally it is a good idea to do this for all connections in a template,
8652   as then they will work for any width signal, and with AUTOWIRE.  See
8653   PTL_BUS becoming PTL_BUSNEW below.
8654
8655   If you have a complicated template, set `verilog-auto-inst-template-numbers'
8656   to see which regexps are matching.  Don't leave that mode set after
8657   debugging is completed though, it will result in lots of extra differences
8658   and merge conflicts.
8659
8660   For example:
8661
8662         /* InstModule AUTO_TEMPLATE (
8663                 .ptl_bus        (ptl_busnew[]),
8664                 );
8665         */
8666         InstModule ms2m (/*AUTOINST*/);
8667
8668   Typing \\[verilog-auto] will make this into:
8669
8670         InstModule ms2m (/*AUTOINST*/
8671             // Outputs
8672             .NotInTemplate      (NotInTemplate),
8673             .ptl_bus            (ptl_busnew[3:0]),  // Templated
8674             ....
8675 \f
8676 @ Templates:
8677
8678   It is common to instantiate a cell multiple times, so templates make it
8679   trivial to substitute part of the cell name into the connection name.
8680
8681         /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
8682                 .sig1   (sigx[@]),
8683                 .sig2   (sigy[@\"(% (+ 1 @) 4)\"]),
8684                 );
8685         */
8686
8687   If no regular expression is provided immediately after the AUTO_TEMPLATE
8688   keyword, then the @ character in any connection names will be replaced
8689   with the instantiation number; the first digits found in the cell's
8690   instantiation name.
8691
8692   If a regular expression is provided, the @ character will be replaced
8693   with the first \(\) grouping that matches against the cell name.  Using a
8694   regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
8695   regexp is provided.  If you use multiple layers of parenthesis,
8696   \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
8697   characters after test and before _, whereas
8698   \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
8699   match.
8700
8701   For example:
8702
8703         /* InstModule AUTO_TEMPLATE (
8704                 .ptl_mapvalidx          (ptl_mapvalid[@]),
8705                 .ptl_mapvalidp1x        (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
8706                 );
8707         */
8708         InstModule ms2m (/*AUTOINST*/);
8709
8710   Typing \\[verilog-auto] will make this into:
8711
8712         InstModule ms2m (/*AUTOINST*/
8713             // Outputs
8714             .ptl_mapvalidx              (ptl_mapvalid[2]),
8715             .ptl_mapvalidp1x            (ptl_mapvalid[3]));
8716
8717   Note the @ character was replaced with the 2 from \"ms2m\".
8718
8719   Alternatively, using a regular expression for @:
8720
8721         /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
8722                 .ptl_mapvalidx          (@_ptl_mapvalid),
8723                 .ptl_mapvalidp1x        (ptl_mapvalid_@),
8724                 );
8725         */
8726         InstModule ms2_FOO (/*AUTOINST*/);
8727         InstModule ms2_BAR (/*AUTOINST*/);
8728
8729   Typing \\[verilog-auto] will make this into:
8730
8731         InstModule ms2_FOO (/*AUTOINST*/
8732             // Outputs
8733             .ptl_mapvalidx              (FOO_ptl_mapvalid),
8734             .ptl_mapvalidp1x            (ptl_mapvalid_FOO));
8735         InstModule ms2_BAR (/*AUTOINST*/
8736             // Outputs
8737             .ptl_mapvalidx              (BAR_ptl_mapvalid),
8738             .ptl_mapvalidp1x            (ptl_mapvalid_BAR));
8739
8740 \f
8741 Regexp Templates:
8742
8743   A template entry of the form
8744
8745             .pci_req\\([0-9]+\\)_l      (pci_req_jtag_[\\1]),
8746
8747   will apply an Emacs style regular expression search for any port beginning
8748   in pci_req followed by numbers and ending in _l and connecting that to
8749   the pci_req_jtag_[] net, with the bus subscript coming from what matches
8750   inside the first set of \\( \\).  Thus pci_req2_l becomes pci_req_jtag_[2].
8751
8752   Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
8753   does the same thing. (Note a @ in the connection/replacement text is
8754   completely different -- still use \\1 there!)  Thus this is the same as
8755   the above template:
8756
8757             .pci_req@_l         (pci_req_jtag_[\\1]),
8758
8759   Here's another example to remove the _l, useful when naming conventions
8760   specify _ alone to mean active low.  Note the use of [] to keep the bus
8761   subscript:
8762
8763             .\\(.*\\)_l         (\\1_[]),
8764 \f
8765 Lisp Templates:
8766
8767   First any regular expression template is expanded.
8768
8769   If the syntax @\"( ... )\" is found in a connection, the expression in
8770   quotes will be evaluated as a Lisp expression, with @ replaced by the
8771   instantiation number.  The MAPVALIDP1X example above would put @+1 modulo
8772   4 into the brackets.  Quote all double-quotes inside the expression with
8773   a leading backslash (\\\").  There are special variables defined that are
8774   useful in these Lisp functions:
8775
8776         vl-name        Name portion of the input/output port.
8777         vl-bits        Bus bits portion of the input/output port ('[2:0]').
8778         vl-width       Width of the input/output port ('3' for [2:0]).
8779                        May be a (...) expression if bits isn't a constant.
8780         vl-dir         Direction of the pin input/output/inout.
8781         vl-cell-type   Module name/type of the cell ('InstModule').
8782         vl-cell-name   Instance name of the cell ('instName').
8783
8784   Normal Lisp variables may be used in expressions.  See
8785   `verilog-read-defines' which can set vh-{definename} variables for use
8786   here.  Also, any comments of the form:
8787
8788         /*AUTO_LISP(setq foo 1)*/
8789
8790   will evaluate any Lisp expression inside the parenthesis between the
8791   beginning of the buffer and the point of the AUTOINST.  This allows
8792   functions to be defined or variables to be changed between instantiations.
8793
8794   Note that when using lisp expressions errors may occur when @ is not a
8795   number; you may need to use the standard Emacs Lisp functions
8796   `number-to-string' and `string-to-number'.
8797
8798   After the evaluation is completed, @ substitution and [] substitution
8799   occur."
8800   (save-excursion
8801     ;; Find beginning
8802     (let* ((pt (point))
8803            (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
8804            (indent-pt (save-excursion (verilog-backward-open-paren)
8805                                       (1+ (current-column))))
8806            (verilog-auto-inst-column (max verilog-auto-inst-column
8807                                           (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
8808            (modi (verilog-modi-current))
8809            (moddecls (verilog-modi-get-decls modi))
8810            (vector-skip-list (unless verilog-auto-inst-vector
8811                                (verilog-decls-get-signals moddecls)))
8812            submod submodi submoddecls
8813            inst skip-pins tpl-list tpl-num did-first par-values)
8814
8815       ;; Find module name that is instantiated
8816       (setq submod  (verilog-read-inst-module)
8817             inst (verilog-read-inst-name)
8818             vl-cell-type submod
8819             vl-cell-name inst
8820             skip-pins (aref (verilog-read-inst-pins) 0))
8821
8822       ;; Parse any AUTO_LISP() before here
8823       (verilog-read-auto-lisp (point-min) pt)
8824
8825       ;; Read parameters (after AUTO_LISP)
8826       (setq par-values (and verilog-auto-inst-param-value
8827                             (verilog-read-inst-param-value)))
8828
8829       ;; Lookup position, etc of submodule
8830       ;; Note this may raise an error
8831       (when (setq submodi (verilog-modi-lookup submod t))
8832         (setq submoddecls (verilog-modi-get-decls submodi))
8833         ;; If there's a number in the instantiation, it may be a argument to the
8834         ;; automatic variable instantiation program.
8835         (let* ((tpl-info (verilog-read-auto-template submod))
8836                (tpl-regexp (aref tpl-info 0)))
8837           (setq tpl-num (if (string-match tpl-regexp inst)
8838                             (match-string 1 inst)
8839                           "")
8840                 tpl-list (aref tpl-info 1)))
8841         ;; Find submodule's signals and dump
8842         (let ((sig-list (verilog-signals-not-in
8843                          (verilog-decls-get-outputs submoddecls)
8844                          skip-pins))
8845               (vl-dir "output"))
8846           (when sig-list
8847             (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8848             (indent-to indent-pt)
8849             ;; Note these are searched for in verilog-read-sub-decls.
8850             (insert "// Outputs\n")
8851             (mapc (lambda (port)
8852                     (verilog-auto-inst-port port indent-pt
8853                                             tpl-list tpl-num for-star par-values))
8854                   sig-list)))
8855         (let ((sig-list (verilog-signals-not-in
8856                          (verilog-decls-get-inouts submoddecls)
8857                          skip-pins))
8858               (vl-dir "inout"))
8859           (when sig-list
8860             (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8861             (indent-to indent-pt)
8862             (insert "// Inouts\n")
8863             (mapc (lambda (port)
8864                     (verilog-auto-inst-port port indent-pt
8865                                             tpl-list tpl-num for-star par-values))
8866                   sig-list)))
8867         (let ((sig-list (verilog-signals-not-in
8868                          (verilog-decls-get-inputs submoddecls)
8869                          skip-pins))
8870               (vl-dir "input"))
8871           (when sig-list
8872             (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8873             (indent-to indent-pt)
8874             (insert "// Inputs\n")
8875             (mapc (lambda (port)
8876                     (verilog-auto-inst-port port indent-pt
8877                                             tpl-list tpl-num for-star par-values))
8878                   sig-list)))
8879         ;; Kill extra semi
8880         (save-excursion
8881           (cond (did-first
8882                  (re-search-backward "," pt t)
8883                  (delete-char 1)
8884                  (insert ");")
8885                  (search-forward "\n")  ;; Added by inst-port
8886                  (delete-backward-char 1)
8887                  (if (search-forward ")" nil t) ;; From user, moved up a line
8888                      (delete-backward-char 1))
8889                  (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
8890                      (delete-backward-char 1)))))))))
8891
8892 (defun verilog-auto-inst-param ()
8893   "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
8894 Replace the parameter connections to an instantiation with ones
8895 automatically derived from the module header of the instantiated netlist.
8896
8897 See \\[verilog-auto-inst] for limitations, and templates to customize the
8898 output.
8899
8900 For example, first take the submodule InstModule.v:
8901
8902         module InstModule (o,i)
8903            parameter PAR;
8904         endmodule
8905
8906 This is then used in a upper level module:
8907
8908         module ExampInst (o,i)
8909            parameter PAR;
8910            InstModule #(/*AUTOINSTPARAM*/)
8911                 instName (/*AUTOINST*/);
8912         endmodule
8913
8914 Typing \\[verilog-auto] will make this into:
8915
8916         module ExampInst (o,i)
8917            output o;
8918            input i;
8919            InstModule #(/*AUTOINSTPARAM*/
8920                         // Parameters
8921                         .PAR    (PAR));
8922                 instName (/*AUTOINST*/);
8923         endmodule
8924
8925 Where the list of parameter connections come from the inst module.
8926 \f
8927 Templates:
8928
8929   You can customize the parameter connections using AUTO_TEMPLATEs,
8930   just as you would with \\[verilog-auto-inst]."
8931   (save-excursion
8932     ;; Find beginning
8933     (let* ((pt (point))
8934            (indent-pt (save-excursion (verilog-backward-open-paren)
8935                                       (1+ (current-column))))
8936            (verilog-auto-inst-column (max verilog-auto-inst-column
8937                                           (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
8938            (modi (verilog-modi-current))
8939            (moddecls (verilog-modi-get-decls modi))
8940            (vector-skip-list (unless verilog-auto-inst-vector
8941                                (verilog-decls-get-signals moddecls)))
8942            submod submodi submoddecls
8943            inst skip-pins tpl-list tpl-num did-first)
8944       ;; Find module name that is instantiated
8945       (setq submod (save-excursion
8946                      ;; Get to the point where AUTOINST normally is to read the module
8947                      (verilog-re-search-forward-quick "[(;]" nil nil)
8948                      (verilog-read-inst-module))
8949             inst   (save-excursion
8950                      ;; Get to the point where AUTOINST normally is to read the module
8951                      (verilog-re-search-forward-quick "[(;]" nil nil)
8952                      (verilog-read-inst-name))
8953             vl-cell-type submod
8954             vl-cell-name inst
8955             skip-pins (aref (verilog-read-inst-pins) 0))
8956
8957       ;; Parse any AUTO_LISP() before here
8958       (verilog-read-auto-lisp (point-min) pt)
8959
8960       ;; Lookup position, etc of submodule
8961       ;; Note this may raise an error
8962       (when (setq submodi (verilog-modi-lookup submod t))
8963         (setq submoddecls (verilog-modi-get-decls submodi))
8964         ;; If there's a number in the instantiation, it may be a argument to the
8965         ;; automatic variable instantiation program.
8966         (let* ((tpl-info (verilog-read-auto-template submod))
8967                (tpl-regexp (aref tpl-info 0)))
8968           (setq tpl-num (if (string-match tpl-regexp inst)
8969                             (match-string 1 inst)
8970                           "")
8971                 tpl-list (aref tpl-info 1)))
8972         ;; Find submodule's signals and dump
8973         (let ((sig-list (verilog-signals-not-in
8974                          (verilog-decls-get-gparams submoddecls)
8975                          skip-pins))
8976               (vl-dir "parameter"))
8977           (when sig-list
8978             (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8979             (indent-to indent-pt)
8980             ;; Note these are searched for in verilog-read-sub-decls.
8981             (insert "// Parameters\n")
8982             (mapc (lambda (port)
8983                     (verilog-auto-inst-port port indent-pt
8984                                             tpl-list tpl-num nil nil))
8985                   sig-list)))
8986         ;; Kill extra semi
8987         (save-excursion
8988           (cond (did-first
8989                  (re-search-backward "," pt t)
8990                  (delete-char 1)
8991                  (insert ")")
8992                  (search-forward "\n")  ;; Added by inst-port
8993                  (delete-backward-char 1)
8994                  (if (search-forward ")" nil t) ;; From user, moved up a line
8995                      (delete-backward-char 1)))))))))
8996
8997 (defun verilog-auto-reg ()
8998   "Expand AUTOREG statements, as part of \\[verilog-auto].
8999 Make reg statements for any output that isn't already declared,
9000 and isn't a wire output from a block.
9001
9002 Limitations:
9003   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9004
9005   This does NOT work on memories, declare those yourself.
9006
9007 An example:
9008
9009         module ExampReg (o,i)
9010            output o;
9011            input i;
9012            /*AUTOREG*/
9013            always o = i;
9014         endmodule
9015
9016 Typing \\[verilog-auto] will make this into:
9017
9018         module ExampReg (o,i)
9019            output o;
9020            input i;
9021            /*AUTOREG*/
9022            // Beginning of automatic regs (for this module's undeclared outputs)
9023            reg          o;
9024            // End of automatics
9025            always o = i;
9026         endmodule"
9027   (save-excursion
9028     ;; Point must be at insertion point.
9029     (let* ((indent-pt (current-indentation))
9030            (modi (verilog-modi-current))
9031            (moddecls (verilog-modi-get-decls modi))
9032            (modsubdecls (verilog-modi-get-sub-decls modi))
9033            (sig-list (verilog-signals-not-in
9034                       (verilog-decls-get-outputs moddecls)
9035                       (append (verilog-decls-get-wires moddecls)
9036                               (verilog-decls-get-regs moddecls)
9037                               (verilog-decls-get-assigns moddecls)
9038                               (verilog-decls-get-consts moddecls)
9039                               (verilog-decls-get-gparams moddecls)
9040                               (verilog-subdecls-get-outputs modsubdecls)
9041                               (verilog-subdecls-get-inouts modsubdecls)))))
9042       (forward-line 1)
9043       (when sig-list
9044         (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
9045         (verilog-insert-definition sig-list "reg" indent-pt nil)
9046         (verilog-modi-cache-add-regs modi sig-list)
9047         (verilog-insert-indent "// End of automatics\n")))))
9048
9049 (defun verilog-auto-reg-input ()
9050   "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
9051 Make reg statements instantiation inputs that aren't already declared.
9052 This is useful for making a top level shell for testing the module that is
9053 to be instantiated.
9054
9055 Limitations:
9056   This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
9057
9058   This does NOT work on memories, declare those yourself.
9059
9060 An example (see `verilog-auto-inst' for what else is going on here):
9061
9062         module ExampRegInput (o,i)
9063            output o;
9064            input i;
9065            /*AUTOREGINPUT*/
9066            InstModule instName
9067              (/*AUTOINST*/);
9068         endmodule
9069
9070 Typing \\[verilog-auto] will make this into:
9071
9072         module ExampRegInput (o,i)
9073            output o;
9074            input i;
9075            /*AUTOREGINPUT*/
9076            // Beginning of automatic reg inputs (for undeclared ...
9077            reg [31:0]           iv;     // From inst of inst.v
9078            // End of automatics
9079            InstModule instName
9080              (/*AUTOINST*/
9081               // Outputs
9082               .o                (o[31:0]),
9083               // Inputs
9084               .iv               (iv));
9085         endmodule"
9086   (save-excursion
9087     ;; Point must be at insertion point.
9088     (let* ((indent-pt (current-indentation))
9089            (modi (verilog-modi-current))
9090            (moddecls (verilog-modi-get-decls modi))
9091            (modsubdecls (verilog-modi-get-sub-decls modi))
9092            (sig-list (verilog-signals-combine-bus
9093                       (verilog-signals-not-in
9094                        (append (verilog-subdecls-get-inputs modsubdecls)
9095                                (verilog-subdecls-get-inouts modsubdecls))
9096                        (verilog-decls-get-signals moddecls)))))
9097       (forward-line 1)
9098       (when sig-list
9099         (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
9100         (verilog-insert-definition sig-list "reg" indent-pt nil)
9101         (verilog-modi-cache-add-regs modi sig-list)
9102         (verilog-insert-indent "// End of automatics\n")))))
9103
9104 (defun verilog-auto-wire ()
9105   "Expand AUTOWIRE statements, as part of \\[verilog-auto].
9106 Make wire statements for instantiations outputs that aren't
9107 already declared.
9108
9109 Limitations:
9110   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
9111   and all busses must have widths, such as those from AUTOINST, or using []
9112   in AUTO_TEMPLATEs.
9113
9114   This does NOT work on memories or SystemVerilog .name connections,
9115   declare those yourself.
9116
9117   Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
9118   determine how to bus together.  This occurs when you have ports with
9119   non-numeric or non-sequential bus subscripts.  If Verilog mode
9120   mis-guessed, you'll have to declare them yourself.
9121
9122 An example (see `verilog-auto-inst' for what else is going on here):
9123
9124         module ExampWire (o,i)
9125            output o;
9126            input i;
9127            /*AUTOWIRE*/
9128            InstModule instName
9129              (/*AUTOINST*/);
9130         endmodule
9131
9132 Typing \\[verilog-auto] will make this into:
9133
9134         module ExampWire (o,i)
9135            output o;
9136            input i;
9137            /*AUTOWIRE*/
9138            // Beginning of automatic wires
9139            wire [31:0]          ov;     // From inst of inst.v
9140            // End of automatics
9141            InstModule instName
9142              (/*AUTOINST*/
9143               // Outputs
9144               .ov       (ov[31:0]),
9145               // Inputs
9146               .i        (i));
9147            wire o = | ov;
9148         endmodule"
9149   (save-excursion
9150     ;; Point must be at insertion point.
9151     (let* ((indent-pt (current-indentation))
9152            (modi (verilog-modi-current))
9153            (moddecls (verilog-modi-get-decls modi))
9154            (modsubdecls (verilog-modi-get-sub-decls modi))
9155            (sig-list (verilog-signals-combine-bus
9156                       (verilog-signals-not-in
9157                        (append (verilog-subdecls-get-outputs modsubdecls)
9158                                (verilog-subdecls-get-inouts modsubdecls))
9159                        (verilog-decls-get-signals moddecls)))))
9160       (forward-line 1)
9161       (when sig-list
9162         (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
9163         (verilog-insert-definition sig-list "wire" indent-pt nil)
9164         (verilog-modi-cache-add-wires modi sig-list)
9165         (verilog-insert-indent "// End of automatics\n")
9166         (when nil       ;; Too slow on huge modules, plus makes everyone's module change
9167           (beginning-of-line)
9168           (setq pnt (point))
9169           (verilog-pretty-declarations quiet)
9170           (goto-char pnt)
9171           (verilog-pretty-expr "//"))))))
9172
9173 (defun verilog-auto-output (&optional with-params)
9174   "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
9175 Make output statements for any output signal from an /*AUTOINST*/ that
9176 isn't a input to another AUTOINST.  This is useful for modules which
9177 only instantiate other modules.
9178
9179 Limitations:
9180   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9181
9182   If placed inside the parenthesis of a module declaration, it creates
9183   Verilog 2001 style, else uses Verilog 1995 style.
9184
9185   If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
9186   instantiation, all bets are off.  (For example due to a AUTO_TEMPLATE).
9187
9188   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9189
9190   Signals matching `verilog-auto-output-ignore-regexp' are not included.
9191
9192 An example (see `verilog-auto-inst' for what else is going on here):
9193
9194         module ExampOutput (ov,i)
9195            input i;
9196            /*AUTOOUTPUT*/
9197            InstModule instName
9198              (/*AUTOINST*/);
9199         endmodule
9200
9201 Typing \\[verilog-auto] will make this into:
9202
9203         module ExampOutput (ov,i)
9204            input i;
9205            /*AUTOOUTPUT*/
9206            // Beginning of automatic outputs (from unused autoinst outputs)
9207            output [31:0]        ov;     // From inst of inst.v
9208            // End of automatics
9209            InstModule instName
9210              (/*AUTOINST*/
9211               // Outputs
9212               .ov       (ov[31:0]),
9213               // Inputs
9214               .i        (i));
9215         endmodule
9216
9217 You may also provide an optional regular expression, in which case only
9218 signals matching the regular expression will be included.  For example the
9219 same expansion will result from only extracting outputs starting with ov:
9220
9221            /*AUTOOUTPUT(\"^ov\")*/"
9222   (save-excursion
9223     ;; Point must be at insertion point.
9224     (let* ((indent-pt (current-indentation))
9225            (regexp (and with-params
9226                         (nth 0 (verilog-read-auto-params 1))))
9227            (v2k  (verilog-in-paren))
9228            (modi (verilog-modi-current))
9229            (moddecls (verilog-modi-get-decls modi))
9230            (modsubdecls (verilog-modi-get-sub-decls modi))
9231            (sig-list (verilog-signals-not-in
9232                       (verilog-subdecls-get-outputs modsubdecls)
9233                       (append (verilog-decls-get-outputs moddecls)
9234                               (verilog-decls-get-inouts moddecls)
9235                               (verilog-subdecls-get-inputs modsubdecls)
9236                               (verilog-subdecls-get-inouts modsubdecls)))))
9237       (when regexp
9238         (setq sig-list (verilog-signals-matching-regexp
9239                         sig-list regexp)))
9240       (setq sig-list (verilog-signals-not-matching-regexp
9241                       sig-list verilog-auto-output-ignore-regexp))
9242       (forward-line 1)
9243       (when v2k (verilog-repair-open-comma))
9244       (when sig-list
9245         (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
9246         (verilog-insert-definition sig-list "output" indent-pt v2k)
9247         (verilog-modi-cache-add-outputs modi sig-list)
9248         (verilog-insert-indent "// End of automatics\n"))
9249       (when v2k (verilog-repair-close-comma)))))
9250
9251 (defun verilog-auto-output-every ()
9252   "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
9253 Make output statements for any signals that aren't primary inputs or
9254 outputs already.  This makes every signal in the design a output.  This is
9255 useful to get Synopsys to preserve every signal in the design, since it
9256 won't optimize away the outputs.
9257
9258 An example:
9259
9260         module ExampOutputEvery (o,i,tempa,tempb)
9261            output o;
9262            input i;
9263            /*AUTOOUTPUTEVERY*/
9264            wire tempa = i;
9265            wire tempb = tempa;
9266            wire o = tempb;
9267         endmodule
9268
9269 Typing \\[verilog-auto] will make this into:
9270
9271         module ExampOutputEvery (o,i,tempa,tempb)
9272            output o;
9273            input i;
9274            /*AUTOOUTPUTEVERY*/
9275            // Beginning of automatic outputs (every signal)
9276            output       tempb;
9277            output       tempa;
9278            // End of automatics
9279            wire tempa = i;
9280            wire tempb = tempa;
9281            wire o = tempb;
9282         endmodule"
9283   (save-excursion
9284     ;;Point must be at insertion point
9285     (let* ((indent-pt (current-indentation))
9286            (v2k  (verilog-in-paren))
9287            (modi (verilog-modi-current))
9288            (moddecls (verilog-modi-get-decls modi))
9289            (sig-list (verilog-signals-combine-bus
9290                       (verilog-signals-not-in
9291                        (verilog-decls-get-signals moddecls)
9292                        (verilog-decls-get-ports moddecls)))))
9293       (forward-line 1)
9294       (when v2k (verilog-repair-open-comma))
9295       (when sig-list
9296         (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
9297         (verilog-insert-definition sig-list "output" indent-pt v2k)
9298         (verilog-modi-cache-add-outputs modi sig-list)
9299         (verilog-insert-indent "// End of automatics\n"))
9300       (when v2k (verilog-repair-close-comma)))))
9301
9302 (defun verilog-auto-input (&optional with-params)
9303   "Expand AUTOINPUT statements, as part of \\[verilog-auto].
9304 Make input statements for any input signal into an /*AUTOINST*/ that
9305 isn't declared elsewhere inside the module.  This is useful for modules which
9306 only instantiate other modules.
9307
9308 Limitations:
9309   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9310
9311   If placed inside the parenthesis of a module declaration, it creates
9312   Verilog 2001 style, else uses Verilog 1995 style.
9313
9314   If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
9315   instantiation, all bets are off.  (For example due to a AUTO_TEMPLATE).
9316
9317   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9318
9319   Signals matching `verilog-auto-input-ignore-regexp' are not included.
9320
9321 An example (see `verilog-auto-inst' for what else is going on here):
9322
9323         module ExampInput (ov,i)
9324            output [31:0] ov;
9325            /*AUTOINPUT*/
9326            InstModule instName
9327              (/*AUTOINST*/);
9328         endmodule
9329
9330 Typing \\[verilog-auto] will make this into:
9331
9332         module ExampInput (ov,i)
9333            output [31:0] ov;
9334            /*AUTOINPUT*/
9335            // Beginning of automatic inputs (from unused autoinst inputs)
9336            input        i;      // From inst of inst.v
9337            // End of automatics
9338            InstModule instName
9339              (/*AUTOINST*/
9340               // Outputs
9341               .ov       (ov[31:0]),
9342               // Inputs
9343               .i        (i));
9344         endmodule
9345
9346 You may also provide an optional regular expression, in which case only
9347 signals matching the regular expression will be included.  For example the
9348 same expansion will result from only extracting inputs starting with i:
9349
9350            /*AUTOINPUT(\"^i\")*/"
9351   (save-excursion
9352     (let* ((indent-pt (current-indentation))
9353            (regexp (and with-params
9354                         (nth 0 (verilog-read-auto-params 1))))
9355            (v2k  (verilog-in-paren))
9356            (modi (verilog-modi-current))
9357            (moddecls (verilog-modi-get-decls modi))
9358            (modsubdecls (verilog-modi-get-sub-decls modi))
9359            (sig-list (verilog-signals-not-in
9360                       (verilog-subdecls-get-inputs modsubdecls)
9361                       (append (verilog-decls-get-inputs moddecls)
9362                               (verilog-decls-get-inouts moddecls)
9363                               (verilog-decls-get-wires moddecls)
9364                               (verilog-decls-get-regs moddecls)
9365                               (verilog-decls-get-consts moddecls)
9366                               (verilog-decls-get-gparams moddecls)
9367                               (verilog-subdecls-get-outputs modsubdecls)
9368                               (verilog-subdecls-get-inouts modsubdecls)))))
9369       (when regexp
9370         (setq sig-list (verilog-signals-matching-regexp
9371                         sig-list regexp)))
9372       (setq sig-list (verilog-signals-not-matching-regexp
9373                       sig-list verilog-auto-input-ignore-regexp))
9374       (forward-line 1)
9375       (when v2k (verilog-repair-open-comma))
9376       (when sig-list
9377         (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
9378         (verilog-insert-definition sig-list "input" indent-pt v2k)
9379         (verilog-modi-cache-add-inputs modi sig-list)
9380         (verilog-insert-indent "// End of automatics\n"))
9381       (when v2k (verilog-repair-close-comma)))))
9382
9383 (defun verilog-auto-inout (&optional with-params)
9384   "Expand AUTOINOUT statements, as part of \\[verilog-auto].
9385 Make inout statements for any inout signal in an /*AUTOINST*/ that
9386 isn't declared elsewhere inside the module.
9387
9388 Limitations:
9389   This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9390
9391   If placed inside the parenthesis of a module declaration, it creates
9392   Verilog 2001 style, else uses Verilog 1995 style.
9393
9394   If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
9395   instantiation, all bets are off.  (For example due to a AUTO_TEMPLATE).
9396
9397   Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9398
9399   Signals matching `verilog-auto-inout-ignore-regexp' are not included.
9400
9401 An example (see `verilog-auto-inst' for what else is going on here):
9402
9403         module ExampInout (ov,i)
9404            input i;
9405            /*AUTOINOUT*/
9406            InstModule instName
9407              (/*AUTOINST*/);
9408         endmodule
9409
9410 Typing \\[verilog-auto] will make this into:
9411
9412         module ExampInout (ov,i)
9413            input i;
9414            /*AUTOINOUT*/
9415            // Beginning of automatic inouts (from unused autoinst inouts)
9416            inout [31:0] ov;     // From inst of inst.v
9417            // End of automatics
9418            InstModule instName
9419              (/*AUTOINST*/
9420               // Inouts
9421               .ov       (ov[31:0]),
9422               // Inputs
9423               .i        (i));
9424         endmodule
9425
9426 You may also provide an optional regular expression, in which case only
9427 signals matching the regular expression will be included.  For example the
9428 same expansion will result from only extracting inouts starting with i:
9429
9430            /*AUTOINOUT(\"^i\")*/"
9431   (save-excursion
9432     ;; Point must be at insertion point.
9433     (let* ((indent-pt (current-indentation))
9434            (regexp (and with-params
9435                         (nth 0 (verilog-read-auto-params 1))))
9436            (v2k  (verilog-in-paren))
9437            (modi (verilog-modi-current))
9438            (moddecls (verilog-modi-get-decls modi))
9439            (modsubdecls (verilog-modi-get-sub-decls modi))
9440            (sig-list (verilog-signals-not-in
9441                       (verilog-subdecls-get-inouts modsubdecls)
9442                       (append (verilog-decls-get-outputs moddecls)
9443                               (verilog-decls-get-inouts moddecls)
9444                               (verilog-decls-get-inputs moddecls)
9445                               (verilog-subdecls-get-inputs modsubdecls)
9446                               (verilog-subdecls-get-outputs modsubdecls)))))
9447       (when regexp
9448         (setq sig-list (verilog-signals-matching-regexp
9449                         sig-list regexp)))
9450       (setq sig-list (verilog-signals-not-matching-regexp
9451                       sig-list verilog-auto-inout-ignore-regexp))
9452       (forward-line 1)
9453       (when v2k (verilog-repair-open-comma))
9454       (when sig-list
9455         (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
9456         (verilog-insert-definition sig-list "inout" indent-pt v2k)
9457         (verilog-modi-cache-add-inouts modi sig-list)
9458         (verilog-insert-indent "// End of automatics\n"))
9459       (when v2k (verilog-repair-close-comma)))))
9460
9461 (defun verilog-auto-inout-module (&optional complement)
9462   "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
9463 Take input/output/inout statements from the specified module and insert
9464 into the current module.  This is useful for making null templates and
9465 shell modules which need to have identical I/O with another module.
9466 Any I/O which are already defined in this module will not be redefined.
9467
9468 Limitations:
9469   If placed inside the parenthesis of a module declaration, it creates
9470   Verilog 2001 style, else uses Verilog 1995 style.
9471
9472   Concatenation and outputting partial busses is not supported.
9473
9474   Module names must be resolvable to filenames.  See `verilog-auto-inst'.
9475
9476   Signals are not inserted in the same order as in the original module,
9477   though they will appear to be in the same order to a AUTOINST
9478   instantiating either module.
9479
9480 An example:
9481
9482         module ExampShell (/*AUTOARG*/)
9483            /*AUTOINOUTMODULE(\"ExampMain\")*/
9484         endmodule
9485
9486         module ExampMain (i,o,io)
9487           input i;
9488           output o;
9489           inout io;
9490         endmodule
9491
9492 Typing \\[verilog-auto] will make this into:
9493
9494         module ExampShell (/*AUTOARG*/i,o,io)
9495            /*AUTOINOUTMODULE(\"ExampMain\")*/
9496            // Beginning of automatic in/out/inouts (from specific module)
9497            output o;
9498            inout io;
9499            input i;
9500            // End of automatics
9501         endmodule
9502
9503 You may also provide an optional regular expression, in which case only
9504 signals matching the regular expression will be included.  For example the
9505 same expansion will result from only extracting signals starting with i:
9506
9507            /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/"
9508   (save-excursion
9509     (let* ((params (verilog-read-auto-params 1 2))
9510            (submod (nth 0 params))
9511            (regexp (nth 1 params))
9512            submodi)
9513       ;; Lookup position, etc of co-module
9514       ;; Note this may raise an error
9515       (when (setq submodi (verilog-modi-lookup submod t))
9516         (let* ((indent-pt (current-indentation))
9517                (v2k  (verilog-in-paren))
9518                (modi (verilog-modi-current))
9519                (moddecls (verilog-modi-get-decls modi))
9520                (submoddecls (verilog-modi-get-decls submodi))
9521                (sig-list-i  (verilog-signals-not-in
9522                              (if complement
9523                                  (verilog-decls-get-outputs submoddecls)
9524                                (verilog-decls-get-inputs submoddecls))
9525                              (append (verilog-decls-get-inputs moddecls))))
9526                (sig-list-o  (verilog-signals-not-in
9527                              (if complement
9528                                  (verilog-decls-get-inputs submoddecls)
9529                                (verilog-decls-get-outputs submoddecls))
9530                              (append (verilog-decls-get-outputs moddecls))))
9531                (sig-list-io (verilog-signals-not-in
9532                              (verilog-decls-get-inouts submoddecls)
9533                              (append (verilog-decls-get-inouts moddecls)))))
9534           (forward-line 1)
9535           (when regexp
9536             (setq sig-list-i  (verilog-signals-matching-regexp
9537                                sig-list-i regexp)
9538                   sig-list-o  (verilog-signals-matching-regexp
9539                                sig-list-o regexp)
9540                   sig-list-io (verilog-signals-matching-regexp
9541                                sig-list-io regexp)))
9542           (when v2k (verilog-repair-open-comma))
9543           (when (or sig-list-i sig-list-o sig-list-io)
9544             (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
9545             ;; Don't sort them so a upper AUTOINST will match the main module
9546             (verilog-insert-definition sig-list-o  "output" indent-pt v2k t)
9547             (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
9548             (verilog-insert-definition sig-list-i  "input" indent-pt v2k t)
9549             (verilog-modi-cache-add-inputs modi sig-list-i)
9550             (verilog-modi-cache-add-outputs modi sig-list-o)
9551             (verilog-modi-cache-add-inouts modi sig-list-io)
9552             (verilog-insert-indent "// End of automatics\n"))
9553           (when v2k (verilog-repair-close-comma)))))))
9554
9555 (defun verilog-auto-inout-comp ()
9556   "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
9557 Take input/output/inout statements from the specified module and
9558 insert the inverse into the current module (inputs become outputs
9559 and vice-versa.)  This is useful for making test and stimulus
9560 modules which need to have complementing I/O with another module.
9561 Any I/O which are already defined in this module will not be
9562 redefined.
9563
9564 Limitations:
9565   If placed inside the parenthesis of a module declaration, it creates
9566   Verilog 2001 style, else uses Verilog 1995 style.
9567
9568   Concatenation and outputting partial busses is not supported.
9569
9570   Module names must be resolvable to filenames.  See `verilog-auto-inst'.
9571
9572   Signals are not inserted in the same order as in the original module,
9573   though they will appear to be in the same order to a AUTOINST
9574   instantiating either module.
9575
9576 An example:
9577
9578         module ExampShell (/*AUTOARG*/)
9579            /*AUTOINOUTCOMP(\"ExampMain\")*/
9580         endmodule
9581
9582         module ExampMain (i,o,io)
9583           input i;
9584           output o;
9585           inout io;
9586         endmodule
9587
9588 Typing \\[verilog-auto] will make this into:
9589
9590         module ExampShell (/*AUTOARG*/i,o,io)
9591            /*AUTOINOUTCOMP(\"ExampMain\")*/
9592            // Beginning of automatic in/out/inouts (from specific module)
9593            output i;
9594            inout io;
9595            input o;
9596            // End of automatics
9597         endmodule
9598
9599 You may also provide an optional regular expression, in which case only
9600 signals matching the regular expression will be included.  For example the
9601 same expansion will result from only extracting signals starting with i:
9602
9603            /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/"
9604   (verilog-auto-inout-module t))
9605
9606 (defun verilog-auto-sense-sigs (moddecls presense-sigs)
9607   "Return list of signals for current AUTOSENSE block."
9608   (let* ((sigss (verilog-read-always-signals))
9609          (sig-list (verilog-signals-not-params
9610                     (verilog-signals-not-in (verilog-alw-get-inputs sigss)
9611                                             (append (and (not verilog-auto-sense-include-inputs)
9612                                                          (verilog-alw-get-outputs sigss))
9613                                                     (verilog-decls-get-consts moddecls)
9614                                                     (verilog-decls-get-gparams moddecls)
9615                                                     presense-sigs)))))
9616     sig-list))
9617
9618 (defun verilog-auto-sense ()
9619   "Expand AUTOSENSE statements, as part of \\[verilog-auto].
9620 Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
9621 with one automatically derived from all inputs declared in the always
9622 statement.  Signals that are generated within the same always block are NOT
9623 placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
9624 Long lines are split based on the `fill-column', see \\[set-fill-column].
9625
9626 Limitations:
9627   Verilog does not allow memories (multidimensional arrays) in sensitivity
9628   lists.  AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
9629
9630 Constant signals:
9631   AUTOSENSE cannot always determine if a `define is a constant or a signal
9632   (it could be in a include file for example).  If a `define or other signal
9633   is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
9634   declaration anywhere in the module (parenthesis are required):
9635
9636         /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
9637
9638   Better yet, use a parameter, which will be understood to be constant
9639   automatically.
9640
9641 OOps!
9642   If AUTOSENSE makes a mistake, please report it.  (First try putting
9643   a begin/end after your always!) As a workaround, if a signal that
9644   shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
9645   If a signal should be in the sensitivity list wasn't, placing it before
9646   the /*AUTOSENSE*/ comment will prevent it from being deleted when the
9647   autos are updated (or added if it occurs there already).
9648
9649 An example:
9650
9651            always @ (/*AS*/) begin
9652               /* AUTO_CONSTANT (`constant) */
9653               outin = ina | inb | `constant;
9654               out = outin;
9655            end
9656
9657 Typing \\[verilog-auto] will make this into:
9658
9659            always @ (/*AS*/ina or inb) begin
9660               /* AUTO_CONSTANT (`constant) */
9661               outin = ina | inb | `constant;
9662               out = outin;
9663            end
9664
9665 Note in Verilog 2001, you can often get the same result from the new @*
9666 operator.  (This was added to the language in part due to AUTOSENSE!)
9667
9668            always @* begin
9669               outin = ina | inb | `constant;
9670               out = outin;
9671            end"
9672   (save-excursion
9673     ;; Find beginning
9674     (let* ((start-pt (save-excursion
9675                        (verilog-re-search-backward "(" nil t)
9676                        (point)))
9677            (indent-pt (save-excursion
9678                         (or (and (goto-char start-pt) (1+ (current-column)))
9679                             (current-indentation))))
9680            (modi (verilog-modi-current))
9681            (moddecls (verilog-modi-get-decls modi))
9682            (sig-memories (verilog-signals-memory
9683                           (append
9684                            (verilog-decls-get-regs moddecls)
9685                            (verilog-decls-get-wires moddecls))))
9686            sig-list not-first presense-sigs)
9687       ;; Read signals in always, eliminate outputs from sense list
9688       (setq presense-sigs (verilog-signals-from-signame
9689                            (save-excursion
9690                              (verilog-read-signals start-pt (point)))))
9691       (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
9692       (when sig-memories
9693         (let ((tlen (length sig-list)))
9694           (setq sig-list (verilog-signals-not-in sig-list sig-memories))
9695           (if (not (eq tlen (length sig-list))) (insert " /*memory or*/ "))))
9696       (if (and presense-sigs  ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
9697                (save-excursion (goto-char (point))
9698                                (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
9699                                (verilog-re-search-backward "\\s-" start-pt t)
9700                                (while (looking-at "\\s-`endif")
9701                                  (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
9702                                  (verilog-re-search-backward "\\s-" start-pt t))
9703                                (not (looking-at "\\s-or\\b"))))
9704           (setq not-first t))
9705       (setq sig-list (sort sig-list `verilog-signals-sort-compare))
9706       (while sig-list
9707         (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
9708                (insert "\n")
9709                (indent-to indent-pt)
9710                (if not-first (insert "or ")))
9711               (not-first (insert " or ")))
9712         (insert (verilog-sig-name (car sig-list)))
9713         (setq sig-list (cdr sig-list)
9714               not-first t)))))
9715
9716 (defun verilog-auto-reset ()
9717   "Expand AUTORESET statements, as part of \\[verilog-auto].
9718 Replace the /*AUTORESET*/ comment with code to initialize all
9719 registers set elsewhere in the always block.
9720
9721 Limitations:
9722   AUTORESET will not clear memories.
9723
9724   AUTORESET uses <= if there are any <= in the block, else it uses =.
9725
9726 /*AUTORESET*/ presumes that any signals mentioned between the previous
9727 begin/case/if statement and the AUTORESET comment are being reset manually
9728 and should not be automatically reset.  This includes omitting any signals
9729 used on the right hand side of assignments.
9730
9731 By default, AUTORESET will include the width of the signal in the autos,
9732 this is a recent change.  To control this behavior, see
9733 `verilog-auto-reset-widths'.
9734
9735 AUTORESET ties signals to deasserted, which is presumed to be zero.
9736 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
9737 them to a one.
9738
9739 An example:
9740
9741     always @(posedge clk or negedge reset_l) begin
9742         if (!reset_l) begin
9743             c <= 1;
9744             /*AUTORESET*/
9745         end
9746         else begin
9747             a <= in_a;
9748             b <= in_b;
9749             c <= in_c;
9750         end
9751     end
9752
9753 Typing \\[verilog-auto] will make this into:
9754
9755     always @(posedge core_clk or negedge reset_l) begin
9756         if (!reset_l) begin
9757             c <= 1;
9758             /*AUTORESET*/
9759             // Beginning of autoreset for uninitialized flops
9760             a <= 0;
9761             b <= 0;
9762             // End of automatics
9763         end
9764         else begin
9765             a <= in_a;
9766             b <= in_b;
9767             c <= in_c;
9768         end
9769     end"
9770
9771   (interactive)
9772   (save-excursion
9773     ;; Find beginning
9774     (let* ((indent-pt (current-indentation))
9775            (modi (verilog-modi-current))
9776            (moddecls (verilog-modi-get-decls modi))
9777            (all-list (verilog-decls-get-signals moddecls))
9778            sigss sig-list prereset-sigs assignment-str)
9779       ;; Read signals in always, eliminate outputs from reset list
9780       (setq prereset-sigs (verilog-signals-from-signame
9781                            (save-excursion
9782                              (verilog-read-signals
9783                               (save-excursion
9784                                 (verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
9785                                 (point))
9786                               (point)))))
9787       (save-excursion
9788         (verilog-re-search-backward "@" nil t)
9789         (setq sigss (verilog-read-always-signals)))
9790       (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
9791                                (concat " <= " verilog-assignment-delay)
9792                              " = "))
9793       (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
9794                                              prereset-sigs))
9795       (setq sig-list (sort sig-list `verilog-signals-sort-compare))
9796       (when sig-list
9797         (insert "\n");
9798         (indent-to indent-pt)
9799         (insert "// Beginning of autoreset for uninitialized flops\n");
9800         (indent-to indent-pt)
9801         (while sig-list
9802           (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
9803                          (car sig-list))))
9804             (insert (verilog-sig-name sig)
9805                     assignment-str
9806                     (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
9807                     ";\n")
9808             (indent-to indent-pt)
9809             (setq sig-list (cdr sig-list))))
9810         (insert "// End of automatics")))))
9811
9812 (defun verilog-auto-tieoff ()
9813   "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
9814 Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
9815 signals to deasserted.
9816
9817 /*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
9818 input/output list as another module, but no internals.  Specifically, it
9819 finds all outputs in the module, and if that input is not otherwise declared
9820 as a register or wire, creates a tieoff.
9821
9822 AUTORESET ties signals to deasserted, which is presumed to be zero.
9823 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
9824 them to a one.
9825
9826 An example of making a stub for another module:
9827
9828     module ExampStub (/*AUTOINST*/);
9829         /*AUTOINOUTMODULE(\"Foo\")*/
9830         /*AUTOTIEOFF*/
9831         // verilator lint_off UNUSED
9832         wire _unused_ok = &{1'b0,
9833                             /*AUTOUNUSED*/
9834                             1'b0};
9835         // verilator lint_on  UNUSED
9836     endmodule
9837
9838 Typing \\[verilog-auto] will make this into:
9839
9840     module ExampStub (/*AUTOINST*/...);
9841         /*AUTOINOUTMODULE(\"Foo\")*/
9842         // Beginning of autotieoff
9843         output [2:0] foo;
9844         // End of automatics
9845
9846         /*AUTOTIEOFF*/
9847         // Beginning of autotieoff
9848         wire [2:0] foo = 3'b0;
9849         // End of automatics
9850         ...
9851     endmodule"
9852   (interactive)
9853   (save-excursion
9854     ;; Find beginning
9855     (let* ((indent-pt (current-indentation))
9856            (modi (verilog-modi-current))
9857            (moddecls (verilog-modi-get-decls modi))
9858            (modsubdecls (verilog-modi-get-sub-decls modi))
9859            (sig-list (verilog-signals-not-in
9860                       (verilog-decls-get-outputs moddecls)
9861                       (append (verilog-decls-get-wires moddecls)
9862                               (verilog-decls-get-regs moddecls)
9863                               (verilog-decls-get-assigns moddecls)
9864                               (verilog-decls-get-consts moddecls)
9865                               (verilog-decls-get-gparams moddecls)
9866                               (verilog-subdecls-get-outputs modsubdecls)
9867                               (verilog-subdecls-get-inouts modsubdecls)))))
9868       (when sig-list
9869         (forward-line 1)
9870         (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
9871         (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
9872         (verilog-modi-cache-add-wires modi sig-list)  ; Before we trash list
9873         (while sig-list
9874           (let ((sig (car sig-list)))
9875             (verilog-insert-one-definition sig "wire" indent-pt)
9876             (indent-to (max 48 (+ indent-pt 40)))
9877             (insert "= " (verilog-sig-tieoff sig)
9878                     ";\n")
9879             (setq sig-list (cdr sig-list))))
9880         (verilog-insert-indent "// End of automatics\n")))))
9881
9882 (defun verilog-auto-unused ()
9883   "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
9884 Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
9885 input and inout signals.
9886
9887 /*AUTOUNUSED*/ is used to make stub modules; modules that have the same
9888 input/output list as another module, but no internals.  Specifically, it
9889 finds all inputs and inouts in the module, and if that input is not otherwise
9890 used, adds it to a comma separated list.
9891
9892 The comma separated list is intended to be used to create a _unused_ok
9893 signal.  Using the exact name \"_unused_ok\" for name of the temporary
9894 signal is recommended as it will insure maximum forward compatibility, it
9895 also makes lint warnings easy to understand; ignore any unused warnings
9896 with \"unused\" in the signal name.
9897
9898 To reduce simulation time, the _unused_ok signal should be forced to a
9899 constant to prevent wiggling.  The easiest thing to do is use a
9900 reduction-and with 1'b0 as shown.
9901
9902 This way all unused signals are in one place, making it convenient to add
9903 your tool's specific pragmas around the assignment to disable any unused
9904 warnings.
9905
9906 You can add signals you do not want included in AUTOUNUSED with
9907 `verilog-auto-unused-ignore-regexp'.
9908
9909 An example of making a stub for another module:
9910
9911     module ExampStub (/*AUTOINST*/);
9912         /*AUTOINOUTMODULE(\"Examp\")*/
9913         /*AUTOTIEOFF*/
9914         // verilator lint_off UNUSED
9915         wire _unused_ok = &{1'b0,
9916                             /*AUTOUNUSED*/
9917                             1'b0};
9918         // verilator lint_on  UNUSED
9919     endmodule
9920
9921 Typing \\[verilog-auto] will make this into:
9922
9923         ...
9924         // verilator lint_off UNUSED
9925         wire _unused_ok = &{1'b0,
9926                             /*AUTOUNUSED*/
9927                             // Beginning of automatics
9928                             unused_input_a,
9929                             unused_input_b,
9930                             unused_input_c,
9931                             // End of automatics
9932                             1'b0};
9933         // verilator lint_on  UNUSED
9934     endmodule"
9935   (interactive)
9936   (save-excursion
9937     ;; Find beginning
9938     (let* ((indent-pt (progn (search-backward "/*") (current-column)))
9939            (modi (verilog-modi-current))
9940            (moddecls (verilog-modi-get-decls modi))
9941            (modsubdecls (verilog-modi-get-sub-decls modi))
9942            (sig-list (verilog-signals-not-in
9943                       (append (verilog-decls-get-inputs moddecls)
9944                               (verilog-decls-get-inouts moddecls))
9945                       (append (verilog-subdecls-get-inputs modsubdecls)
9946                               (verilog-subdecls-get-inouts modsubdecls)))))
9947       (setq sig-list (verilog-signals-not-matching-regexp
9948                       sig-list verilog-auto-unused-ignore-regexp))
9949       (when sig-list
9950         (forward-line 1)
9951         (verilog-insert-indent "// Beginning of automatic unused inputs\n")
9952         (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
9953         (while sig-list
9954           (let ((sig (car sig-list)))
9955             (indent-to indent-pt)
9956             (insert (verilog-sig-name sig) ",\n")
9957             (setq sig-list (cdr sig-list))))
9958         (verilog-insert-indent "// End of automatics\n")))))
9959
9960 (defun verilog-enum-ascii (signm elim-regexp)
9961   "Convert an enum name SIGNM to an ascii string for insertion.
9962 Remove user provided prefix ELIM-REGEXP."
9963   (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
9964   (let ((case-fold-search t))
9965     ;; All upper becomes all lower for readability
9966     (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
9967
9968 (defun verilog-auto-ascii-enum ()
9969   "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
9970 Create a register to contain the ASCII decode of a enumerated signal type.
9971 This will allow trace viewers to show the ASCII name of states.
9972
9973 First, parameters are built into a enumeration using the synopsys enum
9974 comment.  The comment must be between the keyword and the symbol.
9975 \(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
9976
9977 Next, registers which that enum applies to are also tagged with the same
9978 enum.  Synopsys also suggests labeling state vectors, but `verilog-mode'
9979 doesn't care.
9980
9981 Finally, a AUTOASCIIENUM command is used.
9982
9983   The first parameter is the name of the signal to be decoded.
9984
9985   The second parameter is the name to store the ASCII code into.  For the
9986   signal foo, I suggest the name _foo__ascii, where the leading _ indicates
9987   a signal that is just for simulation, and the magic characters _ascii
9988   tell viewers like Dinotrace to display in ASCII format.
9989
9990   The final optional parameter is a string which will be removed from the
9991   state names.
9992
9993 An example:
9994
9995         //== State enumeration
9996         parameter [2:0] // synopsys enum state_info
9997                            SM_IDLE =  3'b000,
9998                            SM_SEND =  3'b001,
9999                            SM_WAIT1 = 3'b010;
10000         //== State variables
10001         reg [2:0]       /* synopsys enum state_info */
10002                         state_r;                /* synopsys state_vector state_r */
10003         reg [2:0]       /* synopsys enum state_info */
10004                         state_e1;
10005
10006         //== ASCII state decoding
10007
10008         /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
10009
10010 Typing \\[verilog-auto] will make this into:
10011
10012         ... same front matter ...
10013
10014         /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
10015         // Beginning of automatic ASCII enum decoding
10016         reg [39:0]              state_ascii_r;          // Decode of state_r
10017         always @(state_r) begin
10018            case ({state_r})
10019                 SM_IDLE:  state_ascii_r = \"idle \";
10020                 SM_SEND:  state_ascii_r = \"send \";
10021                 SM_WAIT1: state_ascii_r = \"wait1\";
10022                 default:  state_ascii_r = \"%Erro\";
10023            endcase
10024         end
10025         // End of automatics"
10026   (save-excursion
10027     (let* ((params (verilog-read-auto-params 2 3))
10028            (undecode-name (nth 0 params))
10029            (ascii-name (nth 1 params))
10030            (elim-regexp (nth 2 params))
10031            ;;
10032            (indent-pt (current-indentation))
10033            (modi (verilog-modi-current))
10034            (moddecls (verilog-modi-get-decls modi))
10035            ;;
10036            (sig-list-consts (append (verilog-decls-get-consts moddecls)
10037                                     (verilog-decls-get-gparams moddecls)))
10038            (sig-list-all  (append (verilog-decls-get-regs moddecls)
10039                                   (verilog-decls-get-outputs moddecls)
10040                                   (verilog-decls-get-inouts moddecls)
10041                                   (verilog-decls-get-inputs moddecls)
10042                                   (verilog-decls-get-wires moddecls)))
10043            ;;
10044            (undecode-sig (or (assoc undecode-name sig-list-all)
10045                              (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
10046            (undecode-enum (or (verilog-sig-enum undecode-sig)
10047                               (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
10048            ;;
10049            (enum-sigs (verilog-signals-not-in
10050                        (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
10051                            (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum))
10052                        nil))
10053            ;;
10054            (enum-chars 0)
10055            (ascii-chars 0))
10056       ;;
10057       ;; Find number of ascii chars needed
10058       (let ((tmp-sigs enum-sigs))
10059         (while tmp-sigs
10060           (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
10061                 ascii-chars (max ascii-chars (length (verilog-enum-ascii
10062                                                       (verilog-sig-name (car tmp-sigs))
10063                                                       elim-regexp)))
10064                 tmp-sigs (cdr tmp-sigs))))
10065       ;;
10066       (forward-line 1)
10067       (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
10068       (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
10069                                          (concat "Decode of " undecode-name) nil nil))))
10070         (verilog-insert-definition decode-sig-list "reg" indent-pt nil)
10071         (verilog-modi-cache-add-regs modi decode-sig-list))
10072       ;;
10073       (verilog-insert-indent "always @(" undecode-name ") begin\n")
10074       (setq indent-pt (+ indent-pt verilog-indent-level))
10075       (indent-to indent-pt)
10076       (insert "case ({" undecode-name "})\n")
10077       (setq indent-pt (+ indent-pt verilog-case-indent))
10078       ;;
10079       (let ((tmp-sigs enum-sigs)
10080             (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n" (1+ (max 8 enum-chars))
10081                             ascii-name ascii-chars))
10082             (errname (substring "%Error" 0 (min 6 ascii-chars))))
10083         (while tmp-sigs
10084           (verilog-insert-indent
10085            (format chrfmt (concat (verilog-sig-name (car tmp-sigs)) ":")
10086                    (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
10087                                        elim-regexp)))
10088           (setq tmp-sigs (cdr tmp-sigs)))
10089         (verilog-insert-indent (format chrfmt "default:" errname)))
10090       ;;
10091       (setq indent-pt (- indent-pt verilog-case-indent))
10092       (verilog-insert-indent "endcase\n")
10093       (setq indent-pt (- indent-pt verilog-indent-level))
10094       (verilog-insert-indent "end\n"
10095                              "// End of automatics\n"))))
10096
10097 (defun verilog-auto-templated-rel ()
10098   "Replace Templated relative line numbers with absolute line numbers.
10099 Internal use only.  This hacks around the line numbers in AUTOINST Templates
10100 being different from the final output's line numbering."
10101   (let ((templateno 0) (template-line (list 0)))
10102     ;; Find line number each template is on
10103     (goto-char (point-min))
10104     (while (search-forward "AUTO_TEMPLATE" nil t)
10105       (setq templateno (1+ templateno))
10106       (setq template-line
10107             (cons (count-lines (point-min) (point)) template-line)))
10108     (setq template-line (nreverse template-line))
10109     ;; Replace T# L# with absolute line number
10110     (goto-char (point-min))
10111     (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
10112       (replace-match
10113        (concat " Templated "
10114                (int-to-string (+ (nth (string-to-number (match-string 1))
10115                                       template-line)
10116                                  (string-to-number (match-string 2)))))
10117        t t))))
10118
10119 \f
10120 ;;
10121 ;; Auto top level
10122 ;;
10123
10124 (defun verilog-auto (&optional inject)  ; Use verilog-inject-auto instead of passing a arg
10125   "Expand AUTO statements.
10126 Look for any /*AUTO...*/ commands in the code, as used in
10127 instantiations or argument headers.  Update the list of signals
10128 following the /*AUTO...*/ command.
10129
10130 Use \\[verilog-delete-auto] to remove the AUTOs.
10131
10132 Use \\[verilog-inject-auto] to insert AUTOs for the first time.
10133
10134 Use \\[verilog-faq] for a pointer to frequently asked questions.
10135
10136 The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
10137 called before and after this function, respectively.
10138
10139 For example:
10140         module ModuleName (/*AUTOARG*/)
10141         /*AUTOINPUT*/
10142         /*AUTOOUTPUT*/
10143         /*AUTOWIRE*/
10144         /*AUTOREG*/
10145         InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
10146
10147 You can also update the AUTOs from the shell using:
10148         emacs --batch  <filenames.v>  -f verilog-batch-auto
10149 Or fix indentation with:
10150         emacs --batch  <filenames.v>  -f verilog-batch-indent
10151 Likewise, you can delete or inject AUTOs with:
10152         emacs --batch  <filenames.v>  -f verilog-batch-delete-auto
10153         emacs --batch  <filenames.v>  -f verilog-batch-inject-auto
10154
10155 Using \\[describe-function], see also:
10156     `verilog-auto-arg'          for AUTOARG module instantiations
10157     `verilog-auto-ascii-enum'   for AUTOASCIIENUM enumeration decoding
10158     `verilog-auto-inout-comp'  for AUTOINOUTCOMP copy complemented i/o
10159     `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
10160     `verilog-auto-inout'        for AUTOINOUT making hierarchy inouts
10161     `verilog-auto-input'        for AUTOINPUT making hierarchy inputs
10162     `verilog-auto-inst'         for AUTOINST instantiation pins
10163     `verilog-auto-star'         for AUTOINST .* SystemVerilog pins
10164     `verilog-auto-inst-param'   for AUTOINSTPARAM instantiation params
10165     `verilog-auto-output'       for AUTOOUTPUT making hierarchy outputs
10166     `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
10167     `verilog-auto-reg'          for AUTOREG registers
10168     `verilog-auto-reg-input'    for AUTOREGINPUT instantiation registers
10169     `verilog-auto-reset'        for AUTORESET flop resets
10170     `verilog-auto-sense'        for AUTOSENSE always sensitivity lists
10171     `verilog-auto-tieoff'       for AUTOTIEOFF output tieoffs
10172     `verilog-auto-unused'       for AUTOUNUSED unused inputs/inouts
10173     `verilog-auto-wire'         for AUTOWIRE instantiation wires
10174
10175     `verilog-read-defines'      for reading `define values
10176     `verilog-read-includes'     for reading `includes
10177
10178 If you have bugs with these autos, try contacting the AUTOAUTHOR
10179 Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.org."
10180   (interactive)
10181   (unless noninteractive (message "Updating AUTOs..."))
10182   (if (fboundp 'dinotrace-unannotate-all)
10183       (dinotrace-unannotate-all))
10184   (let ((oldbuf (if (not (buffer-modified-p))
10185                     (buffer-string)))
10186         ;; Before version 20, match-string with font-lock returns a
10187         ;; vector that is not equal to the string.  IE if on "input"
10188         ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
10189         (fontlocked (when (and (boundp 'font-lock-mode)
10190                                font-lock-mode)
10191                       (font-lock-mode 0)
10192                       t))
10193         ;; Cache directories; we don't write new files, so can't change
10194         (verilog-dir-cache-preserving t))
10195     (unwind-protect
10196         (save-excursion
10197           ;; If we're not in verilog-mode, change syntax table so parsing works right
10198           (unless (eq major-mode `verilog-mode) (verilog-mode))
10199           ;; Allow user to customize
10200           (run-hooks 'verilog-before-auto-hook)
10201           ;; Try to save the user from needing to revert-file to reread file local-variables
10202           (verilog-auto-reeval-locals)
10203           (verilog-read-auto-lisp (point-min) (point-max))
10204           (verilog-getopt-flags)
10205           ;; From here on out, we can cache anything we read from disk
10206           (verilog-preserve-dir-cache
10207            ;; These two may seem obvious to do always, but on large includes it can be way too slow
10208            (when verilog-auto-read-includes
10209              (verilog-read-includes)
10210              (verilog-read-defines nil nil t))
10211            ;; This particular ordering is important
10212            ;; INST: Lower modules correct, no internal dependencies, FIRST
10213            (verilog-preserve-modi-cache
10214             ;; Clear existing autos else we'll be screwed by existing ones
10215             (verilog-delete-auto)
10216             ;; Injection if appropriate
10217             (when inject
10218               (verilog-inject-inst)
10219               (verilog-inject-sense)
10220               (verilog-inject-arg))
10221             ;;
10222             (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
10223             (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
10224             (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
10225             ;; Doesn't matter when done, but combine it with a common changer
10226             (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
10227             (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
10228             ;; Must be done before autoin/out as creates a reg
10229             (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
10230             ;;
10231             ;; first in/outs from other files
10232             (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
10233             (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP([^)]*)\\*/" 'verilog-auto-inout-comp)
10234             ;; next in/outs which need previous sucked inputs first
10235             (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((\"[^\"]*\")\\)\\*/"
10236                                        '(lambda () (verilog-auto-output t)))
10237             (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\*/" 'verilog-auto-output)
10238             (verilog-auto-re-search-do "/\\*AUTOINPUT\\((\"[^\"]*\")\\)\\*/"
10239                                        '(lambda () (verilog-auto-input t)))
10240             (verilog-auto-re-search-do "/\\*AUTOINPUT\\*/"  'verilog-auto-input)
10241             (verilog-auto-re-search-do "/\\*AUTOINOUT\\((\"[^\"]*\")\\)\\*/"
10242                                        '(lambda () (verilog-auto-inout t)))
10243             (verilog-auto-re-search-do "/\\*AUTOINOUT\\*/" 'verilog-auto-inout)
10244             ;; Then tie off those in/outs
10245             (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
10246             ;; Wires/regs must be after inputs/outputs
10247             (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
10248             (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
10249             (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
10250             ;; outputevery needs AUTOOUTPUTs done first
10251             (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\*/" 'verilog-auto-output-every)
10252             ;; After we've created all new variables
10253             (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
10254             ;; Must be after all inputs outputs are generated
10255             (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
10256             ;; Fix line numbers (comments only)
10257             (verilog-auto-templated-rel)))
10258           ;;
10259           (run-hooks 'verilog-auto-hook)
10260           ;;
10261           (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))
10262           ;;
10263           ;; If end result is same as when started, clear modified flag
10264           (cond ((and oldbuf (equal oldbuf (buffer-string)))
10265                  (set-buffer-modified-p nil)
10266                  (unless noninteractive (message "Updating AUTOs...done (no changes)")))
10267                 (t (unless noninteractive (message "Updating AUTOs...done")))))
10268       ;; Unwind forms
10269       (progn
10270         ;; Restore font-lock
10271         (when fontlocked (font-lock-mode t))))))
10272 \f
10273
10274 ;;
10275 ;; Skeleton based code insertion
10276 ;;
10277 (defvar verilog-template-map
10278   (let ((map (make-sparse-keymap)))
10279     (define-key map "a" 'verilog-sk-always)
10280     (define-key map "b" 'verilog-sk-begin)
10281     (define-key map "c" 'verilog-sk-case)
10282     (define-key map "f" 'verilog-sk-for)
10283     (define-key map "g" 'verilog-sk-generate)
10284     (define-key map "h" 'verilog-sk-header)
10285     (define-key map "i" 'verilog-sk-initial)
10286     (define-key map "j" 'verilog-sk-fork)
10287     (define-key map "m" 'verilog-sk-module)
10288     (define-key map "p" 'verilog-sk-primitive)
10289     (define-key map "r" 'verilog-sk-repeat)
10290     (define-key map "s" 'verilog-sk-specify)
10291     (define-key map "t" 'verilog-sk-task)
10292     (define-key map "w" 'verilog-sk-while)
10293     (define-key map "x" 'verilog-sk-casex)
10294     (define-key map "z" 'verilog-sk-casez)
10295     (define-key map "?" 'verilog-sk-if)
10296     (define-key map ":" 'verilog-sk-else-if)
10297     (define-key map "/" 'verilog-sk-comment)
10298     (define-key map "A" 'verilog-sk-assign)
10299     (define-key map "F" 'verilog-sk-function)
10300     (define-key map "I" 'verilog-sk-input)
10301     (define-key map "O" 'verilog-sk-output)
10302     (define-key map "S" 'verilog-sk-state-machine)
10303     (define-key map "=" 'verilog-sk-inout)
10304     (define-key map "W" 'verilog-sk-wire)
10305     (define-key map "R" 'verilog-sk-reg)
10306     (define-key map "D" 'verilog-sk-define-signal)
10307     map)
10308   "Keymap used in Verilog mode for smart template operations.")
10309
10310
10311 ;;
10312 ;; Place the templates into Verilog Mode.  They may be inserted under any key.
10313 ;; C-c C-t will be the default.  If you use templates a lot, you
10314 ;; may want to consider moving the binding to another key in your .emacs
10315 ;; file.
10316 ;;
10317 ;(define-key verilog-mode-map "\C-ct" verilog-template-map)
10318 (define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
10319
10320 ;;; ---- statement skeletons ------------------------------------------
10321
10322 (define-skeleton verilog-sk-prompt-condition
10323   "Prompt for the loop condition."
10324   "[condition]: " str )
10325
10326 (define-skeleton verilog-sk-prompt-init
10327   "Prompt for the loop init statement."
10328   "[initial statement]: " str )
10329
10330 (define-skeleton verilog-sk-prompt-inc
10331   "Prompt for the loop increment statement."
10332   "[increment statement]: " str )
10333
10334 (define-skeleton verilog-sk-prompt-name
10335   "Prompt for the name of something."
10336   "[name]: " str)
10337
10338 (define-skeleton verilog-sk-prompt-clock
10339   "Prompt for the name of something."
10340   "name and edge of clock(s): " str)
10341
10342 (defvar verilog-sk-reset nil)
10343 (defun verilog-sk-prompt-reset ()
10344   "Prompt for the name of a state machine reset."
10345   (setq verilog-sk-reset (read-string "name of reset: " "rst")))
10346
10347
10348 (define-skeleton verilog-sk-prompt-state-selector
10349   "Prompt for the name of a state machine selector."
10350   "name of selector (eg {a,b,c,d}): " str )
10351
10352 (define-skeleton verilog-sk-prompt-output
10353   "Prompt for the name of something."
10354   "output: " str)
10355
10356 (define-skeleton verilog-sk-prompt-msb
10357   "Prompt for least significant bit specification."
10358   "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
10359
10360 (define-skeleton verilog-sk-prompt-lsb
10361   "Prompt for least significant bit specification."
10362   "lsb:" str )
10363
10364 (defvar verilog-sk-p nil)
10365 (define-skeleton verilog-sk-prompt-width
10366   "Prompt for a width specification."
10367   ()
10368   (progn
10369     (setq verilog-sk-p (point))
10370     (verilog-sk-prompt-msb)
10371     (if (> (point) verilog-sk-p) "] " " ")))
10372
10373 (defun verilog-sk-header ()
10374   "Insert a descriptive header at the top of the file."
10375   (interactive "*")
10376   (save-excursion
10377     (goto-char (point-min))
10378     (verilog-sk-header-tmpl)))
10379
10380 (define-skeleton verilog-sk-header-tmpl
10381   "Insert a comment block containing the module title, author, etc."
10382   "[Description]: "
10383   "//                              -*- Mode: Verilog -*-"
10384   "\n// Filename        : " (buffer-name)
10385   "\n// Description     : " str
10386   "\n// Author          : " (user-full-name)
10387   "\n// Created On      : " (current-time-string)
10388   "\n// Last Modified By: ."
10389   "\n// Last Modified On: ."
10390   "\n// Update Count    : 0"
10391   "\n// Status          : Unknown, Use with caution!"
10392   "\n")
10393
10394 (define-skeleton verilog-sk-module
10395   "Insert a module definition."
10396   ()
10397   > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
10398   > _ \n
10399   > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
10400
10401 (define-skeleton verilog-sk-primitive
10402   "Insert a task definition."
10403   ()
10404   > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
10405   > _ \n
10406   > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
10407
10408 (define-skeleton verilog-sk-task
10409   "Insert a task definition."
10410   ()
10411   > "task " '(verilog-sk-prompt-name) & ?; \n
10412   > _ \n
10413   > "begin" \n
10414   > \n
10415   > (- verilog-indent-level-behavioral) "end" \n
10416   > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
10417
10418 (define-skeleton verilog-sk-function
10419   "Insert a function definition."
10420   ()
10421   > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
10422   > _ \n
10423   > "begin" \n
10424   > \n
10425   > (- verilog-indent-level-behavioral) "end" \n
10426   > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
10427
10428 (define-skeleton verilog-sk-always
10429   "Insert always block.  Uses the minibuffer to prompt
10430 for sensitivity list."
10431   ()
10432   > "always @ ( /*AUTOSENSE*/ ) begin\n"
10433   > _ \n
10434   > (- verilog-indent-level-behavioral) "end" \n >
10435   )
10436
10437 (define-skeleton verilog-sk-initial
10438   "Insert an initial block."
10439   ()
10440   > "initial begin\n"
10441   > _ \n
10442   > (- verilog-indent-level-behavioral) "end" \n > )
10443
10444 (define-skeleton verilog-sk-specify
10445   "Insert specify block.  "
10446   ()
10447   > "specify\n"
10448   > _ \n
10449   > (- verilog-indent-level-behavioral) "endspecify" \n > )
10450
10451 (define-skeleton verilog-sk-generate
10452   "Insert generate block.  "
10453   ()
10454   > "generate\n"
10455   > _ \n
10456   > (- verilog-indent-level-behavioral) "endgenerate" \n > )
10457
10458 (define-skeleton verilog-sk-begin
10459   "Insert begin end block.  Uses the minibuffer to prompt for name."
10460   ()
10461   > "begin" '(verilog-sk-prompt-name) \n
10462   > _ \n
10463   > (- verilog-indent-level-behavioral) "end"
10464 )
10465
10466 (define-skeleton verilog-sk-fork
10467   "Insert a fork join block."
10468   ()
10469   > "fork\n"
10470   > "begin" \n
10471   > _ \n
10472   > (- verilog-indent-level-behavioral) "end" \n
10473   > "begin" \n
10474   > \n
10475   > (- verilog-indent-level-behavioral) "end" \n
10476   > (- verilog-indent-level-behavioral) "join" \n
10477   > )
10478
10479
10480 (define-skeleton verilog-sk-case
10481   "Build skeleton case statement, prompting for the selector expression,
10482 and the case items."
10483   "[selector expression]: "
10484   > "case (" str ") " \n
10485   > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
10486   resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
10487
10488 (define-skeleton verilog-sk-casex
10489   "Build skeleton casex statement, prompting for the selector expression,
10490 and the case items."
10491   "[selector expression]: "
10492   > "casex (" str ") " \n
10493   > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
10494   resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
10495
10496 (define-skeleton verilog-sk-casez
10497   "Build skeleton casez statement, prompting for the selector expression,
10498 and the case items."
10499   "[selector expression]: "
10500   > "casez (" str ") " \n
10501   > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
10502   resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
10503
10504 (define-skeleton verilog-sk-if
10505   "Insert a skeleton if statement."
10506   > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
10507   > _ \n
10508   > (- verilog-indent-level-behavioral) "end " \n )
10509
10510 (define-skeleton verilog-sk-else-if
10511   "Insert a skeleton else if statement."
10512   > (verilog-indent-line) "else if ("
10513   (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
10514   > _ \n
10515   > "end" (progn (electric-verilog-terminate-line) nil))
10516
10517 (define-skeleton verilog-sk-datadef
10518   "Common routine to get data definition."
10519   ()
10520   '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
10521
10522 (define-skeleton verilog-sk-input
10523   "Insert an input definition."
10524   ()
10525   > "input  [" '(verilog-sk-datadef))
10526
10527 (define-skeleton verilog-sk-output
10528   "Insert an output definition."
10529   ()
10530   > "output [" '(verilog-sk-datadef))
10531
10532 (define-skeleton verilog-sk-inout
10533   "Insert an inout definition."
10534   ()
10535   > "inout  [" '(verilog-sk-datadef))
10536
10537 (defvar verilog-sk-signal nil)
10538 (define-skeleton verilog-sk-def-reg
10539   "Insert a reg definition."
10540   ()
10541   > "reg    [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
10542
10543 (defun verilog-sk-define-signal ()
10544   "Insert a definition of signal under point at top of module."
10545   (interactive "*")
10546   (let* ((sig-re "[a-zA-Z0-9_]*")
10547          (v1 (buffer-substring
10548                (save-excursion
10549                  (skip-chars-backward sig-re)
10550                  (point))
10551                (save-excursion
10552                  (skip-chars-forward sig-re)
10553                  (point)))))
10554     (if (not (member v1 verilog-keywords))
10555         (save-excursion
10556           (setq verilog-sk-signal v1)
10557           (verilog-beg-of-defun)
10558           (verilog-end-of-statement)
10559           (verilog-forward-syntactic-ws)
10560           (verilog-sk-def-reg)
10561           (message "signal at point is %s" v1))
10562       (message "object at point (%s) is a keyword" v1))))
10563
10564 (define-skeleton verilog-sk-wire
10565   "Insert a wire definition."
10566   ()
10567   > "wire   [" '(verilog-sk-datadef))
10568
10569 (define-skeleton verilog-sk-reg
10570   "Insert a reg definition."
10571   ()
10572   > "reg   [" '(verilog-sk-datadef))
10573
10574 (define-skeleton verilog-sk-assign
10575   "Insert a skeleton assign statement."
10576   ()
10577   > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
10578
10579 (define-skeleton verilog-sk-while
10580   "Insert a skeleton while loop statement."
10581   ()
10582   > "while ("  '(verilog-sk-prompt-condition)  ") begin" \n
10583   > _ \n
10584   > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
10585
10586 (define-skeleton verilog-sk-repeat
10587   "Insert a skeleton repeat loop statement."
10588   ()
10589   > "repeat ("  '(verilog-sk-prompt-condition)  ") begin" \n
10590   > _ \n
10591   > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
10592
10593 (define-skeleton verilog-sk-for
10594   "Insert a skeleton while loop statement."
10595   ()
10596   > "for ("
10597   '(verilog-sk-prompt-init) "; "
10598   '(verilog-sk-prompt-condition) "; "
10599   '(verilog-sk-prompt-inc)
10600   ") begin" \n
10601   > _ \n
10602   > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
10603
10604 (define-skeleton verilog-sk-comment
10605   "Inserts three comment lines, making a display comment."
10606   ()
10607   > "/*\n"
10608   > "* " _ \n
10609   > "*/")
10610
10611 (define-skeleton verilog-sk-state-machine
10612   "Insert a state machine definition."
10613   "Name of state variable: "
10614   '(setq input "state")
10615   > "// State registers for " str | -23 \n
10616   '(setq verilog-sk-state str)
10617   > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
10618   '(setq input nil)
10619   > \n
10620   > "// State FF for " verilog-sk-state \n
10621   > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
10622   > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
10623   > verilog-sk-state " = next_" verilog-sk-state ?; \n
10624   > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
10625   > \n
10626   > "// Next State Logic for " verilog-sk-state \n
10627   > "always @ ( /*AUTOSENSE*/ ) begin\n"
10628   > "case (" '(verilog-sk-prompt-state-selector) ") " \n
10629   > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
10630   resume: >  (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
10631   > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
10632 \f
10633
10634 ;;
10635 ;; Include file loading with mouse/return event
10636 ;;
10637 ;; idea & first impl.: M. Rouat (eldo-mode.el)
10638 ;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
10639
10640 (if (featurep 'xemacs)
10641     (require 'overlay)
10642   (require 'lucid)) ;; what else can we do ??
10643
10644 (defconst verilog-include-file-regexp
10645   "^`include\\s-+\"\\([^\n\"]*\\)\""
10646   "Regexp that matches the include file.")
10647
10648 (defvar verilog-mode-mouse-map
10649   (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
10650     (set-keymap-parent map verilog-mode-map)
10651     ;; mouse button bindings
10652     (define-key map "\r"            'verilog-load-file-at-point)
10653     (if (featurep 'xemacs)
10654         (define-key map 'button2    'verilog-load-file-at-mouse);ffap-at-mouse ?
10655       (define-key map [mouse-2]     'verilog-load-file-at-mouse))
10656     (if (featurep 'xemacs)
10657         (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
10658       (define-key map [S-mouse-2]   'mouse-yank-at-click))
10659     map)
10660   "Map containing mouse bindings for `verilog-mode'.")
10661
10662
10663 (defun verilog-colorize-include-files (beg end old-len)
10664   "This function colorizes included files when the mouse passes over them.
10665 Clicking on the middle-mouse button loads them in a buffer (as in dired)."
10666   (save-excursion
10667     (save-match-data
10668       (let (end-point)
10669         (goto-char end)
10670         (setq end-point (verilog-get-end-of-line))
10671         (goto-char beg)
10672         (beginning-of-line)  ; scan entire line !
10673         ;; delete overlays existing on this line
10674         (let ((overlays (overlays-in (point) end-point)))
10675           (while overlays
10676             (if (and
10677                  (overlay-get (car overlays) 'detachable)
10678                  (overlay-get (car overlays) 'verilog-include-file))
10679                 (delete-overlay (car overlays)))
10680             (setq overlays (cdr overlays)))) ; let
10681         ;; make new ones, could reuse deleted one ?
10682         (while (search-forward-regexp verilog-include-file-regexp end-point t)
10683           (let (ov)
10684             (goto-char (match-beginning 1))
10685             (setq ov (make-overlay (match-beginning 1) (match-end 1)))
10686             (overlay-put ov 'start-closed 't)
10687             (overlay-put ov 'end-closed 't)
10688             (overlay-put ov 'evaporate 't)
10689             (overlay-put ov 'verilog-include-file 't)
10690             (overlay-put ov 'mouse-face 'highlight)
10691             (overlay-put ov 'local-map verilog-mode-mouse-map)))))))
10692
10693
10694 (defun verilog-colorize-include-files-buffer ()
10695   "Colorize an include file."
10696   (interactive)
10697   ;; delete overlays
10698   (let ((overlays (overlays-in (point-min) (point-max))))
10699     (while overlays
10700       (if (and
10701            (overlay-get (car overlays) 'detachable)
10702            (overlay-get (car overlays) 'verilog-include-file))
10703           (delete-overlay (car overlays)))
10704       (setq overlays (cdr overlays)))) ; let
10705   ;; remake overlays
10706   (verilog-colorize-include-files (point-min) (point-max) nil))
10707
10708 ;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
10709 ;; so define this function to do more or less the same as ffap-at-mouse
10710 ;; but first resolve filename...
10711 (defun verilog-load-file-at-mouse (event)
10712   "Load file under button 2 click's EVENT.
10713 Files are checked based on `verilog-library-directories'."
10714   (interactive "@e")
10715   (save-excursion ;; implement a Verilog specific ffap-at-mouse
10716     (mouse-set-point event)
10717     (beginning-of-line)
10718     (if (looking-at verilog-include-file-regexp)
10719         (if (and (car (verilog-library-filenames
10720                        (match-string 1) (buffer-file-name)))
10721                  (file-readable-p (car (verilog-library-filenames
10722                                         (match-string 1) (buffer-file-name)))))
10723             (find-file (car (verilog-library-filenames
10724                              (match-string 1) (buffer-file-name))))
10725           (progn
10726             (message
10727              "File '%s' isn't readable, use shift-mouse2 to paste in this field"
10728              (match-string 1)))))))
10729
10730 ;; ffap isn't useable for Verilog mode. It uses library paths.
10731 ;; so define this function to do more or less the same as ffap
10732 ;; but first resolve filename...
10733 (defun verilog-load-file-at-point ()
10734   "Load file under point.
10735 Files are checked based on `verilog-library-directories'."
10736   (interactive)
10737   (save-excursion ;; implement a Verilog specific ffap
10738     (beginning-of-line)
10739     (if (looking-at verilog-include-file-regexp)
10740         (if (and
10741              (car (verilog-library-filenames
10742                    (match-string 1) (buffer-file-name)))
10743              (file-readable-p (car (verilog-library-filenames
10744                                     (match-string 1) (buffer-file-name)))))
10745             (find-file (car (verilog-library-filenames
10746                              (match-string 1) (buffer-file-name))))))))
10747
10748
10749 ;;
10750 ;; Bug reporting
10751 ;;
10752
10753 (defun verilog-faq ()
10754   "Tell the user their current version, and where to get the FAQ etc."
10755   (interactive)
10756   (with-output-to-temp-buffer "*verilog-mode help*"
10757     (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
10758     (princ "\n")
10759     (princ "For new releases, see http://www.verilog.com\n")
10760     (princ "\n")
10761     (princ "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
10762     (princ "\n")
10763     (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
10764     (princ "\n")))
10765
10766 (autoload 'reporter-submit-bug-report "reporter")
10767 (defvar reporter-prompt-for-summary-p)
10768
10769 (defun verilog-submit-bug-report ()
10770   "Submit via mail a bug report on verilog-mode.el."
10771   (interactive)
10772   (let ((reporter-prompt-for-summary-p t))
10773     (reporter-submit-bug-report
10774      "mac@verilog.com"
10775      (concat "verilog-mode v" verilog-mode-version)
10776      '(
10777        verilog-align-ifelse
10778        verilog-auto-endcomments
10779        verilog-auto-hook
10780        verilog-auto-indent-on-newline
10781        verilog-auto-inst-vector
10782        verilog-auto-inst-template-numbers
10783        verilog-auto-lineup
10784        verilog-auto-newline
10785        verilog-auto-save-policy
10786        verilog-auto-sense-defines-constant
10787        verilog-auto-sense-include-inputs
10788        verilog-before-auto-hook
10789        verilog-case-indent
10790        verilog-cexp-indent
10791        verilog-compiler
10792        verilog-coverage
10793        verilog-highlight-translate-off
10794        verilog-indent-begin-after-if
10795        verilog-indent-declaration-macros
10796        verilog-indent-level
10797        verilog-indent-level-behavioral
10798        verilog-indent-level-declaration
10799        verilog-indent-level-directive
10800        verilog-indent-level-module
10801        verilog-indent-lists
10802        verilog-library-flags
10803        verilog-library-directories
10804        verilog-library-extensions
10805        verilog-library-files
10806        verilog-linter
10807        verilog-minimum-comment-distance
10808        verilog-mode-hook
10809        verilog-simulator
10810        verilog-tab-always-indent
10811        verilog-tab-to-comment
10812        )
10813      nil nil
10814      (concat "Hi Mac,
10815
10816 I want to report a bug.  I've read the `Bugs' section of `Info' on
10817 Emacs, so I know how to make a clear and unambiguous report.  To get
10818 to that Info section, I typed
10819
10820 M-x info RET m " invocation-name " RET m bugs RET
10821
10822 Before I go further, I want to say that Verilog mode has changed my life.
10823 I save so much time, my files are colored nicely, my co workers respect
10824 my coding ability... until now.  I'd really appreciate anything you
10825 could do to help me out with this minor deficiency in the product.
10826
10827 If you have bugs with the AUTO functions, please CC the AUTOAUTHOR Wilson
10828 Snyder (wsnyder@wsnyder.org) and/or see http://www.veripool.org.
10829 You may also want to look at the Verilog-Mode FAQ, see
10830 http://www.veripool.org/verilog-mode-faq.html.
10831
10832 To reproduce the bug, start a fresh Emacs via " invocation-name "
10833 -no-init-file -no-site-file'.  In a new buffer, in Verilog mode, type
10834 the code included below.
10835
10836 Given those lines, I expected [[Fill in here]] to happen;
10837 but instead, [[Fill in here]] happens!.
10838
10839 == The code: =="))))
10840
10841 (provide 'verilog-mode)
10842
10843 ;; Local Variables:
10844 ;; checkdoc-permit-comma-termination-flag:t
10845 ;; checkdoc-force-docstrings-flag:nil
10846 ;; End:
10847
10848 ;; arch-tag: 87923725-57b3-41b5-9494-be21118c6a6f
10849 ;;; verilog-mode.el ends here