]> code.delx.au - gnu-emacs/blob - lisp/progmodes/verilog-mode.el
1c4200e058ac211a8645eb09a1892aac11e62c40
[gnu-emacs] / lisp / progmodes / 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, 2009, 2010, 2011 Free Software Foundation, Inc.
5
6 ;; Author: Michael McNamara (mac@verilog.com),
7 ;; Wilson Snyder (wsnyder@wsnyder.org)
8 ;; Please see our web sites:
9 ;; http://www.verilog.com
10 ;; http://www.veripool.org
11 ;;
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 issues to the issue tracker at
58 ;; http://www.veripool.org/verilog-mode
59 ;; Please use verilog-submit-bug-report to submit a report; type C-c
60 ;; C-b to invoke this and as a result I will have a much easier time
61 ;; of reproducing the bug you find, and hence fixing it.
62
63 ;; INSTALLING THE MODE
64 ;; ===================
65
66 ;; An older version of this mode may be already installed as a part of
67 ;; your environment, and one method of updating would be to update
68 ;; your Emacs environment. Sometimes this is difficult for local
69 ;; political/control reasons, and hence you can always install a
70 ;; private copy (or even a shared copy) which overrides the system
71 ;; default.
72
73 ;; You can get step by step help in installing this file by going to
74 ;; <http://www.verilog.com/emacs_install.html>
75
76 ;; The short list of installation instructions are: To set up
77 ;; automatic Verilog mode, put this file in your load path, and put
78 ;; the following in code (please un comment it first!) in your
79 ;; .emacs, or in your site's site-load.el
80
81 ; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
82 ; (add-to-list 'auto-mode-alist '("\\.[ds]?vh?\\'" . verilog-mode))
83
84 ;; Be sure to examine at the help for verilog-auto, and the other
85 ;; verilog-auto-* functions for some major coding time savers.
86 ;;
87 ;; If you want to customize Verilog mode to fit your needs better,
88 ;; you may add the below lines (the values of the variables presented
89 ;; here are the defaults). Note also that if you use an Emacs that
90 ;; supports custom, it's probably better to use the custom menu to
91 ;; edit these. If working as a member of a large team these settings
92 ;; should be common across all users (in a site-start file), or set
93 ;; in Local Variables in every file. Otherwise, different people's
94 ;; AUTO expansion may result different whitespace changes.
95 ;;
96 ; ;; Enable syntax highlighting of **all** languages
97 ; (global-font-lock-mode t)
98 ;
99 ; ;; User customization for Verilog mode
100 ; (setq verilog-indent-level 3
101 ; verilog-indent-level-module 3
102 ; verilog-indent-level-declaration 3
103 ; verilog-indent-level-behavioral 3
104 ; verilog-indent-level-directive 1
105 ; verilog-case-indent 2
106 ; verilog-auto-newline t
107 ; verilog-auto-indent-on-newline t
108 ; verilog-tab-always-indent t
109 ; verilog-auto-endcomments t
110 ; verilog-minimum-comment-distance 40
111 ; verilog-indent-begin-after-if t
112 ; verilog-auto-lineup 'declarations
113 ; verilog-highlight-p1800-keywords nil
114 ; verilog-linter "my_lint_shell_command"
115 ; )
116
117 ;; \f
118
119 ;;; History:
120 ;;
121 ;; See commit history at http://www.veripool.org/verilog-mode.html
122 ;; (This section is required to appease checkdoc.)
123
124 ;;; Code:
125
126 ;; This variable will always hold the version number of the mode
127 (defconst verilog-mode-version "650"
128 "Version of this Verilog mode.")
129 (defconst verilog-mode-release-date "2010-11-05-GNU"
130 "Release date of this Verilog mode.")
131 (defconst verilog-mode-release-emacs t
132 "If non-nil, this version of Verilog mode was released with Emacs itself.")
133
134 (defun verilog-version ()
135 "Inform caller of the version of this file."
136 (interactive)
137 (message "Using verilog-mode version %s" verilog-mode-version))
138
139 ;; Insure we have certain packages, and deal with it if we don't
140 ;; Be sure to note which Emacs flavor and version added each feature.
141 (eval-when-compile
142 ;; Provide stuff if we are XEmacs
143 (when (featurep 'xemacs)
144 (condition-case nil
145 (require 'easymenu)
146 (error nil))
147 (condition-case nil
148 (require 'regexp-opt)
149 (error nil))
150 ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
151 (condition-case nil
152 (load "skeleton")
153 (error nil))
154 (condition-case nil
155 (if (fboundp 'when)
156 nil ;; fab
157 (defmacro when (cond &rest body)
158 (list 'if cond (cons 'progn body))))
159 (error nil))
160 (condition-case nil
161 (if (fboundp 'unless)
162 nil ;; fab
163 (defmacro unless (cond &rest body)
164 (cons 'if (cons cond (cons nil body)))))
165 (error nil))
166 (condition-case nil
167 (if (fboundp 'store-match-data)
168 nil ;; fab
169 (defmacro store-match-data (&rest args) nil))
170 (error nil))
171 (condition-case nil
172 (if (fboundp 'char-before)
173 nil ;; great
174 (defmacro char-before (&rest body)
175 (char-after (1- (point)))))
176 (error nil))
177 (condition-case nil
178 (require 'custom)
179 (error nil))
180 (condition-case nil
181 (if (fboundp 'match-string-no-properties)
182 nil ;; great
183 (defsubst match-string-no-properties (num &optional string)
184 "Return string of text matched by last search, without text properties.
185 NUM specifies which parenthesized expression in the last regexp.
186 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
187 Zero means the entire text matched by the whole regexp or whole string.
188 STRING should be given if the last search was by `string-match' on STRING."
189 (if (match-beginning num)
190 (if string
191 (let ((result
192 (substring string
193 (match-beginning num) (match-end num))))
194 (set-text-properties 0 (length result) nil result)
195 result)
196 (buffer-substring-no-properties (match-beginning num)
197 (match-end num)
198 (current-buffer)))))
199 )
200 (error nil))
201 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
202 nil ;; We've got what we needed
203 ;; We have the old custom-library, hack around it!
204 (defmacro defgroup (&rest args) nil)
205 (defmacro customize (&rest args)
206 (message
207 "Sorry, Customize is not available with this version of Emacs"))
208 (defmacro defcustom (var value doc &rest args)
209 `(defvar ,var ,value ,doc))
210 )
211 (if (fboundp 'defface)
212 nil ; great!
213 (defmacro defface (var values doc &rest args)
214 `(make-face ,var))
215 )
216
217 (if (and (featurep 'custom) (fboundp 'customize-group))
218 nil ;; We've got what we needed
219 ;; We have an intermediate custom-library, hack around it!
220 (defmacro customize-group (var &rest args)
221 `(customize ,var))
222 )
223
224 (unless (boundp 'inhibit-point-motion-hooks)
225 (defvar inhibit-point-motion-hooks nil))
226 (unless (boundp 'deactivate-mark)
227 (defvar deactivate-mark nil))
228 )
229 ;;
230 ;; OK, do this stuff if we are NOT XEmacs:
231 (unless (featurep 'xemacs)
232 (unless (fboundp 'region-active-p)
233 (defmacro region-active-p ()
234 `(and transient-mark-mode mark-active))))
235 )
236
237 ;; Provide a regular expression optimization routine, using regexp-opt
238 ;; if provided by the user's elisp libraries
239 (eval-and-compile
240 ;; The below were disabled when GNU Emacs 22 was released;
241 ;; perhaps some still need to be there to support Emacs 21.
242 (if (featurep 'xemacs)
243 (if (fboundp 'regexp-opt)
244 ;; regexp-opt is defined, does it take 3 or 2 arguments?
245 (if (fboundp 'function-max-args)
246 (let ((args (function-max-args `regexp-opt)))
247 (cond
248 ((eq args 3) ;; It takes 3
249 (condition-case nil ; Hide this defun from emacses
250 ;with just a two input regexp
251 (defun verilog-regexp-opt (a b)
252 "Deal with differing number of required arguments for `regexp-opt'.
253 Call 'regexp-opt' on A and B."
254 (regexp-opt a b 't))
255 (error nil))
256 )
257 ((eq args 2) ;; It takes 2
258 (defun verilog-regexp-opt (a b)
259 "Call 'regexp-opt' on A and B."
260 (regexp-opt a b))
261 )
262 (t nil)))
263 ;; We can't tell; assume it takes 2
264 (defun verilog-regexp-opt (a b)
265 "Call 'regexp-opt' on A and B."
266 (regexp-opt a b))
267 )
268 ;; There is no regexp-opt, provide our own
269 (defun verilog-regexp-opt (strings &optional paren shy)
270 (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
271 (concat open (mapconcat 'regexp-quote strings "\\|") close)))
272 )
273 ;; Emacs.
274 (defalias 'verilog-regexp-opt 'regexp-opt)))
275
276 (eval-and-compile
277 ;; Both xemacs and emacs
278 (condition-case nil
279 (unless (fboundp 'buffer-chars-modified-tick) ;; Emacs 22 added
280 (defmacro buffer-chars-modified-tick () (buffer-modified-tick)))
281 (error nil)))
282
283 (eval-when-compile
284 (defun verilog-regexp-words (a)
285 "Call 'regexp-opt' with word delimiters for the words A."
286 (concat "\\<" (verilog-regexp-opt a t) "\\>")))
287 (defun verilog-regexp-words (a)
288 "Call 'regexp-opt' with word delimiters for the words A."
289 ;; The FAQ references this function, so user LISP sometimes calls it
290 (concat "\\<" (verilog-regexp-opt a t) "\\>"))
291
292 (defun verilog-easy-menu-filter (menu)
293 "Filter `easy-menu-define' MENU to support new features."
294 (cond ((not (featurep 'xemacs))
295 menu) ;; GNU Emacs - passthru
296 ;; Xemacs doesn't support :help. Strip it.
297 ;; Recursively filter the a submenu
298 ((listp menu)
299 (mapcar 'verilog-easy-menu-filter menu))
300 ;; Look for [:help "blah"] and remove
301 ((vectorp menu)
302 (let ((i 0) (out []))
303 (while (< i (length menu))
304 (if (equal `:help (aref menu i))
305 (setq i (+ 2 i))
306 (setq out (vconcat out (vector (aref menu i)))
307 i (1+ i))))
308 out))
309 (t menu))) ;; Default - ok
310 ;;(verilog-easy-menu-filter
311 ;; `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
312 ;; "----" ["MB" nil :help "Help MB"]))
313
314 (defun verilog-customize ()
315 "Customize variables and other settings used by Verilog-Mode."
316 (interactive)
317 (customize-group 'verilog-mode))
318
319 (defun verilog-font-customize ()
320 "Customize fonts used by Verilog-Mode."
321 (interactive)
322 (if (fboundp 'customize-apropos)
323 (customize-apropos "font-lock-*" 'faces)))
324
325 (defun verilog-booleanp (value)
326 "Return t if VALUE is boolean.
327 This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
328 This function may be removed when Emacs 21 is no longer supported."
329 (or (equal value t) (equal value nil)))
330
331 (defun verilog-insert-last-command-event ()
332 "Insert the `last-command-event'."
333 (insert (if (featurep 'xemacs)
334 ;; XEmacs 21.5 doesn't like last-command-event
335 last-command-char
336 ;; And GNU Emacs 22 has obsoleted last-command-char
337 last-command-event)))
338
339 (defalias 'verilog-syntax-ppss
340 (if (fboundp 'syntax-ppss) 'syntax-ppss
341 (lambda (&optional pos) (parse-partial-sexp (point-min) (or pos (point))))))
342
343 (defgroup verilog-mode nil
344 "Facilitates easy editing of Verilog source text."
345 :version "22.2"
346 :group 'languages)
347
348 ; (defgroup verilog-mode-fonts nil
349 ; "Facilitates easy customization fonts used in Verilog source text"
350 ; :link '(customize-apropos "font-lock-*" 'faces)
351 ; :group 'verilog-mode)
352
353 (defgroup verilog-mode-indent nil
354 "Customize indentation and highlighting of Verilog source text."
355 :group 'verilog-mode)
356
357 (defgroup verilog-mode-actions nil
358 "Customize actions on Verilog source text."
359 :group 'verilog-mode)
360
361 (defgroup verilog-mode-auto nil
362 "Customize AUTO actions when expanding Verilog source text."
363 :group 'verilog-mode)
364
365 (defvar verilog-debug nil
366 "If set, enable debug messages for `verilog-mode' internals.")
367
368 (defcustom verilog-linter
369 "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
370 "*Unix program and arguments to call to run a lint checker on Verilog source.
371 Depending on the `verilog-set-compile-command', this may be invoked when
372 you type \\[compile]. When the compile completes, \\[next-error] will take
373 you to the next lint error."
374 :type 'string
375 :group 'verilog-mode-actions)
376 ;; We don't mark it safe, as it's used as a shell command
377
378 (defcustom verilog-coverage
379 "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
380 "*Program and arguments to use to annotate for coverage Verilog source.
381 Depending on the `verilog-set-compile-command', this may be invoked when
382 you type \\[compile]. When the compile completes, \\[next-error] will take
383 you to the next lint error."
384 :type 'string
385 :group 'verilog-mode-actions)
386 ;; We don't mark it safe, as it's used as a shell command
387
388 (defcustom verilog-simulator
389 "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
390 "*Program and arguments to use to interpret Verilog source.
391 Depending on the `verilog-set-compile-command', this may be invoked when
392 you type \\[compile]. When the compile completes, \\[next-error] will take
393 you to the next lint error."
394 :type 'string
395 :group 'verilog-mode-actions)
396 ;; We don't mark it safe, as it's used as a shell command
397
398 (defcustom verilog-compiler
399 "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
400 "*Program and arguments to use to compile Verilog source.
401 Depending on the `verilog-set-compile-command', this may be invoked when
402 you type \\[compile]. When the compile completes, \\[next-error] will take
403 you to the next lint error."
404 :type 'string
405 :group 'verilog-mode-actions)
406 ;; We don't mark it safe, as it's used as a shell command
407
408 (defcustom verilog-preprocessor
409 ;; Very few tools give preprocessed output, so we'll default to Verilog-Perl
410 "vppreproc __FLAGS__ __FILE__"
411 "*Program and arguments to use to preprocess Verilog source.
412 This is invoked with `verilog-preprocess', and depending on the
413 `verilog-set-compile-command', may also be invoked when you type
414 \\[compile]. When the compile completes, \\[next-error] will
415 take you to the next lint error."
416 :type 'string
417 :group 'verilog-mode-actions)
418 ;; We don't mark it safe, as it's used as a shell command
419
420 (defvar verilog-preprocess-history nil
421 "History for `verilog-preprocess'.")
422
423 (defvar verilog-tool 'verilog-linter
424 "Which tool to use for building compiler-command.
425 Either nil, `verilog-linter, `verilog-compiler,
426 `verilog-coverage, `verilog-preprocessor, or `verilog-simulator.
427 Alternatively use the \"Choose Compilation Action\" menu. See
428 `verilog-set-compile-command' for more information.")
429
430 (defcustom verilog-highlight-translate-off nil
431 "*Non-nil means background-highlight code excluded from translation.
432 That is, all code between \"// synopsys translate_off\" and
433 \"// synopsys translate_on\" is highlighted using a different background color
434 \(face `verilog-font-lock-translate-off-face').
435
436 Note: This will slow down on-the-fly fontification (and thus editing).
437
438 Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
439 entry \"Fontify Buffer\"). XEmacs: turn off and on font locking."
440 :type 'boolean
441 :group 'verilog-mode-indent)
442 ;; Note we don't use :safe, as that would break on Emacsen before 22.0.
443 (put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
444
445 (defcustom verilog-auto-lineup 'declarations
446 "*Type of statements to lineup across multiple lines.
447 If 'all' is selected, then all line ups described below are done.
448
449 If 'declaration', then just declarations are lined up with any
450 preceding declarations, taking into account widths and the like,
451 so or example the code:
452 reg [31:0] a;
453 reg b;
454 would become
455 reg [31:0] a;
456 reg b;
457
458 If 'assignment', then assignments are lined up with any preceding
459 assignments, so for example the code
460 a_long_variable <= b + c;
461 d = e + f;
462 would become
463 a_long_variable <= b + c;
464 d = e + f;
465
466 In order to speed up editing, large blocks of statements are lined up
467 only when a \\[verilog-pretty-expr] is typed; and large blocks of declarations
468 are lineup only when \\[verilog-pretty-declarations] is typed."
469
470 :type '(radio (const :tag "Line up Assignments and Declarations" all)
471 (const :tag "Line up Assignment statements" assignments )
472 (const :tag "Line up Declarations" declarations)
473 (function :tag "Other"))
474 :group 'verilog-mode-indent )
475
476 (defcustom verilog-indent-level 3
477 "*Indentation of Verilog statements with respect to containing block."
478 :group 'verilog-mode-indent
479 :type 'integer)
480 (put 'verilog-indent-level 'safe-local-variable 'integerp)
481
482 (defcustom verilog-indent-level-module 3
483 "*Indentation of Module level Verilog statements (eg always, initial).
484 Set to 0 to get initial and always statements lined up on the left side of
485 your screen."
486 :group 'verilog-mode-indent
487 :type 'integer)
488 (put 'verilog-indent-level-module 'safe-local-variable 'integerp)
489
490 (defcustom verilog-indent-level-declaration 3
491 "*Indentation of declarations with respect to containing block.
492 Set to 0 to get them list right under containing block."
493 :group 'verilog-mode-indent
494 :type 'integer)
495 (put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
496
497 (defcustom verilog-indent-declaration-macros nil
498 "*How to treat macro expansions in a declaration.
499 If nil, indent as:
500 input [31:0] a;
501 input `CP;
502 output c;
503 If non nil, treat as:
504 input [31:0] a;
505 input `CP ;
506 output c;"
507 :group 'verilog-mode-indent
508 :type 'boolean)
509 (put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
510
511 (defcustom verilog-indent-lists t
512 "*How to treat indenting items in a list.
513 If t (the default), indent as:
514 always @( posedge a or
515 reset ) begin
516
517 If nil, treat as:
518 always @( posedge a or
519 reset ) begin"
520 :group 'verilog-mode-indent
521 :type 'boolean)
522 (put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
523
524 (defcustom verilog-indent-level-behavioral 3
525 "*Absolute indentation of first begin in a task or function block.
526 Set to 0 to get such code to start at the left side of the screen."
527 :group 'verilog-mode-indent
528 :type 'integer)
529 (put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
530
531 (defcustom verilog-indent-level-directive 1
532 "*Indentation to add to each level of `ifdef declarations.
533 Set to 0 to have all directives start at the left side of the screen."
534 :group 'verilog-mode-indent
535 :type 'integer)
536 (put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
537
538 (defcustom verilog-cexp-indent 2
539 "*Indentation of Verilog statements split across lines."
540 :group 'verilog-mode-indent
541 :type 'integer)
542 (put 'verilog-cexp-indent 'safe-local-variable 'integerp)
543
544 (defcustom verilog-case-indent 2
545 "*Indentation for case statements."
546 :group 'verilog-mode-indent
547 :type 'integer)
548 (put 'verilog-case-indent 'safe-local-variable 'integerp)
549
550 (defcustom verilog-auto-newline t
551 "*True means automatically newline after semicolons."
552 :group 'verilog-mode-indent
553 :type 'boolean)
554 (put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
555
556 (defcustom verilog-auto-indent-on-newline t
557 "*True means automatically indent line after newline."
558 :group 'verilog-mode-indent
559 :type 'boolean)
560 (put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
561
562 (defcustom verilog-tab-always-indent t
563 "*True means TAB should always re-indent the current line.
564 A nil value means TAB will only reindent when at the beginning of the line."
565 :group 'verilog-mode-indent
566 :type 'boolean)
567 (put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
568
569 (defcustom verilog-tab-to-comment nil
570 "*True means TAB moves to the right hand column in preparation for a comment."
571 :group 'verilog-mode-actions
572 :type 'boolean)
573 (put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
574
575 (defcustom verilog-indent-begin-after-if t
576 "*If true, indent begin statements following if, else, while, for and repeat.
577 Otherwise, line them up."
578 :group 'verilog-mode-indent
579 :type 'boolean)
580 (put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
581
582
583 (defcustom verilog-align-ifelse nil
584 "*If true, align `else' under matching `if'.
585 Otherwise else is lined up with first character on line holding matching if."
586 :group 'verilog-mode-indent
587 :type 'boolean)
588 (put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
589
590 (defcustom verilog-minimum-comment-distance 10
591 "*Minimum distance (in lines) between begin and end required before a comment.
592 Setting this variable to zero results in every end acquiring a comment; the
593 default avoids too many redundant comments in tight quarters."
594 :group 'verilog-mode-indent
595 :type 'integer)
596 (put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
597
598 (defcustom verilog-highlight-p1800-keywords nil
599 "*True means highlight words newly reserved by IEEE-1800.
600 These will appear in `verilog-font-lock-p1800-face' in order to gently
601 suggest changing where these words are used as variables to something else.
602 A nil value means highlight these words as appropriate for the SystemVerilog
603 IEEE-1800 standard. Note that changing this will require restarting Emacs
604 to see the effect as font color choices are cached by Emacs."
605 :group 'verilog-mode-indent
606 :type 'boolean)
607 (put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
608
609 (defcustom verilog-highlight-grouping-keywords nil
610 "*True means highlight grouping keywords 'begin' and 'end' more dramatically.
611 If false, these words are in the `font-lock-type-face'; if True then they are in
612 `verilog-font-lock-ams-face'. Some find that special highlighting on these
613 grouping constructs allow the structure of the code to be understood at a glance."
614 :group 'verilog-mode-indent
615 :type 'boolean)
616 (put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
617
618 (defcustom verilog-highlight-modules nil
619 "*True means highlight module statements for `verilog-load-file-at-point'.
620 When true, mousing over module names will allow jumping to the
621 module definition. If false, this is not supported. Setting
622 this is experimental, and may lead to bad performance."
623 :group 'verilog-mode-indent
624 :type 'boolean)
625 (put 'verilog-highlight-modules 'safe-local-variable 'verilog-booleanp)
626
627 (defcustom verilog-highlight-includes t
628 "*True means highlight module statements for `verilog-load-file-at-point'.
629 When true, mousing over include file names will allow jumping to the
630 file referenced. If false, this is not supported."
631 :group 'verilog-mode-indent
632 :type 'boolean)
633 (put 'verilog-highlight-includes 'safe-local-variable 'verilog-booleanp)
634
635 (defcustom verilog-auto-endcomments t
636 "*True means insert a comment /* ... */ after 'end's.
637 The name of the function or case will be set between the braces."
638 :group 'verilog-mode-actions
639 :type 'boolean)
640 (put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
641
642 (defcustom verilog-auto-ignore-concat nil
643 "*True means ignore signals in {...} concatenations for AUTOWIRE etc.
644 This will exclude signals referenced as pin connections in {...}
645 from AUTOWIRE, AUTOOUTPUT and friends. This flag should be set
646 for backward compatibility only and not set in new designs; it
647 may be removed in future versions."
648 :group 'verilog-mode-actions
649 :type 'boolean)
650 (put 'verilog-auto-ignore-concat 'safe-local-variable 'verilog-booleanp)
651
652 (defcustom verilog-auto-read-includes nil
653 "*True means to automatically read includes before AUTOs.
654 This will do a `verilog-read-defines' and `verilog-read-includes' before
655 each AUTO expansion. This makes it easier to embed defines and includes,
656 but can result in very slow reading times if there are many or large
657 include files."
658 :group 'verilog-mode-actions
659 :type 'boolean)
660 (put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
661
662 (defcustom verilog-auto-save-policy nil
663 "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
664 A value of `force' will always do a \\[verilog-auto] automatically if
665 needed on every save. A value of `detect' will do \\[verilog-auto]
666 automatically when it thinks necessary. A value of `ask' will query the
667 user when it thinks updating is needed.
668
669 You should not rely on the 'ask or 'detect policies, they are safeguards
670 only. They do not detect when AUTOINSTs need to be updated because a
671 sub-module's port list has changed."
672 :group 'verilog-mode-actions
673 :type '(choice (const nil) (const ask) (const detect) (const force)))
674
675 (defcustom verilog-auto-star-expand t
676 "*Non-nil indicates to expand a SystemVerilog .* instance ports.
677 They will be expanded in the same way as if there was a AUTOINST in the
678 instantiation. See also `verilog-auto-star' and `verilog-auto-star-save'."
679 :group 'verilog-mode-actions
680 :type 'boolean)
681 (put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
682
683 (defcustom verilog-auto-star-save nil
684 "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
685 A nil value indicates direct connections will be removed before saving.
686 Only meaningful to those created due to `verilog-auto-star-expand' being set.
687
688 Instead of setting this, you may want to use /*AUTOINST*/, which will
689 always be saved."
690 :group 'verilog-mode-actions
691 :type 'boolean)
692 (put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
693
694 (defvar verilog-auto-update-tick nil
695 "Modification tick at which autos were last performed.")
696
697 (defvar verilog-auto-last-file-locals nil
698 "Text from file-local-variables during last evaluation.")
699
700 ;;; Compile support
701 (require 'compile)
702 (defvar verilog-error-regexp-added nil)
703
704 (defvar verilog-error-regexp-emacs-alist
705 '(
706 (verilog-xl-1
707 "\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
708 (verilog-xl-2
709 "([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 3)
710 (verilog-IES
711 ".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)" 2 3)
712 (verilog-surefire-1
713 "[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
714 (verilog-surefire-2
715 "\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\),\\s-+\\(line \\)?\\([0-9]+\\):" 2 4 )
716 (verilog-verbose
717 "\
718 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
719 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
720 (verilog-xsim
721 "\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
722 (verilog-vcs-1
723 "\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
724 (verilog-vcs-2
725 "Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
726 (verilog-vcs-3
727 "\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
728 (verilog-vcs-4
729 "syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
730 (verilog-verilator
731 "%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
732 (verilog-leda
733 "^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 2)
734 )
735 "List of regexps for Verilog compilers.
736 See `compilation-error-regexp-alist' for the formatting. For Emacs 22+.")
737
738 (defvar verilog-error-regexp-xemacs-alist
739 ;; Emacs form is '((v-tool "re" 1 2) ...)
740 ;; XEmacs form is '(verilog ("re" 1 2) ...)
741 ;; So we can just map from Emacs to Xemacs
742 (cons 'verilog (mapcar 'cdr verilog-error-regexp-emacs-alist))
743 "List of regexps for Verilog compilers.
744 See `compilation-error-regexp-alist-alist' for the formatting. For XEmacs.")
745
746 (defvar verilog-error-font-lock-keywords
747 '(
748 ;; verilog-xl-1
749 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
750 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
751 ;; verilog-xl-2
752 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 bold t)
753 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 3 bold t)
754 ;; verilog-IES (nc-verilog)
755 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
756 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 3 bold t)
757 ;; verilog-surefire-1
758 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
759 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
760 ;; verilog-surefire-2
761 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
762 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
763 ;; verilog-verbose
764 ("\
765 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
766 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
767 ("\
768 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
769 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
770 ;; verilog-vcs-1
771 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
772 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
773 ;; verilog-vcs-2
774 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
775 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
776 ;; verilog-vcs-3
777 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
778 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
779 ;; verilog-vcs-4
780 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
781 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
782 ;; verilog-verilator
783 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
784 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
785 ;; verilog-leda
786 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 bold t)
787 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 2 bold t)
788 )
789 "*Keywords to also highlight in Verilog *compilation* buffers.
790 Only used in XEmacs; GNU Emacs uses `verilog-error-regexp-emacs-alist'.")
791
792 (defcustom verilog-library-flags '("")
793 "*List of standard Verilog arguments to use for /*AUTOINST*/.
794 These arguments are used to find files for `verilog-auto', and match
795 the flags accepted by a standard Verilog-XL simulator.
796
797 -f filename Reads more `verilog-library-flags' from the filename.
798 +incdir+dir Adds the directory to `verilog-library-directories'.
799 -Idir Adds the directory to `verilog-library-directories'.
800 -y dir Adds the directory to `verilog-library-directories'.
801 +libext+.v Adds the extensions to `verilog-library-extensions'.
802 -v filename Adds the filename to `verilog-library-files'.
803
804 filename Adds the filename to `verilog-library-files'.
805 This is not recommended, -v is a better choice.
806
807 You might want these defined in each file; put at the *END* of your file
808 something like:
809
810 // Local Variables:
811 // verilog-library-flags:(\"-y dir -y otherdir\")
812 // End:
813
814 Verilog-mode attempts to detect changes to this local variable, but they
815 are only insured to be correct when the file is first visited. Thus if you
816 have problems, use \\[find-alternate-file] RET to have these take effect.
817
818 See also the variables mentioned above."
819 :group 'verilog-mode-auto
820 :type '(repeat string))
821 (put 'verilog-library-flags 'safe-local-variable 'listp)
822
823 (defcustom verilog-library-directories '(".")
824 "*List of directories when looking for files for /*AUTOINST*/.
825 The directory may be relative to the current file, or absolute.
826 Environment variables are also expanded in the directory names.
827 Having at least the current directory is a good idea.
828
829 You might want these defined in each file; put at the *END* of your file
830 something like:
831
832 // Local Variables:
833 // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
834 // End:
835
836 Verilog-mode attempts to detect changes to this local variable, but they
837 are only insured to be correct when the file is first visited. Thus if you
838 have problems, use \\[find-alternate-file] RET to have these take effect.
839
840 See also `verilog-library-flags', `verilog-library-files'
841 and `verilog-library-extensions'."
842 :group 'verilog-mode-auto
843 :type '(repeat file))
844 (put 'verilog-library-directories 'safe-local-variable 'listp)
845
846 (defcustom verilog-library-files '()
847 "*List of files to search for modules.
848 AUTOINST will use this when it needs to resolve a module name.
849 This is a complete path, usually to a technology file with many standard
850 cells defined in it.
851
852 You might want these defined in each file; put at the *END* of your file
853 something like:
854
855 // Local Variables:
856 // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
857 // End:
858
859 Verilog-mode attempts to detect changes to this local variable, but they
860 are only insured to be correct when the file is first visited. Thus if you
861 have problems, use \\[find-alternate-file] RET to have these take effect.
862
863 See also `verilog-library-flags', `verilog-library-directories'."
864 :group 'verilog-mode-auto
865 :type '(repeat directory))
866 (put 'verilog-library-files 'safe-local-variable 'listp)
867
868 (defcustom verilog-library-extensions '(".v" ".sv")
869 "*List of extensions to use when looking for files for /*AUTOINST*/.
870 See also `verilog-library-flags', `verilog-library-directories'."
871 :type '(repeat string)
872 :group 'verilog-mode-auto)
873 (put 'verilog-library-extensions 'safe-local-variable 'listp)
874
875 (defcustom verilog-active-low-regexp nil
876 "*If set, treat signals matching this regexp as active low.
877 This is used for AUTORESET and AUTOTIEOFF. For proper behavior,
878 you will probably also need `verilog-auto-reset-widths' set."
879 :group 'verilog-mode-auto
880 :type 'string)
881 (put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
882
883 (defcustom verilog-auto-sense-include-inputs nil
884 "*If true, AUTOSENSE should include all inputs.
885 If nil, only inputs that are NOT output signals in the same block are
886 included."
887 :group 'verilog-mode-auto
888 :type 'boolean)
889 (put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
890
891 (defcustom verilog-auto-sense-defines-constant nil
892 "*If true, AUTOSENSE should assume all defines represent constants.
893 When true, the defines will not be included in sensitivity lists. To
894 maintain compatibility with other sites, this should be set at the bottom
895 of each Verilog file that requires it, rather than being set globally."
896 :group 'verilog-mode-auto
897 :type 'boolean)
898 (put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
899
900 (defcustom verilog-auto-reset-widths t
901 "*If true, AUTORESET should determine the width of signals.
902 This is then used to set the width of the zero (32'h0 for example). This
903 is required by some lint tools that aren't smart enough to ignore widths of
904 the constant zero. This may result in ugly code when parameters determine
905 the MSB or LSB of a signal inside an AUTORESET."
906 :type 'boolean
907 :group 'verilog-mode-auto)
908 (put 'verilog-auto-reset-widths 'safe-local-variable 'verilog-booleanp)
909
910 (defcustom verilog-assignment-delay ""
911 "*Text used for delays in delayed assignments. Add a trailing space if set."
912 :group 'verilog-mode-auto
913 :type 'string)
914 (put 'verilog-assignment-delay 'safe-local-variable 'stringp)
915
916 (defcustom verilog-auto-arg-sort nil
917 "*If set, AUTOARG signal names will be sorted, not in delaration order.
918 Declaration order is advantageous with order based instantiations
919 and is the default for backward compatibility. Sorted order
920 reduces changes when declarations are moved around in a file, and
921 it's bad practice to rely on order based instantiations anyhow."
922 :group 'verilog-mode-auto
923 :type 'boolean)
924 (put 'verilog-auto-arg-sort 'safe-local-variable 'verilog-booleanp)
925
926 (defcustom verilog-auto-inst-dot-name nil
927 "*If true, when creating ports with AUTOINST, use .name syntax.
928 This will use \".port\" instead of \".port(port)\" when possible.
929 This is only legal in SystemVerilog files, and will confuse older
930 simulators. Setting `verilog-auto-inst-vector' to nil may also
931 be desirable to increase how often .name will be used."
932 :group 'verilog-mode-auto
933 :type 'boolean)
934 (put 'verilog-auto-inst-dot-name 'safe-local-variable 'verilog-booleanp)
935
936 (defcustom verilog-auto-inst-param-value nil
937 "*If set, AUTOINST will replace parameters with the parameter value.
938 If nil, leave parameters as symbolic names.
939
940 Parameters must be in Verilog 2001 format #(...), and if a parameter is not
941 listed as such there (as when the default value is acceptable), it will not
942 be replaced, and will remain symbolic.
943
944 For example, imagine a submodule uses parameters to declare the size of its
945 inputs. This is then used by a upper module:
946
947 module InstModule (o,i);
948 parameter WIDTH;
949 input [WIDTH-1:0] i;
950 endmodule
951
952 module ExampInst;
953 InstModule
954 #(PARAM(10))
955 instName
956 (/*AUTOINST*/
957 .i (i[PARAM-1:0]));
958
959 Note even though PARAM=10, the AUTOINST has left the parameter as a
960 symbolic name. If `verilog-auto-inst-param-value' is set, this will
961 instead expand to:
962
963 module ExampInst;
964 InstModule
965 #(PARAM(10))
966 instName
967 (/*AUTOINST*/
968 .i (i[9:0]));"
969 :group 'verilog-mode-auto
970 :type 'boolean)
971 (put 'verilog-auto-inst-param-value 'safe-local-variable 'verilog-booleanp)
972
973 (defcustom verilog-auto-inst-vector t
974 "*If true, when creating default ports with AUTOINST, use bus subscripts.
975 If nil, skip the subscript when it matches the entire bus as declared in
976 the module (AUTOWIRE signals always are subscripted, you must manually
977 declare the wire to have the subscripts removed.) Setting this to nil may
978 speed up some simulators, but is less general and harder to read, so avoid."
979 :group 'verilog-mode-auto
980 :type 'boolean)
981 (put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
982
983 (defcustom verilog-auto-inst-template-numbers nil
984 "*If true, when creating templated ports with AUTOINST, add a comment.
985 The comment will add the line number of the template that was used for that
986 port declaration. Setting this aids in debugging, but nil is suggested for
987 regular use to prevent large numbers of merge conflicts."
988 :group 'verilog-mode-auto
989 :type 'boolean)
990 (put 'verilog-auto-inst-template-numbers 'safe-local-variable 'verilog-booleanp)
991
992 (defcustom verilog-auto-inst-column 40
993 "*Indent-to column number for net name part of AUTOINST created pin."
994 :group 'verilog-mode-indent
995 :type 'integer)
996 (put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
997
998 (defcustom verilog-auto-input-ignore-regexp nil
999 "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
1000 See the \\[verilog-faq] for examples on using this."
1001 :group 'verilog-mode-auto
1002 :type 'string)
1003 (put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
1004
1005 (defcustom verilog-auto-inout-ignore-regexp nil
1006 "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
1007 See the \\[verilog-faq] for examples on using this."
1008 :group 'verilog-mode-auto
1009 :type 'string)
1010 (put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
1011
1012 (defcustom verilog-auto-output-ignore-regexp nil
1013 "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
1014 See the \\[verilog-faq] for examples on using this."
1015 :group 'verilog-mode-auto
1016 :type 'string)
1017 (put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
1018
1019 (defcustom verilog-auto-tieoff-ignore-regexp nil
1020 "*If set, when creating AUTOTIEOFF list, ignore signals matching this regexp.
1021 See the \\[verilog-faq] for examples on using this."
1022 :group 'verilog-mode-auto
1023 :type 'string)
1024 (put 'verilog-auto-tieoff-ignore-regexp 'safe-local-variable 'stringp)
1025
1026 (defcustom verilog-auto-unused-ignore-regexp nil
1027 "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
1028 See the \\[verilog-faq] for examples on using this."
1029 :group 'verilog-mode-auto
1030 :type 'string)
1031 (put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
1032
1033 (defcustom verilog-typedef-regexp nil
1034 "*If non-nil, regular expression that matches Verilog-2001 typedef names.
1035 For example, \"_t$\" matches typedefs named with _t, as in the C language."
1036 :group 'verilog-mode-auto
1037 :type 'string)
1038 (put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
1039
1040 (defcustom verilog-mode-hook 'verilog-set-compile-command
1041 "*Hook run after Verilog mode is loaded."
1042 :type 'hook
1043 :group 'verilog-mode)
1044
1045 (defcustom verilog-auto-hook nil
1046 "*Hook run after `verilog-mode' updates AUTOs."
1047 :group 'verilog-mode-auto
1048 :type 'hook)
1049
1050 (defcustom verilog-before-auto-hook nil
1051 "*Hook run before `verilog-mode' updates AUTOs."
1052 :group 'verilog-mode-auto
1053 :type 'hook)
1054
1055 (defcustom verilog-delete-auto-hook nil
1056 "*Hook run after `verilog-mode' deletes AUTOs."
1057 :group 'verilog-mode-auto
1058 :type 'hook)
1059
1060 (defcustom verilog-before-delete-auto-hook nil
1061 "*Hook run before `verilog-mode' deletes AUTOs."
1062 :group 'verilog-mode-auto
1063 :type 'hook)
1064
1065 (defcustom verilog-getopt-flags-hook nil
1066 "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
1067 :group 'verilog-mode-auto
1068 :type 'hook)
1069
1070 (defcustom verilog-before-getopt-flags-hook nil
1071 "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
1072 :group 'verilog-mode-auto
1073 :type 'hook)
1074
1075 (defvar verilog-imenu-generic-expression
1076 '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
1077 ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
1078 "Imenu expression for Verilog mode. See `imenu-generic-expression'.")
1079
1080 ;;
1081 ;; provide a verilog-header function.
1082 ;; Customization variables:
1083 ;;
1084 (defvar verilog-date-scientific-format nil
1085 "*If non-nil, dates are written in scientific format (e.g. 1997/09/17).
1086 If nil, in European format (e.g. 17.09.1997). The brain-dead American
1087 format (e.g. 09/17/1997) is not supported.")
1088
1089 (defvar verilog-company nil
1090 "*Default name of Company for Verilog header.
1091 If set will become buffer local.")
1092 (make-variable-buffer-local 'verilog-company)
1093
1094 (defvar verilog-project nil
1095 "*Default name of Project for Verilog header.
1096 If set will become buffer local.")
1097 (make-variable-buffer-local 'verilog-project)
1098
1099 (defvar verilog-mode-map
1100 (let ((map (make-sparse-keymap)))
1101 (define-key map ";" 'electric-verilog-semi)
1102 (define-key map [(control 59)] 'electric-verilog-semi-with-comment)
1103 (define-key map ":" 'electric-verilog-colon)
1104 ;;(define-key map "=" 'electric-verilog-equal)
1105 (define-key map "\`" 'electric-verilog-tick)
1106 (define-key map "\t" 'electric-verilog-tab)
1107 (define-key map "\r" 'electric-verilog-terminate-line)
1108 ;; backspace/delete key bindings
1109 (define-key map [backspace] 'backward-delete-char-untabify)
1110 (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
1111 (define-key map [delete] 'delete-char)
1112 (define-key map [(meta delete)] 'kill-word))
1113 (define-key map "\M-\C-b" 'electric-verilog-backward-sexp)
1114 (define-key map "\M-\C-f" 'electric-verilog-forward-sexp)
1115 (define-key map "\M-\r" `electric-verilog-terminate-and-indent)
1116 (define-key map "\M-\t" 'verilog-complete-word)
1117 (define-key map "\M-?" 'verilog-show-completions)
1118 (define-key map "\C-c\`" 'verilog-lint-off)
1119 (define-key map "\C-c\*" 'verilog-delete-auto-star-implicit)
1120 (define-key map "\C-c\C-r" 'verilog-label-be)
1121 (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
1122 (define-key map "\C-c=" 'verilog-pretty-expr)
1123 (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
1124 (define-key map "\M-*" 'verilog-star-comment)
1125 (define-key map "\C-c\C-c" 'verilog-comment-region)
1126 (define-key map "\C-c\C-u" 'verilog-uncomment-region)
1127 (when (featurep 'xemacs)
1128 (define-key map [(meta control h)] 'verilog-mark-defun)
1129 (define-key map "\M-\C-a" 'verilog-beg-of-defun)
1130 (define-key map "\M-\C-e" 'verilog-end-of-defun))
1131 (define-key map "\C-c\C-d" 'verilog-goto-defun)
1132 (define-key map "\C-c\C-k" 'verilog-delete-auto)
1133 (define-key map "\C-c\C-a" 'verilog-auto)
1134 (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
1135 (define-key map "\C-c\C-p" 'verilog-preprocess)
1136 (define-key map "\C-c\C-z" 'verilog-inject-auto)
1137 (define-key map "\C-c\C-e" 'verilog-expand-vector)
1138 (define-key map "\C-c\C-h" 'verilog-header)
1139 map)
1140 "Keymap used in Verilog mode.")
1141
1142 ;; menus
1143 (easy-menu-define
1144 verilog-menu verilog-mode-map "Menu for Verilog mode"
1145 (verilog-easy-menu-filter
1146 '("Verilog"
1147 ("Choose Compilation Action"
1148 ["None"
1149 (progn
1150 (setq verilog-tool nil)
1151 (verilog-set-compile-command))
1152 :style radio
1153 :selected (equal verilog-tool nil)
1154 :help "When invoking compilation, use compile-command"]
1155 ["Lint"
1156 (progn
1157 (setq verilog-tool 'verilog-linter)
1158 (verilog-set-compile-command))
1159 :style radio
1160 :selected (equal verilog-tool `verilog-linter)
1161 :help "When invoking compilation, use lint checker"]
1162 ["Coverage"
1163 (progn
1164 (setq verilog-tool 'verilog-coverage)
1165 (verilog-set-compile-command))
1166 :style radio
1167 :selected (equal verilog-tool `verilog-coverage)
1168 :help "When invoking compilation, annotate for coverage"]
1169 ["Simulator"
1170 (progn
1171 (setq verilog-tool 'verilog-simulator)
1172 (verilog-set-compile-command))
1173 :style radio
1174 :selected (equal verilog-tool `verilog-simulator)
1175 :help "When invoking compilation, interpret Verilog source"]
1176 ["Compiler"
1177 (progn
1178 (setq verilog-tool 'verilog-compiler)
1179 (verilog-set-compile-command))
1180 :style radio
1181 :selected (equal verilog-tool `verilog-compiler)
1182 :help "When invoking compilation, compile Verilog source"]
1183 ["Preprocessor"
1184 (progn
1185 (setq verilog-tool 'verilog-preprocessor)
1186 (verilog-set-compile-command))
1187 :style radio
1188 :selected (equal verilog-tool `verilog-preprocessor)
1189 :help "When invoking compilation, preprocess Verilog source, see also `verilog-preprocess'"]
1190 )
1191 ("Move"
1192 ["Beginning of function" verilog-beg-of-defun
1193 :keys "C-M-a"
1194 :help "Move backward to the beginning of the current function or procedure"]
1195 ["End of function" verilog-end-of-defun
1196 :keys "C-M-e"
1197 :help "Move forward to the end of the current function or procedure"]
1198 ["Mark function" verilog-mark-defun
1199 :keys "C-M-h"
1200 :help "Mark the current Verilog function or procedure"]
1201 ["Goto function/module" verilog-goto-defun
1202 :help "Move to specified Verilog module/task/function"]
1203 ["Move to beginning of block" electric-verilog-backward-sexp
1204 :help "Move backward over one balanced expression"]
1205 ["Move to end of block" electric-verilog-forward-sexp
1206 :help "Move forward over one balanced expression"]
1207 )
1208 ("Comments"
1209 ["Comment Region" verilog-comment-region
1210 :help "Put marked area into a comment"]
1211 ["UnComment Region" verilog-uncomment-region
1212 :help "Uncomment an area commented with Comment Region"]
1213 ["Multi-line comment insert" verilog-star-comment
1214 :help "Insert Verilog /* */ comment at point"]
1215 ["Lint error to comment" verilog-lint-off
1216 :help "Convert a Verilog linter warning line into a disable statement"]
1217 )
1218 "----"
1219 ["Compile" compile
1220 :help "Perform compilation-action (above) on the current buffer"]
1221 ["AUTO, Save, Compile" verilog-auto-save-compile
1222 :help "Recompute AUTOs, save buffer, and compile"]
1223 ["Next Compile Error" next-error
1224 :help "Visit next compilation error message and corresponding source code"]
1225 ["Ignore Lint Warning at point" verilog-lint-off
1226 :help "Convert a Verilog linter warning line into a disable statement"]
1227 "----"
1228 ["Line up declarations around point" verilog-pretty-declarations
1229 :help "Line up declarations around point"]
1230 ["Line up equations around point" verilog-pretty-expr
1231 :help "Line up expressions around point"]
1232 ["Redo/insert comments on every end" verilog-label-be
1233 :help "Label matching begin ... end statements"]
1234 ["Expand [x:y] vector line" verilog-expand-vector
1235 :help "Take a signal vector on the current line and expand it to multiple lines"]
1236 ["Insert begin-end block" verilog-insert-block
1237 :help "Insert begin ... end"]
1238 ["Complete word" verilog-complete-word
1239 :help "Complete word at point"]
1240 "----"
1241 ["Recompute AUTOs" verilog-auto
1242 :help "Expand AUTO meta-comment statements"]
1243 ["Kill AUTOs" verilog-delete-auto
1244 :help "Remove AUTO expansions"]
1245 ["Inject AUTOs" verilog-inject-auto
1246 :help "Inject AUTOs into legacy non-AUTO buffer"]
1247 ("AUTO Help..."
1248 ["AUTO General" (describe-function 'verilog-auto)
1249 :help "Help introduction on AUTOs"]
1250 ["AUTO Library Flags" (describe-variable 'verilog-library-flags)
1251 :help "Help on verilog-library-flags"]
1252 ["AUTO Library Path" (describe-variable 'verilog-library-directories)
1253 :help "Help on verilog-library-directories"]
1254 ["AUTO Library Files" (describe-variable 'verilog-library-files)
1255 :help "Help on verilog-library-files"]
1256 ["AUTO Library Extensions" (describe-variable 'verilog-library-extensions)
1257 :help "Help on verilog-library-extensions"]
1258 ["AUTO `define Reading" (describe-function 'verilog-read-defines)
1259 :help "Help on reading `defines"]
1260 ["AUTO `include Reading" (describe-function 'verilog-read-includes)
1261 :help "Help on parsing `includes"]
1262 ["AUTOARG" (describe-function 'verilog-auto-arg)
1263 :help "Help on AUTOARG - declaring module port list"]
1264 ["AUTOASCIIENUM" (describe-function 'verilog-auto-ascii-enum)
1265 :help "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
1266 ["AUTOINOUTCOMP" (describe-function 'verilog-auto-inout-comp)
1267 :help "Help on AUTOINOUTCOMP - copying complemented i/o from another file"]
1268 ["AUTOINOUTMODULE" (describe-function 'verilog-auto-inout-module)
1269 :help "Help on AUTOINOUTMODULE - copying i/o from another file"]
1270 ["AUTOINSERTLISP" (describe-function 'verilog-auto-insert-lisp)
1271 :help "Help on AUTOINSERTLISP - insert text from a lisp function"]
1272 ["AUTOINOUT" (describe-function 'verilog-auto-inout)
1273 :help "Help on AUTOINOUT - adding inouts from cells"]
1274 ["AUTOINPUT" (describe-function 'verilog-auto-input)
1275 :help "Help on AUTOINPUT - adding inputs from cells"]
1276 ["AUTOINST" (describe-function 'verilog-auto-inst)
1277 :help "Help on AUTOINST - adding pins for cells"]
1278 ["AUTOINST (.*)" (describe-function 'verilog-auto-star)
1279 :help "Help on expanding Verilog-2001 .* pins"]
1280 ["AUTOINSTPARAM" (describe-function 'verilog-auto-inst-param)
1281 :help "Help on AUTOINSTPARAM - adding parameter pins to cells"]
1282 ["AUTOOUTPUT" (describe-function 'verilog-auto-output)
1283 :help "Help on AUTOOUTPUT - adding outputs from cells"]
1284 ["AUTOOUTPUTEVERY" (describe-function 'verilog-auto-output-every)
1285 :help "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
1286 ["AUTOREG" (describe-function 'verilog-auto-reg)
1287 :help "Help on AUTOREG - declaring registers for non-wires"]
1288 ["AUTOREGINPUT" (describe-function 'verilog-auto-reg-input)
1289 :help "Help on AUTOREGINPUT - declaring inputs for non-wires"]
1290 ["AUTORESET" (describe-function 'verilog-auto-reset)
1291 :help "Help on AUTORESET - resetting always blocks"]
1292 ["AUTOSENSE" (describe-function 'verilog-auto-sense)
1293 :help "Help on AUTOSENSE - sensitivity lists for always blocks"]
1294 ["AUTOTIEOFF" (describe-function 'verilog-auto-tieoff)
1295 :help "Help on AUTOTIEOFF - tieing off unused outputs"]
1296 ["AUTOUNUSED" (describe-function 'verilog-auto-unused)
1297 :help "Help on AUTOUNUSED - terminating unused inputs"]
1298 ["AUTOWIRE" (describe-function 'verilog-auto-wire)
1299 :help "Help on AUTOWIRE - declaring wires for cells"]
1300 )
1301 "----"
1302 ["Submit bug report" verilog-submit-bug-report
1303 :help "Submit via mail a bug report on verilog-mode.el"]
1304 ["Version and FAQ" verilog-faq
1305 :help "Show the current version, and where to get the FAQ etc"]
1306 ["Customize Verilog Mode..." verilog-customize
1307 :help "Customize variables and other settings used by Verilog-Mode"]
1308 ["Customize Verilog Fonts & Colors" verilog-font-customize
1309 :help "Customize fonts used by Verilog-Mode."])))
1310
1311 (easy-menu-define
1312 verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
1313 (verilog-easy-menu-filter
1314 '("Statements"
1315 ["Header" verilog-sk-header
1316 :help "Insert a header block at the top of file"]
1317 ["Comment" verilog-sk-comment
1318 :help "Insert a comment block"]
1319 "----"
1320 ["Module" verilog-sk-module
1321 :help "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
1322 ["Primitive" verilog-sk-primitive
1323 :help "Insert a primitive .. (.. );.. endprimitive block"]
1324 "----"
1325 ["Input" verilog-sk-input
1326 :help "Insert an input declaration"]
1327 ["Output" verilog-sk-output
1328 :help "Insert an output declaration"]
1329 ["Inout" verilog-sk-inout
1330 :help "Insert an inout declaration"]
1331 ["Wire" verilog-sk-wire
1332 :help "Insert a wire declaration"]
1333 ["Reg" verilog-sk-reg
1334 :help "Insert a register declaration"]
1335 ["Define thing under point as a register" verilog-sk-define-signal
1336 :help "Define signal under point as a register at the top of the module"]
1337 "----"
1338 ["Initial" verilog-sk-initial
1339 :help "Insert an initial begin .. end block"]
1340 ["Always" verilog-sk-always
1341 :help "Insert an always @(AS) begin .. end block"]
1342 ["Function" verilog-sk-function
1343 :help "Insert a function .. begin .. end endfunction block"]
1344 ["Task" verilog-sk-task
1345 :help "Insert a task .. begin .. end endtask block"]
1346 ["Specify" verilog-sk-specify
1347 :help "Insert a specify .. endspecify block"]
1348 ["Generate" verilog-sk-generate
1349 :help "Insert a generate .. endgenerate block"]
1350 "----"
1351 ["Begin" verilog-sk-begin
1352 :help "Insert a begin .. end block"]
1353 ["If" verilog-sk-if
1354 :help "Insert an if (..) begin .. end block"]
1355 ["(if) else" verilog-sk-else-if
1356 :help "Insert an else if (..) begin .. end block"]
1357 ["For" verilog-sk-for
1358 :help "Insert a for (...) begin .. end block"]
1359 ["While" verilog-sk-while
1360 :help "Insert a while (...) begin .. end block"]
1361 ["Fork" verilog-sk-fork
1362 :help "Insert a fork begin .. end .. join block"]
1363 ["Repeat" verilog-sk-repeat
1364 :help "Insert a repeat (..) begin .. end block"]
1365 ["Case" verilog-sk-case
1366 :help "Insert a case block, prompting for details"]
1367 ["Casex" verilog-sk-casex
1368 :help "Insert a casex (...) item: begin.. end endcase block"]
1369 ["Casez" verilog-sk-casez
1370 :help "Insert a casez (...) item: begin.. end endcase block"])))
1371
1372 (defvar verilog-mode-abbrev-table nil
1373 "Abbrev table in use in Verilog-mode buffers.")
1374
1375 (define-abbrev-table 'verilog-mode-abbrev-table ())
1376
1377 ;;
1378 ;; Macros
1379 ;;
1380
1381 (defsubst verilog-within-string ()
1382 (nth 3 (parse-partial-sexp (point-at-bol) (point))))
1383
1384 (defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1385 "Replace occurrences of FROM-STRING with TO-STRING.
1386 FIXEDCASE and LITERAL as in `replace-match`. STRING is what to replace.
1387 The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1388 will break, as the o's continuously replace. xa -> x works ok though."
1389 ;; Hopefully soon to a emacs built-in
1390 (let ((start 0))
1391 (while (string-match from-string string start)
1392 (setq string (replace-match to-string fixedcase literal string)
1393 start (min (length string) (+ (match-beginning 0) (length to-string)))))
1394 string))
1395
1396 (defsubst verilog-string-remove-spaces (string)
1397 "Remove spaces surrounding STRING."
1398 (save-match-data
1399 (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1400 (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1401 string))
1402
1403 (defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1404 ; checkdoc-params: (REGEXP BOUND NOERROR)
1405 "Like `re-search-forward', but skips over match in comments or strings."
1406 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1407 (while (and
1408 (re-search-forward REGEXP BOUND NOERROR)
1409 (setq mdata (match-data))
1410 (and (verilog-skip-forward-comment-or-string)
1411 (progn
1412 (setq mdata '(nil nil))
1413 (if BOUND
1414 (< (point) BOUND)
1415 t)))))
1416 (store-match-data mdata)
1417 (match-end 0)))
1418
1419 (defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1420 ; checkdoc-params: (REGEXP BOUND NOERROR)
1421 "Like `re-search-backward', but skips over match in comments or strings."
1422 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1423 (while (and
1424 (re-search-backward REGEXP BOUND NOERROR)
1425 (setq mdata (match-data))
1426 (and (verilog-skip-backward-comment-or-string)
1427 (progn
1428 (setq mdata '(nil nil))
1429 (if BOUND
1430 (> (point) BOUND)
1431 t)))))
1432 (store-match-data mdata)
1433 (match-end 0)))
1434
1435 (defsubst verilog-re-search-forward-quick (regexp bound noerror)
1436 "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1437 but trashes match data and is faster for REGEXP that doesn't match often.
1438 This may at some point use text properties to ignore comments,
1439 so there may be a large up front penalty for the first search."
1440 (let (pt)
1441 (while (and (not pt)
1442 (re-search-forward regexp bound noerror))
1443 (if (not (verilog-inside-comment-p))
1444 (setq pt (match-end 0))))
1445 pt))
1446
1447 (defsubst verilog-re-search-backward-quick (regexp bound noerror)
1448 ; checkdoc-params: (REGEXP BOUND NOERROR)
1449 "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1450 but trashes match data and is faster for REGEXP that doesn't match often.
1451 This may at some point use text properties to ignore comments,
1452 so there may be a large up front penalty for the first search."
1453 (let (pt)
1454 (while (and (not pt)
1455 (re-search-backward regexp bound noerror))
1456 (if (not (verilog-inside-comment-p))
1457 (setq pt (match-end 0))))
1458 pt))
1459
1460 (defsubst verilog-re-search-forward-substr (substr regexp bound noerror)
1461 "Like `re-search-forward', but first search for SUBSTR constant.
1462 Then searched for the normal REGEXP (which contains SUBSTR), with given
1463 BOUND and NOERROR. The REGEXP must fit within a single line.
1464 This speeds up complicated regexp matches."
1465 ;; Problem with overlap: search-forward BAR then FOOBARBAZ won't match.
1466 ;; thus require matches to be on one line, and use beginning-of-line.
1467 (let (done)
1468 (while (and (not done)
1469 (search-forward substr bound noerror))
1470 (save-excursion
1471 (beginning-of-line)
1472 (setq done (re-search-forward regexp (point-at-eol) noerror)))
1473 (unless (and (<= (match-beginning 0) (point))
1474 (>= (match-end 0) (point)))
1475 (setq done nil)))
1476 (when done (goto-char done))
1477 done))
1478 ;;(verilog-re-search-forward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1479
1480 (defsubst verilog-re-search-backward-substr (substr regexp bound noerror)
1481 "Like `re-search-backward', but first search for SUBSTR constant.
1482 Then searched for the normal REGEXP (which contains SUBSTR), with given
1483 BOUND and NOERROR. The REGEXP must fit within a single line.
1484 This speeds up complicated regexp matches."
1485 ;; Problem with overlap: search-backward BAR then FOOBARBAZ won't match.
1486 ;; thus require matches to be on one line, and use beginning-of-line.
1487 (let (done)
1488 (while (and (not done)
1489 (search-backward substr bound noerror))
1490 (save-excursion
1491 (end-of-line)
1492 (setq done (re-search-backward regexp (point-at-bol) noerror)))
1493 (unless (and (<= (match-beginning 0) (point))
1494 (>= (match-end 0) (point)))
1495 (setq done nil)))
1496 (when done (goto-char done))
1497 done))
1498 ;;(verilog-re-search-backward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1499
1500 (defvar compile-command)
1501
1502 ;; compilation program
1503 (defun verilog-set-compile-command ()
1504 "Function to compute shell command to compile Verilog.
1505
1506 This reads `verilog-tool' and sets `compile-command'. This specifies the
1507 program that executes when you type \\[compile] or
1508 \\[verilog-auto-save-compile].
1509
1510 By default `verilog-tool' uses a Makefile if one exists in the
1511 current directory. If not, it is set to the `verilog-linter',
1512 `verilog-compiler', `verilog-coverage', `verilog-preprocessor',
1513 or `verilog-simulator' variables, as selected with the Verilog ->
1514 \"Choose Compilation Action\" menu.
1515
1516 You should set `verilog-tool' or the other variables to the path and
1517 arguments for your Verilog simulator. For example:
1518 \"vcs -p123 -O\"
1519 or a string like:
1520 \"(cd /tmp; surecov %s)\".
1521
1522 In the former case, the path to the current buffer is concat'ed to the
1523 value of `verilog-tool'; in the later, the path to the current buffer is
1524 substituted for the %s.
1525
1526 Where __FLAGS__ appears in the string `verilog-current-flags'
1527 will be substituted.
1528
1529 Where __FILE__ appears in the string, the variable
1530 `buffer-file-name' of the current buffer, without the directory
1531 portion, will be substituted."
1532 (interactive)
1533 (cond
1534 ((or (file-exists-p "makefile") ;If there is a makefile, use it
1535 (file-exists-p "Makefile"))
1536 (set (make-local-variable 'compile-command) "make "))
1537 (t
1538 (set (make-local-variable 'compile-command)
1539 (if verilog-tool
1540 (if (string-match "%s" (eval verilog-tool))
1541 (format (eval verilog-tool) (or buffer-file-name ""))
1542 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1543 ""))))
1544 (verilog-modify-compile-command))
1545
1546 (defun verilog-expand-command (command)
1547 "Replace meta-information in COMMAND and return it.
1548 Where __FLAGS__ appears in the string `verilog-current-flags'
1549 will be substituted. Where __FILE__ appears in the string, the
1550 current buffer's file-name, without the directory portion, will
1551 be substituted."
1552 (setq command (verilog-string-replace-matches
1553 ;; Note \\b only works if under verilog syntax table
1554 "\\b__FLAGS__\\b" (verilog-current-flags)
1555 t t command))
1556 (setq command (verilog-string-replace-matches
1557 "\\b__FILE__\\b" (file-name-nondirectory
1558 (or (buffer-file-name) ""))
1559 t t command))
1560 command)
1561
1562 (defun verilog-modify-compile-command ()
1563 "Update `compile-command' using `verilog-expand-command'."
1564 (when (and
1565 (stringp compile-command)
1566 (string-match "\\b\\(__FLAGS__\\|__FILE__\\)\\b" compile-command))
1567 (set (make-local-variable 'compile-command)
1568 (verilog-expand-command compile-command))))
1569
1570 (if (featurep 'xemacs)
1571 ;; Following code only gets called from compilation-mode-hook on XEmacs to add error handling.
1572 (defun verilog-error-regexp-add-xemacs ()
1573 "Teach XEmacs about verilog errors.
1574 Called by `compilation-mode-hook'. This allows \\[next-error] to
1575 find the errors."
1576 (interactive)
1577 (if (boundp 'compilation-error-regexp-systems-alist)
1578 (if (and
1579 (not (equal compilation-error-regexp-systems-list 'all))
1580 (not (member compilation-error-regexp-systems-list 'verilog)))
1581 (push 'verilog compilation-error-regexp-systems-list)))
1582 (if (boundp 'compilation-error-regexp-alist-alist)
1583 (if (not (assoc 'verilog compilation-error-regexp-alist-alist))
1584 (setcdr compilation-error-regexp-alist-alist
1585 (cons verilog-error-regexp-xemacs-alist
1586 (cdr compilation-error-regexp-alist-alist)))))
1587 (if (boundp 'compilation-font-lock-keywords)
1588 (progn
1589 (set (make-local-variable 'compilation-font-lock-keywords)
1590 verilog-error-font-lock-keywords)
1591 (font-lock-set-defaults)))
1592 ;; Need to re-run compilation-error-regexp builder
1593 (if (fboundp 'compilation-build-compilation-error-regexp-alist)
1594 (compilation-build-compilation-error-regexp-alist))
1595 ))
1596
1597 ;; Following code only gets called from compilation-mode-hook on Emacs to add error handling.
1598 (defun verilog-error-regexp-add-emacs ()
1599 "Tell Emacs compile that we are Verilog.
1600 Called by `compilation-mode-hook'. This allows \\[next-error] to
1601 find the errors."
1602 (interactive)
1603 (if (boundp 'compilation-error-regexp-alist-alist)
1604 (progn
1605 (if (not (assoc 'verilog-xl-1 compilation-error-regexp-alist-alist))
1606 (mapcar
1607 (lambda (item)
1608 (push (car item) compilation-error-regexp-alist)
1609 (push item compilation-error-regexp-alist-alist)
1610 )
1611 verilog-error-regexp-emacs-alist)))))
1612
1613 (if (featurep 'xemacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-xemacs))
1614 (if (featurep 'emacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-emacs))
1615
1616 (defconst verilog-directive-re
1617 (eval-when-compile
1618 (verilog-regexp-words
1619 '(
1620 "`case" "`default" "`define" "`else" "`elsif" "`endfor" "`endif"
1621 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1622 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1623 "`time_scale" "`undef" "`while" ))))
1624
1625 (defconst verilog-directive-re-1
1626 (concat "[ \t]*" verilog-directive-re))
1627
1628 (defconst verilog-directive-begin
1629 "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1630
1631 (defconst verilog-directive-middle
1632 "\\<`\\(else\\|elsif\\|default\\|case\\)\\>")
1633
1634 (defconst verilog-directive-end
1635 "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1636
1637 (defconst verilog-ovm-begin-re
1638 (eval-when-compile
1639 (verilog-regexp-opt
1640 '(
1641 "`ovm_component_utils_begin"
1642 "`ovm_component_param_utils_begin"
1643 "`ovm_field_utils_begin"
1644 "`ovm_object_utils_begin"
1645 "`ovm_object_param_utils_begin"
1646 "`ovm_sequence_utils_begin"
1647 "`ovm_sequencer_utils_begin"
1648 ) nil )))
1649
1650 (defconst verilog-ovm-end-re
1651 (eval-when-compile
1652 (verilog-regexp-opt
1653 '(
1654 "`ovm_component_utils_end"
1655 "`ovm_field_utils_end"
1656 "`ovm_object_utils_end"
1657 "`ovm_sequence_utils_end"
1658 "`ovm_sequencer_utils_end"
1659 ) nil )))
1660
1661 (defconst verilog-vmm-begin-re
1662 (eval-when-compile
1663 (verilog-regexp-opt
1664 '(
1665 "`vmm_data_member_begin"
1666 "`vmm_env_member_begin"
1667 "`vmm_scenario_member_begin"
1668 "`vmm_subenv_member_begin"
1669 "`vmm_xactor_member_begin"
1670 ) nil ) ) )
1671
1672 (defconst verilog-vmm-end-re
1673 (eval-when-compile
1674 (verilog-regexp-opt
1675 '(
1676 "`vmm_data_member_end"
1677 "`vmm_env_member_end"
1678 "`vmm_scenario_member_end"
1679 "`vmm_subenv_member_end"
1680 "`vmm_xactor_member_end"
1681 ) nil ) ) )
1682
1683 (defconst verilog-vmm-statement-re
1684 (eval-when-compile
1685 (verilog-regexp-opt
1686 '(
1687 ;; "`vmm_xactor_member_enum_array"
1688 "`vmm_\\(data\\|env\\|scenario\\|subenv\\|xactor\\)_member_\\(scalar\\|string\\|enum\\|vmm_data\\|channel\\|xactor\\|subenv\\|user_defined\\)\\(_array\\)?"
1689 ;; "`vmm_xactor_member_scalar_array"
1690 ;; "`vmm_xactor_member_scalar"
1691 ) nil )))
1692
1693 (defconst verilog-ovm-statement-re
1694 (eval-when-compile
1695 (verilog-regexp-opt
1696 '(
1697 ;; Statements
1698 "`DUT_ERROR"
1699 "`MESSAGE"
1700 "`dut_error"
1701 "`message"
1702 "`ovm_analysis_imp_decl"
1703 "`ovm_blocking_get_imp_decl"
1704 "`ovm_blocking_get_peek_imp_decl"
1705 "`ovm_blocking_master_imp_decl"
1706 "`ovm_blocking_peek_imp_decl"
1707 "`ovm_blocking_put_imp_decl"
1708 "`ovm_blocking_slave_imp_decl"
1709 "`ovm_blocking_transport_imp_decl"
1710 "`ovm_component_registry"
1711 "`ovm_component_registry_param"
1712 "`ovm_component_utils"
1713 "`ovm_create"
1714 "`ovm_create_seq"
1715 "`ovm_declare_sequence_lib"
1716 "`ovm_do"
1717 "`ovm_do_seq"
1718 "`ovm_do_seq_with"
1719 "`ovm_do_with"
1720 "`ovm_error"
1721 "`ovm_fatal"
1722 "`ovm_field_aa_int_byte"
1723 "`ovm_field_aa_int_byte_unsigned"
1724 "`ovm_field_aa_int_int"
1725 "`ovm_field_aa_int_int_unsigned"
1726 "`ovm_field_aa_int_integer"
1727 "`ovm_field_aa_int_integer_unsigned"
1728 "`ovm_field_aa_int_key"
1729 "`ovm_field_aa_int_longint"
1730 "`ovm_field_aa_int_longint_unsigned"
1731 "`ovm_field_aa_int_shortint"
1732 "`ovm_field_aa_int_shortint_unsigned"
1733 "`ovm_field_aa_int_string"
1734 "`ovm_field_aa_object_int"
1735 "`ovm_field_aa_object_string"
1736 "`ovm_field_aa_string_int"
1737 "`ovm_field_aa_string_string"
1738 "`ovm_field_array_int"
1739 "`ovm_field_array_object"
1740 "`ovm_field_array_string"
1741 "`ovm_field_enum"
1742 "`ovm_field_event"
1743 "`ovm_field_int"
1744 "`ovm_field_object"
1745 "`ovm_field_queue_int"
1746 "`ovm_field_queue_object"
1747 "`ovm_field_queue_string"
1748 "`ovm_field_sarray_int"
1749 "`ovm_field_string"
1750 "`ovm_field_utils"
1751 "`ovm_file"
1752 "`ovm_get_imp_decl"
1753 "`ovm_get_peek_imp_decl"
1754 "`ovm_info"
1755 "`ovm_info1"
1756 "`ovm_info2"
1757 "`ovm_info3"
1758 "`ovm_info4"
1759 "`ovm_line"
1760 "`ovm_master_imp_decl"
1761 "`ovm_msg_detail"
1762 "`ovm_non_blocking_transport_imp_decl"
1763 "`ovm_nonblocking_get_imp_decl"
1764 "`ovm_nonblocking_get_peek_imp_decl"
1765 "`ovm_nonblocking_master_imp_decl"
1766 "`ovm_nonblocking_peek_imp_decl"
1767 "`ovm_nonblocking_put_imp_decl"
1768 "`ovm_nonblocking_slave_imp_decl"
1769 "`ovm_object_registry"
1770 "`ovm_object_registry_param"
1771 "`ovm_object_utils"
1772 "`ovm_peek_imp_decl"
1773 "`ovm_phase_func_decl"
1774 "`ovm_phase_task_decl"
1775 "`ovm_print_aa_int_object"
1776 "`ovm_print_aa_string_int"
1777 "`ovm_print_aa_string_object"
1778 "`ovm_print_aa_string_string"
1779 "`ovm_print_array_int"
1780 "`ovm_print_array_object"
1781 "`ovm_print_array_string"
1782 "`ovm_print_object_queue"
1783 "`ovm_print_queue_int"
1784 "`ovm_print_string_queue"
1785 "`ovm_put_imp_decl"
1786 "`ovm_rand_send"
1787 "`ovm_rand_send_with"
1788 "`ovm_send"
1789 "`ovm_sequence_utils"
1790 "`ovm_slave_imp_decl"
1791 "`ovm_transport_imp_decl"
1792 "`ovm_update_sequence_lib"
1793 "`ovm_update_sequence_lib_and_item"
1794 "`ovm_warning"
1795 "`static_dut_error"
1796 "`static_message") nil )))
1797
1798
1799 ;;
1800 ;; Regular expressions used to calculate indent, etc.
1801 ;;
1802 (defconst verilog-symbol-re "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
1803 ;; Want to match
1804 ;; aa :
1805 ;; aa,bb :
1806 ;; a[34:32] :
1807 ;; a,
1808 ;; b :
1809
1810 (defconst verilog-label-re (concat verilog-symbol-re "\\s-*:\\s-*"))
1811 (defconst verilog-property-re
1812 (concat "\\(" verilog-label-re "\\)?"
1813 "\\(\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(assert\\)"))
1814 ;; "\\(assert\\|assume\\|cover\\)\\s-+property\\>"
1815
1816 (defconst verilog-no-indent-begin-re
1817 "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
1818
1819 (defconst verilog-ends-re
1820 ;; Parenthesis indicate type of keyword found
1821 (concat
1822 "\\(\\<else\\>\\)\\|" ; 1
1823 "\\(\\<if\\>\\)\\|" ; 2
1824 "\\(\\<assert\\>\\)\\|" ; 3
1825 "\\(\\<end\\>\\)\\|" ; 3.1
1826 "\\(\\<endcase\\>\\)\\|" ; 4
1827 "\\(\\<endfunction\\>\\)\\|" ; 5
1828 "\\(\\<endtask\\>\\)\\|" ; 6
1829 "\\(\\<endspecify\\>\\)\\|" ; 7
1830 "\\(\\<endtable\\>\\)\\|" ; 8
1831 "\\(\\<endgenerate\\>\\)\\|" ; 9
1832 "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
1833 "\\(\\<endclass\\>\\)\\|" ; 11
1834 "\\(\\<endgroup\\>\\)\\|" ; 12
1835 ;; VMM
1836 "\\(\\<`vmm_data_member_end\\>\\)\\|"
1837 "\\(\\<`vmm_env_member_end\\>\\)\\|"
1838 "\\(\\<`vmm_scenario_member_end\\>\\)\\|"
1839 "\\(\\<`vmm_subenv_member_end\\>\\)\\|"
1840 "\\(\\<`vmm_xactor_member_end\\>\\)\\|"
1841 ;; OVM
1842 "\\(\\<`ovm_component_utils_end\\>\\)\\|"
1843 "\\(\\<`ovm_field_utils_end\\>\\)\\|"
1844 "\\(\\<`ovm_object_utils_end\\>\\)\\|"
1845 "\\(\\<`ovm_sequence_utils_end\\>\\)\\|"
1846 "\\(\\<`ovm_sequencer_utils_end\\>\\)"
1847
1848 ))
1849
1850 (defconst verilog-auto-end-comment-lines-re
1851 ;; Matches to names in this list cause auto-end-commentation
1852 (concat "\\("
1853 verilog-directive-re "\\)\\|\\("
1854 (eval-when-compile
1855 (verilog-regexp-words
1856 `( "begin"
1857 "else"
1858 "end"
1859 "endcase"
1860 "endclass"
1861 "endclocking"
1862 "endgroup"
1863 "endfunction"
1864 "endmodule"
1865 "endprogram"
1866 "endprimitive"
1867 "endinterface"
1868 "endpackage"
1869 "endsequence"
1870 "endspecify"
1871 "endtable"
1872 "endtask"
1873 "join"
1874 "join_any"
1875 "join_none"
1876 "module"
1877 "macromodule"
1878 "primitive"
1879 "interface"
1880 "package")))
1881 "\\)"))
1882
1883 ;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
1884 ;;; verilog-end-block-ordered-re matches exactly the same strings.
1885 (defconst verilog-end-block-ordered-re
1886 ;; Parenthesis indicate type of keyword found
1887 (concat "\\(\\<endcase\\>\\)\\|" ; 1
1888 "\\(\\<end\\>\\)\\|" ; 2
1889 "\\(\\<end" ; 3, but not used
1890 "\\(" ; 4, but not used
1891 "\\(function\\)\\|" ; 5
1892 "\\(task\\)\\|" ; 6
1893 "\\(module\\)\\|" ; 7
1894 "\\(primitive\\)\\|" ; 8
1895 "\\(interface\\)\\|" ; 9
1896 "\\(package\\)\\|" ; 10
1897 "\\(class\\)\\|" ; 11
1898 "\\(group\\)\\|" ; 12
1899 "\\(program\\)\\|" ; 13
1900 "\\(sequence\\)\\|" ; 14
1901 "\\(clocking\\)\\|" ; 15
1902 "\\)\\>\\)"))
1903 (defconst verilog-end-block-re
1904 (eval-when-compile
1905 (verilog-regexp-words
1906
1907 `("end" ;; closes begin
1908 "endcase" ;; closes any of case, casex casez or randcase
1909 "join" "join_any" "join_none" ;; closes fork
1910 "endclass"
1911 "endtable"
1912 "endspecify"
1913 "endfunction"
1914 "endgenerate"
1915 "endtask"
1916 "endgroup"
1917 "endproperty"
1918 "endinterface"
1919 "endpackage"
1920 "endprogram"
1921 "endsequence"
1922 "endclocking"
1923 ;; OVM
1924 "`ovm_component_utils_end"
1925 "`ovm_field_utils_end"
1926 "`ovm_object_utils_end"
1927 "`ovm_sequence_utils_end"
1928 "`ovm_sequencer_utils_end"
1929 ;; VMM
1930 "`vmm_data_member_end"
1931 "`vmm_env_member_end"
1932 "`vmm_scenario_member_end"
1933 "`vmm_subenv_member_end"
1934 "`vmm_xactor_member_end"
1935 ))))
1936
1937
1938 (defconst verilog-endcomment-reason-re
1939 ;; Parenthesis indicate type of keyword found
1940 (concat
1941 "\\(\\<begin\\>\\)\\|" ; 1
1942 "\\(\\<else\\>\\)\\|" ; 2
1943 "\\(\\<end\\>\\s-+\\<else\\>\\)\\|" ; 3
1944 "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|" ; 4
1945 "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|" ; 5
1946 "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|" ; 6
1947 "\\(\\<fork\\>\\)\\|" ; 7
1948 "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
1949 "\\(\\<if\\>\\)\\|"
1950 verilog-property-re "\\|"
1951 "\\(\\(" verilog-label-re "\\)?\\<assert\\>\\)\\|"
1952 "\\(\\<clocking\\>\\)\\|"
1953 "\\(\\<task\\>\\)\\|"
1954 "\\(\\<function\\>\\)\\|"
1955 "\\(\\<initial\\>\\)\\|"
1956 "\\(\\<interface\\>\\)\\|"
1957 "\\(\\<package\\>\\)\\|"
1958 "\\(\\<final\\>\\)\\|"
1959 "\\(@\\)\\|"
1960 "\\(\\<while\\>\\)\\|"
1961 "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
1962 "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
1963 "#"))
1964
1965 (defconst verilog-named-block-re "begin[ \t]*:")
1966
1967 ;; These words begin a block which can occur inside a module which should be indented,
1968 ;; and closed with the respective word from the end-block list
1969
1970 (defconst verilog-beg-block-re
1971 (eval-when-compile
1972 (verilog-regexp-words
1973 `("begin"
1974 "case" "casex" "casez" "randcase"
1975 "clocking"
1976 "generate"
1977 "fork"
1978 "function"
1979 "property"
1980 "specify"
1981 "table"
1982 "task"
1983 ;;; OVM
1984 "`ovm_component_utils_begin"
1985 "`ovm_component_param_utils_begin"
1986 "`ovm_field_utils_begin"
1987 "`ovm_object_utils_begin"
1988 "`ovm_object_param_utils_begin"
1989 "`ovm_sequence_utils_begin"
1990 "`ovm_sequencer_utils_begin"
1991 ;; VMM
1992 "`vmm_data_member_begin"
1993 "`vmm_env_member_begin"
1994 "`vmm_scenario_member_begin"
1995 "`vmm_subenv_member_begin"
1996 "`vmm_xactor_member_begin"
1997 ))))
1998 ;; These are the same words, in a specific order in the regular
1999 ;; expression so that matching will work nicely for
2000 ;; verilog-forward-sexp and verilog-calc-indent
2001 (defconst verilog-beg-block-re-ordered
2002 ( concat "\\(\\<begin\\>\\)" ;1
2003 "\\|\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
2004 "\\|\\(\\(\\<disable\\>\\s-+\\)?fork\\>\\)" ;4,5
2005 "\\|\\(\\<class\\>\\)" ;6
2006 "\\|\\(\\<table\\>\\)" ;7
2007 "\\|\\(\\<specify\\>\\)" ;8
2008 "\\|\\(\\<function\\>\\)" ;9
2009 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<function\\>\\)" ;10
2010 "\\|\\(\\<task\\>\\)" ;14
2011 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)" ;15
2012 "\\|\\(\\<generate\\>\\)" ;18
2013 "\\|\\(\\<covergroup\\>\\)" ;16 20
2014 "\\|\\(\\(\\(\\<cover\\>\\s-+\\)\\|\\(\\<assert\\>\\s-+\\)\\)*\\<property\\>\\)" ;17 21
2015 "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;21 25
2016 "\\|\\(\\<clocking\\>\\)" ;22 27
2017 "\\|\\(\\<`ovm_[a-z_]+_begin\\>\\)" ;28
2018 "\\|\\(\\<`vmm_[a-z_]+_member_begin\\>\\)"
2019 ;;
2020
2021 ))
2022
2023 (defconst verilog-end-block-ordered-rry
2024 [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2025 "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
2026 "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2027 "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
2028 "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
2029 "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
2030 "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
2031 "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
2032 "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
2033 "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
2034 "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
2035 "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
2036 "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
2037 ] )
2038
2039 (defconst verilog-nameable-item-re
2040 (eval-when-compile
2041 (verilog-regexp-words
2042 `("begin"
2043 "fork"
2044 "join" "join_any" "join_none"
2045 "end"
2046 "endcase"
2047 "endconfig"
2048 "endclass"
2049 "endclocking"
2050 "endfunction"
2051 "endgenerate"
2052 "endmodule"
2053 "endprimitive"
2054 "endinterface"
2055 "endpackage"
2056 "endspecify"
2057 "endtable"
2058 "endtask" )
2059 )))
2060
2061 (defconst verilog-declaration-opener
2062 (eval-when-compile
2063 (verilog-regexp-words
2064 `("module" "begin" "task" "function"))))
2065
2066 (defconst verilog-declaration-prefix-re
2067 (eval-when-compile
2068 (verilog-regexp-words
2069 `(
2070 ;; port direction
2071 "inout" "input" "output" "ref"
2072 ;; changeableness
2073 "const" "static" "protected" "local"
2074 ;; parameters
2075 "localparam" "parameter" "var"
2076 ;; type creation
2077 "typedef"
2078 ))))
2079 (defconst verilog-declaration-core-re
2080 (eval-when-compile
2081 (verilog-regexp-words
2082 `(
2083 ;; port direction (by themselves)
2084 "inout" "input" "output"
2085 ;; integer_atom_type
2086 "byte" "shortint" "int" "longint" "integer" "time"
2087 ;; integer_vector_type
2088 "bit" "logic" "reg"
2089 ;; non_integer_type
2090 "shortreal" "real" "realtime"
2091 ;; net_type
2092 "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
2093 ;; misc
2094 "string" "event" "chandle" "virtual" "enum" "genvar"
2095 "struct" "union"
2096 ;; builtin classes
2097 "mailbox" "semaphore"
2098 ))))
2099 (defconst verilog-declaration-re
2100 (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
2101 (defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
2102 (defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
2103 (defconst verilog-optional-signed-range-re
2104 (concat
2105 "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
2106 (defconst verilog-macroexp-re "`\\sw+")
2107
2108 (defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
2109 (defconst verilog-declaration-re-2-no-macro
2110 (concat "\\s-*" verilog-declaration-re
2111 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2112 "\\)?"))
2113 (defconst verilog-declaration-re-2-macro
2114 (concat "\\s-*" verilog-declaration-re
2115 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2116 "\\|\\(" verilog-macroexp-re "\\)"
2117 "\\)?"))
2118 (defconst verilog-declaration-re-1-macro
2119 (concat "^" verilog-declaration-re-2-macro))
2120
2121 (defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
2122
2123 (defconst verilog-defun-re
2124 (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
2125 (defconst verilog-end-defun-re
2126 (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
2127 (defconst verilog-zero-indent-re
2128 (concat verilog-defun-re "\\|" verilog-end-defun-re))
2129
2130 (defconst verilog-behavioral-block-beg-re
2131 (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
2132 "function" "task"))))
2133 (defconst verilog-coverpoint-re "\\w+\\s*:\\s*\\(coverpoint\\|cross\\constraint\\)" )
2134 (defconst verilog-indent-re
2135 (eval-when-compile
2136 (verilog-regexp-words
2137 `(
2138 "{"
2139 "always" "always_latch" "always_ff" "always_comb"
2140 "begin" "end"
2141 ; "unique" "priority"
2142 "case" "casex" "casez" "randcase" "endcase"
2143 "class" "endclass"
2144 "clocking" "endclocking"
2145 "config" "endconfig"
2146 "covergroup" "endgroup"
2147 "fork" "join" "join_any" "join_none"
2148 "function" "endfunction"
2149 "final"
2150 "generate" "endgenerate"
2151 "initial"
2152 "interface" "endinterface"
2153 "module" "macromodule" "endmodule"
2154 "package" "endpackage"
2155 "primitive" "endprimative"
2156 "program" "endprogram"
2157 "property" "endproperty"
2158 "sequence" "randsequence" "endsequence"
2159 "specify" "endspecify"
2160 "table" "endtable"
2161 "task" "endtask"
2162 "virtual"
2163 "`case"
2164 "`default"
2165 "`define" "`undef"
2166 "`if" "`ifdef" "`ifndef" "`else" "`elsif" "`endif"
2167 "`while" "`endwhile"
2168 "`for" "`endfor"
2169 "`format"
2170 "`include"
2171 "`let"
2172 "`protect" "`endprotect"
2173 "`switch" "`endswitch"
2174 "`timescale"
2175 "`time_scale"
2176 ;; OVM Begin tokens
2177 "`ovm_component_utils_begin"
2178 "`ovm_component_param_utils_begin"
2179 "`ovm_field_utils_begin"
2180 "`ovm_object_utils_begin"
2181 "`ovm_object_param_utils_begin"
2182 "`ovm_sequence_utils_begin"
2183 "`ovm_sequencer_utils_begin"
2184 ;; OVM End tokens
2185 "`ovm_component_utils_end"
2186 "`ovm_field_utils_end"
2187 "`ovm_object_utils_end"
2188 "`ovm_sequence_utils_end"
2189 "`ovm_sequencer_utils_end"
2190 ;; VMM Begin tokens
2191 "`vmm_data_member_begin"
2192 "`vmm_env_member_begin"
2193 "`vmm_scenario_member_begin"
2194 "`vmm_subenv_member_begin"
2195 "`vmm_xactor_member_begin"
2196 ;; VMM End tokens
2197 "`vmm_data_member_end"
2198 "`vmm_env_member_end"
2199 "`vmm_scenario_member_end"
2200 "`vmm_subenv_member_end"
2201 "`vmm_xactor_member_end"
2202 ))))
2203
2204 (defconst verilog-defun-level-not-generate-re
2205 (eval-when-compile
2206 (verilog-regexp-words
2207 `( "module" "macromodule" "primitive" "class" "program"
2208 "interface" "package" "config"))))
2209
2210 (defconst verilog-defun-level-re
2211 (eval-when-compile
2212 (verilog-regexp-words
2213 (append
2214 `( "module" "macromodule" "primitive" "class" "program"
2215 "interface" "package" "config")
2216 `( "initial" "final" "always" "always_comb" "always_ff"
2217 "always_latch" "endtask" "endfunction" )))))
2218
2219 (defconst verilog-defun-level-generate-only-re
2220 (eval-when-compile
2221 (verilog-regexp-words
2222 `( "initial" "final" "always" "always_comb" "always_ff"
2223 "always_latch" "endtask" "endfunction" ))))
2224
2225 (defconst verilog-cpp-level-re
2226 (eval-when-compile
2227 (verilog-regexp-words
2228 `(
2229 "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
2230 ))))
2231 (defconst verilog-disable-fork-re "disable\\s-+fork\\>")
2232 (defconst verilog-fork-wait-re "fork\\s-+wait\\>")
2233 (defconst verilog-extended-case-re "\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?")
2234 (defconst verilog-extended-complete-re
2235 (concat "\\(\\<extern\\s-+\\|\\<\\(\\<pure\\>\\s-+\\)?virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)"
2236 "\\|\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)"
2237 "\\|\\(\\<import\\>\\s-+\\)?\"DPI-C\"\\s-+\\(function\\>\\|task\\>\\)"
2238 "\\|" verilog-extended-case-re ))
2239 (defconst verilog-basic-complete-re
2240 (eval-when-compile
2241 (verilog-regexp-words
2242 `(
2243 "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
2244 "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
2245 "if" "for" "forever" "foreach" "else" "parameter" "do" "localparam" "assert"
2246 ))))
2247 (defconst verilog-complete-reg
2248 (concat
2249 verilog-extended-complete-re
2250 "\\|"
2251 verilog-basic-complete-re))
2252
2253 (defconst verilog-end-statement-re
2254 (concat "\\(" verilog-beg-block-re "\\)\\|\\("
2255 verilog-end-block-re "\\)"))
2256
2257 (defconst verilog-endcase-re
2258 (concat verilog-extended-case-re "\\|"
2259 "\\(endcase\\)\\|"
2260 verilog-defun-re
2261 ))
2262
2263 (defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
2264 "String used to mark beginning of excluded text.")
2265 (defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
2266 "String used to mark end of excluded text.")
2267 (defconst verilog-preprocessor-re
2268 (eval-when-compile
2269 (verilog-regexp-words
2270 `(
2271 "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
2272 ))))
2273
2274 (defconst verilog-keywords
2275 '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
2276 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
2277 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
2278 "`time_scale" "`undef" "`while"
2279
2280 "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
2281 "assert" "assign" "assume" "automatic" "before" "begin" "bind"
2282 "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
2283 "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
2284 "config" "const" "constraint" "context" "continue" "cover"
2285 "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
2286 "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
2287 "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
2288 "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
2289 "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
2290 "endtask" "enum" "event" "expect" "export" "extends" "extern"
2291 "final" "first_match" "for" "force" "foreach" "forever" "fork"
2292 "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
2293 "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
2294 "include" "initial" "inout" "input" "inside" "instance" "int"
2295 "integer" "interface" "intersect" "join" "join_any" "join_none"
2296 "large" "liblist" "library" "local" "localparam" "logic"
2297 "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
2298 "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
2299 "notif0" "notif1" "null" "or" "output" "package" "packed"
2300 "parameter" "pmos" "posedge" "primitive" "priority" "program"
2301 "property" "protected" "pull0" "pull1" "pulldown" "pullup"
2302 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2303 "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
2304 "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
2305 "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
2306 "showcancelled" "signed" "small" "solve" "specify" "specparam"
2307 "static" "string" "strong0" "strong1" "struct" "super" "supply0"
2308 "supply1" "table" "tagged" "task" "this" "throughout" "time"
2309 "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
2310 "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
2311 "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
2312 "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
2313 "wire" "with" "within" "wor" "xnor" "xor"
2314 ;; 1800-2009
2315 "accept_on" "checker" "endchecker" "eventually" "global" "implies"
2316 "let" "nexttime" "reject_on" "restrict" "s_always" "s_eventually"
2317 "s_nexttime" "s_until" "s_until_with" "strong" "sync_accept_on"
2318 "sync_reject_on" "unique0" "until" "until_with" "untyped" "weak"
2319 )
2320 "List of Verilog keywords.")
2321
2322 (defconst verilog-comment-start-regexp "//\\|/\\*"
2323 "Dual comment value for `comment-start-regexp'.")
2324
2325 (defvar verilog-mode-syntax-table
2326 (let ((table (make-syntax-table)))
2327 ;; Populate the syntax TABLE.
2328 (modify-syntax-entry ?\\ "\\" table)
2329 (modify-syntax-entry ?+ "." table)
2330 (modify-syntax-entry ?- "." table)
2331 (modify-syntax-entry ?= "." table)
2332 (modify-syntax-entry ?% "." table)
2333 (modify-syntax-entry ?< "." table)
2334 (modify-syntax-entry ?> "." table)
2335 (modify-syntax-entry ?& "." table)
2336 (modify-syntax-entry ?| "." table)
2337 (modify-syntax-entry ?` "w" table)
2338 (modify-syntax-entry ?_ "w" table)
2339 (modify-syntax-entry ?\' "." table)
2340
2341 ;; Set up TABLE to handle block and line style comments.
2342 (if (featurep 'xemacs)
2343 (progn
2344 ;; XEmacs (formerly Lucid) has the best implementation
2345 (modify-syntax-entry ?/ ". 1456" table)
2346 (modify-syntax-entry ?* ". 23" table)
2347 (modify-syntax-entry ?\n "> b" table))
2348 ;; Emacs does things differently, but we can work with it
2349 (modify-syntax-entry ?/ ". 124b" table)
2350 (modify-syntax-entry ?* ". 23" table)
2351 (modify-syntax-entry ?\n "> b" table))
2352 table)
2353 "Syntax table used in Verilog mode buffers.")
2354
2355 (defvar verilog-font-lock-keywords nil
2356 "Default highlighting for Verilog mode.")
2357
2358 (defvar verilog-font-lock-keywords-1 nil
2359 "Subdued level highlighting for Verilog mode.")
2360
2361 (defvar verilog-font-lock-keywords-2 nil
2362 "Medium level highlighting for Verilog mode.
2363 See also `verilog-font-lock-extra-types'.")
2364
2365 (defvar verilog-font-lock-keywords-3 nil
2366 "Gaudy level highlighting for Verilog mode.
2367 See also `verilog-font-lock-extra-types'.")
2368 (defvar verilog-font-lock-translate-off-face
2369 'verilog-font-lock-translate-off-face
2370 "Font to use for translated off regions.")
2371 (defface verilog-font-lock-translate-off-face
2372 '((((class color)
2373 (background light))
2374 (:background "gray90" :italic t ))
2375 (((class color)
2376 (background dark))
2377 (:background "gray10" :italic t ))
2378 (((class grayscale) (background light))
2379 (:foreground "DimGray" :italic t))
2380 (((class grayscale) (background dark))
2381 (:foreground "LightGray" :italic t))
2382 (t (:italis t)))
2383 "Font lock mode face used to background highlight translate-off regions."
2384 :group 'font-lock-highlighting-faces)
2385
2386 (defvar verilog-font-lock-p1800-face
2387 'verilog-font-lock-p1800-face
2388 "Font to use for p1800 keywords.")
2389 (defface verilog-font-lock-p1800-face
2390 '((((class color)
2391 (background light))
2392 (:foreground "DarkOrange3" :bold t ))
2393 (((class color)
2394 (background dark))
2395 (:foreground "orange1" :bold t ))
2396 (t (:italic t)))
2397 "Font lock mode face used to highlight P1800 keywords."
2398 :group 'font-lock-highlighting-faces)
2399
2400 (defvar verilog-font-lock-ams-face
2401 'verilog-font-lock-ams-face
2402 "Font to use for Analog/Mixed Signal keywords.")
2403 (defface verilog-font-lock-ams-face
2404 '((((class color)
2405 (background light))
2406 (:foreground "Purple" :bold t ))
2407 (((class color)
2408 (background dark))
2409 (:foreground "orange1" :bold t ))
2410 (t (:italic t)))
2411 "Font lock mode face used to highlight AMS keywords."
2412 :group 'font-lock-highlighting-faces)
2413
2414 (defvar verilog-font-grouping-keywords-face
2415 'verilog-font-lock-grouping-keywords-face
2416 "Font to use for Verilog Grouping Keywords (such as begin..end).")
2417 (defface verilog-font-lock-grouping-keywords-face
2418 '((((class color)
2419 (background light))
2420 (:foreground "red4" :bold t ))
2421 (((class color)
2422 (background dark))
2423 (:foreground "red4" :bold t ))
2424 (t (:italic t)))
2425 "Font lock mode face used to highlight verilog grouping keywords."
2426 :group 'font-lock-highlighting-faces)
2427
2428 (let* ((verilog-type-font-keywords
2429 (eval-when-compile
2430 (verilog-regexp-opt
2431 '(
2432 "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
2433 "event" "genvar" "inout" "input" "integer" "localparam"
2434 "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
2435 "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
2436 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
2437 "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
2438 "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
2439 "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
2440 "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
2441 ) nil )))
2442
2443 (verilog-pragma-keywords
2444 (eval-when-compile
2445 (verilog-regexp-opt
2446 '("surefire" "synopsys" "rtl_synthesis" "verilint" "leda" "0in") nil
2447 )))
2448
2449 (verilog-1800-2005-keywords
2450 (eval-when-compile
2451 (verilog-regexp-opt
2452 '("alias" "assert" "assume" "automatic" "before" "bind"
2453 "bins" "binsof" "break" "byte" "cell" "chandle" "class"
2454 "clocking" "config" "const" "constraint" "context" "continue"
2455 "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
2456 "dist" "do" "edge" "endclass" "endclocking" "endconfig"
2457 "endgroup" "endprogram" "endproperty" "endsequence" "enum"
2458 "expect" "export" "extends" "extern" "first_match" "foreach"
2459 "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
2460 "illegal_bins" "import" "incdir" "include" "inside" "instance"
2461 "int" "intersect" "large" "liblist" "library" "local" "longint"
2462 "matches" "medium" "modport" "new" "noshowcancelled" "null"
2463 "packed" "program" "property" "protected" "pull0" "pull1"
2464 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2465 "randcase" "randsequence" "ref" "release" "return" "scalared"
2466 "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
2467 "specparam" "static" "string" "strong0" "strong1" "struct"
2468 "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
2469 "type" "union" "unsigned" "use" "var" "virtual" "void"
2470 "wait_order" "weak0" "weak1" "wildcard" "with" "within"
2471 ) nil )))
2472
2473 (verilog-1800-2009-keywords
2474 (eval-when-compile
2475 (verilog-regexp-opt
2476 '("accept_on" "checker" "endchecker" "eventually" "global"
2477 "implies" "let" "nexttime" "reject_on" "restrict" "s_always"
2478 "s_eventually" "s_nexttime" "s_until" "s_until_with" "strong"
2479 "sync_accept_on" "sync_reject_on" "unique0" "until"
2480 "until_with" "untyped" "weak" ) nil )))
2481
2482 (verilog-ams-keywords
2483 (eval-when-compile
2484 (verilog-regexp-opt
2485 '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
2486 "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
2487 "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
2488 "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
2489 "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
2490 "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
2491 "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
2492 "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
2493 "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
2494 "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
2495 "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
2496
2497 (verilog-font-keywords
2498 (eval-when-compile
2499 (verilog-regexp-opt
2500 '(
2501 "assign" "case" "casex" "casez" "randcase" "deassign"
2502 "default" "disable" "else" "endcase" "endfunction"
2503 "endgenerate" "endinterface" "endmodule" "endprimitive"
2504 "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
2505 "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
2506 "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
2507 "package" "endpackage" "always" "always_comb" "always_ff"
2508 "always_latch" "posedge" "primitive" "priority" "release"
2509 "repeat" "specify" "table" "task" "unique" "wait" "while"
2510 "class" "program" "endclass" "endprogram"
2511 ) nil )))
2512
2513 (verilog-font-grouping-keywords
2514 (eval-when-compile
2515 (verilog-regexp-opt
2516 '( "begin" "end" ) nil ))))
2517
2518 (setq verilog-font-lock-keywords
2519 (list
2520 ;; Fontify all builtin keywords
2521 (concat "\\<\\(" verilog-font-keywords "\\|"
2522 ;; And user/system tasks and functions
2523 "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
2524 "\\)\\>")
2525 ;; Fontify all types
2526 (if verilog-highlight-grouping-keywords
2527 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2528 'verilog-font-lock-ams-face)
2529 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2530 'font-lock-type-face))
2531 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
2532 'font-lock-type-face)
2533 ;; Fontify IEEE-1800-2005 keywords appropriately
2534 (if verilog-highlight-p1800-keywords
2535 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
2536 'verilog-font-lock-p1800-face)
2537 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
2538 'font-lock-type-face))
2539 ;; Fontify IEEE-1800-2009 keywords appropriately
2540 (if verilog-highlight-p1800-keywords
2541 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
2542 'verilog-font-lock-p1800-face)
2543 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
2544 'font-lock-type-face))
2545 ;; Fontify Verilog-AMS keywords
2546 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
2547 'verilog-font-lock-ams-face)))
2548
2549 (setq verilog-font-lock-keywords-1
2550 (append verilog-font-lock-keywords
2551 (list
2552 ;; Fontify module definitions
2553 (list
2554 "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
2555 '(1 font-lock-keyword-face)
2556 '(3 font-lock-function-name-face 'prepend))
2557 ;; Fontify function definitions
2558 (list
2559 (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
2560 '(1 font-lock-keyword-face)
2561 '(3 font-lock-constant-face prepend))
2562 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
2563 (1 font-lock-keyword-face)
2564 (2 font-lock-constant-face append))
2565 '("\\<function\\>\\s-+\\(\\sw+\\)"
2566 1 'font-lock-constant-face append))))
2567
2568 (setq verilog-font-lock-keywords-2
2569 (append verilog-font-lock-keywords-1
2570 (list
2571 ;; Fontify pragmas
2572 (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
2573 ;; Fontify escaped names
2574 '("\\(\\\\\\S-*\\s-\\)" 0 font-lock-function-name-face)
2575 ;; Fontify macro definitions/ uses
2576 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
2577 'font-lock-preprocessor-face
2578 'font-lock-type-face))
2579 ;; Fontify delays/numbers
2580 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
2581 0 font-lock-type-face append)
2582 ;; Fontify instantiation names
2583 '("\\([A-Za-z][A-Za-z0-9_]*\\)\\s-*(" 1 font-lock-function-name-face)
2584 )))
2585
2586 (setq verilog-font-lock-keywords-3
2587 (append verilog-font-lock-keywords-2
2588 (when verilog-highlight-translate-off
2589 (list
2590 ;; Fontify things in translate off regions
2591 '(verilog-match-translate-off
2592 (0 'verilog-font-lock-translate-off-face prepend))
2593 )))))
2594
2595 ;;
2596 ;; Buffer state preservation
2597
2598 (defmacro verilog-save-buffer-state (&rest body)
2599 "Execute BODY forms, saving state around insignificant change.
2600 Changes in text properties like `face' or `syntax-table' are
2601 considered insignificant. This macro allows text properties to
2602 be changed, even in a read-only buffer.
2603
2604 A change is considered significant if it affects the buffer text
2605 in any way that isn't completely restored again. Any
2606 user-visible changes to the buffer must not be within a
2607 `verilog-save-buffer-state'."
2608 ;; From c-save-buffer-state
2609 `(let* ((modified (buffer-modified-p))
2610 (buffer-undo-list t)
2611 (inhibit-read-only t)
2612 (inhibit-point-motion-hooks t)
2613 before-change-functions
2614 after-change-functions
2615 deactivate-mark
2616 buffer-file-name ; Prevent primitives checking
2617 buffer-file-truename) ; for file modification
2618 (unwind-protect
2619 (progn ,@body)
2620 (and (not modified)
2621 (buffer-modified-p)
2622 (set-buffer-modified-p nil)))))
2623
2624 (defmacro verilog-save-no-change-functions (&rest body)
2625 "Execute BODY forms, disabling all change hooks in BODY.
2626 For insigificant changes, see instead `verilog-save-buffer-state'."
2627 `(let* ((inhibit-point-motion-hooks t)
2628 before-change-functions
2629 after-change-functions)
2630 (progn ,@body)))
2631
2632 ;;
2633 ;; Comment detection and caching
2634
2635 (defvar verilog-scan-cache-preserving nil
2636 "If set, the specified buffer's comment properties are static.
2637 Buffer changes will be ignored. See `verilog-inside-comment-p'
2638 and `verilog-scan'.")
2639
2640 (defvar verilog-scan-cache-tick nil
2641 "Modification tick at which `verilog-scan' was last completed.")
2642 (make-variable-buffer-local 'verilog-scan-cache-tick)
2643
2644 (defun verilog-scan-cache-ok-p ()
2645 "Return t iff the scan cache is up to date."
2646 (or (and verilog-scan-cache-preserving
2647 (eq verilog-scan-cache-preserving (current-buffer))
2648 verilog-scan-cache-tick)
2649 (equal verilog-scan-cache-tick (buffer-chars-modified-tick))))
2650
2651 (defmacro verilog-save-scan-cache (&rest body)
2652 "Execute the BODY forms, allowing scan cache preservation within BODY.
2653 This requires that insertions must use `verilog-insert'."
2654 ;; If the buffer is out of date, trash it, as we'll not check later the tick
2655 ;; Note this must work properly if there's multiple layers of calls
2656 ;; to verilog-save-scan-cache even with differing ticks.
2657 `(progn
2658 (unless (verilog-scan-cache-ok-p) ;; Must be before let
2659 (setq verilog-scan-cache-tick nil))
2660 (let* ((verilog-scan-cache-preserving (current-buffer)))
2661 (progn ,@body))))
2662
2663 (defun verilog-scan-region (beg end)
2664 "Parse comments between BEG and END for `verilog-inside-comment-p'.
2665 This creates v-cmt properties where comments are in force."
2666 ;; Why properties and not overlays? Overlays have much slower non O(1)
2667 ;; lookup times.
2668 ;; This function is warm - called on every verilog-insert
2669 (save-excursion
2670 (save-match-data
2671 (verilog-save-buffer-state
2672 (let (pt)
2673 (goto-char beg)
2674 (while (< (point) end)
2675 (cond ((looking-at "//")
2676 (setq pt (point))
2677 (or (search-forward "\n" end t)
2678 (goto-char end))
2679 ;; "1+": The leading // or /* itself isn't considered as
2680 ;; being "inside" the comment, so that a (search-backward)
2681 ;; that lands at the start of the // won't mis-indicate
2682 ;; it's inside a comment
2683 (put-text-property (1+ pt) (point) 'v-cmt t))
2684 ((looking-at "/\\*")
2685 (setq pt (point))
2686 (or (search-forward "*/" end t)
2687 ;; No error - let later code indicate it so we can
2688 ;; use inside functions on-the-fly
2689 ;;(error "%s: Unmatched /* */, at char %d"
2690 ;; (verilog-point-text) (point))
2691 (goto-char end))
2692 (put-text-property (1+ pt) (point) 'v-cmt t))
2693 (t
2694 (forward-char 1)
2695 (if (re-search-forward "/[/*]" end t)
2696 (backward-char 2)
2697 (goto-char end))))))))))
2698
2699 (defun verilog-scan ()
2700 "Parse the buffer, marking all comments with properties.
2701 Also assumes any text inserted since `verilog-scan-cache-tick'
2702 either is ok to parse as a non-comment, or `verilog-insert' was used."
2703 (unless (verilog-scan-cache-ok-p)
2704 (save-excursion
2705 (verilog-save-buffer-state
2706 (when verilog-debug
2707 (message "Scanning %s cache=%s cachetick=%S tick=%S" (current-buffer)
2708 verilog-scan-cache-preserving verilog-scan-cache-tick
2709 (buffer-chars-modified-tick)))
2710 (remove-text-properties (point-min) (point-max) '(v-cmt nil))
2711 (verilog-scan-region (point-min) (point-max))
2712 (setq verilog-scan-cache-tick (buffer-chars-modified-tick))
2713 (when verilog-debug (message "Scaning... done"))))))
2714
2715 (defun verilog-inside-comment-p ()
2716 "Check if point inside a comment.
2717 This may require a slow pre-parse of the buffer with `verilog-scan'
2718 to establish comment properties on all text."
2719 ;; This function is very hot
2720 (verilog-scan)
2721 (get-text-property (point) 'v-cmt))
2722
2723 (defun verilog-insert (&rest stuff)
2724 "Insert STUFF arguments, tracking comments for `verilog-inside-comment-p'.
2725 Any insert that includes a comment must have the entire commente
2726 inserted using a single call to `verilog-insert'."
2727 (let ((pt (point)))
2728 (while stuff
2729 (insert (car stuff))
2730 (setq stuff (cdr stuff)))
2731 (verilog-scan-region pt (point))))
2732
2733 ;; More searching
2734
2735 (defun verilog-declaration-end ()
2736 (search-forward ";"))
2737
2738 (defun verilog-point-text (&optional pointnum)
2739 "Return text describing where POINTNUM or current point is (for errors).
2740 Use filename, if current buffer being edited shorten to just buffer name."
2741 (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
2742 (buffer-name))
2743 buffer-file-name
2744 (buffer-name))
2745 ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
2746
2747 (defun electric-verilog-backward-sexp ()
2748 "Move backward over one balanced expression."
2749 (interactive)
2750 ;; before that see if we are in a comment
2751 (verilog-backward-sexp))
2752
2753 (defun electric-verilog-forward-sexp ()
2754 "Move forward over one balanced expression."
2755 (interactive)
2756 ;; before that see if we are in a comment
2757 (verilog-forward-sexp))
2758
2759 ;;;used by hs-minor-mode
2760 (defun verilog-forward-sexp-function (arg)
2761 (if (< arg 0)
2762 (verilog-backward-sexp)
2763 (verilog-forward-sexp)))
2764
2765
2766 (defun verilog-backward-sexp ()
2767 (let ((reg)
2768 (elsec 1)
2769 (found nil)
2770 (st (point)))
2771 (if (not (looking-at "\\<"))
2772 (forward-word -1))
2773 (cond
2774 ((verilog-skip-backward-comment-or-string))
2775 ((looking-at "\\<else\\>")
2776 (setq reg (concat
2777 verilog-end-block-re
2778 "\\|\\(\\<else\\>\\)"
2779 "\\|\\(\\<if\\>\\)"))
2780 (while (and (not found)
2781 (verilog-re-search-backward reg nil 'move))
2782 (cond
2783 ((match-end 1) ; matched verilog-end-block-re
2784 ; try to leap back to matching outward block by striding across
2785 ; indent level changing tokens then immediately
2786 ; previous line governs indentation.
2787 (verilog-leap-to-head))
2788 ((match-end 2) ; else, we're in deep
2789 (setq elsec (1+ elsec)))
2790 ((match-end 3) ; found it
2791 (setq elsec (1- elsec))
2792 (if (= 0 elsec)
2793 ;; Now previous line describes syntax
2794 (setq found 't))))))
2795 ((looking-at verilog-end-block-re)
2796 (verilog-leap-to-head))
2797 ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
2798 (cond
2799 ((match-end 1)
2800 (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
2801 ((match-end 2)
2802 (verilog-re-search-backward "\\<primitive\\>" nil 'move))
2803 ((match-end 3)
2804 (verilog-re-search-backward "\\<class\\>" nil 'move))
2805 ((match-end 4)
2806 (verilog-re-search-backward "\\<program\\>" nil 'move))
2807 ((match-end 5)
2808 (verilog-re-search-backward "\\<interface\\>" nil 'move))
2809 ((match-end 6)
2810 (verilog-re-search-backward "\\<package\\>" nil 'move))
2811 (t
2812 (goto-char st)
2813 (backward-sexp 1))))
2814 (t
2815 (goto-char st)
2816 (backward-sexp)))))
2817
2818 (defun verilog-forward-sexp ()
2819 (let ((reg)
2820 (md 2)
2821 (st (point))
2822 (nest 'yes))
2823 (if (not (looking-at "\\<"))
2824 (forward-word -1))
2825 (cond
2826 ((verilog-skip-forward-comment-or-string)
2827 (verilog-forward-syntactic-ws))
2828 ((looking-at verilog-beg-block-re-ordered)
2829 (cond
2830 ((match-end 1);
2831 ;; Search forward for matching end
2832 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
2833 ((match-end 2)
2834 ;; Search forward for matching endcase
2835 (setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2836 (setq md 3) ;; ender is third item in regexp
2837 )
2838 ((match-end 4)
2839 ;; might be "disable fork" or "fork wait"
2840 (let
2841 (here)
2842 (if (looking-at verilog-fork-wait-re)
2843 (progn ;; it is a fork wait; ignore it
2844 (goto-char (match-end 0))
2845 (setq reg nil))
2846 (if (or
2847 (looking-at verilog-disable-fork-re)
2848 (and (looking-at "fork")
2849 (progn
2850 (setq here (point)) ;; sometimes a fork is just a fork
2851 (forward-word -1)
2852 (looking-at verilog-disable-fork-re))))
2853 (progn ;; it is a disable fork; ignore it
2854 (goto-char (match-end 0))
2855 (forward-word 1)
2856 (setq reg nil))
2857 (progn ;; it is a nice simple fork
2858 (goto-char here) ;; return from looking for "disable fork"
2859 ;; Search forward for matching join
2860 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))))))
2861 ((match-end 6)
2862 ;; Search forward for matching endclass
2863 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
2864
2865 ((match-end 7)
2866 ;; Search forward for matching endtable
2867 (setq reg "\\<endtable\\>" )
2868 (setq nest 'no))
2869 ((match-end 8)
2870 ;; Search forward for matching endspecify
2871 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
2872 ((match-end 9)
2873 ;; Search forward for matching endfunction
2874 (setq reg "\\<endfunction\\>" )
2875 (setq nest 'no))
2876 ((match-end 10)
2877 ;; Search forward for matching endfunction
2878 (setq reg "\\<endfunction\\>" )
2879 (setq nest 'no))
2880 ((match-end 14)
2881 ;; Search forward for matching endtask
2882 (setq reg "\\<endtask\\>" )
2883 (setq nest 'no))
2884 ((match-end 15)
2885 ;; Search forward for matching endtask
2886 (setq reg "\\<endtask\\>" )
2887 (setq nest 'no))
2888 ((match-end 19)
2889 ;; Search forward for matching endgenerate
2890 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
2891 ((match-end 20)
2892 ;; Search forward for matching endgroup
2893 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
2894 ((match-end 21)
2895 ;; Search forward for matching endproperty
2896 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
2897 ((match-end 25)
2898 ;; Search forward for matching endsequence
2899 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
2900 (setq md 3)) ; 3 to get to endsequence in the reg above
2901 ((match-end 27)
2902 ;; Search forward for matching endclocking
2903 (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
2904 (if (and reg
2905 (forward-word 1))
2906 (catch 'skip
2907 (if (eq nest 'yes)
2908 (let ((depth 1)
2909 here)
2910 (while (verilog-re-search-forward reg nil 'move)
2911 (cond
2912 ((match-end md) ; a closer in regular expression, so we are climbing out
2913 (setq depth (1- depth))
2914 (if (= 0 depth) ; we are out!
2915 (throw 'skip 1)))
2916 ((match-end 1) ; an opener in the r-e, so we are in deeper now
2917 (setq here (point)) ; remember where we started
2918 (goto-char (match-beginning 1))
2919 (cond
2920 ((looking-at verilog-fork-wait-re)
2921 (goto-char (match-end 0))) ; false alarm
2922 ((if (or
2923 (looking-at verilog-disable-fork-re)
2924 (and (looking-at "fork")
2925 (progn
2926 (forward-word -1)
2927 (looking-at verilog-disable-fork-re))))
2928 (progn ;; it is a disable fork; another false alarm
2929 (goto-char (match-end 0)))
2930 (progn ;; it is a simple fork (or has nothing to do with fork)
2931 (goto-char here)
2932 (setq depth (1+ depth))))))))))
2933 (if (verilog-re-search-forward reg nil 'move)
2934 (throw 'skip 1))))))
2935
2936 ((looking-at (concat
2937 "\\(\\<\\(macro\\)?module\\>\\)\\|"
2938 "\\(\\<primitive\\>\\)\\|"
2939 "\\(\\<class\\>\\)\\|"
2940 "\\(\\<program\\>\\)\\|"
2941 "\\(\\<interface\\>\\)\\|"
2942 "\\(\\<package\\>\\)"))
2943 (cond
2944 ((match-end 1)
2945 (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
2946 ((match-end 2)
2947 (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
2948 ((match-end 3)
2949 (verilog-re-search-forward "\\<endclass\\>" nil 'move))
2950 ((match-end 4)
2951 (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
2952 ((match-end 5)
2953 (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
2954 ((match-end 6)
2955 (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
2956 (t
2957 (goto-char st)
2958 (if (= (following-char) ?\) )
2959 (forward-char 1)
2960 (forward-sexp 1)))))
2961 (t
2962 (goto-char st)
2963 (if (= (following-char) ?\) )
2964 (forward-char 1)
2965 (forward-sexp 1))))))
2966
2967 (defun verilog-declaration-beg ()
2968 (verilog-re-search-backward verilog-declaration-re (bobp) t))
2969
2970 ;;
2971 ;;
2972 ;; Mode
2973 ;;
2974 (defvar verilog-which-tool 1)
2975 ;;;###autoload
2976 (define-derived-mode verilog-mode prog-mode "Verilog"
2977 "Major mode for editing Verilog code.
2978 \\<verilog-mode-map>
2979 See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
2980 AUTOs can improve coding efficiency.
2981
2982 Use \\[verilog-faq] for a pointer to frequently asked questions.
2983
2984 NEWLINE, TAB indents for Verilog code.
2985 Delete converts tabs to spaces as it moves back.
2986
2987 Supports highlighting.
2988
2989 Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
2990 with no args, if that value is non-nil.
2991
2992 Variables controlling indentation/edit style:
2993
2994 variable `verilog-indent-level' (default 3)
2995 Indentation of Verilog statements with respect to containing block.
2996 `verilog-indent-level-module' (default 3)
2997 Absolute indentation of Module level Verilog statements.
2998 Set to 0 to get initial and always statements lined up
2999 on the left side of your screen.
3000 `verilog-indent-level-declaration' (default 3)
3001 Indentation of declarations with respect to containing block.
3002 Set to 0 to get them list right under containing block.
3003 `verilog-indent-level-behavioral' (default 3)
3004 Indentation of first begin in a task or function block
3005 Set to 0 to get such code to lined up underneath the task or
3006 function keyword.
3007 `verilog-indent-level-directive' (default 1)
3008 Indentation of `ifdef/`endif blocks.
3009 `verilog-cexp-indent' (default 1)
3010 Indentation of Verilog statements broken across lines i.e.:
3011 if (a)
3012 begin
3013 `verilog-case-indent' (default 2)
3014 Indentation for case statements.
3015 `verilog-auto-newline' (default nil)
3016 Non-nil means automatically newline after semicolons and the punctuation
3017 mark after an end.
3018 `verilog-auto-indent-on-newline' (default t)
3019 Non-nil means automatically indent line after newline.
3020 `verilog-tab-always-indent' (default t)
3021 Non-nil means TAB in Verilog mode should always reindent the current line,
3022 regardless of where in the line point is when the TAB command is used.
3023 `verilog-indent-begin-after-if' (default t)
3024 Non-nil means to indent begin statements following a preceding
3025 if, else, while, for and repeat statements, if any. Otherwise,
3026 the begin is lined up with the preceding token. If t, you get:
3027 if (a)
3028 begin // amount of indent based on `verilog-cexp-indent'
3029 otherwise you get:
3030 if (a)
3031 begin
3032 `verilog-auto-endcomments' (default t)
3033 Non-nil means a comment /* ... */ is set after the ends which ends
3034 cases, tasks, functions and modules.
3035 The type and name of the object will be set between the braces.
3036 `verilog-minimum-comment-distance' (default 10)
3037 Minimum distance (in lines) between begin and end required before a comment
3038 will be inserted. Setting this variable to zero results in every
3039 end acquiring a comment; the default avoids too many redundant
3040 comments in tight quarters.
3041 `verilog-auto-lineup' (default 'declarations)
3042 List of contexts where auto lineup of code should be done.
3043
3044 Variables controlling other actions:
3045
3046 `verilog-linter' (default surelint)
3047 Unix program to call to run the lint checker. This is the default
3048 command for \\[compile-command] and \\[verilog-auto-save-compile].
3049
3050 See \\[customize] for the complete list of variables.
3051
3052 AUTO expansion functions are, in part:
3053
3054 \\[verilog-auto] Expand AUTO statements.
3055 \\[verilog-delete-auto] Remove the AUTOs.
3056 \\[verilog-inject-auto] Insert AUTOs for the first time.
3057
3058 Some other functions are:
3059
3060 \\[verilog-complete-word] Complete word with appropriate possibilities.
3061 \\[verilog-mark-defun] Mark function.
3062 \\[verilog-beg-of-defun] Move to beginning of current function.
3063 \\[verilog-end-of-defun] Move to end of current function.
3064 \\[verilog-label-be] Label matching begin ... end, fork ... join, etc statements.
3065
3066 \\[verilog-comment-region] Put marked area in a comment.
3067 \\[verilog-uncomment-region] Uncomment an area commented with \\[verilog-comment-region].
3068 \\[verilog-insert-block] Insert begin ... end.
3069 \\[verilog-star-comment] Insert /* ... */.
3070
3071 \\[verilog-sk-always] Insert an always @(AS) begin .. end block.
3072 \\[verilog-sk-begin] Insert a begin .. end block.
3073 \\[verilog-sk-case] Insert a case block, prompting for details.
3074 \\[verilog-sk-for] Insert a for (...) begin .. end block, prompting for details.
3075 \\[verilog-sk-generate] Insert a generate .. endgenerate block.
3076 \\[verilog-sk-header] Insert a header block at the top of file.
3077 \\[verilog-sk-initial] Insert an initial begin .. end block.
3078 \\[verilog-sk-fork] Insert a fork begin .. end .. join block.
3079 \\[verilog-sk-module] Insert a module .. (/*AUTOARG*/);.. endmodule block.
3080 \\[verilog-sk-primitive] Insert a primitive .. (.. );.. endprimitive block.
3081 \\[verilog-sk-repeat] Insert a repeat (..) begin .. end block.
3082 \\[verilog-sk-specify] Insert a specify .. endspecify block.
3083 \\[verilog-sk-task] Insert a task .. begin .. end endtask block.
3084 \\[verilog-sk-while] Insert a while (...) begin .. end block, prompting for details.
3085 \\[verilog-sk-casex] Insert a casex (...) item: begin.. end endcase block, prompting for details.
3086 \\[verilog-sk-casez] Insert a casez (...) item: begin.. end endcase block, prompting for details.
3087 \\[verilog-sk-if] Insert an if (..) begin .. end block.
3088 \\[verilog-sk-else-if] Insert an else if (..) begin .. end block.
3089 \\[verilog-sk-comment] Insert a comment block.
3090 \\[verilog-sk-assign] Insert an assign .. = ..; statement.
3091 \\[verilog-sk-function] Insert a function .. begin .. end endfunction block.
3092 \\[verilog-sk-input] Insert an input declaration, prompting for details.
3093 \\[verilog-sk-output] Insert an output declaration, prompting for details.
3094 \\[verilog-sk-state-machine] Insert a state machine definition, prompting for details.
3095 \\[verilog-sk-inout] Insert an inout declaration, prompting for details.
3096 \\[verilog-sk-wire] Insert a wire declaration, prompting for details.
3097 \\[verilog-sk-reg] Insert a register declaration, prompting for details.
3098 \\[verilog-sk-define-signal] Define signal under point as a register at the top of the module.
3099
3100 All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
3101 Key bindings specific to `verilog-mode-map' are:
3102
3103 \\{verilog-mode-map}"
3104 :abbrev-table verilog-mode-abbrev-table
3105 (set (make-local-variable 'beginning-of-defun-function)
3106 'verilog-beg-of-defun)
3107 (set (make-local-variable 'end-of-defun-function)
3108 'verilog-end-of-defun)
3109 (set-syntax-table verilog-mode-syntax-table)
3110 (set (make-local-variable 'indent-line-function)
3111 #'verilog-indent-line-relative)
3112 (setq comment-indent-function 'verilog-comment-indent)
3113 (set (make-local-variable 'parse-sexp-ignore-comments) nil)
3114
3115 (set (make-local-variable 'comment-start) "// ")
3116 (set (make-local-variable 'comment-end) "")
3117 (set (make-local-variable 'comment-start-skip) "/\\*+ *\\|// *")
3118 (set (make-local-variable 'comment-multi-line) nil)
3119 ;; Set up for compilation
3120 (setq verilog-which-tool 1)
3121 (setq verilog-tool 'verilog-linter)
3122 (verilog-set-compile-command)
3123 (when (boundp 'hack-local-variables-hook) ;; Also modify any file-local-variables
3124 (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
3125
3126 ;; Setting up menus
3127 (when (featurep 'xemacs)
3128 (easy-menu-add verilog-stmt-menu)
3129 (easy-menu-add verilog-menu)
3130 (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
3131
3132 ;; Stuff for GNU Emacs
3133 (set (make-local-variable 'font-lock-defaults)
3134 `((verilog-font-lock-keywords verilog-font-lock-keywords-1
3135 verilog-font-lock-keywords-2
3136 verilog-font-lock-keywords-3)
3137 nil nil nil
3138 ,(if (functionp 'syntax-ppss)
3139 ;; verilog-beg-of-defun uses syntax-ppss, and syntax-ppss uses
3140 ;; font-lock-beginning-of-syntax-function, so
3141 ;; font-lock-beginning-of-syntax-function, can't use
3142 ;; verilog-beg-of-defun.
3143 nil
3144 'verilog-beg-of-defun)))
3145 ;;------------------------------------------------------------
3146 ;; now hook in 'verilog-highlight-include-files (eldo-mode.el&spice-mode.el)
3147 ;; all buffer local:
3148 (unless noninteractive ;; Else can't see the result, and change hooks are slow
3149 (when (featurep 'xemacs)
3150 (make-local-hook 'font-lock-mode-hook)
3151 (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
3152 (make-local-hook 'after-change-functions))
3153 (add-hook 'font-lock-mode-hook 'verilog-highlight-buffer t t)
3154 (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-highlight-buffer t t) ; not in Emacs
3155 (add-hook 'after-change-functions 'verilog-highlight-region t t))
3156
3157 ;; Tell imenu how to handle Verilog.
3158 (set (make-local-variable 'imenu-generic-expression)
3159 verilog-imenu-generic-expression)
3160 ;; Tell which-func-modes that imenu knows about verilog
3161 (when (boundp 'which-function-modes)
3162 (add-to-list 'which-func-modes 'verilog-mode))
3163 ;; hideshow support
3164 (when (boundp 'hs-special-modes-alist)
3165 (unless (assq 'verilog-mode hs-special-modes-alist)
3166 (setq hs-special-modes-alist
3167 (cons '(verilog-mode-mode "\\<begin\\>" "\\<end\\>" nil
3168 verilog-forward-sexp-function)
3169 hs-special-modes-alist))))
3170
3171 ;; Stuff for autos
3172 (add-hook 'write-contents-hooks 'verilog-auto-save-check nil 'local))
3173 \f
3174
3175 ;;
3176 ;; Electric functions
3177 ;;
3178 (defun electric-verilog-terminate-line (&optional arg)
3179 "Terminate line and indent next line.
3180 With optional ARG, remove existing end of line comments."
3181 (interactive)
3182 ;; before that see if we are in a comment
3183 (let ((state (save-excursion (verilog-syntax-ppss))))
3184 (cond
3185 ((nth 7 state) ; Inside // comment
3186 (if (eolp)
3187 (progn
3188 (delete-horizontal-space)
3189 (newline))
3190 (progn
3191 (newline)
3192 (insert "// ")
3193 (beginning-of-line)))
3194 (verilog-indent-line))
3195 ((nth 4 state) ; Inside any comment (hence /**/)
3196 (newline)
3197 (verilog-more-comment))
3198 ((eolp)
3199 ;; First, check if current line should be indented
3200 (if (save-excursion
3201 (delete-horizontal-space)
3202 (beginning-of-line)
3203 (skip-chars-forward " \t")
3204 (if (looking-at verilog-auto-end-comment-lines-re)
3205 (let ((indent-str (verilog-indent-line)))
3206 ;; Maybe we should set some endcomments
3207 (if verilog-auto-endcomments
3208 (verilog-set-auto-endcomments indent-str arg))
3209 (end-of-line)
3210 (delete-horizontal-space)
3211 (if arg
3212 ()
3213 (newline))
3214 nil)
3215 (progn
3216 (end-of-line)
3217 (delete-horizontal-space)
3218 't)))
3219 ;; see if we should line up assignments
3220 (progn
3221 (if (or (eq 'all verilog-auto-lineup)
3222 (eq 'assignments verilog-auto-lineup))
3223 (verilog-pretty-expr t "\\(<\\|:\\)?=" ))
3224 (newline))
3225 (forward-line 1))
3226 ;; Indent next line
3227 (if verilog-auto-indent-on-newline
3228 (verilog-indent-line)))
3229 (t
3230 (newline)))))
3231
3232 (defun electric-verilog-terminate-and-indent ()
3233 "Insert a newline and indent for the next statement."
3234 (interactive)
3235 (electric-verilog-terminate-line 1))
3236
3237 (defun electric-verilog-semi ()
3238 "Insert `;' character and reindent the line."
3239 (interactive)
3240 (verilog-insert-last-command-event)
3241
3242 (if (or (verilog-in-comment-or-string-p)
3243 (verilog-in-escaped-name-p))
3244 ()
3245 (save-excursion
3246 (beginning-of-line)
3247 (verilog-forward-ws&directives)
3248 (verilog-indent-line))
3249 (if (and verilog-auto-newline
3250 (not (verilog-parenthesis-depth)))
3251 (electric-verilog-terminate-line))))
3252
3253 (defun electric-verilog-semi-with-comment ()
3254 "Insert `;' character, reindent the line and indent for comment."
3255 (interactive)
3256 (insert "\;")
3257 (save-excursion
3258 (beginning-of-line)
3259 (verilog-indent-line))
3260 (indent-for-comment))
3261
3262 (defun electric-verilog-colon ()
3263 "Insert `:' and do all indentations except line indent on this line."
3264 (interactive)
3265 (verilog-insert-last-command-event)
3266 ;; Do nothing if within string.
3267 (if (or
3268 (verilog-within-string)
3269 (not (verilog-in-case-region-p)))
3270 ()
3271 (save-excursion
3272 (let ((p (point))
3273 (lim (progn (verilog-beg-of-statement) (point))))
3274 (goto-char p)
3275 (verilog-backward-case-item lim)
3276 (verilog-indent-line)))
3277 ;; (let ((verilog-tab-always-indent nil))
3278 ;; (verilog-indent-line))
3279 ))
3280
3281 ;;(defun electric-verilog-equal ()
3282 ;; "Insert `=', and do indentation if within block."
3283 ;; (interactive)
3284 ;; (verilog-insert-last-command-event)
3285 ;; Could auto line up expressions, but not yet
3286 ;; (if (eq (car (verilog-calculate-indent)) 'block)
3287 ;; (let ((verilog-tab-always-indent nil))
3288 ;; (verilog-indent-command)))
3289 ;; )
3290
3291 (defun electric-verilog-tick ()
3292 "Insert back-tick, and indent to column 0 if this is a CPP directive."
3293 (interactive)
3294 (verilog-insert-last-command-event)
3295 (save-excursion
3296 (if (verilog-in-directive-p)
3297 (verilog-indent-line))))
3298
3299 (defun electric-verilog-tab ()
3300 "Function called when TAB is pressed in Verilog mode."
3301 (interactive)
3302 ;; If verilog-tab-always-indent, indent the beginning of the line.
3303 (cond
3304 ;; The region is active, indent it.
3305 ((and (region-active-p)
3306 (not (eq (region-beginning) (region-end))))
3307 (indent-region (region-beginning) (region-end) nil))
3308 ((or verilog-tab-always-indent
3309 (save-excursion
3310 (skip-chars-backward " \t")
3311 (bolp)))
3312 (let* ((oldpnt (point))
3313 (boi-point
3314 (save-excursion
3315 (beginning-of-line)
3316 (skip-chars-forward " \t")
3317 (verilog-indent-line)
3318 (back-to-indentation)
3319 (point))))
3320 (if (< (point) boi-point)
3321 (back-to-indentation)
3322 (cond ((not verilog-tab-to-comment))
3323 ((not (eolp))
3324 (end-of-line))
3325 (t
3326 (indent-for-comment)
3327 (when (and (eolp) (= oldpnt (point)))
3328 ; kill existing comment
3329 (beginning-of-line)
3330 (re-search-forward comment-start-skip oldpnt 'move)
3331 (goto-char (match-beginning 0))
3332 (skip-chars-backward " \t")
3333 (kill-region (point) oldpnt)))))))
3334 (t (progn (insert "\t")))))
3335
3336 \f
3337
3338 ;;
3339 ;; Interactive functions
3340 ;;
3341
3342 (defun verilog-indent-buffer ()
3343 "Indent-region the entire buffer as Verilog code.
3344 To call this from the command line, see \\[verilog-batch-indent]."
3345 (interactive)
3346 (verilog-mode)
3347 (indent-region (point-min) (point-max) nil))
3348
3349 (defun verilog-insert-block ()
3350 "Insert Verilog begin ... end; block in the code with right indentation."
3351 (interactive)
3352 (verilog-indent-line)
3353 (insert "begin")
3354 (electric-verilog-terminate-line)
3355 (save-excursion
3356 (electric-verilog-terminate-line)
3357 (insert "end")
3358 (beginning-of-line)
3359 (verilog-indent-line)))
3360
3361 (defun verilog-star-comment ()
3362 "Insert Verilog star comment at point."
3363 (interactive)
3364 (verilog-indent-line)
3365 (insert "/*")
3366 (save-excursion
3367 (newline)
3368 (insert " */"))
3369 (newline)
3370 (insert " * "))
3371
3372 (defun verilog-insert-1 (fmt max)
3373 "Use format string FMT to insert integers 0 to MAX - 1.
3374 Inserts one integer per line, at the current column. Stops early
3375 if it reaches the end of the buffer."
3376 (let ((col (current-column))
3377 (n 0))
3378 (save-excursion
3379 (while (< n max)
3380 (insert (format fmt n))
3381 (forward-line 1)
3382 ;; Note that this function does not bother to check for lines
3383 ;; shorter than col.
3384 (if (eobp)
3385 (setq n max)
3386 (setq n (1+ n))
3387 (move-to-column col))))))
3388
3389 (defun verilog-insert-indices (max)
3390 "Insert a set of indices into a rectangle.
3391 The upper left corner is defined by point. Indices begin with 0
3392 and extend to the MAX - 1. If no prefix arg is given, the user
3393 is prompted for a value. The indices are surrounded by square
3394 brackets \[]. For example, the following code with the point
3395 located after the first 'a' gives:
3396
3397 a = b a[ 0] = b
3398 a = b a[ 1] = b
3399 a = b a[ 2] = b
3400 a = b a[ 3] = b
3401 a = b ==> insert-indices ==> a[ 4] = b
3402 a = b a[ 5] = b
3403 a = b a[ 6] = b
3404 a = b a[ 7] = b
3405 a = b a[ 8] = b"
3406
3407 (interactive "NMAX: ")
3408 (verilog-insert-1 "[%3d]" max))
3409
3410 (defun verilog-generate-numbers (max)
3411 "Insert a set of generated numbers into a rectangle.
3412 The upper left corner is defined by point. The numbers are padded to three
3413 digits, starting with 000 and extending to (MAX - 1). If no prefix argument
3414 is supplied, then the user is prompted for the MAX number. Consider the
3415 following code fragment:
3416
3417 buf buf buf buf000
3418 buf buf buf buf001
3419 buf buf buf buf002
3420 buf buf buf buf003
3421 buf buf ==> generate-numbers ==> buf buf004
3422 buf buf buf buf005
3423 buf buf buf buf006
3424 buf buf buf buf007
3425 buf buf buf buf008"
3426
3427 (interactive "NMAX: ")
3428 (verilog-insert-1 "%3.3d" max))
3429
3430 (defun verilog-mark-defun ()
3431 "Mark the current Verilog function (or procedure).
3432 This puts the mark at the end, and point at the beginning."
3433 (interactive)
3434 (if (featurep 'xemacs)
3435 (progn
3436 (push-mark (point))
3437 (verilog-end-of-defun)
3438 (push-mark (point))
3439 (verilog-beg-of-defun)
3440 (if (fboundp 'zmacs-activate-region)
3441 (zmacs-activate-region)))
3442 (mark-defun)))
3443
3444 (defun verilog-comment-region (start end)
3445 ; checkdoc-params: (start end)
3446 "Put the region into a Verilog comment.
3447 The comments that are in this area are \"deformed\":
3448 `*)' becomes `!(*' and `}' becomes `!{'.
3449 These deformed comments are returned to normal if you use
3450 \\[verilog-uncomment-region] to undo the commenting.
3451
3452 The commented area starts with `verilog-exclude-str-start', and ends with
3453 `verilog-exclude-str-end'. But if you change these variables,
3454 \\[verilog-uncomment-region] won't recognize the comments."
3455 (interactive "r")
3456 (save-excursion
3457 ;; Insert start and endcomments
3458 (goto-char end)
3459 (if (and (save-excursion (skip-chars-forward " \t") (eolp))
3460 (not (save-excursion (skip-chars-backward " \t") (bolp))))
3461 (forward-line 1)
3462 (beginning-of-line))
3463 (insert verilog-exclude-str-end)
3464 (setq end (point))
3465 (newline)
3466 (goto-char start)
3467 (beginning-of-line)
3468 (insert verilog-exclude-str-start)
3469 (newline)
3470 ;; Replace end-comments within commented area
3471 (goto-char end)
3472 (save-excursion
3473 (while (re-search-backward "\\*/" start t)
3474 (replace-match "*-/" t t)))
3475 (save-excursion
3476 (let ((s+1 (1+ start)))
3477 (while (re-search-backward "/\\*" s+1 t)
3478 (replace-match "/-*" t t))))))
3479
3480 (defun verilog-uncomment-region ()
3481 "Uncomment a commented area; change deformed comments back to normal.
3482 This command does nothing if the pointer is not in a commented
3483 area. See also `verilog-comment-region'."
3484 (interactive)
3485 (save-excursion
3486 (let ((start (point))
3487 (end (point)))
3488 ;; Find the boundaries of the comment
3489 (save-excursion
3490 (setq start (progn (search-backward verilog-exclude-str-start nil t)
3491 (point)))
3492 (setq end (progn (search-forward verilog-exclude-str-end nil t)
3493 (point))))
3494 ;; Check if we're really inside a comment
3495 (if (or (equal start (point)) (<= end (point)))
3496 (message "Not standing within commented area.")
3497 (progn
3498 ;; Remove endcomment
3499 (goto-char end)
3500 (beginning-of-line)
3501 (let ((pos (point)))
3502 (end-of-line)
3503 (delete-region pos (1+ (point))))
3504 ;; Change comments back to normal
3505 (save-excursion
3506 (while (re-search-backward "\\*-/" start t)
3507 (replace-match "*/" t t)))
3508 (save-excursion
3509 (while (re-search-backward "/-\\*" start t)
3510 (replace-match "/*" t t)))
3511 ;; Remove start comment
3512 (goto-char start)
3513 (beginning-of-line)
3514 (let ((pos (point)))
3515 (end-of-line)
3516 (delete-region pos (1+ (point)))))))))
3517
3518 (defun verilog-beg-of-defun ()
3519 "Move backward to the beginning of the current function or procedure."
3520 (interactive)
3521 (verilog-re-search-backward verilog-defun-re nil 'move))
3522
3523 (defun verilog-end-of-defun ()
3524 "Move forward to the end of the current function or procedure."
3525 (interactive)
3526 (verilog-re-search-forward verilog-end-defun-re nil 'move))
3527
3528 (defun verilog-get-beg-of-defun (&optional warn)
3529 (save-excursion
3530 (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
3531 (point))
3532 (t
3533 (error "%s: Can't find module beginning" (verilog-point-text))
3534 (point-max)))))
3535 (defun verilog-get-end-of-defun (&optional warn)
3536 (save-excursion
3537 (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
3538 (point))
3539 (t
3540 (error "%s: Can't find endmodule" (verilog-point-text))
3541 (point-max)))))
3542
3543 (defun verilog-label-be (&optional arg)
3544 "Label matching begin ... end, fork ... join and case ... endcase statements.
3545 With ARG, first kill any existing labels."
3546 (interactive)
3547 (let ((cnt 0)
3548 (oldpos (point))
3549 (b (progn
3550 (verilog-beg-of-defun)
3551 (point-marker)))
3552 (e (progn
3553 (verilog-end-of-defun)
3554 (point-marker))))
3555 (goto-char (marker-position b))
3556 (if (> (- e b) 200)
3557 (message "Relabeling module..."))
3558 (while (and
3559 (> (marker-position e) (point))
3560 (verilog-re-search-forward
3561 (concat
3562 "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
3563 "\\|\\(`endif\\)\\|\\(`else\\)")
3564 nil 'move))
3565 (goto-char (match-beginning 0))
3566 (let ((indent-str (verilog-indent-line)))
3567 (verilog-set-auto-endcomments indent-str 't)
3568 (end-of-line)
3569 (delete-horizontal-space))
3570 (setq cnt (1+ cnt))
3571 (if (= 9 (% cnt 10))
3572 (message "%d..." cnt)))
3573 (goto-char oldpos)
3574 (if (or
3575 (> (- e b) 200)
3576 (> cnt 20))
3577 (message "%d lines auto commented" cnt))))
3578
3579 (defun verilog-beg-of-statement ()
3580 "Move backward to beginning of statement."
3581 (interactive)
3582 ;; Move back token by token until we see the end
3583 ;; of some ealier line.
3584 (let (h)
3585 (while
3586 ;; If the current point does not begin a new
3587 ;; statement, as in the character ahead of us is a ';', or SOF
3588 ;; or the string after us unambiguously starts a statement,
3589 ;; or the token before us unambiguously ends a statement,
3590 ;; then move back a token and test again.
3591 (not (or
3592 ;; stop if beginning of buffer
3593 (bolp)
3594 ;; stop if we find a ;
3595 (= (preceding-char) ?\;)
3596 ;; stop if we see a named coverpoint
3597 (looking-at "\\w+\\W*:\\W*\\(coverpoint\\|cross\\|constraint\\)")
3598 ;; keep going if we are in the middle of a word
3599 (not (or (looking-at "\\<") (forward-word -1)))
3600 ;; stop if we see an assertion (perhaps labled)
3601 (and
3602 (looking-at "\\(\\<\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(\\<assert\\>\\)")
3603 (progn
3604 (setq h (point))
3605 (save-excursion
3606 (verilog-backward-token)
3607 (if (looking-at verilog-label-re)
3608 (setq h (point))))
3609 (goto-char h)))
3610 ;; stop if we see a complete reg, perhaps an extended one
3611 (and
3612 (looking-at verilog-complete-reg)
3613 (let* ((p (point)))
3614 (while (and (looking-at verilog-extended-complete-re)
3615 (progn (setq p (point))
3616 (verilog-backward-token)
3617 (/= p (point)))))
3618 (goto-char p)))
3619 ;; stop if we see a complete reg (previous found extended ones)
3620 (looking-at verilog-basic-complete-re)
3621 ;; stop if previous token is an ender
3622 (save-excursion
3623 (verilog-backward-token)
3624 (or
3625 (looking-at verilog-end-block-re)
3626 (looking-at verilog-preprocessor-re))))) ;; end of test
3627 (verilog-backward-syntactic-ws)
3628 (verilog-backward-token))
3629 ;; Now point is where the previous line ended.
3630 (verilog-forward-syntactic-ws)))
3631
3632 (defun verilog-beg-of-statement-1 ()
3633 "Move backward to beginning of statement."
3634 (interactive)
3635 (if (verilog-in-comment-p)
3636 (verilog-backward-syntactic-ws))
3637 (let ((pt (point)))
3638 (catch 'done
3639 (while (not (looking-at verilog-complete-reg))
3640 (setq pt (point))
3641 (verilog-backward-syntactic-ws)
3642 (if (or (bolp)
3643 (= (preceding-char) ?\;)
3644 (save-excursion
3645 (verilog-backward-token)
3646 (looking-at verilog-ends-re)))
3647 (progn
3648 (goto-char pt)
3649 (throw 'done t))
3650 (verilog-backward-token))))
3651 (verilog-forward-syntactic-ws)))
3652 ;
3653 ; (while (and
3654 ; (not (looking-at verilog-complete-reg))
3655 ; (not (bolp))
3656 ; (not (= (preceding-char) ?\;)))
3657 ; (verilog-backward-token)
3658 ; (verilog-backward-syntactic-ws)
3659 ; (setq pt (point)))
3660 ; (goto-char pt)
3661 ; ;(verilog-forward-syntactic-ws)
3662
3663 (defun verilog-end-of-statement ()
3664 "Move forward to end of current statement."
3665 (interactive)
3666 (let ((nest 0) pos)
3667 (cond
3668 ((verilog-in-directive-p)
3669 (forward-line 1)
3670 (backward-char 1))
3671
3672 ((looking-at verilog-beg-block-re)
3673 (verilog-forward-sexp))
3674
3675 ((equal (char-after) ?\})
3676 (forward-char))
3677
3678 ;; Skip to end of statement
3679 ((condition-case nil
3680 (setq pos
3681 (catch 'found
3682 (while t
3683 (forward-sexp 1)
3684 (verilog-skip-forward-comment-or-string)
3685 (if (eolp)
3686 (forward-line 1))
3687 (cond ((looking-at "[ \t]*;")
3688 (skip-chars-forward "^;")
3689 (forward-char 1)
3690 (throw 'found (point)))
3691 ((save-excursion
3692 (forward-sexp -1)
3693 (looking-at verilog-beg-block-re))
3694 (goto-char (match-beginning 0))
3695 (throw 'found nil))
3696 ((looking-at "[ \t]*)")
3697 (throw 'found (point)))
3698 ((eobp)
3699 (throw 'found (point)))
3700 )))
3701
3702 )
3703 (error nil))
3704 (if (not pos)
3705 ;; Skip a whole block
3706 (catch 'found
3707 (while t
3708 (verilog-re-search-forward verilog-end-statement-re nil 'move)
3709 (setq nest (if (match-end 1)
3710 (1+ nest)
3711 (1- nest)))
3712 (cond ((eobp)
3713 (throw 'found (point)))
3714 ((= 0 nest)
3715 (throw 'found (verilog-end-of-statement))))))
3716 pos)))))
3717
3718 (defun verilog-in-case-region-p ()
3719 "Return true if in a case region.
3720 More specifically, point @ in the line foo : @ begin"
3721 (interactive)
3722 (save-excursion
3723 (if (and
3724 (progn (verilog-forward-syntactic-ws)
3725 (looking-at "\\<begin\\>"))
3726 (progn (verilog-backward-syntactic-ws)
3727 (= (preceding-char) ?\:)))
3728 (catch 'found
3729 (let ((nest 1))
3730 (while t
3731 (verilog-re-search-backward
3732 (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
3733 "\\(\\<endcase\\>\\)\\>")
3734 nil 'move)
3735 (cond
3736 ((match-end 3)
3737 (setq nest (1+ nest)))
3738 ((match-end 2)
3739 (if (= nest 1)
3740 (throw 'found 1))
3741 (setq nest (1- nest)))
3742 (t
3743 (throw 'found (= nest 0)))))))
3744 nil)))
3745 (defun verilog-backward-up-list (arg)
3746 "Like backward-up-list, but deal with comments."
3747 (let (saved-psic parse-sexp-ignore-comments)
3748 (setq parse-sexp-ignore-comments 1)
3749 (backward-up-list arg)
3750 (setq parse-sexp-ignore-comments saved-psic)
3751 ))
3752
3753 (defun verilog-in-struct-region-p ()
3754 "Return true if in a struct region.
3755 More specifically, in a list after a struct|union keyword."
3756 (interactive)
3757 (save-excursion
3758 (let* ((state (verilog-syntax-ppss))
3759 (depth (nth 0 state)))
3760 (if depth
3761 (progn (verilog-backward-up-list depth)
3762 (verilog-beg-of-statement)
3763 (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>"))))))
3764
3765 (defun verilog-in-generate-region-p ()
3766 "Return true if in a generate region.
3767 More specifically, after a generate and before an endgenerate."
3768 (interactive)
3769 (let ((nest 1))
3770 (save-excursion
3771 (catch 'done
3772 (while (and
3773 (/= nest 0)
3774 (verilog-re-search-backward
3775 "\\<\\(module\\)\\|\\(generate\\)\\|\\(endgenerate\\)\\>" nil 'move)
3776 (cond
3777 ((match-end 1) ; module - we have crawled out
3778 (throw 'done 1))
3779 ((match-end 2) ; generate
3780 (setq nest (1- nest)))
3781 ((match-end 3) ; endgenerate
3782 (setq nest (1+ nest))))))))
3783 (= nest 0) )) ; return nest
3784
3785 (defun verilog-in-fork-region-p ()
3786 "Return true if between a fork and join."
3787 (interactive)
3788 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
3789 (nest 1))
3790 (save-excursion
3791 (while (and
3792 (/= nest 0)
3793 (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
3794 (cond
3795 ((match-end 1) ; fork
3796 (setq nest (1- nest)))
3797 ((match-end 2) ; join
3798 (setq nest (1+ nest)))))))
3799 (= nest 0) )) ; return nest
3800
3801 (defun verilog-backward-case-item (lim)
3802 "Skip backward to nearest enclosing case item.
3803 Limit search to point LIM."
3804 (interactive)
3805 (let ((str 'nil)
3806 (lim1
3807 (progn
3808 (save-excursion
3809 (verilog-re-search-backward verilog-endcomment-reason-re
3810 lim 'move)
3811 (point)))))
3812 ;; Try to find the real :
3813 (if (save-excursion (search-backward ":" lim1 t))
3814 (let ((colon 0)
3815 b e )
3816 (while
3817 (and
3818 (< colon 1)
3819 (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
3820 lim1 'move))
3821 (cond
3822 ((match-end 1) ;; [
3823 (setq colon (1+ colon))
3824 (if (>= colon 0)
3825 (error "%s: unbalanced [" (verilog-point-text))))
3826 ((match-end 2) ;; ]
3827 (setq colon (1- colon)))
3828
3829 ((match-end 3) ;; :
3830 (setq colon (1+ colon)))))
3831 ;; Skip back to beginning of case item
3832 (skip-chars-backward "\t ")
3833 (verilog-skip-backward-comment-or-string)
3834 (setq e (point))
3835 (setq b
3836 (progn
3837 (if
3838 (verilog-re-search-backward
3839 "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
3840 (progn
3841 (cond
3842 ((match-end 1)
3843 (goto-char (match-end 1))
3844 (verilog-forward-ws&directives)
3845 (if (looking-at "(")
3846 (progn
3847 (forward-sexp)
3848 (verilog-forward-ws&directives)))
3849 (point))
3850 (t
3851 (goto-char (match-end 0))
3852 (verilog-forward-ws&directives)
3853 (point))))
3854 (error "Malformed case item"))))
3855 (setq str (buffer-substring b e))
3856 (if
3857 (setq e
3858 (string-match
3859 "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3860 (setq str (concat (substring str 0 e) "...")))
3861 str)
3862 'nil)))
3863 \f
3864
3865 ;;
3866 ;; Other functions
3867 ;;
3868
3869 (defun verilog-kill-existing-comment ()
3870 "Kill auto comment on this line."
3871 (save-excursion
3872 (let* (
3873 (e (progn
3874 (end-of-line)
3875 (point)))
3876 (b (progn
3877 (beginning-of-line)
3878 (search-forward "//" e t))))
3879 (if b
3880 (delete-region (- b 2) e)))))
3881
3882 (defconst verilog-directive-nest-re
3883 (concat "\\(`else\\>\\)\\|"
3884 "\\(`endif\\>\\)\\|"
3885 "\\(`if\\>\\)\\|"
3886 "\\(`ifdef\\>\\)\\|"
3887 "\\(`ifndef\\>\\)\\|"
3888 "\\(`elsif\\>\\)"))
3889 (defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
3890 "Add ending comment with given INDENT-STR.
3891 With KILL-EXISTING-COMMENT, remove what was there before.
3892 Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
3893 Insert `// case expr ' if this line ends a case block.
3894 Insert `// ifdef FOO ' if this line ends code conditional on FOO.
3895 Insert `// NAME ' if this line ends a function, task, module,
3896 primitive or interface named NAME."
3897 (save-excursion
3898 (cond
3899 (; Comment close preprocessor directives
3900 (and
3901 (looking-at "\\(`endif\\)\\|\\(`else\\)")
3902 (or kill-existing-comment
3903 (not (save-excursion
3904 (end-of-line)
3905 (search-backward "//" (point-at-bol) t)))))
3906 (let ((nest 1) b e
3907 m
3908 (else (if (match-end 2) "!" " ")))
3909 (end-of-line)
3910 (if kill-existing-comment
3911 (verilog-kill-existing-comment))
3912 (delete-horizontal-space)
3913 (save-excursion
3914 (backward-sexp 1)
3915 (while (and (/= nest 0)
3916 (verilog-re-search-backward verilog-directive-nest-re nil 'move))
3917 (cond
3918 ((match-end 1) ; `else
3919 (if (= nest 1)
3920 (setq else "!")))
3921 ((match-end 2) ; `endif
3922 (setq nest (1+ nest)))
3923 ((match-end 3) ; `if
3924 (setq nest (1- nest)))
3925 ((match-end 4) ; `ifdef
3926 (setq nest (1- nest)))
3927 ((match-end 5) ; `ifndef
3928 (setq nest (1- nest)))
3929 ((match-end 6) ; `elsif
3930 (if (= nest 1)
3931 (progn
3932 (setq else "!")
3933 (setq nest 0))))))
3934 (if (match-end 0)
3935 (setq
3936 m (buffer-substring
3937 (match-beginning 0)
3938 (match-end 0))
3939 b (progn
3940 (skip-chars-forward "^ \t")
3941 (verilog-forward-syntactic-ws)
3942 (point))
3943 e (progn
3944 (skip-chars-forward "a-zA-Z0-9_")
3945 (point)))))
3946 (if b
3947 (if (> (count-lines (point) b) verilog-minimum-comment-distance)
3948 (insert (concat " // " else m " " (buffer-substring b e))))
3949 (progn
3950 (insert " // unmatched `else, `elsif or `endif")
3951 (ding 't)))))
3952
3953 (; Comment close case/class/function/task/module and named block
3954 (and (looking-at "\\<end")
3955 (or kill-existing-comment
3956 (not (save-excursion
3957 (end-of-line)
3958 (search-backward "//" (point-at-bol) t)))))
3959 (let ((type (car indent-str)))
3960 (unless (eq type 'declaration)
3961 (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
3962 (if (looking-at verilog-end-block-ordered-re)
3963 (cond
3964 (;- This is a case block; search back for the start of this case
3965 (match-end 1) ;; of verilog-end-block-ordered-re
3966
3967 (let ((err 't)
3968 (str "UNMATCHED!!"))
3969 (save-excursion
3970 (verilog-leap-to-head)
3971 (cond
3972 ((looking-at "\\<randcase\\>")
3973 (setq str "randcase")
3974 (setq err nil))
3975 ((looking-at "\\(\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?\\)")
3976 (goto-char (match-end 0))
3977 (setq str (concat (match-string 0) " " (verilog-get-expr)))
3978 (setq err nil))
3979 ))
3980 (end-of-line)
3981 (if kill-existing-comment
3982 (verilog-kill-existing-comment))
3983 (delete-horizontal-space)
3984 (insert (concat " // " str ))
3985 (if err (ding 't))))
3986
3987 (;- This is a begin..end block
3988 (match-end 2) ;; of verilog-end-block-ordered-re
3989 (let ((str " // UNMATCHED !!")
3990 (err 't)
3991 (here (point))
3992 there
3993 cntx)
3994 (save-excursion
3995 (verilog-leap-to-head)
3996 (setq there (point))
3997 (if (not (match-end 0))
3998 (progn
3999 (goto-char here)
4000 (end-of-line)
4001 (if kill-existing-comment
4002 (verilog-kill-existing-comment))
4003 (delete-horizontal-space)
4004 (insert str)
4005 (ding 't))
4006 (let ((lim
4007 (save-excursion (verilog-beg-of-defun) (point)))
4008 (here (point)))
4009 (cond
4010 (;-- handle named block differently
4011 (looking-at verilog-named-block-re)
4012 (search-forward ":")
4013 (setq there (point))
4014 (setq str (verilog-get-expr))
4015 (setq err nil)
4016 (setq str (concat " // block: " str )))
4017
4018 ((verilog-in-case-region-p) ;-- handle case item differently
4019 (goto-char here)
4020 (setq str (verilog-backward-case-item lim))
4021 (setq there (point))
4022 (setq err nil)
4023 (setq str (concat " // case: " str )))
4024
4025 (;- try to find "reason" for this begin
4026 (cond
4027 (;
4028 (eq here (progn
4029 ;; (verilog-backward-token)
4030 (verilog-beg-of-statement)
4031 (point)))
4032 (setq err nil)
4033 (setq str ""))
4034 ((looking-at verilog-endcomment-reason-re)
4035 (setq there (match-end 0))
4036 (setq cntx (concat (match-string 0) " "))
4037 (cond
4038 (;- begin
4039 (match-end 1)
4040 (setq err nil)
4041 (save-excursion
4042 (if (and (verilog-continued-line)
4043 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
4044 (progn
4045 (goto-char (match-end 0))
4046 (setq there (point))
4047 (setq str
4048 (concat " // " (match-string 0) " " (verilog-get-expr))))
4049 (setq str ""))))
4050
4051 (;- else
4052 (match-end 2)
4053 (let ((nest 0)
4054 ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
4055 (catch 'skip
4056 (while (verilog-re-search-backward reg nil 'move)
4057 (cond
4058 ((match-end 1) ; begin
4059 (setq nest (1- nest)))
4060 ((match-end 2) ; end
4061 (setq nest (1+ nest)))
4062 ((match-end 3)
4063 (if (= 0 nest)
4064 (progn
4065 (goto-char (match-end 0))
4066 (setq there (point))
4067 (setq err nil)
4068 (setq str (verilog-get-expr))
4069 (setq str (concat " // else: !if" str ))
4070 (throw 'skip 1))))
4071 ((match-end 4)
4072 (if (= 0 nest)
4073 (progn
4074 (goto-char (match-end 0))
4075 (setq there (point))
4076 (setq err nil)
4077 (setq str (verilog-get-expr))
4078 (setq str (concat " // else: !assert " str ))
4079 (throw 'skip 1)))))))))
4080 (;- end else
4081 (match-end 3)
4082 (goto-char there)
4083 (let ((nest 0)
4084 (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
4085 (catch 'skip
4086 (while (verilog-re-search-backward reg nil 'move)
4087 (cond
4088 ((match-end 1) ; begin
4089 (setq nest (1- nest)))
4090 ((match-end 2) ; end
4091 (setq nest (1+ nest)))
4092 ((match-end 3)
4093 (if (= 0 nest)
4094 (progn
4095 (goto-char (match-end 0))
4096 (setq there (point))
4097 (setq err nil)
4098 (setq str (verilog-get-expr))
4099 (setq str (concat " // else: !if" str ))
4100 (throw 'skip 1))))
4101 ((match-end 4)
4102 (if (= 0 nest)
4103 (progn
4104 (goto-char (match-end 0))
4105 (setq there (point))
4106 (setq err nil)
4107 (setq str (verilog-get-expr))
4108 (setq str (concat " // else: !assert " str ))
4109 (throw 'skip 1)))))))))
4110
4111 (; always_comb, always_ff, always_latch
4112 (or (match-end 4) (match-end 5) (match-end 6))
4113 (goto-char (match-end 0))
4114 (setq there (point))
4115 (setq err nil)
4116 (setq str (concat " // " cntx )))
4117
4118 (;- task/function/initial et cetera
4119 t
4120 (match-end 0)
4121 (goto-char (match-end 0))
4122 (setq there (point))
4123 (setq err nil)
4124 (setq str (concat " // " cntx (verilog-get-expr))))
4125
4126 (;-- otherwise...
4127 (setq str " // auto-endcomment confused "))))
4128
4129 ((and
4130 (verilog-in-case-region-p) ;-- handle case item differently
4131 (progn
4132 (setq there (point))
4133 (goto-char here)
4134 (setq str (verilog-backward-case-item lim))))
4135 (setq err nil)
4136 (setq str (concat " // case: " str )))
4137
4138 ((verilog-in-fork-region-p)
4139 (setq err nil)
4140 (setq str " // fork branch" ))
4141
4142 ((looking-at "\\<end\\>")
4143 ;; HERE
4144 (forward-word 1)
4145 (verilog-forward-syntactic-ws)
4146 (setq err nil)
4147 (setq str (verilog-get-expr))
4148 (setq str (concat " // " cntx str )))
4149
4150 ))))
4151 (goto-char here)
4152 (end-of-line)
4153 (if kill-existing-comment
4154 (verilog-kill-existing-comment))
4155 (delete-horizontal-space)
4156 (if (or err
4157 (> (count-lines here there) verilog-minimum-comment-distance))
4158 (insert str))
4159 (if err (ding 't))
4160 ))))
4161 (;- this is endclass, which can be nested
4162 (match-end 11) ;; of verilog-end-block-ordered-re
4163 ;;(goto-char there)
4164 (let ((nest 0)
4165 (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
4166 string)
4167 (save-excursion
4168 (catch 'skip
4169 (while (verilog-re-search-backward reg nil 'move)
4170 (cond
4171 ((match-end 3) ; endclass
4172 (ding 't)
4173 (setq string "unmatched endclass")
4174 (throw 'skip 1))
4175
4176 ((match-end 2) ; endclass
4177 (setq nest (1+ nest)))
4178
4179 ((match-end 1) ; class
4180 (setq nest (1- nest))
4181 (if (< nest 0)
4182 (progn
4183 (goto-char (match-end 0))
4184 (let (b e)
4185 (setq b (progn
4186 (skip-chars-forward "^ \t")
4187 (verilog-forward-ws&directives)
4188 (point))
4189 e (progn
4190 (skip-chars-forward "a-zA-Z0-9_")
4191 (point)))
4192 (setq string (buffer-substring b e)))
4193 (throw 'skip 1))))
4194 ))))
4195 (end-of-line)
4196 (insert (concat " // " string ))))
4197
4198 (;- this is end{function,generate,task,module,primitive,table,generate}
4199 ;- which can not be nested.
4200 t
4201 (let (string reg (name-re nil))
4202 (end-of-line)
4203 (if kill-existing-comment
4204 (save-match-data
4205 (verilog-kill-existing-comment)))
4206 (delete-horizontal-space)
4207 (backward-sexp)
4208 (cond
4209 ((match-end 5) ;; of verilog-end-block-ordered-re
4210 (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
4211 (setq name-re "\\w+\\s-*(")
4212 )
4213 ((match-end 6) ;; of verilog-end-block-ordered-re
4214 (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
4215 ((match-end 7) ;; of verilog-end-block-ordered-re
4216 (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
4217 ((match-end 8) ;; of verilog-end-block-ordered-re
4218 (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4219 ((match-end 9) ;; of verilog-end-block-ordered-re
4220 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
4221 ((match-end 10) ;; of verilog-end-block-ordered-re
4222 (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4223 ((match-end 11) ;; of verilog-end-block-ordered-re
4224 (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4225 ((match-end 12) ;; of verilog-end-block-ordered-re
4226 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4227 ((match-end 13) ;; of verilog-end-block-ordered-re
4228 (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4229 ((match-end 14) ;; of verilog-end-block-ordered-re
4230 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4231 ((match-end 15) ;; of verilog-end-block-ordered-re
4232 (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
4233
4234 (t (error "Problem in verilog-set-auto-endcomments")))
4235 (let (b e)
4236 (save-excursion
4237 (verilog-re-search-backward reg nil 'move)
4238 (cond
4239 ((match-end 1)
4240 (setq b (progn
4241 (skip-chars-forward "^ \t")
4242 (verilog-forward-ws&directives)
4243 (if (looking-at "static\\|automatic")
4244 (progn
4245 (goto-char (match-end 0))
4246 (verilog-forward-ws&directives)))
4247 (if (and name-re (verilog-re-search-forward name-re nil 'move))
4248 (progn
4249 (goto-char (match-beginning 0))
4250 (verilog-forward-ws&directives)))
4251 (point))
4252 e (progn
4253 (skip-chars-forward "a-zA-Z0-9_")
4254 (point)))
4255 (setq string (buffer-substring b e)))
4256 (t
4257 (ding 't)
4258 (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
4259 (end-of-line)
4260 (insert (concat " // " string )))
4261 ))))))))))
4262
4263 (defun verilog-get-expr()
4264 "Grab expression at point, e.g, case ( a | b & (c ^d))."
4265 (let* ((b (progn
4266 (verilog-forward-syntactic-ws)
4267 (skip-chars-forward " \t")
4268 (point)))
4269 (e (let ((par 1))
4270 (cond
4271 ((looking-at "@")
4272 (forward-char 1)
4273 (verilog-forward-syntactic-ws)
4274 (if (looking-at "(")
4275 (progn
4276 (forward-char 1)
4277 (while (and (/= par 0)
4278 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4279 (cond
4280 ((match-end 1)
4281 (setq par (1+ par)))
4282 ((match-end 2)
4283 (setq par (1- par)))))))
4284 (point))
4285 ((looking-at "(")
4286 (forward-char 1)
4287 (while (and (/= par 0)
4288 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4289 (cond
4290 ((match-end 1)
4291 (setq par (1+ par)))
4292 ((match-end 2)
4293 (setq par (1- par)))))
4294 (point))
4295 ((looking-at "\\[")
4296 (forward-char 1)
4297 (while (and (/= par 0)
4298 (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
4299 (cond
4300 ((match-end 1)
4301 (setq par (1+ par)))
4302 ((match-end 2)
4303 (setq par (1- par)))))
4304 (verilog-forward-syntactic-ws)
4305 (skip-chars-forward "^ \t\n\f")
4306 (point))
4307 ((looking-at "/[/\\*]")
4308 b)
4309 ('t
4310 (skip-chars-forward "^: \t\n\f")
4311 (point)))))
4312 (str (buffer-substring b e)))
4313 (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
4314 (setq str (concat (substring str 0 e) "...")))
4315 str))
4316
4317 (defun verilog-expand-vector ()
4318 "Take a signal vector on the current line and expand it to multiple lines.
4319 Useful for creating tri's and other expanded fields."
4320 (interactive)
4321 (verilog-expand-vector-internal "[" "]"))
4322
4323 (defun verilog-expand-vector-internal (bra ket)
4324 "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
4325 (save-excursion
4326 (forward-line 0)
4327 (let ((signal-string (buffer-substring (point)
4328 (progn
4329 (end-of-line) (point)))))
4330 (if (string-match
4331 (concat "\\(.*\\)"
4332 (regexp-quote bra)
4333 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
4334 (regexp-quote ket)
4335 "\\(.*\\)$") signal-string)
4336 (let* ((sig-head (match-string 1 signal-string))
4337 (vec-start (string-to-number (match-string 2 signal-string)))
4338 (vec-end (if (= (match-beginning 3) (match-end 3))
4339 vec-start
4340 (string-to-number
4341 (substring signal-string (1+ (match-beginning 3))
4342 (match-end 3)))))
4343 (vec-range
4344 (if (= (match-beginning 4) (match-end 4))
4345 1
4346 (string-to-number
4347 (substring signal-string (+ 2 (match-beginning 4))
4348 (match-end 4)))))
4349 (sig-tail (match-string 5 signal-string))
4350 vec)
4351 ;; Decode vectors
4352 (setq vec nil)
4353 (if (< vec-range 0)
4354 (let ((tmp vec-start))
4355 (setq vec-start vec-end
4356 vec-end tmp
4357 vec-range (- vec-range))))
4358 (if (< vec-end vec-start)
4359 (while (<= vec-end vec-start)
4360 (setq vec (append vec (list vec-start)))
4361 (setq vec-start (- vec-start vec-range)))
4362 (while (<= vec-start vec-end)
4363 (setq vec (append vec (list vec-start)))
4364 (setq vec-start (+ vec-start vec-range))))
4365 ;;
4366 ;; Delete current line
4367 (delete-region (point) (progn (forward-line 0) (point)))
4368 ;;
4369 ;; Expand vector
4370 (while vec
4371 (insert (concat sig-head bra
4372 (int-to-string (car vec)) ket sig-tail "\n"))
4373 (setq vec (cdr vec)))
4374 (delete-char -1)
4375 ;;
4376 )))))
4377
4378 (defun verilog-strip-comments ()
4379 "Strip all comments from the Verilog code."
4380 (interactive)
4381 (goto-char (point-min))
4382 (while (re-search-forward "//" nil t)
4383 (if (verilog-within-string)
4384 (re-search-forward "\"" nil t)
4385 (if (verilog-in-star-comment-p)
4386 (re-search-forward "\*/" nil t)
4387 (let ((bpt (- (point) 2)))
4388 (end-of-line)
4389 (delete-region bpt (point))))))
4390 ;;
4391 (goto-char (point-min))
4392 (while (re-search-forward "/\\*" nil t)
4393 (if (verilog-within-string)
4394 (re-search-forward "\"" nil t)
4395 (let ((bpt (- (point) 2)))
4396 (re-search-forward "\\*/")
4397 (delete-region bpt (point))))))
4398
4399 (defun verilog-one-line ()
4400 "Convert structural Verilog instances to occupy one line."
4401 (interactive)
4402 (goto-char (point-min))
4403 (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
4404 (replace-match "\\1 " nil nil)))
4405
4406 (defun verilog-linter-name ()
4407 "Return name of linter, either surelint or verilint."
4408 (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4409 compile-command))
4410 (lint-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4411 verilog-linter)))
4412 (cond ((equal compile-word1 "surelint") `surelint)
4413 ((equal compile-word1 "verilint") `verilint)
4414 ((equal lint-word1 "surelint") `surelint)
4415 ((equal lint-word1 "verilint") `verilint)
4416 (t `surelint)))) ;; back compatibility
4417
4418 (defun verilog-lint-off ()
4419 "Convert a Verilog linter warning line into a disable statement.
4420 For example:
4421 pci_bfm_null.v, line 46: Unused input: pci_rst_
4422 becomes a comment for the appropriate tool.
4423
4424 The first word of the `compile-command' or `verilog-linter'
4425 variables is used to determine which product is being used.
4426
4427 See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
4428 (interactive)
4429 (let ((linter (verilog-linter-name)))
4430 (cond ((equal linter `surelint)
4431 (verilog-surelint-off))
4432 ((equal linter `verilint)
4433 (verilog-verilint-off))
4434 (t (error "Linter name not set")))))
4435
4436 (defvar compilation-last-buffer)
4437 (defvar next-error-last-buffer)
4438
4439 (defun verilog-surelint-off ()
4440 "Convert a SureLint warning line into a disable statement.
4441 Run from Verilog source window; assumes there is a *compile* buffer
4442 with point set appropriately.
4443
4444 For example:
4445 WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
4446 becomes:
4447 // surefire lint_line_off UDDONX"
4448 (interactive)
4449 (let ((buff (if (boundp 'next-error-last-buffer)
4450 next-error-last-buffer
4451 compilation-last-buffer)))
4452 (when (buffer-live-p buff)
4453 ;; FIXME with-current-buffer?
4454 (save-excursion
4455 (switch-to-buffer buff)
4456 (beginning-of-line)
4457 (when
4458 (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
4459 (let* ((code (match-string 2))
4460 (file (match-string 3))
4461 (line (match-string 4))
4462 (buffer (get-file-buffer file))
4463 dir filename)
4464 (unless buffer
4465 (progn
4466 (setq buffer
4467 (and (file-exists-p file)
4468 (find-file-noselect file)))
4469 (or buffer
4470 (let* ((pop-up-windows t))
4471 (let ((name (expand-file-name
4472 (read-file-name
4473 (format "Find this error in: (default %s) "
4474 file)
4475 dir file t))))
4476 (if (file-directory-p name)
4477 (setq name (expand-file-name filename name)))
4478 (setq buffer
4479 (and (file-exists-p name)
4480 (find-file-noselect name))))))))
4481 (switch-to-buffer buffer)
4482 (goto-char (point-min))
4483 (forward-line (- (string-to-number line)))
4484 (end-of-line)
4485 (catch 'already
4486 (cond
4487 ((verilog-in-slash-comment-p)
4488 (re-search-backward "//")
4489 (cond
4490 ((looking-at "// surefire lint_off_line ")
4491 (goto-char (match-end 0))
4492 (let ((lim (point-at-eol)))
4493 (if (re-search-forward code lim 'move)
4494 (throw 'already t)
4495 (insert (concat " " code)))))
4496 (t
4497 )))
4498 ((verilog-in-star-comment-p)
4499 (re-search-backward "/\*")
4500 (insert (format " // surefire lint_off_line %6s" code )))
4501 (t
4502 (insert (format " // surefire lint_off_line %6s" code ))
4503 )))))))))
4504
4505 (defun verilog-verilint-off ()
4506 "Convert a Verilint warning line into a disable statement.
4507
4508 For example:
4509 (W240) pci_bfm_null.v, line 46: Unused input: pci_rst_
4510 becomes:
4511 //Verilint 240 off // WARNING: Unused input"
4512 (interactive)
4513 (save-excursion
4514 (beginning-of-line)
4515 (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
4516 (replace-match (format
4517 ;; %3s makes numbers 1-999 line up nicely
4518 "\\1//Verilint %3s off // WARNING: \\3"
4519 (match-string 2)))
4520 (beginning-of-line)
4521 (verilog-indent-line))))
4522
4523 (defun verilog-auto-save-compile ()
4524 "Update automatics with \\[verilog-auto], save the buffer, and compile."
4525 (interactive)
4526 (verilog-auto) ; Always do it for safety
4527 (save-buffer)
4528 (compile compile-command))
4529
4530 (defun verilog-preprocess (&optional command filename)
4531 "Preprocess the buffer, similar to `compile', but leave output in Verilog-Mode.
4532 Takes optional COMMAND or defaults to `verilog-preprocessor', and
4533 FILENAME or defaults to `buffer-file-name`."
4534 (interactive
4535 (list
4536 (let ((default (verilog-expand-command verilog-preprocessor)))
4537 (set (make-local-variable `verilog-preprocessor)
4538 (read-from-minibuffer "Run Preprocessor (like this): "
4539 default nil nil
4540 'verilog-preprocess-history default)))))
4541 (unless command (setq command (verilog-expand-command verilog-preprocessor)))
4542 (let* ((fontlocked (and (boundp 'font-lock-mode) font-lock-mode))
4543 (dir (file-name-directory (or filename buffer-file-name)))
4544 (file (file-name-nondirectory (or filename buffer-file-name)))
4545 (cmd (concat "cd " dir "; " command " " file)))
4546 (with-output-to-temp-buffer "*Verilog-Preprocessed*"
4547 (with-current-buffer (get-buffer "*Verilog-Preprocessed*")
4548 (insert (concat "// " cmd "\n"))
4549 (shell-command cmd "*Verilog-Preprocessed*")
4550 (verilog-mode)
4551 ;; Without this force, it takes a few idle seconds
4552 ;; to get the color, which is very jarring
4553 (when fontlocked (font-lock-fontify-buffer))))))
4554 \f
4555
4556 ;;
4557 ;; Batch
4558 ;;
4559
4560 (defmacro verilog-batch-error-wrapper (&rest body)
4561 "Execute BODY and add error prefix to any errors found.
4562 This lets programs calling batch mode to easily extract error messages."
4563 `(condition-case err
4564 (progn ,@body)
4565 (error
4566 (error "%%Error: %s%s" (error-message-string err)
4567 (if (featurep 'xemacs) "\n" ""))))) ;; XEmacs forgets to add a newline
4568
4569 (defun verilog-batch-execute-func (funref)
4570 "Internal processing of a batch command, running FUNREF on all command arguments."
4571 (verilog-batch-error-wrapper
4572 ;; Setting global variables like that is *VERY NASTY* !!! --Stef
4573 ;; However, this function is called only when Emacs is being used as
4574 ;; a standalone language instead of as an editor, so we'll live.
4575 ;;
4576 ;; General globals needed
4577 (setq make-backup-files nil)
4578 (setq-default make-backup-files nil)
4579 (setq enable-local-variables t)
4580 (setq enable-local-eval t)
4581 ;; Make sure any sub-files we read get proper mode
4582 (setq-default major-mode 'verilog-mode)
4583 ;; Ditto files already read in
4584 (mapc (lambda (buf)
4585 (when (buffer-file-name buf)
4586 (with-current-buffer buf
4587 (verilog-mode))))
4588 (buffer-list))
4589 ;; Process the files
4590 (mapcar '(lambda (buf)
4591 (when (buffer-file-name buf)
4592 (save-excursion
4593 (if (not (file-exists-p (buffer-file-name buf)))
4594 (error
4595 (concat "File not found: " (buffer-file-name buf))))
4596 (message (concat "Processing " (buffer-file-name buf)))
4597 (set-buffer buf)
4598 (funcall funref)
4599 (save-buffer))))
4600 (buffer-list))))
4601
4602 (defun verilog-batch-auto ()
4603 "For use with --batch, perform automatic expansions as a stand-alone tool.
4604 This sets up the appropriate Verilog mode environment, updates automatics
4605 with \\[verilog-auto] on all command-line files, and saves the buffers.
4606 For proper results, multiple filenames need to be passed on the command
4607 line in bottom-up order."
4608 (unless noninteractive
4609 (error "Use verilog-batch-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4610 (verilog-batch-execute-func `verilog-auto))
4611
4612 (defun verilog-batch-delete-auto ()
4613 "For use with --batch, perform automatic deletion as a stand-alone tool.
4614 This sets up the appropriate Verilog mode environment, deletes automatics
4615 with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
4616 (unless noninteractive
4617 (error "Use verilog-batch-delete-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4618 (verilog-batch-execute-func `verilog-delete-auto))
4619
4620 (defun verilog-batch-inject-auto ()
4621 "For use with --batch, perform automatic injection as a stand-alone tool.
4622 This sets up the appropriate Verilog mode environment, injects new automatics
4623 with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
4624 For proper results, multiple filenames need to be passed on the command
4625 line in bottom-up order."
4626 (unless noninteractive
4627 (error "Use verilog-batch-inject-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4628 (verilog-batch-execute-func `verilog-inject-auto))
4629
4630 (defun verilog-batch-indent ()
4631 "For use with --batch, reindent an a entire file as a stand-alone tool.
4632 This sets up the appropriate Verilog mode environment, calls
4633 \\[verilog-indent-buffer] on all command-line files, and saves the buffers."
4634 (unless noninteractive
4635 (error "Use verilog-batch-indent only with --batch")) ;; Otherwise we'd mess up buffer modes
4636 (verilog-batch-execute-func `verilog-indent-buffer))
4637 \f
4638
4639 ;;
4640 ;; Indentation
4641 ;;
4642 (defconst verilog-indent-alist
4643 '((block . (+ ind verilog-indent-level))
4644 (case . (+ ind verilog-case-indent))
4645 (cparenexp . (+ ind verilog-indent-level))
4646 (cexp . (+ ind verilog-cexp-indent))
4647 (defun . verilog-indent-level-module)
4648 (declaration . verilog-indent-level-declaration)
4649 (directive . (verilog-calculate-indent-directive))
4650 (tf . verilog-indent-level)
4651 (behavioral . (+ verilog-indent-level-behavioral verilog-indent-level-module))
4652 (statement . ind)
4653 (cpp . 0)
4654 (comment . (verilog-comment-indent))
4655 (unknown . 3)
4656 (string . 0)))
4657
4658 (defun verilog-continued-line-1 (lim)
4659 "Return true if this is a continued line.
4660 Set point to where line starts. Limit search to point LIM."
4661 (let ((continued 't))
4662 (if (eq 0 (forward-line -1))
4663 (progn
4664 (end-of-line)
4665 (verilog-backward-ws&directives lim)
4666 (if (bobp)
4667 (setq continued nil)
4668 (setq continued (verilog-backward-token))))
4669 (setq continued nil))
4670 continued))
4671
4672 (defun verilog-calculate-indent ()
4673 "Calculate the indent of the current Verilog line.
4674 Examine previous lines. Once a line is found that is definitive as to the
4675 type of the current line, return that lines' indent level and its type.
4676 Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
4677 (save-excursion
4678 (let* ((starting_position (point))
4679 (par 0)
4680 (begin (looking-at "[ \t]*begin\\>"))
4681 (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
4682 (type (catch 'nesting
4683 ;; Keep working backwards until we can figure out
4684 ;; what type of statement this is.
4685 ;; Basically we need to figure out
4686 ;; 1) if this is a continuation of the previous line;
4687 ;; 2) are we in a block scope (begin..end)
4688
4689 ;; if we are in a comment, done.
4690 (if (verilog-in-star-comment-p)
4691 (throw 'nesting 'comment))
4692
4693 ;; if we have a directive, done.
4694 (if (save-excursion (beginning-of-line)
4695 (and (looking-at verilog-directive-re-1)
4696 (not (or (looking-at "[ \t]*`ovm_")
4697 (looking-at "[ \t]*`vmm_")))))
4698 (throw 'nesting 'directive))
4699 ;; indent structs as if there were module level
4700 (if (verilog-in-struct-p)
4701 (throw 'nesting 'block))
4702
4703 ;; unless we are in the newfangled coverpoint or constraint blocks
4704 ;; if we are in a parenthesized list, and the user likes to indent these, return.
4705 (if (and
4706 verilog-indent-lists
4707 (verilog-in-paren)
4708 (not (verilog-in-coverage-p))
4709 )
4710 (progn (setq par 1)
4711 (throw 'nesting 'block)))
4712
4713 ;; See if we are continuing a previous line
4714 (while t
4715 ;; trap out if we crawl off the top of the buffer
4716 (if (bobp) (throw 'nesting 'cpp))
4717
4718 (if (verilog-continued-line-1 lim)
4719 (let ((sp (point)))
4720 (if (and
4721 (not (looking-at verilog-complete-reg))
4722 (verilog-continued-line-1 lim))
4723 (progn (goto-char sp)
4724 (throw 'nesting 'cexp))
4725
4726 (goto-char sp))
4727
4728 (if (and begin
4729 (not verilog-indent-begin-after-if)
4730 (looking-at verilog-no-indent-begin-re))
4731 (progn
4732 (beginning-of-line)
4733 (skip-chars-forward " \t")
4734 (throw 'nesting 'statement))
4735 (progn
4736 (throw 'nesting 'cexp))))
4737 ;; not a continued line
4738 (goto-char starting_position))
4739
4740 (if (looking-at "\\<else\\>")
4741 ;; search back for governing if, striding across begin..end pairs
4742 ;; appropriately
4743 (let ((elsec 1))
4744 (while (verilog-re-search-backward verilog-ends-re nil 'move)
4745 (cond
4746 ((match-end 1) ; else, we're in deep
4747 (setq elsec (1+ elsec)))
4748 ((match-end 2) ; if
4749 (setq elsec (1- elsec))
4750 (if (= 0 elsec)
4751 (if verilog-align-ifelse
4752 (throw 'nesting 'statement)
4753 (progn ;; back up to first word on this line
4754 (beginning-of-line)
4755 (verilog-forward-syntactic-ws)
4756 (throw 'nesting 'statement)))))
4757 ((match-end 3) ; assert block
4758 (setq elsec (1- elsec))
4759 (verilog-beg-of-statement) ;; doesn't get to beginning
4760 (if (looking-at verilog-property-re)
4761 (throw 'nesting 'statement) ; We don't need an endproperty for these
4762 (throw 'nesting 'block) ;We still need a endproperty
4763 ))
4764 (t ; endblock
4765 ; try to leap back to matching outward block by striding across
4766 ; indent level changing tokens then immediately
4767 ; previous line governs indentation.
4768 (let (( reg) (nest 1))
4769 ;; verilog-ends => else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
4770 (cond
4771 ((match-end 4) ; end
4772 ;; Search back for matching begin
4773 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
4774 ((match-end 5) ; endcase
4775 ;; Search back for matching case
4776 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4777 ((match-end 6) ; endfunction
4778 ;; Search back for matching function
4779 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4780 ((match-end 7) ; endtask
4781 ;; Search back for matching task
4782 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
4783 ((match-end 8) ; endspecify
4784 ;; Search back for matching specify
4785 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4786 ((match-end 9) ; endtable
4787 ;; Search back for matching table
4788 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4789 ((match-end 10) ; endgenerate
4790 ;; Search back for matching generate
4791 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4792 ((match-end 11) ; joins
4793 ;; Search back for matching fork
4794 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
4795 ((match-end 12) ; class
4796 ;; Search back for matching class
4797 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4798 ((match-end 13) ; covergroup
4799 ;; Search back for matching covergroup
4800 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
4801 (catch 'skip
4802 (while (verilog-re-search-backward reg nil 'move)
4803 (cond
4804 ((match-end 1) ; begin
4805 (setq nest (1- nest))
4806 (if (= 0 nest)
4807 (throw 'skip 1)))
4808 ((match-end 2) ; end
4809 (setq nest (1+ nest)))))
4810 )))))))
4811 (throw 'nesting (verilog-calc-1)))
4812 );; catch nesting
4813 );; type
4814 )
4815 ;; Return type of block and indent level.
4816 (if (not type)
4817 (setq type 'cpp))
4818 (if (> par 0) ; Unclosed Parenthesis
4819 (list 'cparenexp par)
4820 (cond
4821 ((eq type 'case)
4822 (list type (verilog-case-indent-level)))
4823 ((eq type 'statement)
4824 (list type (current-column)))
4825 ((eq type 'defun)
4826 (list type 0))
4827 (t
4828 (list type (verilog-current-indent-level))))))))
4829
4830 (defun verilog-wai ()
4831 "Show matching nesting block for debugging."
4832 (interactive)
4833 (save-excursion
4834 (let* ((type (verilog-calc-1))
4835 depth)
4836 ;; Return type of block and indent level.
4837 (if (not type)
4838 (setq type 'cpp))
4839 (if (and
4840 verilog-indent-lists
4841 (not(or (verilog-in-coverage-p)
4842 (verilog-in-struct-p)))
4843 (verilog-in-paren))
4844 (setq depth 1)
4845 (cond
4846 ((eq type 'case)
4847 (setq depth (verilog-case-indent-level)))
4848 ((eq type 'statement)
4849 (setq depth (current-column)))
4850 ((eq type 'defun)
4851 (setq depth 0))
4852 (t
4853 (setq depth (verilog-current-indent-level)))))
4854 (message "You are at nesting %s depth %d" type depth))))
4855
4856 (defun verilog-calc-1 ()
4857 (catch 'nesting
4858 (let ((re (concat "\\({\\|}\\|" verilog-indent-re "\\)")))
4859 (while (verilog-re-search-backward re nil 'move)
4860 (catch 'continue
4861 (cond
4862 ((equal (char-after) ?\{)
4863 (if (verilog-at-constraint-p)
4864 (throw 'nesting 'block)))
4865
4866 ((equal (char-after) ?\})
4867 (let ((there (verilog-at-close-constraint-p)))
4868 (if there ;; we are at the } that closes a constraint. Find the { that opens it
4869 (progn
4870 (forward-char 1)
4871 (backward-list 1)
4872 (verilog-beg-of-statement)))))
4873
4874 ((looking-at verilog-beg-block-re-ordered)
4875 (cond
4876 ((match-end 2) ; *sigh* could be "unique case" or "priority casex"
4877 (let ((here (point)))
4878 (verilog-beg-of-statement)
4879 (if (looking-at verilog-extended-case-re)
4880 (throw 'nesting 'case)
4881 (goto-char here)))
4882 (throw 'nesting 'case))
4883
4884 ((match-end 4) ; *sigh* could be "disable fork"
4885 (let ((here (point)))
4886 (verilog-beg-of-statement)
4887 (if (or (looking-at verilog-disable-fork-re)
4888 (looking-at verilog-fork-wait-re))
4889 t ; this is a normal statement
4890 (progn ; or is fork, starts a new block
4891 (goto-char here)
4892 (throw 'nesting 'block)))))
4893
4894 ((match-end 27) ; *sigh* might be a clocking declaration
4895 (let ((here (point)))
4896 (if (verilog-in-paren)
4897 t ; this is a normal statement
4898 (progn ; or is fork, starts a new block
4899 (goto-char here)
4900 (throw 'nesting 'block)))))
4901
4902 ;; need to consider typedef struct here...
4903 ((looking-at "\\<class\\|struct\\|function\\|task\\>")
4904 ; *sigh* These words have an optional prefix:
4905 ; extern {virtual|protected}? function a();
4906 ; typedef class foo;
4907 ; and we don't want to confuse this with
4908 ; function a();
4909 ; property
4910 ; ...
4911 ; endfunction
4912 (verilog-beg-of-statement)
4913 (if (looking-at verilog-beg-block-re-ordered)
4914 (throw 'nesting 'block)
4915 (throw 'nesting 'defun)))
4916
4917 ((looking-at "\\<property\\>")
4918 ; *sigh*
4919 ; {assert|assume|cover} property (); are complete
4920 ; and could also be labeled: - foo: assert property
4921 ; but
4922 ; property ID () ... needs end_property
4923 (verilog-beg-of-statement)
4924 (if (looking-at verilog-property-re)
4925 (throw 'continue 'statement) ; We don't need an endproperty for these
4926 (throw 'nesting 'block) ;We still need a endproperty
4927 ))
4928
4929 (t (throw 'nesting 'block))))
4930
4931 ((looking-at verilog-end-block-re)
4932 (verilog-leap-to-head)
4933 (if (verilog-in-case-region-p)
4934 (progn
4935 (verilog-leap-to-case-head)
4936 (if (looking-at verilog-extended-case-re)
4937 (throw 'nesting 'case)))))
4938
4939 ((looking-at verilog-defun-level-re)
4940 (if (looking-at verilog-defun-level-generate-only-re)
4941 (if (verilog-in-generate-region-p)
4942 (throw 'continue 'foo) ; always block in a generate - keep looking
4943 (throw 'nesting 'defun))
4944 (throw 'nesting 'defun)))
4945
4946 ((looking-at verilog-cpp-level-re)
4947 (throw 'nesting 'cpp))
4948
4949 ((bobp)
4950 (throw 'nesting 'cpp)))))
4951
4952 (throw 'nesting 'cpp))))
4953
4954 (defun verilog-calculate-indent-directive ()
4955 "Return indentation level for directive.
4956 For speed, the searcher looks at the last directive, not the indent
4957 of the appropriate enclosing block."
4958 (let ((base -1) ;; Indent of the line that determines our indentation
4959 (ind 0)) ;; Relative offset caused by other directives (like `endif on same line as `else)
4960 ;; Start at current location, scan back for another directive
4961
4962 (save-excursion
4963 (beginning-of-line)
4964 (while (and (< base 0)
4965 (verilog-re-search-backward verilog-directive-re nil t))
4966 (cond ((save-excursion (skip-chars-backward " \t") (bolp))
4967 (setq base (current-indentation))))
4968 (cond ((and (looking-at verilog-directive-end) (< base 0)) ;; Only matters when not at BOL
4969 (setq ind (- ind verilog-indent-level-directive)))
4970 ((and (looking-at verilog-directive-middle) (>= base 0)) ;; Only matters when at BOL
4971 (setq ind (+ ind verilog-indent-level-directive)))
4972 ((looking-at verilog-directive-begin)
4973 (setq ind (+ ind verilog-indent-level-directive)))))
4974 ;; Adjust indent to starting indent of critical line
4975 (setq ind (max 0 (+ ind base))))
4976
4977 (save-excursion
4978 (beginning-of-line)
4979 (skip-chars-forward " \t")
4980 (cond ((or (looking-at verilog-directive-middle)
4981 (looking-at verilog-directive-end))
4982 (setq ind (max 0 (- ind verilog-indent-level-directive))))))
4983 ind))
4984
4985 (defun verilog-leap-to-case-head ()
4986 (let ((nest 1))
4987 (while (/= 0 nest)
4988 (verilog-re-search-backward
4989 (concat
4990 "\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?\\<case[xz]?\\>\\)"
4991 "\\|\\(\\<endcase\\>\\)" )
4992 nil 'move)
4993 (cond
4994 ((match-end 1)
4995 (let ((here (point)))
4996 (verilog-beg-of-statement)
4997 (unless (looking-at verilog-extended-case-re)
4998 (goto-char here)))
4999 (setq nest (1- nest)))
5000 ((match-end 3)
5001 (setq nest (1+ nest)))
5002 ((bobp)
5003 (ding 't)
5004 (setq nest 0))))))
5005
5006 (defun verilog-leap-to-head ()
5007 "Move point to the head of this block.
5008 Jump from end to matching begin, from endcase to matching case, and so on."
5009 (let ((reg nil)
5010 snest
5011 (nesting 'yes)
5012 (nest 1))
5013 (cond
5014 ((looking-at "\\<end\\>")
5015 ;; 1: Search back for matching begin
5016 (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
5017 "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
5018 ((looking-at "\\<endtask\\>")
5019 ;; 2: Search back for matching task
5020 (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
5021 (setq nesting 'no))
5022 ((looking-at "\\<endcase\\>")
5023 (catch 'nesting
5024 (verilog-leap-to-case-head) )
5025 (setq reg nil) ; to force skip
5026 )
5027
5028 ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
5029 ;; 4: Search back for matching fork
5030 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5031 ((looking-at "\\<endclass\\>")
5032 ;; 5: Search back for matching class
5033 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
5034 ((looking-at "\\<endtable\\>")
5035 ;; 6: Search back for matching table
5036 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
5037 ((looking-at "\\<endspecify\\>")
5038 ;; 7: Search back for matching specify
5039 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
5040 ((looking-at "\\<endfunction\\>")
5041 ;; 8: Search back for matching function
5042 (setq reg "\\(\\<function\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<function\\>\\)")
5043 (setq nesting 'no))
5044 ;;(setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
5045 ((looking-at "\\<endgenerate\\>")
5046 ;; 8: Search back for matching generate
5047 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
5048 ((looking-at "\\<endgroup\\>")
5049 ;; 10: Search back for matching covergroup
5050 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
5051 ((looking-at "\\<endproperty\\>")
5052 ;; 11: Search back for matching property
5053 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
5054 ((looking-at verilog-ovm-end-re)
5055 ;; 12: Search back for matching sequence
5056 (setq reg (concat "\\(" verilog-ovm-begin-re "\\|" verilog-ovm-end-re "\\)")))
5057 ((looking-at verilog-vmm-end-re)
5058 ;; 12: Search back for matching sequence
5059 (setq reg (concat "\\(" verilog-vmm-begin-re "\\|" verilog-vmm-end-re "\\)")))
5060 ((looking-at "\\<endinterface\\>")
5061 ;; 12: Search back for matching interface
5062 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
5063 ((looking-at "\\<endsequence\\>")
5064 ;; 12: Search back for matching sequence
5065 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
5066 ((looking-at "\\<endclocking\\>")
5067 ;; 12: Search back for matching clocking
5068 (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
5069 (if reg
5070 (catch 'skip
5071 (if (eq nesting 'yes)
5072 (let (sreg)
5073 (while (verilog-re-search-backward reg nil 'move)
5074 (cond
5075 ((match-end 1) ; begin
5076 (if (looking-at "fork")
5077 (let ((here (point)))
5078 (verilog-beg-of-statement)
5079 (unless (looking-at verilog-disable-fork-re)
5080 (goto-char here)
5081 (setq nest (1- nest))))
5082 (setq nest (1- nest)))
5083 (if (= 0 nest)
5084 ;; Now previous line describes syntax
5085 (throw 'skip 1))
5086 (if (and snest
5087 (= snest nest))
5088 (setq reg sreg)))
5089 ((match-end 2) ; end
5090 (setq nest (1+ nest)))
5091 ((match-end 3)
5092 ;; endcase, jump to case
5093 (setq snest nest)
5094 (setq nest (1+ nest))
5095 (setq sreg reg)
5096 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
5097 ((match-end 4)
5098 ;; join, jump to fork
5099 (setq snest nest)
5100 (setq nest (1+ nest))
5101 (setq sreg reg)
5102 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5103 )))
5104 ;no nesting
5105 (if (and
5106 (verilog-re-search-backward reg nil 'move)
5107 (match-end 1)) ; task -> could be virtual and/or protected
5108 (progn
5109 (verilog-beg-of-statement)
5110 (throw 'skip 1))
5111 (throw 'skip 1)))))))
5112
5113 (defun verilog-continued-line ()
5114 "Return true if this is a continued line.
5115 Set point to where line starts."
5116 (let ((continued 't))
5117 (if (eq 0 (forward-line -1))
5118 (progn
5119 (end-of-line)
5120 (verilog-backward-ws&directives)
5121 (if (bobp)
5122 (setq continued nil)
5123 (while (and continued
5124 (save-excursion
5125 (skip-chars-backward " \t")
5126 (not (bolp))))
5127 (setq continued (verilog-backward-token)))))
5128 (setq continued nil))
5129 continued))
5130
5131 (defun verilog-backward-token ()
5132 "Step backward token, returing true if this is a continued line."
5133 (interactive)
5134 (verilog-backward-syntactic-ws)
5135 (cond
5136 ((bolp)
5137 nil)
5138 (;-- Anything ending in a ; is complete
5139 (= (preceding-char) ?\;)
5140 nil)
5141 (; If a "}" is prefixed by a ";", then this is a complete statement
5142 ; i.e.: constraint foo { a = b; }
5143 (= (preceding-char) ?\})
5144 (progn
5145 (backward-char)
5146 (not(verilog-at-close-constraint-p))))
5147 (;-- constraint foo { a = b }
5148 ; is a complete statement. *sigh*
5149 (= (preceding-char) ?\{)
5150 (progn
5151 (backward-char)
5152 (not (verilog-at-constraint-p))))
5153 (;" string "
5154 (= (preceding-char) ?\")
5155 (backward-char)
5156 (verilog-skip-backward-comment-or-string)
5157 nil)
5158
5159 (; [3:4]
5160 (= (preceding-char) ?\])
5161 (backward-char)
5162 (verilog-backward-open-bracket)
5163 t)
5164
5165 (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
5166 ; also could be simply '@(foo)'
5167 ; or foo u1 #(a=8)
5168 ; (b, ... which ISN'T complete
5169 ;;;; Do we need this???
5170 (= (preceding-char) ?\))
5171 (progn
5172 (backward-char)
5173 (verilog-backward-up-list 1)
5174 (verilog-backward-syntactic-ws)
5175 (let ((back (point)))
5176 (forward-word -1)
5177 (cond
5178 ;;XX
5179 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
5180 (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
5181 ((looking-at verilog-ovm-statement-re)
5182 nil)
5183 ((looking-at verilog-ovm-begin-re)
5184 t)
5185 ((looking-at verilog-ovm-end-re)
5186 t)
5187 ;; JBA find VMM macros
5188 ((looking-at verilog-vmm-statement-re)
5189 nil )
5190 ((looking-at verilog-vmm-begin-re)
5191 t)
5192 ((looking-at verilog-vmm-end-re)
5193 nil)
5194 ;; JBA trying to catch macro lines with no ; at end
5195 ((looking-at "\\<`")
5196 nil)
5197 (t
5198 (goto-char back)
5199 (cond
5200 ((= (preceding-char) ?\@)
5201 (backward-char)
5202 (save-excursion
5203 (verilog-backward-token)
5204 (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
5205 ((= (preceding-char) ?\#)
5206 (backward-char))
5207 (t t)))))))
5208
5209 (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
5210 t
5211 (forward-word -1)
5212 (while (= (preceding-char) ?\_)
5213 (forward-word -1))
5214 (cond
5215 ((looking-at "\\<else\\>")
5216 t)
5217 ((looking-at verilog-behavioral-block-beg-re)
5218 t)
5219 ((looking-at verilog-indent-re)
5220 nil)
5221 (t
5222 (let
5223 ((back (point)))
5224 (verilog-backward-syntactic-ws)
5225 (cond
5226 ((= (preceding-char) ?\:)
5227 (backward-char)
5228 (verilog-backward-syntactic-ws)
5229 (backward-sexp)
5230 (if (looking-at verilog-nameable-item-re )
5231 nil
5232 t))
5233 ((= (preceding-char) ?\#)
5234 (backward-char)
5235 t)
5236 ((= (preceding-char) ?\`)
5237 (backward-char)
5238 t)
5239
5240 (t
5241 (goto-char back)
5242 t))))))))
5243
5244 (defun verilog-backward-syntactic-ws ()
5245 (verilog-skip-backward-comments)
5246 (forward-comment (- (buffer-size))))
5247
5248 (defun verilog-forward-syntactic-ws ()
5249 (verilog-skip-forward-comment-p)
5250 (forward-comment (buffer-size)))
5251
5252 (defun verilog-backward-ws&directives (&optional bound)
5253 "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
5254 Optional BOUND limits search."
5255 (save-restriction
5256 (let* ((bound (or bound (point-min)))
5257 (here bound)
5258 (p nil) )
5259 (if (< bound (point))
5260 (progn
5261 (let ((state (save-excursion (verilog-syntax-ppss))))
5262 (cond
5263 ((nth 7 state) ;; in // comment
5264 (verilog-re-search-backward "//" nil 'move)
5265 (skip-chars-backward "/"))
5266 ((nth 4 state) ;; in /* */ comment
5267 (verilog-re-search-backward "/\*" nil 'move))))
5268 (narrow-to-region bound (point))
5269 (while (/= here (point))
5270 (setq here (point))
5271 (verilog-skip-backward-comments)
5272 (setq p
5273 (save-excursion
5274 (beginning-of-line)
5275 (cond
5276 ((and verilog-highlight-translate-off
5277 (verilog-within-translate-off))
5278 (verilog-back-to-start-translate-off (point-min)))
5279 ((looking-at verilog-directive-re-1)
5280 (point))
5281 (t
5282 nil))))
5283 (if p (goto-char p))))))))
5284
5285 (defun verilog-forward-ws&directives (&optional bound)
5286 "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
5287 Optional BOUND limits search."
5288 (save-restriction
5289 (let* ((bound (or bound (point-max)))
5290 (here bound)
5291 jump)
5292 (if (> bound (point))
5293 (progn
5294 (let ((state (save-excursion (verilog-syntax-ppss))))
5295 (cond
5296 ((nth 7 state) ;; in // comment
5297 (end-of-line)
5298 (forward-char 1)
5299 (skip-chars-forward " \t\n\f")
5300 )
5301 ((nth 4 state) ;; in /* */ comment
5302 (verilog-re-search-forward "\*\/\\s-*" nil 'move))))
5303 (narrow-to-region (point) bound)
5304 (while (/= here (point))
5305 (setq here (point)
5306 jump nil)
5307 (forward-comment (buffer-size))
5308 (and (looking-at "\\s-*(\\*.*\\*)\\s-*") ;; Attribute
5309 (goto-char (match-end 0)))
5310 (save-excursion
5311 (beginning-of-line)
5312 (if (looking-at verilog-directive-re-1)
5313 (setq jump t)))
5314 (if jump
5315 (beginning-of-line 2))))))))
5316
5317 (defun verilog-in-comment-p ()
5318 "Return true if in a star or // comment."
5319 (let ((state (save-excursion (verilog-syntax-ppss))))
5320 (or (nth 4 state) (nth 7 state))))
5321
5322 (defun verilog-in-star-comment-p ()
5323 "Return true if in a star comment."
5324 (let ((state (save-excursion (verilog-syntax-ppss))))
5325 (and
5326 (nth 4 state) ; t if in a comment of style a // or b /**/
5327 (not
5328 (nth 7 state) ; t if in a comment of style b /**/
5329 ))))
5330
5331 (defun verilog-in-slash-comment-p ()
5332 "Return true if in a slash comment."
5333 (let ((state (save-excursion (verilog-syntax-ppss))))
5334 (nth 7 state)))
5335
5336 (defun verilog-in-comment-or-string-p ()
5337 "Return true if in a string or comment."
5338 (let ((state (save-excursion (verilog-syntax-ppss))))
5339 (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
5340
5341 (defun verilog-in-attribute-p ()
5342 "Return true if point is in an attribute (* [] attribute *)."
5343 (save-excursion
5344 (verilog-re-search-backward "\\((\\*\\)\\|\\(\\*)\\)" nil 'move)
5345 (numberp (match-beginning 1))))
5346
5347 (defun verilog-in-escaped-name-p ()
5348 "Return true if in an escaped name."
5349 (save-excursion
5350 (backward-char)
5351 (skip-chars-backward "^ \t\n\f")
5352 (if (equal (char-after (point) ) ?\\ )
5353 t
5354 nil)))
5355 (defun verilog-in-directive-p ()
5356 "Return true if in a directive."
5357 (save-excursion
5358 (beginning-of-line)
5359 (looking-at verilog-directive-re-1)))
5360
5361 (defun verilog-in-paren ()
5362 "Return true if in a parenthetical expression."
5363 (let ((state (save-excursion (verilog-syntax-ppss))))
5364 (> (nth 0 state) 0 )))
5365
5366 (defun verilog-in-struct-p ()
5367 "Return true if in a struct declaration."
5368 (interactive)
5369 (save-excursion
5370 (if (verilog-in-paren)
5371 (progn
5372 (verilog-backward-up-list 1)
5373 (verilog-at-struct-p)
5374 )
5375 nil)))
5376
5377 (defun verilog-in-coverage-p ()
5378 "Return true if in a constraint or coverpoint expression."
5379 (interactive)
5380 (save-excursion
5381 (if (verilog-in-paren)
5382 (progn
5383 (verilog-backward-up-list 1)
5384 (verilog-at-constraint-p)
5385 )
5386 nil)))
5387 (defun verilog-at-close-constraint-p ()
5388 "If at the } that closes a constraint or covergroup, return true."
5389 (if (and
5390 (equal (char-after) ?\})
5391 (verilog-in-paren))
5392
5393 (save-excursion
5394 (verilog-backward-ws&directives)
5395 (if (equal (char-before) ?\;)
5396 (point)
5397 nil))))
5398
5399 (defun verilog-at-constraint-p ()
5400 "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
5401 (if (save-excursion
5402 (and
5403 (equal (char-after) ?\{)
5404 (forward-list)
5405 (progn (backward-char 1)
5406 (verilog-backward-ws&directives)
5407 (equal (char-before) ?\;))))
5408 ;; maybe
5409 (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
5410 ;; not
5411 nil))
5412
5413 (defun verilog-at-struct-p ()
5414 "If at the { of a struct, return true, moving point to struct."
5415 (save-excursion
5416 (if (and (equal (char-after) ?\{)
5417 (verilog-backward-token))
5418 (looking-at "\\<struct\\|union\\|packed\\|\\(un\\)?signed\\>")
5419 nil)))
5420
5421 (defun verilog-parenthesis-depth ()
5422 "Return non zero if in parenthetical-expression."
5423 (save-excursion (nth 1 (verilog-syntax-ppss))))
5424
5425
5426 (defun verilog-skip-forward-comment-or-string ()
5427 "Return true if in a string or comment."
5428 (let ((state (save-excursion (verilog-syntax-ppss))))
5429 (cond
5430 ((nth 3 state) ;Inside string
5431 (search-forward "\"")
5432 t)
5433 ((nth 7 state) ;Inside // comment
5434 (forward-line 1)
5435 t)
5436 ((nth 4 state) ;Inside any comment (hence /**/)
5437 (search-forward "*/"))
5438 (t
5439 nil))))
5440
5441 (defun verilog-skip-backward-comment-or-string ()
5442 "Return true if in a string or comment."
5443 (let ((state (save-excursion (verilog-syntax-ppss))))
5444 (cond
5445 ((nth 3 state) ;Inside string
5446 (search-backward "\"")
5447 t)
5448 ((nth 7 state) ;Inside // comment
5449 (search-backward "//")
5450 (skip-chars-backward "/")
5451 t)
5452 ((nth 4 state) ;Inside /* */ comment
5453 (search-backward "/*")
5454 t)
5455 (t
5456 nil))))
5457
5458 (defun verilog-skip-backward-comments ()
5459 "Return true if a comment was skipped."
5460 (let ((more t))
5461 (while more
5462 (setq more
5463 (let ((state (save-excursion (verilog-syntax-ppss))))
5464 (cond
5465 ((nth 7 state) ;Inside // comment
5466 (search-backward "//")
5467 (skip-chars-backward "/")
5468 (skip-chars-backward " \t\n\f")
5469 t)
5470 ((nth 4 state) ;Inside /* */ comment
5471 (search-backward "/*")
5472 (skip-chars-backward " \t\n\f")
5473 t)
5474 ((and (not (bobp))
5475 (= (char-before) ?\/)
5476 (= (char-before (1- (point))) ?\*))
5477 (goto-char (- (point) 2))
5478 t) ;; Let nth 4 state handle the rest
5479 ((and (not (bobp))
5480 (= (char-before) ?\))
5481 (= (char-before (1- (point))) ?\*))
5482 (goto-char (- (point) 2))
5483 (if (search-backward "(*" nil t)
5484 (progn
5485 (skip-chars-backward " \t\n\f")
5486 t)
5487 (progn
5488 (goto-char (+ (point) 2))
5489 nil)))
5490 (t
5491 (/= (skip-chars-backward " \t\n\f") 0))))))))
5492
5493 (defun verilog-skip-forward-comment-p ()
5494 "If in comment, move to end and return true."
5495 (let* (h
5496 (state (save-excursion (verilog-syntax-ppss)))
5497 (skip (cond
5498 ((nth 3 state) ;Inside string
5499 t)
5500 ((nth 7 state) ;Inside // comment
5501 (end-of-line)
5502 (forward-char 1)
5503 t)
5504 ((nth 4 state) ;Inside /* comment
5505 (search-forward "*/")
5506 t)
5507 ((verilog-in-attribute-p) ;Inside (* attribute
5508 (search-forward "*)" nil t)
5509 t)
5510 (t nil))))
5511 (skip-chars-forward " \t\n\f")
5512 (while
5513 (cond
5514 ((looking-at "\\/\\*")
5515 (progn
5516 (setq h (point))
5517 (goto-char (match-end 0))
5518 (if (search-forward "*/" nil t)
5519 (progn
5520 (skip-chars-forward " \t\n\f")
5521 (setq skip 't))
5522 (progn
5523 (goto-char h)
5524 nil))))
5525 ((looking-at "(\\*")
5526 (progn
5527 (setq h (point))
5528 (goto-char (match-end 0))
5529 (if (search-forward "*)" nil t)
5530 (progn
5531 (skip-chars-forward " \t\n\f")
5532 (setq skip 't))
5533 (progn
5534 (goto-char h)
5535 nil))))
5536 (t nil)))
5537 skip))
5538
5539 (defun verilog-indent-line-relative ()
5540 "Cheap version of indent line.
5541 Only look at a few lines to determine indent level."
5542 (interactive)
5543 (let ((indent-str)
5544 (sp (point)))
5545 (if (looking-at "^[ \t]*$")
5546 (cond ;- A blank line; No need to be too smart.
5547 ((bobp)
5548 (setq indent-str (list 'cpp 0)))
5549 ((verilog-continued-line)
5550 (let ((sp1 (point)))
5551 (if (verilog-continued-line)
5552 (progn
5553 (goto-char sp)
5554 (setq indent-str
5555 (list 'statement (verilog-current-indent-level))))
5556 (goto-char sp1)
5557 (setq indent-str (list 'block (verilog-current-indent-level)))))
5558 (goto-char sp))
5559 ((goto-char sp)
5560 (setq indent-str (verilog-calculate-indent))))
5561 (progn (skip-chars-forward " \t")
5562 (setq indent-str (verilog-calculate-indent))))
5563 (verilog-do-indent indent-str)))
5564
5565 (defun verilog-indent-line ()
5566 "Indent for special part of code."
5567 (verilog-do-indent (verilog-calculate-indent)))
5568
5569 (defun verilog-do-indent (indent-str)
5570 (let ((type (car indent-str))
5571 (ind (car (cdr indent-str))))
5572 (cond
5573 (; handle continued exp
5574 (eq type 'cexp)
5575 (let ((here (point)))
5576 (verilog-backward-syntactic-ws)
5577 (cond
5578 ((or
5579 (= (preceding-char) ?\,)
5580 (= (preceding-char) ?\])
5581 (save-excursion
5582 (verilog-beg-of-statement-1)
5583 (looking-at verilog-declaration-re)))
5584 (let* ( fst
5585 (val
5586 (save-excursion
5587 (backward-char 1)
5588 (verilog-beg-of-statement-1)
5589 (setq fst (point))
5590 (if (looking-at verilog-declaration-re)
5591 (progn ;; we have multiple words
5592 (goto-char (match-end 0))
5593 (skip-chars-forward " \t")
5594 (cond
5595 ((and verilog-indent-declaration-macros
5596 (= (following-char) ?\`))
5597 (progn
5598 (forward-char 1)
5599 (forward-word 1)
5600 (skip-chars-forward " \t")))
5601 ((= (following-char) ?\[)
5602 (progn
5603 (forward-char 1)
5604 (verilog-backward-up-list -1)
5605 (skip-chars-forward " \t"))))
5606 (current-column))
5607 (progn
5608 (goto-char fst)
5609 (+ (current-column) verilog-cexp-indent))))))
5610 (goto-char here)
5611 (indent-line-to val)))
5612 ((= (preceding-char) ?\) )
5613 (goto-char here)
5614 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5615 (indent-line-to val)))
5616 (t
5617 (goto-char here)
5618 (let ((val))
5619 (verilog-beg-of-statement-1)
5620 (if (and (< (point) here)
5621 (verilog-re-search-forward "=[ \\t]*" here 'move))
5622 (setq val (current-column))
5623 (setq val (eval (cdr (assoc type verilog-indent-alist)))))
5624 (goto-char here)
5625 (indent-line-to val))))))
5626
5627 (; handle inside parenthetical expressions
5628 (eq type 'cparenexp)
5629 (let* ( here
5630 (val (save-excursion
5631 (verilog-backward-up-list 1)
5632 (forward-char 1)
5633 (if verilog-indent-lists
5634 (skip-chars-forward " \t")
5635 (verilog-forward-syntactic-ws))
5636 (setq here (point))
5637 (current-column)))
5638
5639 (decl (save-excursion
5640 (goto-char here)
5641 (verilog-forward-syntactic-ws)
5642 (setq here (point))
5643 (looking-at verilog-declaration-re))))
5644 (indent-line-to val)
5645 (if decl
5646 (verilog-pretty-declarations))))
5647
5648 (;-- Handle the ends
5649 (or
5650 (looking-at verilog-end-block-re )
5651 (verilog-at-close-constraint-p))
5652 (let ((val (if (eq type 'statement)
5653 (- ind verilog-indent-level)
5654 ind)))
5655 (indent-line-to val)))
5656
5657 (;-- Case -- maybe line 'em up
5658 (and (eq type 'case) (not (looking-at "^[ \t]*$")))
5659 (progn
5660 (cond
5661 ((looking-at "\\<endcase\\>")
5662 (indent-line-to ind))
5663 (t
5664 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5665 (indent-line-to val))))))
5666
5667 (;-- defun
5668 (and (eq type 'defun)
5669 (looking-at verilog-zero-indent-re))
5670 (indent-line-to 0))
5671
5672 (;-- declaration
5673 (and (or
5674 (eq type 'defun)
5675 (eq type 'block))
5676 (looking-at verilog-declaration-re))
5677 (verilog-indent-declaration ind))
5678
5679 (;-- Everything else
5680 t
5681 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5682 (indent-line-to val))))
5683
5684 (if (looking-at "[ \t]+$")
5685 (skip-chars-forward " \t"))
5686 indent-str ; Return indent data
5687 ))
5688
5689 (defun verilog-current-indent-level ()
5690 "Return the indent-level of the current statement."
5691 (save-excursion
5692 (let (par-pos)
5693 (beginning-of-line)
5694 (setq par-pos (verilog-parenthesis-depth))
5695 (while par-pos
5696 (goto-char par-pos)
5697 (beginning-of-line)
5698 (setq par-pos (verilog-parenthesis-depth)))
5699 (skip-chars-forward " \t")
5700 (current-column))))
5701
5702 (defun verilog-case-indent-level ()
5703 "Return the indent-level of the current statement.
5704 Do not count named blocks or case-statements."
5705 (save-excursion
5706 (skip-chars-forward " \t")
5707 (cond
5708 ((looking-at verilog-named-block-re)
5709 (current-column))
5710 ((and (not (looking-at verilog-extended-case-re))
5711 (looking-at "^[^:;]+[ \t]*:"))
5712 (verilog-re-search-forward ":" nil t)
5713 (skip-chars-forward " \t")
5714 (current-column))
5715 (t
5716 (current-column)))))
5717
5718 (defun verilog-indent-comment ()
5719 "Indent current line as comment."
5720 (let* ((stcol
5721 (cond
5722 ((verilog-in-star-comment-p)
5723 (save-excursion
5724 (re-search-backward "/\\*" nil t)
5725 (1+(current-column))))
5726 (comment-column
5727 comment-column )
5728 (t
5729 (save-excursion
5730 (re-search-backward "//" nil t)
5731 (current-column))))))
5732 (indent-line-to stcol)
5733 stcol))
5734
5735 (defun verilog-more-comment ()
5736 "Make more comment lines like the previous."
5737 (let* ((star 0)
5738 (stcol
5739 (cond
5740 ((verilog-in-star-comment-p)
5741 (save-excursion
5742 (setq star 1)
5743 (re-search-backward "/\\*" nil t)
5744 (1+(current-column))))
5745 (comment-column
5746 comment-column )
5747 (t
5748 (save-excursion
5749 (re-search-backward "//" nil t)
5750 (current-column))))))
5751 (progn
5752 (indent-to stcol)
5753 (if (and star
5754 (save-excursion
5755 (forward-line -1)
5756 (skip-chars-forward " \t")
5757 (looking-at "\*")))
5758 (insert "* ")))))
5759
5760 (defun verilog-comment-indent (&optional arg)
5761 "Return the column number the line should be indented to.
5762 ARG is ignored, for `comment-indent-function' compatibility."
5763 (cond
5764 ((verilog-in-star-comment-p)
5765 (save-excursion
5766 (re-search-backward "/\\*" nil t)
5767 (1+(current-column))))
5768 ( comment-column
5769 comment-column )
5770 (t
5771 (save-excursion
5772 (re-search-backward "//" nil t)
5773 (current-column)))))
5774
5775 ;;
5776
5777 (defun verilog-pretty-declarations (&optional quiet)
5778 "Line up declarations around point.
5779 Be verbose about progress unless optional QUIET set."
5780 (interactive)
5781 (let* ((m1 (make-marker))
5782 (e (point))
5783 el
5784 r
5785 (here (point))
5786 ind
5787 start
5788 startpos
5789 end
5790 endpos
5791 base-ind
5792 )
5793 (save-excursion
5794 (if (progn
5795 ; (verilog-beg-of-statement-1)
5796 (beginning-of-line)
5797 (verilog-forward-syntactic-ws)
5798 (and (not (verilog-in-directive-p)) ;; could have `define input foo
5799 (looking-at verilog-declaration-re)))
5800 (progn
5801 (if (verilog-parenthesis-depth)
5802 ;; in an argument list or parameter block
5803 (setq el (verilog-backward-up-list -1)
5804 start (progn
5805 (goto-char e)
5806 (verilog-backward-up-list 1)
5807 (forward-line) ;; ignore ( input foo,
5808 (verilog-re-search-forward verilog-declaration-re el 'move)
5809 (goto-char (match-beginning 0))
5810 (skip-chars-backward " \t")
5811 (point))
5812 startpos (set-marker (make-marker) start)
5813 end (progn
5814 (goto-char start)
5815 (verilog-backward-up-list -1)
5816 (forward-char -1)
5817 (verilog-backward-syntactic-ws)
5818 (point))
5819 endpos (set-marker (make-marker) end)
5820 base-ind (progn
5821 (goto-char start)
5822 (forward-char 1)
5823 (skip-chars-forward " \t")
5824 (current-column))
5825 )
5826 ;; in a declaration block (not in argument list)
5827 (setq
5828 start (progn
5829 (verilog-beg-of-statement-1)
5830 (while (and (looking-at verilog-declaration-re)
5831 (not (bobp)))
5832 (skip-chars-backward " \t")
5833 (setq e (point))
5834 (beginning-of-line)
5835 (verilog-backward-syntactic-ws)
5836 (backward-char)
5837 (verilog-beg-of-statement-1))
5838 e)
5839 startpos (set-marker (make-marker) start)
5840 end (progn
5841 (goto-char here)
5842 (verilog-end-of-statement)
5843 (setq e (point)) ;Might be on last line
5844 (verilog-forward-syntactic-ws)
5845 (while (looking-at verilog-declaration-re)
5846 (verilog-end-of-statement)
5847 (setq e (point))
5848 (verilog-forward-syntactic-ws))
5849 e)
5850 endpos (set-marker (make-marker) end)
5851 base-ind (progn
5852 (goto-char start)
5853 (verilog-do-indent (verilog-calculate-indent))
5854 (verilog-forward-ws&directives)
5855 (current-column))))
5856 ;; OK, start and end are set
5857 (goto-char (marker-position startpos))
5858 (if (and (not quiet)
5859 (> (- end start) 100))
5860 (message "Lining up declarations..(please stand by)"))
5861 ;; Get the beginning of line indent first
5862 (while (progn (setq e (marker-position endpos))
5863 (< (point) e))
5864 (cond
5865 ((save-excursion (skip-chars-backward " \t")
5866 (bolp))
5867 (verilog-forward-ws&directives)
5868 (indent-line-to base-ind)
5869 (verilog-forward-ws&directives)
5870 (if (< (point) e)
5871 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5872 (t
5873 (just-one-space)
5874 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5875 ;;(forward-line)
5876 )
5877 ;; Now find biggest prefix
5878 (setq ind (verilog-get-lineup-indent (marker-position startpos) endpos))
5879 ;; Now indent each line.
5880 (goto-char (marker-position startpos))
5881 (while (progn (setq e (marker-position endpos))
5882 (setq r (- e (point)))
5883 (> r 0))
5884 (setq e (point))
5885 (unless quiet (message "%d" r))
5886 ;;(verilog-do-indent (verilog-calculate-indent)))
5887 (verilog-forward-ws&directives)
5888 (cond
5889 ((or (and verilog-indent-declaration-macros
5890 (looking-at verilog-declaration-re-2-macro))
5891 (looking-at verilog-declaration-re-2-no-macro))
5892 (let ((p (match-end 0)))
5893 (set-marker m1 p)
5894 (if (verilog-re-search-forward "[[#`]" p 'move)
5895 (progn
5896 (forward-char -1)
5897 (just-one-space)
5898 (goto-char (marker-position m1))
5899 (just-one-space)
5900 (indent-to ind))
5901 (progn
5902 (just-one-space)
5903 (indent-to ind)))))
5904 ((verilog-continued-line-1 (marker-position startpos))
5905 (goto-char e)
5906 (indent-line-to ind))
5907 ((verilog-in-struct-p)
5908 ;; could have a declaration of a user defined item
5909 (goto-char e)
5910 (verilog-end-of-statement))
5911 (t ; Must be comment or white space
5912 (goto-char e)
5913 (verilog-forward-ws&directives)
5914 (forward-line -1)))
5915 (forward-line 1))
5916 (unless quiet (message "")))))))
5917
5918 (defun verilog-pretty-expr (&optional quiet myre)
5919 "Line up expressions around point, optionally QUIET with regexp MYRE."
5920 (interactive "i\nsRegular Expression: ((<|:)?=) ")
5921 (save-excursion
5922 (if (or (eq myre nil)
5923 (string-equal myre ""))
5924 (setq myre "\\(<\\|:\\)?="))
5925 ;; want to match the first <= | := | =
5926 (setq myre (concat "\\(^.*?\\)\\(" myre "\\)"))
5927 (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
5928 (beginning-of-line)
5929 (if (and (not (looking-at rexp ))
5930 (looking-at myre)
5931 (save-excursion
5932 (goto-char (match-beginning 2))
5933 (not (verilog-in-comment-or-string-p))))
5934 (let* ((here (point))
5935 (e) (r)
5936 (start
5937 (progn
5938 (beginning-of-line)
5939 (setq e (point))
5940 (verilog-backward-syntactic-ws)
5941 (beginning-of-line)
5942 (while (and (not (looking-at rexp ))
5943 (looking-at myre)
5944 (not (bobp))
5945 )
5946 (setq e (point))
5947 (verilog-backward-syntactic-ws)
5948 (beginning-of-line)
5949 ) ;Ack, need to grok `define
5950 e))
5951 (end
5952 (progn
5953 (goto-char here)
5954 (end-of-line)
5955 (setq e (point)) ;Might be on last line
5956 (verilog-forward-syntactic-ws)
5957 (beginning-of-line)
5958 (while (and
5959 (not (looking-at rexp ))
5960 (looking-at myre)
5961 (progn
5962 (end-of-line)
5963 (not (eq e (point)))))
5964 (setq e (point))
5965 (verilog-forward-syntactic-ws)
5966 (beginning-of-line)
5967 )
5968 e))
5969 (endpos (set-marker (make-marker) end))
5970 (ind)
5971 )
5972 (goto-char start)
5973 (verilog-do-indent (verilog-calculate-indent))
5974 (if (and (not quiet)
5975 (> (- end start) 100))
5976 (message "Lining up expressions..(please stand by)"))
5977
5978 ;; Set indent to minimum throughout region
5979 (while (< (point) (marker-position endpos))
5980 (beginning-of-line)
5981 (verilog-just-one-space myre)
5982 (end-of-line)
5983 (verilog-forward-syntactic-ws)
5984 )
5985
5986 ;; Now find biggest prefix
5987 (setq ind (verilog-get-lineup-indent-2 myre start endpos))
5988
5989 ;; Now indent each line.
5990 (goto-char start)
5991 (while (progn (setq e (marker-position endpos))
5992 (setq r (- e (point)))
5993 (> r 0))
5994 (setq e (point))
5995 (if (not quiet) (message "%d" r))
5996 (cond
5997 ((looking-at myre)
5998 (goto-char (match-beginning 2))
5999 (if (not (verilog-parenthesis-depth)) ;; ignore parenthesized exprs
6000 (if (eq (char-after) ?=)
6001 (indent-to (1+ ind)) ; line up the = of the <= with surrounding =
6002 (indent-to ind)
6003 )))
6004 ((verilog-continued-line-1 start)
6005 (goto-char e)
6006 (indent-line-to ind))
6007 (t ; Must be comment or white space
6008 (goto-char e)
6009 (verilog-forward-ws&directives)
6010 (forward-line -1))
6011 )
6012 (forward-line 1))
6013 (unless quiet (message ""))
6014 )))))
6015
6016 (defun verilog-just-one-space (myre)
6017 "Remove extra spaces around regular expression MYRE."
6018 (interactive)
6019 (if (and (not(looking-at verilog-complete-reg))
6020 (looking-at myre))
6021 (let ((p1 (match-end 1))
6022 (p2 (match-end 2)))
6023 (progn
6024 (goto-char p2)
6025 (if (looking-at "\\s-") (just-one-space))
6026 (goto-char p1)
6027 (forward-char -1)
6028 (if (looking-at "\\s-") (just-one-space))
6029 ))))
6030
6031 (defun verilog-indent-declaration (baseind)
6032 "Indent current lines as declaration.
6033 Line up the variable names based on previous declaration's indentation.
6034 BASEIND is the base indent to offset everything."
6035 (interactive)
6036 (let ((pos (point-marker))
6037 (lim (save-excursion
6038 ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
6039 (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
6040 (point)))
6041 (ind)
6042 (val)
6043 (m1 (make-marker)))
6044 (setq val
6045 (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6046 (indent-line-to val)
6047
6048 ;; Use previous declaration (in this module) as template.
6049 (if (or (eq 'all verilog-auto-lineup)
6050 (eq 'declarations verilog-auto-lineup))
6051 (if (verilog-re-search-backward
6052 (or (and verilog-indent-declaration-macros
6053 verilog-declaration-re-1-macro)
6054 verilog-declaration-re-1-no-macro) lim t)
6055 (progn
6056 (goto-char (match-end 0))
6057 (skip-chars-forward " \t")
6058 (setq ind (current-column))
6059 (goto-char pos)
6060 (setq val
6061 (+ baseind
6062 (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6063 (indent-line-to val)
6064 (if (and verilog-indent-declaration-macros
6065 (looking-at verilog-declaration-re-2-macro))
6066 (let ((p (match-end 0)))
6067 (set-marker m1 p)
6068 (if (verilog-re-search-forward "[[#`]" p 'move)
6069 (progn
6070 (forward-char -1)
6071 (just-one-space)
6072 (goto-char (marker-position m1))
6073 (just-one-space)
6074 (indent-to ind))
6075 (if (/= (current-column) ind)
6076 (progn
6077 (just-one-space)
6078 (indent-to ind)))))
6079 (if (looking-at verilog-declaration-re-2-no-macro)
6080 (let ((p (match-end 0)))
6081 (set-marker m1 p)
6082 (if (verilog-re-search-forward "[[`#]" p 'move)
6083 (progn
6084 (forward-char -1)
6085 (just-one-space)
6086 (goto-char (marker-position m1))
6087 (just-one-space)
6088 (indent-to ind))
6089 (if (/= (current-column) ind)
6090 (progn
6091 (just-one-space)
6092 (indent-to ind))))))))))
6093 (goto-char pos)))
6094
6095 (defun verilog-get-lineup-indent (b edpos)
6096 "Return the indent level that will line up several lines within the region.
6097 Region is defined by B and EDPOS."
6098 (save-excursion
6099 (let ((ind 0) e)
6100 (goto-char b)
6101 ;; Get rightmost position
6102 (while (progn (setq e (marker-position edpos))
6103 (< (point) e))
6104 (if (verilog-re-search-forward
6105 (or (and verilog-indent-declaration-macros
6106 verilog-declaration-re-1-macro)
6107 verilog-declaration-re-1-no-macro) e 'move)
6108 (progn
6109 (goto-char (match-end 0))
6110 (verilog-backward-syntactic-ws)
6111 (if (> (current-column) ind)
6112 (setq ind (current-column)))
6113 (goto-char (match-end 0)))))
6114 (if (> ind 0)
6115 (1+ ind)
6116 ;; No lineup-string found
6117 (goto-char b)
6118 (end-of-line)
6119 (verilog-backward-syntactic-ws)
6120 ;;(skip-chars-backward " \t")
6121 (1+ (current-column))))))
6122
6123 (defun verilog-get-lineup-indent-2 (myre b edpos)
6124 "Return the indent level that will line up several lines within the region."
6125 (save-excursion
6126 (let ((ind 0) e)
6127 (goto-char b)
6128 ;; Get rightmost position
6129 (while (progn (setq e (marker-position edpos))
6130 (< (point) e))
6131 (if (and (verilog-re-search-forward myre e 'move)
6132 (not (verilog-parenthesis-depth))) ;; skip parenthesized exprs
6133 (progn
6134 (goto-char (match-beginning 2))
6135 (verilog-backward-syntactic-ws)
6136 (if (> (current-column) ind)
6137 (setq ind (current-column)))
6138 (goto-char (match-end 0)))
6139 ))
6140 (if (> ind 0)
6141 (1+ ind)
6142 ;; No lineup-string found
6143 (goto-char b)
6144 (end-of-line)
6145 (skip-chars-backward " \t")
6146 (1+ (current-column))))))
6147
6148 (defun verilog-comment-depth (type val)
6149 "A useful mode debugging aide. TYPE and VAL are comments for insertion."
6150 (save-excursion
6151 (let
6152 ((b (prog2
6153 (beginning-of-line)
6154 (point-marker)
6155 (end-of-line)))
6156 (e (point-marker)))
6157 (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
6158 (progn
6159 (replace-match " /* -# ## */")
6160 (end-of-line))
6161 (progn
6162 (end-of-line)
6163 (insert " /* ## ## */"))))
6164 (backward-char 6)
6165 (insert
6166 (format "%s %d" type val))))
6167
6168 ;; \f
6169 ;;
6170 ;; Completion
6171 ;;
6172 (defvar verilog-str nil)
6173 (defvar verilog-all nil)
6174 (defvar verilog-pred nil)
6175 (defvar verilog-buffer-to-use nil)
6176 (defvar verilog-flag nil)
6177 (defvar verilog-toggle-completions nil
6178 "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
6179 Repeated use of \\[verilog-complete-word] will show you all of them.
6180 Normally, when there is more than one possible completion,
6181 it displays a list of all possible completions.")
6182
6183
6184 (defvar verilog-type-keywords
6185 '(
6186 "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
6187 "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
6188 "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
6189 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
6190 "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
6191 "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
6192 )
6193 "*Keywords for types used when completing a word in a declaration or parmlist.
6194 \(integer, real, reg...)")
6195
6196 (defvar verilog-cpp-keywords
6197 '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
6198 "endif")
6199 "*Keywords to complete when at first word of a line in declarative scope.
6200 \(initial, always, begin, assign...)
6201 The procedures and variables defined within the Verilog program
6202 will be completed at runtime and should not be added to this list.")
6203
6204 (defvar verilog-defun-keywords
6205 (append
6206 '(
6207 "always" "always_comb" "always_ff" "always_latch" "assign"
6208 "begin" "end" "generate" "endgenerate" "module" "endmodule"
6209 "specify" "endspecify" "function" "endfunction" "initial" "final"
6210 "task" "endtask" "primitive" "endprimitive"
6211 )
6212 verilog-type-keywords)
6213 "*Keywords to complete when at first word of a line in declarative scope.
6214 \(initial, always, begin, assign...)
6215 The procedures and variables defined within the Verilog program
6216 will be completed at runtime and should not be added to this list.")
6217
6218 (defvar verilog-block-keywords
6219 '(
6220 "begin" "break" "case" "continue" "else" "end" "endfunction"
6221 "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
6222 "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
6223 "while")
6224 "*Keywords to complete when at first word of a line in behavioral scope.
6225 \(begin, if, then, else, for, fork...)
6226 The procedures and variables defined within the Verilog program
6227 will be completed at runtime and should not be added to this list.")
6228
6229 (defvar verilog-tf-keywords
6230 '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
6231 "*Keywords to complete when at first word of a line in a task or function.
6232 \(begin, if, then, else, for, fork.)
6233 The procedures and variables defined within the Verilog program
6234 will be completed at runtime and should not be added to this list.")
6235
6236 (defvar verilog-case-keywords
6237 '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
6238 "*Keywords to complete when at first word of a line in case scope.
6239 \(begin, if, then, else, for, fork...)
6240 The procedures and variables defined within the Verilog program
6241 will be completed at runtime and should not be added to this list.")
6242
6243 (defvar verilog-separator-keywords
6244 '("else" "then" "begin")
6245 "*Keywords to complete when NOT standing at the first word of a statement.
6246 \(else, then, begin...)
6247 Variables and function names defined within the Verilog program
6248 will be completed at runtime and should not be added to this list.")
6249
6250 (defvar verilog-gate-ios
6251 ;; All these have an implied {"input"...} at the end
6252 '(("and" "output")
6253 ("buf" "output")
6254 ("bufif0" "output")
6255 ("bufif1" "output")
6256 ("cmos" "output")
6257 ("nand" "output")
6258 ("nmos" "output")
6259 ("nor" "output")
6260 ("not" "output")
6261 ("notif0" "output")
6262 ("notif1" "output")
6263 ("or" "output")
6264 ("pmos" "output")
6265 ("pulldown" "output")
6266 ("pullup" "output")
6267 ("rcmos" "output")
6268 ("rnmos" "output")
6269 ("rpmos" "output")
6270 ("rtran" "inout" "inout")
6271 ("rtranif0" "inout" "inout")
6272 ("rtranif1" "inout" "inout")
6273 ("tran" "inout" "inout")
6274 ("tranif0" "inout" "inout")
6275 ("tranif1" "inout" "inout")
6276 ("xnor" "output")
6277 ("xor" "output"))
6278 "*Map of direction for each positional argument to each gate primitive.")
6279
6280 (defvar verilog-gate-keywords (mapcar `car verilog-gate-ios)
6281 "*Keywords for gate primitives.")
6282
6283 (defun verilog-string-diff (str1 str2)
6284 "Return index of first letter where STR1 and STR2 differs."
6285 (catch 'done
6286 (let ((diff 0))
6287 (while t
6288 (if (or (> (1+ diff) (length str1))
6289 (> (1+ diff) (length str2)))
6290 (throw 'done diff))
6291 (or (equal (aref str1 diff) (aref str2 diff))
6292 (throw 'done diff))
6293 (setq diff (1+ diff))))))
6294
6295 ;; Calculate all possible completions for functions if argument is `function',
6296 ;; completions for procedures if argument is `procedure' or both functions and
6297 ;; procedures otherwise.
6298
6299 (defun verilog-func-completion (type)
6300 "Build regular expression for module/task/function names.
6301 TYPE is 'module, 'tf for task or function, or t if unknown."
6302 (if (string= verilog-str "")
6303 (setq verilog-str "[a-zA-Z_]"))
6304 (let ((verilog-str (concat (cond
6305 ((eq type 'module) "\\<\\(module\\)\\s +")
6306 ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
6307 (t "\\<\\(task\\|function\\|module\\)\\s +"))
6308 "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
6309 match)
6310
6311 (if (not (looking-at verilog-defun-re))
6312 (verilog-re-search-backward verilog-defun-re nil t))
6313 (forward-char 1)
6314
6315 ;; Search through all reachable functions
6316 (goto-char (point-min))
6317 (while (verilog-re-search-forward verilog-str (point-max) t)
6318 (progn (setq match (buffer-substring (match-beginning 2)
6319 (match-end 2)))
6320 (if (or (null verilog-pred)
6321 (funcall verilog-pred match))
6322 (setq verilog-all (cons match verilog-all)))))
6323 (if (match-beginning 0)
6324 (goto-char (match-beginning 0)))))
6325
6326 (defun verilog-get-completion-decl (end)
6327 "Macro for searching through current declaration (var, type or const)
6328 for matches of `str' and adding the occurrence tp `all' through point END."
6329 (let ((re (or (and verilog-indent-declaration-macros
6330 verilog-declaration-re-2-macro)
6331 verilog-declaration-re-2-no-macro))
6332 decl-end match)
6333 ;; Traverse lines
6334 (while (and (< (point) end)
6335 (verilog-re-search-forward re end t))
6336 ;; Traverse current line
6337 (setq decl-end (save-excursion (verilog-declaration-end)))
6338 (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
6339 (not (match-end 1)))
6340 (setq match (buffer-substring (match-beginning 0) (match-end 0)))
6341 (if (string-match (concat "\\<" verilog-str) match)
6342 (if (or (null verilog-pred)
6343 (funcall verilog-pred match))
6344 (setq verilog-all (cons match verilog-all)))))
6345 (forward-line 1)))
6346 verilog-all)
6347
6348 (defun verilog-type-completion ()
6349 "Calculate all possible completions for types."
6350 (let ((start (point))
6351 goon)
6352 ;; Search for all reachable type declarations
6353 (while (or (verilog-beg-of-defun)
6354 (setq goon (not goon)))
6355 (save-excursion
6356 (if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
6357 (point))
6358 (forward-char 1)))
6359 (verilog-re-search-forward
6360 "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
6361 start t)
6362 (not (match-end 1)))
6363 ;; Check current type declaration
6364 (verilog-get-completion-decl start))))))
6365
6366 (defun verilog-var-completion ()
6367 "Calculate all possible completions for variables (or constants)."
6368 (let ((start (point)))
6369 ;; Search for all reachable var declarations
6370 (verilog-beg-of-defun)
6371 (save-excursion
6372 ;; Check var declarations
6373 (verilog-get-completion-decl start))))
6374
6375 (defun verilog-keyword-completion (keyword-list)
6376 "Give list of all possible completions of keywords in KEYWORD-LIST."
6377 (mapcar '(lambda (s)
6378 (if (string-match (concat "\\<" verilog-str) s)
6379 (if (or (null verilog-pred)
6380 (funcall verilog-pred s))
6381 (setq verilog-all (cons s verilog-all)))))
6382 keyword-list))
6383
6384
6385 (defun verilog-completion (verilog-str verilog-pred verilog-flag)
6386 "Function passed to `completing-read', `try-completion' or `all-completions'.
6387 Called to get completion on VERILOG-STR. If VERILOG-PRED is non-nil, it
6388 must be a function to be called for every match to check if this should
6389 really be a match. If VERILOG-FLAG is t, the function returns a list of
6390 all possible completions. If VERILOG-FLAG is nil it returns a string,
6391 the longest possible completion, or t if VERILOG-STR is an exact match.
6392 If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
6393 exact match, nil otherwise."
6394 (save-excursion
6395 (let ((verilog-all nil))
6396 ;; Set buffer to use for searching labels. This should be set
6397 ;; within functions which use verilog-completions
6398 (set-buffer verilog-buffer-to-use)
6399
6400 ;; Determine what should be completed
6401 (let ((state (car (verilog-calculate-indent))))
6402 (cond ((eq state 'defun)
6403 (save-excursion (verilog-var-completion))
6404 (verilog-func-completion 'module)
6405 (verilog-keyword-completion verilog-defun-keywords))
6406
6407 ((eq state 'behavioral)
6408 (save-excursion (verilog-var-completion))
6409 (verilog-func-completion 'module)
6410 (verilog-keyword-completion verilog-defun-keywords))
6411
6412 ((eq state 'block)
6413 (save-excursion (verilog-var-completion))
6414 (verilog-func-completion 'tf)
6415 (verilog-keyword-completion verilog-block-keywords))
6416
6417 ((eq state 'case)
6418 (save-excursion (verilog-var-completion))
6419 (verilog-func-completion 'tf)
6420 (verilog-keyword-completion verilog-case-keywords))
6421
6422 ((eq state 'tf)
6423 (save-excursion (verilog-var-completion))
6424 (verilog-func-completion 'tf)
6425 (verilog-keyword-completion verilog-tf-keywords))
6426
6427 ((eq state 'cpp)
6428 (save-excursion (verilog-var-completion))
6429 (verilog-keyword-completion verilog-cpp-keywords))
6430
6431 ((eq state 'cparenexp)
6432 (save-excursion (verilog-var-completion)))
6433
6434 (t;--Anywhere else
6435 (save-excursion (verilog-var-completion))
6436 (verilog-func-completion 'both)
6437 (verilog-keyword-completion verilog-separator-keywords))))
6438
6439 ;; Now we have built a list of all matches. Give response to caller
6440 (verilog-completion-response))))
6441
6442 (defun verilog-completion-response ()
6443 (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
6444 ;; This was not called by all-completions
6445 (if (null verilog-all)
6446 ;; Return nil if there was no matching label
6447 nil
6448 ;; Get longest string common in the labels
6449 (let* ((elm (cdr verilog-all))
6450 (match (car verilog-all))
6451 (min (length match))
6452 tmp)
6453 (if (string= match verilog-str)
6454 ;; Return t if first match was an exact match
6455 (setq match t)
6456 (while (not (null elm))
6457 ;; Find longest common string
6458 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
6459 (progn
6460 (setq min tmp)
6461 (setq match (substring match 0 min))))
6462 ;; Terminate with match=t if this is an exact match
6463 (if (string= (car elm) verilog-str)
6464 (progn
6465 (setq match t)
6466 (setq elm nil))
6467 (setq elm (cdr elm)))))
6468 ;; If this is a test just for exact match, return nil ot t
6469 (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
6470 nil
6471 match))))
6472 ;; If flag is t, this was called by all-completions. Return
6473 ;; list of all possible completions
6474 (verilog-flag
6475 verilog-all)))
6476
6477 (defvar verilog-last-word-numb 0)
6478 (defvar verilog-last-word-shown nil)
6479 (defvar verilog-last-completions nil)
6480
6481 (defun verilog-complete-word ()
6482 "Complete word at current point.
6483 \(See also `verilog-toggle-completions', `verilog-type-keywords',
6484 and `verilog-separator-keywords'.)"
6485 (interactive)
6486 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
6487 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
6488 (verilog-str (buffer-substring b e))
6489 ;; The following variable is used in verilog-completion
6490 (verilog-buffer-to-use (current-buffer))
6491 (allcomp (if (and verilog-toggle-completions
6492 (string= verilog-last-word-shown verilog-str))
6493 verilog-last-completions
6494 (all-completions verilog-str 'verilog-completion)))
6495 (match (if verilog-toggle-completions
6496 "" (try-completion
6497 verilog-str (mapcar '(lambda (elm)
6498 (cons elm 0)) allcomp)))))
6499 ;; Delete old string
6500 (delete-region b e)
6501
6502 ;; Toggle-completions inserts whole labels
6503 (if verilog-toggle-completions
6504 (progn
6505 ;; Update entry number in list
6506 (setq verilog-last-completions allcomp
6507 verilog-last-word-numb
6508 (if (>= verilog-last-word-numb (1- (length allcomp)))
6509 0
6510 (1+ verilog-last-word-numb)))
6511 (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
6512 ;; Display next match or same string if no match was found
6513 (if (not (null allcomp))
6514 (insert "" verilog-last-word-shown)
6515 (insert "" verilog-str)
6516 (message "(No match)")))
6517 ;; The other form of completion does not necessarily do that.
6518
6519 ;; Insert match if found, or the original string if no match
6520 (if (or (null match) (equal match 't))
6521 (progn (insert "" verilog-str)
6522 (message "(No match)"))
6523 (insert "" match))
6524 ;; Give message about current status of completion
6525 (cond ((equal match 't)
6526 (if (not (null (cdr allcomp)))
6527 (message "(Complete but not unique)")
6528 (message "(Sole completion)")))
6529 ;; Display buffer if the current completion didn't help
6530 ;; on completing the label.
6531 ((and (not (null (cdr allcomp))) (= (length verilog-str)
6532 (length match)))
6533 (with-output-to-temp-buffer "*Completions*"
6534 (display-completion-list allcomp))
6535 ;; Wait for a key press. Then delete *Completion* window
6536 (momentary-string-display "" (point))
6537 (delete-window (get-buffer-window (get-buffer "*Completions*")))
6538 )))))
6539
6540 (defun verilog-show-completions ()
6541 "Show all possible completions at current point."
6542 (interactive)
6543 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
6544 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
6545 (verilog-str (buffer-substring b e))
6546 ;; The following variable is used in verilog-completion
6547 (verilog-buffer-to-use (current-buffer))
6548 (allcomp (if (and verilog-toggle-completions
6549 (string= verilog-last-word-shown verilog-str))
6550 verilog-last-completions
6551 (all-completions verilog-str 'verilog-completion))))
6552 ;; Show possible completions in a temporary buffer.
6553 (with-output-to-temp-buffer "*Completions*"
6554 (display-completion-list allcomp))
6555 ;; Wait for a key press. Then delete *Completion* window
6556 (momentary-string-display "" (point))
6557 (delete-window (get-buffer-window (get-buffer "*Completions*")))))
6558
6559
6560 (defun verilog-get-default-symbol ()
6561 "Return symbol around current point as a string."
6562 (save-excursion
6563 (buffer-substring (progn
6564 (skip-chars-backward " \t")
6565 (skip-chars-backward "a-zA-Z0-9_")
6566 (point))
6567 (progn
6568 (skip-chars-forward "a-zA-Z0-9_")
6569 (point)))))
6570
6571 (defun verilog-build-defun-re (str &optional arg)
6572 "Return function/task/module starting with STR as regular expression.
6573 With optional second ARG non-nil, STR is the complete name of the instruction."
6574 (if arg
6575 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
6576 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
6577
6578 (defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
6579 "Function passed to `completing-read', `try-completion' or `all-completions'.
6580 Returns a completion on any function name based on VERILOG-STR prefix. If
6581 VERILOG-PRED is non-nil, it must be a function to be called for every match
6582 to check if this should really be a match. If VERILOG-FLAG is t, the
6583 function returns a list of all possible completions. If it is nil it
6584 returns a string, the longest possible completion, or t if VERILOG-STR is
6585 an exact match. If VERILOG-FLAG is 'lambda, the function returns t if
6586 VERILOG-STR is an exact match, nil otherwise."
6587 (save-excursion
6588 (let ((verilog-all nil)
6589 match)
6590
6591 ;; Set buffer to use for searching labels. This should be set
6592 ;; within functions which use verilog-completions
6593 (set-buffer verilog-buffer-to-use)
6594
6595 (let ((verilog-str verilog-str))
6596 ;; Build regular expression for functions
6597 (if (string= verilog-str "")
6598 (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
6599 (setq verilog-str (verilog-build-defun-re verilog-str)))
6600 (goto-char (point-min))
6601
6602 ;; Build a list of all possible completions
6603 (while (verilog-re-search-forward verilog-str nil t)
6604 (setq match (buffer-substring (match-beginning 2) (match-end 2)))
6605 (if (or (null verilog-pred)
6606 (funcall verilog-pred match))
6607 (setq verilog-all (cons match verilog-all)))))
6608
6609 ;; Now we have built a list of all matches. Give response to caller
6610 (verilog-completion-response))))
6611
6612 (defun verilog-goto-defun ()
6613 "Move to specified Verilog module/interface/task/function.
6614 The default is a name found in the buffer around point.
6615 If search fails, other files are checked based on
6616 `verilog-library-flags'."
6617 (interactive)
6618 (let* ((default (verilog-get-default-symbol))
6619 ;; The following variable is used in verilog-comp-function
6620 (verilog-buffer-to-use (current-buffer))
6621 (label (if (not (string= default ""))
6622 ;; Do completion with default
6623 (completing-read (concat "Goto-Label: (default "
6624 default ") ")
6625 'verilog-comp-defun nil nil "")
6626 ;; There is no default value. Complete without it
6627 (completing-read "Goto-Label: "
6628 'verilog-comp-defun nil nil "")))
6629 pt)
6630 ;; Make sure library paths are correct, in case need to resolve module
6631 (verilog-auto-reeval-locals)
6632 (verilog-getopt-flags)
6633 ;; If there was no response on prompt, use default value
6634 (if (string= label "")
6635 (setq label default))
6636 ;; Goto right place in buffer if label is not an empty string
6637 (or (string= label "")
6638 (progn
6639 (save-excursion
6640 (goto-char (point-min))
6641 (setq pt
6642 (re-search-forward (verilog-build-defun-re label t) nil t)))
6643 (when pt
6644 (goto-char pt)
6645 (beginning-of-line))
6646 pt)
6647 (verilog-goto-defun-file label))))
6648
6649 ;; Eliminate compile warning
6650 (defvar occur-pos-list)
6651
6652 (defun verilog-showscopes ()
6653 "List all scopes in this module."
6654 (interactive)
6655 (let ((buffer (current-buffer))
6656 (linenum 1)
6657 (nlines 0)
6658 (first 1)
6659 (prevpos (point-min))
6660 (final-context-start (make-marker))
6661 (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
6662 (with-output-to-temp-buffer "*Occur*"
6663 (save-excursion
6664 (message (format "Searching for %s ..." regexp))
6665 ;; Find next match, but give up if prev match was at end of buffer.
6666 (while (and (not (= prevpos (point-max)))
6667 (verilog-re-search-forward regexp nil t))
6668 (goto-char (match-beginning 0))
6669 (beginning-of-line)
6670 (save-match-data
6671 (setq linenum (+ linenum (count-lines prevpos (point)))))
6672 (setq prevpos (point))
6673 (goto-char (match-end 0))
6674 (let* ((start (save-excursion
6675 (goto-char (match-beginning 0))
6676 (forward-line (if (< nlines 0) nlines (- nlines)))
6677 (point)))
6678 (end (save-excursion
6679 (goto-char (match-end 0))
6680 (if (> nlines 0)
6681 (forward-line (1+ nlines))
6682 (forward-line 1))
6683 (point)))
6684 (tag (format "%3d" linenum))
6685 (empty (make-string (length tag) ?\ ))
6686 tem)
6687 (save-excursion
6688 (setq tem (make-marker))
6689 (set-marker tem (point))
6690 (set-buffer standard-output)
6691 (setq occur-pos-list (cons tem occur-pos-list))
6692 (or first (zerop nlines)
6693 (insert "--------\n"))
6694 (setq first nil)
6695 (insert-buffer-substring buffer start end)
6696 (backward-char (- end start))
6697 (setq tem (if (< nlines 0) (- nlines) nlines))
6698 (while (> tem 0)
6699 (insert empty ?:)
6700 (forward-line 1)
6701 (setq tem (1- tem)))
6702 (let ((this-linenum linenum))
6703 (set-marker final-context-start
6704 (+ (point) (- (match-end 0) (match-beginning 0))))
6705 (while (< (point) final-context-start)
6706 (if (null tag)
6707 (setq tag (format "%3d" this-linenum)))
6708 (insert tag ?:)))))))
6709 (set-buffer-modified-p nil))))
6710
6711
6712 ;; Highlight helper functions
6713 (defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
6714 (defun verilog-within-translate-off ()
6715 "Return point if within translate-off region, else nil."
6716 (and (save-excursion
6717 (re-search-backward
6718 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
6719 nil t))
6720 (equal "off" (match-string 2))
6721 (point)))
6722
6723 (defun verilog-start-translate-off (limit)
6724 "Return point before translate-off directive if before LIMIT, else nil."
6725 (when (re-search-forward
6726 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6727 limit t)
6728 (match-beginning 0)))
6729
6730 (defun verilog-back-to-start-translate-off (limit)
6731 "Return point before translate-off directive if before LIMIT, else nil."
6732 (when (re-search-backward
6733 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6734 limit t)
6735 (match-beginning 0)))
6736
6737 (defun verilog-end-translate-off (limit)
6738 "Return point after translate-on directive if before LIMIT, else nil."
6739
6740 (re-search-forward (concat
6741 "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
6742
6743 (defun verilog-match-translate-off (limit)
6744 "Match a translate-off block, setting `match-data' and returning t, else nil.
6745 Bound search by LIMIT."
6746 (when (< (point) limit)
6747 (let ((start (or (verilog-within-translate-off)
6748 (verilog-start-translate-off limit)))
6749 (case-fold-search t))
6750 (when start
6751 (let ((end (or (verilog-end-translate-off limit) limit)))
6752 (set-match-data (list start end))
6753 (goto-char end))))))
6754
6755 (defun verilog-font-lock-match-item (limit)
6756 "Match, and move over, any declaration item after point.
6757 Bound search by LIMIT. Adapted from
6758 `font-lock-match-c-style-declaration-item-and-skip-to-next'."
6759 (condition-case nil
6760 (save-restriction
6761 (narrow-to-region (point-min) limit)
6762 ;; match item
6763 (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
6764 (save-match-data
6765 (goto-char (match-end 1))
6766 ;; move to next item
6767 (if (looking-at "\\(\\s-*,\\)")
6768 (goto-char (match-end 1))
6769 (end-of-line) t))))
6770 (error nil)))
6771
6772
6773 ;; Added by Subbu Meiyappan for Header
6774
6775 (defun verilog-header ()
6776 "Insert a standard Verilog file header.
6777 See also `verilog-sk-header' for an alternative format."
6778 (interactive)
6779 (let ((start (point)))
6780 (insert "\
6781 //-----------------------------------------------------------------------------
6782 // Title : <title>
6783 // Project : <project>
6784 //-----------------------------------------------------------------------------
6785 // File : <filename>
6786 // Author : <author>
6787 // Created : <credate>
6788 // Last modified : <moddate>
6789 //-----------------------------------------------------------------------------
6790 // Description :
6791 // <description>
6792 //-----------------------------------------------------------------------------
6793 // Copyright (c) <copydate> by <company> This model is the confidential and
6794 // proprietary property of <company> and the possession or use of this
6795 // file requires a written license from <company>.
6796 //------------------------------------------------------------------------------
6797 // Modification history :
6798 // <modhist>
6799 //-----------------------------------------------------------------------------
6800
6801 ")
6802 (goto-char start)
6803 (search-forward "<filename>")
6804 (replace-match (buffer-name) t t)
6805 (search-forward "<author>") (replace-match "" t t)
6806 (insert (user-full-name))
6807 (insert " <" (user-login-name) "@" (system-name) ">")
6808 (search-forward "<credate>") (replace-match "" t t)
6809 (verilog-insert-date)
6810 (search-forward "<moddate>") (replace-match "" t t)
6811 (verilog-insert-date)
6812 (search-forward "<copydate>") (replace-match "" t t)
6813 (verilog-insert-year)
6814 (search-forward "<modhist>") (replace-match "" t t)
6815 (verilog-insert-date)
6816 (insert " : created")
6817 (goto-char start)
6818 (let (string)
6819 (setq string (read-string "title: "))
6820 (search-forward "<title>")
6821 (replace-match string t t)
6822 (setq string (read-string "project: " verilog-project))
6823 (setq verilog-project string)
6824 (search-forward "<project>")
6825 (replace-match string t t)
6826 (setq string (read-string "Company: " verilog-company))
6827 (setq verilog-company string)
6828 (search-forward "<company>")
6829 (replace-match string t t)
6830 (search-forward "<company>")
6831 (replace-match string t t)
6832 (search-forward "<company>")
6833 (replace-match string t t)
6834 (search-backward "<description>")
6835 (replace-match "" t t))))
6836
6837 ;; verilog-header Uses the verilog-insert-date function
6838
6839 (defun verilog-insert-date ()
6840 "Insert date from the system."
6841 (interactive)
6842 (if verilog-date-scientific-format
6843 (insert (format-time-string "%Y/%m/%d"))
6844 (insert (format-time-string "%d.%m.%Y"))))
6845
6846 (defun verilog-insert-year ()
6847 "Insert year from the system."
6848 (interactive)
6849 (insert (format-time-string "%Y")))
6850
6851 \f
6852 ;;
6853 ;; Signal list parsing
6854 ;;
6855
6856 ;; Elements of a signal list
6857 (defsubst verilog-sig-new (name bits comment mem enum signed type multidim modport)
6858 (list name bits comment mem enum signed type multidim modport))
6859 (defsubst verilog-sig-name (sig)
6860 (car sig))
6861 (defsubst verilog-sig-bits (sig)
6862 (nth 1 sig))
6863 (defsubst verilog-sig-comment (sig)
6864 (nth 2 sig))
6865 (defsubst verilog-sig-memory (sig)
6866 (nth 3 sig))
6867 (defsubst verilog-sig-enum (sig)
6868 (nth 4 sig))
6869 (defsubst verilog-sig-signed (sig)
6870 (nth 5 sig))
6871 (defsubst verilog-sig-type (sig)
6872 (nth 6 sig))
6873 (defsubst verilog-sig-multidim (sig)
6874 (nth 7 sig))
6875 (defsubst verilog-sig-multidim-string (sig)
6876 (if (verilog-sig-multidim sig)
6877 (let ((str "") (args (verilog-sig-multidim sig)))
6878 (while args
6879 (setq str (concat str (car args)))
6880 (setq args (cdr args)))
6881 str)))
6882 (defsubst verilog-sig-modport (sig)
6883 (nth 8 sig))
6884 (defsubst verilog-sig-width (sig)
6885 (verilog-make-width-expression (verilog-sig-bits sig)))
6886
6887 (defsubst verilog-alw-new (outputs temps inputs delayed)
6888 (list outputs temps inputs delayed))
6889 (defsubst verilog-alw-get-outputs (sigs)
6890 (nth 0 sigs))
6891 (defsubst verilog-alw-get-temps (sigs)
6892 (nth 1 sigs))
6893 (defsubst verilog-alw-get-inputs (sigs)
6894 (nth 2 sigs))
6895 (defsubst verilog-alw-get-uses-delayed (sigs)
6896 (nth 3 sigs))
6897
6898 (defsubst verilog-modi-new (name fob pt type)
6899 (vector name fob pt type))
6900 (defsubst verilog-modi-name (modi)
6901 (aref modi 0))
6902 (defsubst verilog-modi-file-or-buffer (modi)
6903 (aref modi 1))
6904 (defsubst verilog-modi-get-point (modi)
6905 (aref modi 2))
6906 (defsubst verilog-modi-get-type (modi) ;; "module" or "interface"
6907 (aref modi 3))
6908 (defsubst verilog-modi-get-decls (modi)
6909 (verilog-modi-cache-results modi 'verilog-read-decls))
6910 (defsubst verilog-modi-get-sub-decls (modi)
6911 (verilog-modi-cache-results modi 'verilog-read-sub-decls))
6912
6913 ;; Signal reading for given module
6914 ;; Note these all take modi's - as returned from verilog-modi-current
6915 (defsubst verilog-decls-new (out inout in wires regs assigns consts gparams interfaces)
6916 (vector out inout in wires regs assigns consts gparams interfaces))
6917 (defsubst verilog-decls-get-outputs (decls)
6918 (aref decls 0))
6919 (defsubst verilog-decls-get-inouts (decls)
6920 (aref decls 1))
6921 (defsubst verilog-decls-get-inputs (decls)
6922 (aref decls 2))
6923 (defsubst verilog-decls-get-wires (decls)
6924 (aref decls 3))
6925 (defsubst verilog-decls-get-regs (decls)
6926 (aref decls 4))
6927 (defsubst verilog-decls-get-assigns (decls)
6928 (aref decls 5))
6929 (defsubst verilog-decls-get-consts (decls)
6930 (aref decls 6))
6931 (defsubst verilog-decls-get-gparams (decls)
6932 (aref decls 7))
6933 (defsubst verilog-decls-get-interfaces (decls)
6934 (aref decls 8))
6935
6936 (defsubst verilog-subdecls-new (out inout in intf intfd)
6937 (vector out inout in intf intfd))
6938 (defsubst verilog-subdecls-get-outputs (subdecls)
6939 (aref subdecls 0))
6940 (defsubst verilog-subdecls-get-inouts (subdecls)
6941 (aref subdecls 1))
6942 (defsubst verilog-subdecls-get-inputs (subdecls)
6943 (aref subdecls 2))
6944 (defsubst verilog-subdecls-get-interfaces (subdecls)
6945 (aref subdecls 3))
6946 (defsubst verilog-subdecls-get-interfaced (subdecls)
6947 (aref subdecls 4))
6948
6949 (defun verilog-signals-not-in (in-list not-list)
6950 "Return list of signals in IN-LIST that aren't also in NOT-LIST.
6951 Also remove any duplicates in IN-LIST.
6952 Signals must be in standard (base vector) form."
6953 ;; This function is hot, so implemented as O(1)
6954 (cond ((eval-when-compile (fboundp 'make-hash-table))
6955 (let ((ht (make-hash-table :test 'equal :rehash-size 4.0))
6956 out-list)
6957 (while not-list
6958 (puthash (car (car not-list)) t ht)
6959 (setq not-list (cdr not-list)))
6960 (while in-list
6961 (when (not (gethash (car (car in-list)) ht))
6962 (setq out-list (cons (car in-list) out-list))
6963 (puthash (car (car in-list)) t ht))
6964 (setq in-list (cdr in-list)))
6965 (nreverse out-list)))
6966 ;; Slower Fallback if no hash tables (pre Emacs 21.1/XEmacs 21.4)
6967 (t
6968 (let (out-list)
6969 (while in-list
6970 (if (not (or (assoc (car (car in-list)) not-list)
6971 (assoc (car (car in-list)) out-list)))
6972 (setq out-list (cons (car in-list) out-list)))
6973 (setq in-list (cdr in-list)))
6974 (nreverse out-list)))))
6975 ;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
6976
6977 (defun verilog-signals-memory (in-list)
6978 "Return list of signals in IN-LIST that are memoried (multidimensional)."
6979 (let (out-list)
6980 (while in-list
6981 (if (nth 3 (car in-list))
6982 (setq out-list (cons (car in-list) out-list)))
6983 (setq in-list (cdr in-list)))
6984 out-list))
6985 ;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
6986
6987 (defun verilog-signals-sort-compare (a b)
6988 "Compare signal A and B for sorting."
6989 (string< (car a) (car b)))
6990
6991 (defun verilog-signals-not-params (in-list)
6992 "Return list of signals in IN-LIST that aren't parameters or numeric constants."
6993 (let (out-list)
6994 (while in-list
6995 (unless (boundp (intern (concat "vh-" (car (car in-list)))))
6996 (setq out-list (cons (car in-list) out-list)))
6997 (setq in-list (cdr in-list)))
6998 (nreverse out-list)))
6999
7000 (defun verilog-signals-combine-bus (in-list)
7001 "Return a list of signals in IN-LIST, with busses combined.
7002 Duplicate signals are also removed. For example A[2] and A[1] become A[2:1]."
7003 (let (combo buswarn
7004 out-list
7005 sig highbit lowbit ; Temp information about current signal
7006 sv-name sv-highbit sv-lowbit ; Details about signal we are forming
7007 sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
7008 sv-modport
7009 bus)
7010 ;; Shove signals so duplicated signals will be adjacent
7011 (setq in-list (sort in-list `verilog-signals-sort-compare))
7012 (while in-list
7013 (setq sig (car in-list))
7014 ;; No current signal; form from existing details
7015 (unless sv-name
7016 (setq sv-name (verilog-sig-name sig)
7017 sv-highbit nil
7018 sv-busstring nil
7019 sv-comment (verilog-sig-comment sig)
7020 sv-memory (verilog-sig-memory sig)
7021 sv-enum (verilog-sig-enum sig)
7022 sv-signed (verilog-sig-signed sig)
7023 sv-type (verilog-sig-type sig)
7024 sv-multidim (verilog-sig-multidim sig)
7025 sv-modport (verilog-sig-modport sig)
7026 combo ""
7027 buswarn ""))
7028 ;; Extract bus details
7029 (setq bus (verilog-sig-bits sig))
7030 (cond ((and bus
7031 (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
7032 (setq highbit (string-to-number (match-string 1 bus))
7033 lowbit (string-to-number
7034 (match-string 2 bus))))
7035 (and (string-match "\\[\\([0-9]+\\)\\]" bus)
7036 (setq highbit (string-to-number (match-string 1 bus))
7037 lowbit highbit))))
7038 ;; Combine bits in bus
7039 (if sv-highbit
7040 (setq sv-highbit (max highbit sv-highbit)
7041 sv-lowbit (min lowbit sv-lowbit))
7042 (setq sv-highbit highbit
7043 sv-lowbit lowbit)))
7044 (bus
7045 ;; String, probably something like `preproc:0
7046 (setq sv-busstring bus)))
7047 ;; Peek ahead to next signal
7048 (setq in-list (cdr in-list))
7049 (setq sig (car in-list))
7050 (cond ((and sig (equal sv-name (verilog-sig-name sig)))
7051 ;; Combine with this signal
7052 (when (and sv-busstring
7053 (not (equal sv-busstring (verilog-sig-bits sig))))
7054 (when nil ;; Debugging
7055 (message (concat "Warning, can't merge into single bus "
7056 sv-name bus
7057 ", the AUTOs may be wrong")))
7058 (setq buswarn ", Couldn't Merge"))
7059 (if (verilog-sig-comment sig) (setq combo ", ..."))
7060 (setq sv-memory (or sv-memory (verilog-sig-memory sig))
7061 sv-enum (or sv-enum (verilog-sig-enum sig))
7062 sv-signed (or sv-signed (verilog-sig-signed sig))
7063 sv-type (or sv-type (verilog-sig-type sig))
7064 sv-multidim (or sv-multidim (verilog-sig-multidim sig))
7065 sv-modport (or sv-modport (verilog-sig-modport sig))))
7066 ;; Doesn't match next signal, add to queue, zero in prep for next
7067 ;; Note sig may also be nil for the last signal in the list
7068 (t
7069 (setq out-list
7070 (cons (verilog-sig-new
7071 sv-name
7072 (or sv-busstring
7073 (if sv-highbit
7074 (concat "[" (int-to-string sv-highbit) ":"
7075 (int-to-string sv-lowbit) "]")))
7076 (concat sv-comment combo buswarn)
7077 sv-memory sv-enum sv-signed sv-type sv-multidim sv-modport)
7078 out-list)
7079 sv-name nil))))
7080 ;;
7081 out-list))
7082
7083 (defun verilog-sig-tieoff (sig &optional no-width)
7084 "Return tieoff expression for given SIG, with appropriate width.
7085 Ignore width if optional NO-WIDTH is set."
7086 (let* ((width (if no-width nil (verilog-sig-width sig))))
7087 (concat
7088 (if (and verilog-active-low-regexp
7089 (string-match verilog-active-low-regexp (verilog-sig-name sig)))
7090 "~" "")
7091 (cond ((not width)
7092 "0")
7093 ((string-match "^[0-9]+$" width)
7094 (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
7095 (t
7096 (concat "{" width "{1'b0}}"))))))
7097
7098 ;;
7099 ;; Port/Wire/Etc Reading
7100 ;;
7101
7102 (defun verilog-read-inst-backward-name ()
7103 "Internal. Move point back to beginning of inst-name."
7104 (verilog-backward-open-paren)
7105 (let (done)
7106 (while (not done)
7107 (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil) ; ] isn't word boundary
7108 (cond ((looking-at ")")
7109 (verilog-backward-open-paren))
7110 (t (setq done t)))))
7111 (while (looking-at "\\]")
7112 (verilog-backward-open-bracket)
7113 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
7114 (skip-chars-backward "a-zA-Z0-9`_$"))
7115
7116 (defun verilog-read-inst-module-matcher ()
7117 "Set match data 0 with module_name when point is inside instantiation."
7118 (verilog-read-inst-backward-name)
7119 ;; Skip over instantiation name
7120 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
7121 ;; Check for parameterized instantiations
7122 (when (looking-at ")")
7123 (verilog-backward-open-paren)
7124 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
7125 (skip-chars-backward "a-zA-Z0-9'_$")
7126 (looking-at "[a-zA-Z0-9`_\$]+")
7127 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7128 (buffer-substring-no-properties (match-beginning 0) (match-end 0))
7129 ;; Caller assumes match-beginning/match-end is still set
7130 )
7131
7132 (defun verilog-read-inst-module ()
7133 "Return module_name when point is inside instantiation."
7134 (save-excursion
7135 (verilog-read-inst-module-matcher)))
7136
7137 (defun verilog-read-inst-name ()
7138 "Return instance_name when point is inside instantiation."
7139 (save-excursion
7140 (verilog-read-inst-backward-name)
7141 (looking-at "[a-zA-Z0-9`_\$]+")
7142 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7143 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
7144
7145 (defun verilog-read-module-name ()
7146 "Return module name when after its ( or ;."
7147 (save-excursion
7148 (re-search-backward "[(;]")
7149 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
7150 (skip-chars-backward "a-zA-Z0-9`_$")
7151 (looking-at "[a-zA-Z0-9`_\$]+")
7152 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7153 (verilog-symbol-detick
7154 (buffer-substring-no-properties (match-beginning 0) (match-end 0)) t)))
7155
7156 (defun verilog-read-inst-param-value ()
7157 "Return list of parameters and values when point is inside instantiation."
7158 (save-excursion
7159 (verilog-read-inst-backward-name)
7160 ;; Skip over instantiation name
7161 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
7162 ;; If there are parameterized instantiations
7163 (when (looking-at ")")
7164 (let ((end-pt (point))
7165 params
7166 param-name paren-beg-pt param-value)
7167 (verilog-backward-open-paren)
7168 (while (verilog-re-search-forward-quick "\\." end-pt t)
7169 (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
7170 (skip-chars-backward "a-zA-Z0-9'_$")
7171 (looking-at "[a-zA-Z0-9`_\$]+")
7172 (setq param-name (buffer-substring-no-properties
7173 (match-beginning 0) (match-end 0)))
7174 (verilog-re-search-forward-quick "(" nil nil)
7175 (setq paren-beg-pt (point))
7176 (verilog-forward-close-paren)
7177 (setq param-value (verilog-string-remove-spaces
7178 (buffer-substring-no-properties
7179 paren-beg-pt (1- (point)))))
7180 (setq params (cons (list param-name param-value) params)))
7181 params))))
7182
7183 (defun verilog-read-auto-params (num-param &optional max-param)
7184 "Return parameter list inside auto.
7185 Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
7186 (let ((olist))
7187 (save-excursion
7188 ;; /*AUTOPUNT("parameter", "parameter")*/
7189 (search-backward "(")
7190 (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
7191 (setq olist (cons (match-string 1) olist))
7192 (goto-char (match-end 0))))
7193 (or (eq nil num-param)
7194 (<= num-param (length olist))
7195 (error "%s: Expected %d parameters" (verilog-point-text) num-param))
7196 (if (eq max-param nil) (setq max-param num-param))
7197 (or (eq nil max-param)
7198 (>= max-param (length olist))
7199 (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
7200 (nreverse olist)))
7201
7202 (defun verilog-read-decls ()
7203 "Compute signal declaration information for the current module at point.
7204 Return a array of [outputs inouts inputs wire reg assign const]."
7205 (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
7206 (functask 0) (paren 0) (sig-paren 0) (v2kargs-ok t)
7207 in-modport
7208 sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const
7209 sigs-gparam sigs-intf
7210 vec expect-signal keywd newsig rvalue enum io signed typedefed multidim
7211 modport)
7212 (save-excursion
7213 (verilog-beg-of-defun)
7214 (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
7215 (while (< (point) end-mod-point)
7216 ;;(if dbg (setq dbg (concat dbg (format "Pt %s Vec %s C%c Kwd'%s'\n" (point) vec (following-char) keywd))))
7217 (cond
7218 ((looking-at "//")
7219 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
7220 (setq enum (match-string 1)))
7221 (search-forward "\n"))
7222 ((looking-at "/\\*")
7223 (forward-char 2)
7224 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
7225 (setq enum (match-string 1)))
7226 (or (search-forward "*/")
7227 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7228 ((looking-at "(\\*")
7229 (forward-char 2)
7230 (or (looking-at "\\s-*)") ; It's an "always @ (*)"
7231 (search-forward "*)")
7232 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7233 ((eq ?\" (following-char))
7234 (or (re-search-forward "[^\\]\"" nil t) ;; don't forward-char first, since we look for a non backslash first
7235 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
7236 ((eq ?\; (following-char))
7237 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil
7238 v2kargs-ok nil in-modport nil)
7239 (forward-char 1))
7240 ((eq ?= (following-char))
7241 (setq rvalue t newsig nil)
7242 (forward-char 1))
7243 ((and (eq ?, (following-char))
7244 (eq paren sig-paren))
7245 (setq rvalue nil)
7246 (forward-char 1))
7247 ;; ,'s can occur inside {} & funcs
7248 ((looking-at "[{(]")
7249 (setq paren (1+ paren))
7250 (forward-char 1))
7251 ((looking-at "[})]")
7252 (setq paren (1- paren))
7253 (forward-char 1)
7254 (when (< paren sig-paren)
7255 (setq expect-signal nil))) ; ) that ends variables inside v2k arg list
7256 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
7257 (goto-char (match-end 0))
7258 (cond (newsig ; Memory, not just width. Patch last signal added's memory (nth 3)
7259 (setcar (cdr (cdr (cdr newsig)))
7260 (if (verilog-sig-memory newsig)
7261 (concat (verilog-sig-memory newsig) (match-string 1))
7262 (match-string 1))))
7263 (vec ;; Multidimensional
7264 (setq multidim (cons vec multidim))
7265 (setq vec (verilog-string-replace-matches
7266 "\\s-+" "" nil nil (match-string 1))))
7267 (t ;; Bit width
7268 (setq vec (verilog-string-replace-matches
7269 "\\s-+" "" nil nil (match-string 1))))))
7270 ;; Normal or escaped identifier -- note we remember the \ if escaped
7271 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
7272 (goto-char (match-end 0))
7273 (setq keywd (match-string 1))
7274 (when (string-match "^\\\\" (match-string 1))
7275 (setq keywd (concat keywd " "))) ;; Escaped ID needs space at end
7276 ;; Add any :: package names to same identifier
7277 (while (looking-at "\\s-*::\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
7278 (goto-char (match-end 0))
7279 (setq keywd (concat keywd "::" (match-string 1)))
7280 (when (string-match "^\\\\" (match-string 1))
7281 (setq keywd (concat keywd " ")))) ;; Escaped ID needs space at end
7282 (cond ((equal keywd "input")
7283 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
7284 expect-signal 'sigs-in io t modport nil))
7285 ((equal keywd "output")
7286 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
7287 expect-signal 'sigs-out io t modport nil))
7288 ((equal keywd "inout")
7289 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
7290 expect-signal 'sigs-inout io t modport nil))
7291 ((equal keywd "parameter")
7292 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7293 expect-signal 'sigs-gparam io t modport nil))
7294 ((member keywd '("wire" "tri" "tri0" "tri1" "triand" "trior" "wand" "wor"))
7295 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7296 expect-signal 'sigs-wire modport nil)))
7297 ((member keywd '("reg" "trireg"
7298 "byte" "shortint" "int" "longint" "integer" "time"
7299 "bit" "logic"
7300 "shortreal" "real" "realtime"
7301 "string" "event" "chandle"))
7302 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7303 expect-signal 'sigs-reg modport nil)))
7304 ((equal keywd "assign")
7305 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7306 expect-signal 'sigs-assign modport nil))
7307 ((member keywd '("supply0" "supply1" "supply"
7308 "localparam" "genvar"))
7309 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7310 expect-signal 'sigs-const modport nil)))
7311 ((equal keywd "signed")
7312 (setq signed "signed"))
7313 ((member keywd '("class" "clocking" "covergroup" "function"
7314 "property" "randsequence" "sequence" "task"))
7315 (setq functask (1+ functask)))
7316 ((member keywd '("endclass" "endclocking" "endgroup" "endfunction"
7317 "endproperty" "endsequence" "endtask"))
7318 (setq functask (1- functask)))
7319 ((equal keywd "modport")
7320 (setq in-modport t))
7321 ;; Ifdef? Ignore name of define
7322 ((member keywd '("`ifdef" "`ifndef" "`elsif"))
7323 (setq rvalue t))
7324 ;; Type?
7325 ((verilog-typedef-name-p keywd)
7326 (setq typedefed keywd))
7327 ;; Interface with optional modport in v2k arglist?
7328 ;; Skip over parsing modport, and take the interface name as the type
7329 ((and v2kargs-ok
7330 (eq paren 1)
7331 (not rvalue)
7332 (looking-at "\\s-*\\(\\.\\(\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*\\)\\|\\)\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*"))
7333 (when (match-end 2) (goto-char (match-end 2)))
7334 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed keywd multidim nil sig-paren paren
7335 expect-signal 'sigs-intf io t modport (match-string 2)))
7336 ;; Ignore dotted LHS assignments: "assign foo.bar = z;"
7337 ((looking-at "\\s-*\\.")
7338 (goto-char (match-end 0))
7339 (when (not rvalue)
7340 (setq expect-signal nil)))
7341 ;; New signal, maybe?
7342 ((and expect-signal
7343 (not rvalue)
7344 (eq functask 0)
7345 (not in-modport)
7346 (not (member keywd verilog-keywords)))
7347 ;; Add new signal to expect-signal's variable
7348 (setq newsig (verilog-sig-new keywd vec nil nil enum signed typedefed multidim modport))
7349 (set expect-signal (cons newsig
7350 (symbol-value expect-signal))))))
7351 (t
7352 (forward-char 1)))
7353 (skip-syntax-forward " "))
7354 ;; Return arguments
7355 (verilog-decls-new (nreverse sigs-out)
7356 (nreverse sigs-inout)
7357 (nreverse sigs-in)
7358 (nreverse sigs-wire)
7359 (nreverse sigs-reg)
7360 (nreverse sigs-assign)
7361 (nreverse sigs-const)
7362 (nreverse sigs-gparam)
7363 (nreverse sigs-intf)))))
7364
7365 (defvar verilog-read-sub-decls-in-interfaced nil
7366 "For `verilog-read-sub-decls', process next signal as under interfaced block.")
7367
7368 (defvar verilog-read-sub-decls-gate-ios nil
7369 "For `verilog-read-sub-decls', gate IO pins remaining, nil if non-primitive.")
7370
7371 (eval-when-compile
7372 ;; Prevent compile warnings; these are let's, not globals
7373 ;; Do not remove the eval-when-compile
7374 ;; - we want a error when we are debugging this code if they are refed.
7375 (defvar sigs-in)
7376 (defvar sigs-inout)
7377 (defvar sigs-out)
7378 (defvar sigs-intf)
7379 (defvar sigs-intfd))
7380
7381 (defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
7382 "For `verilog-read-sub-decls-line', add a signal."
7383 ;; sig eq t to indicate .name syntax
7384 ;;(message "vrsds: %s(%S)" port sig)
7385 (let ((dotname (eq sig t))
7386 portdata)
7387 (when sig
7388 (setq port (verilog-symbol-detick-denumber port))
7389 (setq sig (if dotname port (verilog-symbol-detick-denumber sig)))
7390 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
7391 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
7392 (unless (or (not sig)
7393 (equal sig "")) ;; Ignore .foo(1'b1) assignments
7394 (cond ((or (setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
7395 (equal "inout" verilog-read-sub-decls-gate-ios))
7396 (setq sigs-inout
7397 (cons (verilog-sig-new
7398 sig
7399 (if dotname (verilog-sig-bits portdata) vec)
7400 (concat "To/From " comment)
7401 (verilog-sig-memory portdata)
7402 nil
7403 (verilog-sig-signed portdata)
7404 (verilog-sig-type portdata)
7405 multidim nil)
7406 sigs-inout)))
7407 ((or (setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
7408 (equal "output" verilog-read-sub-decls-gate-ios))
7409 (setq sigs-out
7410 (cons (verilog-sig-new
7411 sig
7412 (if dotname (verilog-sig-bits portdata) vec)
7413 (concat "From " comment)
7414 (verilog-sig-memory portdata)
7415 nil
7416 (verilog-sig-signed portdata)
7417 (verilog-sig-type portdata)
7418 multidim nil)
7419 sigs-out)))
7420 ((or (setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
7421 (equal "input" verilog-read-sub-decls-gate-ios))
7422 (setq sigs-in
7423 (cons (verilog-sig-new
7424 sig
7425 (if dotname (verilog-sig-bits portdata) vec)
7426 (concat "To " comment)
7427 (verilog-sig-memory portdata)
7428 nil
7429 (verilog-sig-signed portdata)
7430 (verilog-sig-type portdata)
7431 multidim nil)
7432 sigs-in)))
7433 ((setq portdata (assoc port (verilog-decls-get-interfaces submoddecls)))
7434 (setq sigs-intf
7435 (cons (verilog-sig-new
7436 sig
7437 (if dotname (verilog-sig-bits portdata) vec)
7438 (concat "To/From " comment)
7439 (verilog-sig-memory portdata)
7440 nil
7441 (verilog-sig-signed portdata)
7442 (verilog-sig-type portdata)
7443 multidim nil)
7444 sigs-intf)))
7445 ((setq portdata (and verilog-read-sub-decls-in-interfaced
7446 (or (assoc port (verilog-decls-get-regs submoddecls))
7447 (assoc port (verilog-decls-get-wires submoddecls)))))
7448 (setq sigs-intfd
7449 (cons (verilog-sig-new
7450 sig
7451 (if dotname (verilog-sig-bits portdata) vec)
7452 (concat "To/From " comment)
7453 (verilog-sig-memory portdata)
7454 nil
7455 (verilog-sig-signed portdata)
7456 (verilog-sig-type portdata)
7457 multidim nil)
7458 sigs-intf)))
7459 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
7460 )))))
7461
7462 (defun verilog-read-sub-decls-expr (submoddecls comment port expr)
7463 "For `verilog-read-sub-decls-line', parse a subexpression and add signals."
7464 ;;(message "vrsde: '%s'" expr)
7465 ;; Replace special /*[....]*/ comments inserted by verilog-auto-inst-port
7466 (setq expr (verilog-string-replace-matches "/\\*\\(\\[[^*]+\\]\\)\\*/" "\\1" nil nil expr))
7467 ;; Remove front operators
7468 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
7469 ;;
7470 (cond
7471 ;; {..., a, b} requires us to recurse on a,b
7472 ;; To support {#{},{#{a,b}} we'll just split everything on [{},]
7473 ((string-match "^\\s-*{\\(.*\\)}\\s-*$" expr)
7474 (unless verilog-auto-ignore-concat
7475 (let ((mlst (split-string (match-string 1 expr) "[{},]"))
7476 mstr)
7477 (while (setq mstr (pop mlst))
7478 (verilog-read-sub-decls-expr submoddecls comment port mstr)))))
7479 (t
7480 (let (sig vec multidim)
7481 ;; Remove leading reduction operators, etc
7482 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
7483 ;;(message "vrsde-ptop: '%s'" expr)
7484 (cond ;; Find \signal. Final space is part of escaped signal name
7485 ((string-match "^\\s-*\\(\\\\[^ \t\n\f]+\\s-\\)" expr)
7486 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
7487 (setq sig (match-string 1 expr)
7488 expr (substring expr (match-end 0))))
7489 ;; Find signal
7490 ((string-match "^\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" expr)
7491 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
7492 (setq sig (verilog-string-remove-spaces (match-string 1 expr))
7493 expr (substring expr (match-end 0)))))
7494 ;; Find [vector] or [multi][multi][multi][vector]
7495 (while (string-match "^\\s-*\\(\\[[^]]+\\]\\)" expr)
7496 ;;(message "vrsde-v: '%s'" (match-string 1 expr))
7497 (when vec (setq multidim (cons vec multidim)))
7498 (setq vec (match-string 1 expr)
7499 expr (substring expr (match-end 0))))
7500 ;; If found signal, and nothing unrecognized, add the signal
7501 ;;(message "vrsde-rem: '%s'" expr)
7502 (when (and sig (string-match "^\\s-*$" expr))
7503 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))))
7504
7505 (defun verilog-read-sub-decls-line (submoddecls comment)
7506 "For `verilog-read-sub-decls', read lines of port defs until none match.
7507 Inserts the list of signals found, using submodi to look up each port."
7508 (let (done port)
7509 (save-excursion
7510 (forward-line 1)
7511 (while (not done)
7512 ;; Get port name
7513 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
7514 (setq port (match-string 1))
7515 (goto-char (match-end 0)))
7516 ;; .\escaped (
7517 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
7518 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
7519 (goto-char (match-end 0)))
7520 ;; .name
7521 ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*[,)/]")
7522 (verilog-read-sub-decls-sig
7523 submoddecls comment (match-string 1) t ; sig==t for .name
7524 nil nil) ; vec multidim
7525 (setq port nil))
7526 ;; .\escaped_name
7527 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*[,)/]")
7528 (verilog-read-sub-decls-sig
7529 submoddecls comment (concat (match-string 1) " ") t ; sig==t for .name
7530 nil nil) ; vec multidim
7531 (setq port nil))
7532 ;; random
7533 ((looking-at "\\s-*\\.[^(]*(")
7534 (setq port nil) ;; skip this line
7535 (goto-char (match-end 0)))
7536 (t
7537 (setq port nil done t))) ;; Unknown, ignore rest of line
7538 ;; Get signal name. Point is at the first-non-space after (
7539 ;; We intentionally ignore (non-escaped) signals with .s in them
7540 ;; this prevents AUTOWIRE etc from noticing hierarchical sigs.
7541 (when port
7542 (cond ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*)")
7543 (verilog-read-sub-decls-sig
7544 submoddecls comment port
7545 (verilog-string-remove-spaces (match-string 1)) ; sig
7546 nil nil)) ; vec multidim
7547 ;;
7548 ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
7549 (verilog-read-sub-decls-sig
7550 submoddecls comment port
7551 (verilog-string-remove-spaces (match-string 1)) ; sig
7552 (match-string 2) nil)) ; vec multidim
7553 ;; Fastpath was above looking-at's.
7554 ;; For something more complicated invoke a parser
7555 ((looking-at "[^)]+")
7556 (verilog-read-sub-decls-expr
7557 submoddecls comment port
7558 (buffer-substring
7559 (point) (1- (progn (search-backward "(") ; start at (
7560 (forward-sexp 1) (point)))))))) ; expr
7561 ;;
7562 (forward-line 1)))))
7563
7564 (defun verilog-read-sub-decls-gate (submoddecls comment submod end-inst-point)
7565 "For `verilog-read-sub-decls', read lines of UDP gate decl until none match.
7566 Inserts the list of signals found."
7567 (save-excursion
7568 (let ((iolist (cdr (assoc submod verilog-gate-ios))))
7569 (while (< (point) end-inst-point)
7570 ;; Get primitive's signal name, as will never have port, and no trailing )
7571 (cond ((looking-at "//")
7572 (search-forward "\n"))
7573 ((looking-at "/\\*")
7574 (or (search-forward "*/")
7575 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7576 ((looking-at "(\\*")
7577 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7578 (search-forward "*)")
7579 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7580 ;; On pins, parse and advance to next pin
7581 ;; Looking at pin, but *not* an // Output comment, or ) to end the inst
7582 ((looking-at "\\s-*[a-zA-Z0-9`_$({}\\\\][^,]*")
7583 (goto-char (match-end 0))
7584 (setq verilog-read-sub-decls-gate-ios (or (car iolist) "input")
7585 iolist (cdr iolist))
7586 (verilog-read-sub-decls-expr
7587 submoddecls comment "primitive_port"
7588 (match-string 0)))
7589 (t
7590 (forward-char 1)
7591 (skip-syntax-forward " ")))))))
7592
7593 (defun verilog-read-sub-decls ()
7594 "Internally parse signals going to modules under this module.
7595 Return a array of [ outputs inouts inputs ] signals for modules that are
7596 instantiated in this module. For example if declare A A (.B(SIG)) and SIG
7597 is a output, then SIG will be included in the list.
7598
7599 This only works on instantiations created with /*AUTOINST*/ converted by
7600 \\[verilog-auto-inst]. Otherwise, it would have to read in the whole
7601 component library to determine connectivity of the design.
7602
7603 One work around for this problem is to manually create // Inputs and //
7604 Outputs comments above subcell signals, for example:
7605
7606 module ModuleName (
7607 // Outputs
7608 .out (out),
7609 // Inputs
7610 .in (in));"
7611 (save-excursion
7612 (let ((end-mod-point (verilog-get-end-of-defun t))
7613 st-point end-inst-point
7614 ;; below 3 modified by verilog-read-sub-decls-line
7615 sigs-out sigs-inout sigs-in sigs-intf sigs-intfd)
7616 (verilog-beg-of-defun)
7617 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
7618 (save-excursion
7619 (goto-char (match-beginning 0))
7620 (unless (verilog-inside-comment-p)
7621 ;; Attempt to snarf a comment
7622 (let* ((submod (verilog-read-inst-module))
7623 (inst (verilog-read-inst-name))
7624 (subprim (member submod verilog-gate-keywords))
7625 (comment (concat inst " of " submod ".v"))
7626 submodi submoddecls)
7627 (cond
7628 (subprim
7629 (setq submodi `primitive
7630 submoddecls (verilog-decls-new nil nil nil nil nil nil nil nil nil)
7631 comment (concat inst " of " submod))
7632 (verilog-backward-open-paren)
7633 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
7634 st-point (point))
7635 (forward-char 1)
7636 (verilog-read-sub-decls-gate submoddecls comment submod end-inst-point))
7637 ;; Non-primitive
7638 (t
7639 (when (setq submodi (verilog-modi-lookup submod t))
7640 (setq submoddecls (verilog-modi-get-decls submodi)
7641 verilog-read-sub-decls-gate-ios nil)
7642 (verilog-backward-open-paren)
7643 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
7644 st-point (point))
7645 ;; This could have used a list created by verilog-auto-inst
7646 ;; However I want it to be runnable even on user's manually added signals
7647 (let ((verilog-read-sub-decls-in-interfaced t))
7648 (while (re-search-forward "\\s *(?\\s *// Interfaced" end-inst-point t)
7649 (verilog-read-sub-decls-line submoddecls comment))) ;; Modifies sigs-ifd
7650 (goto-char st-point)
7651 (while (re-search-forward "\\s *(?\\s *// Interfaces" end-inst-point t)
7652 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
7653 (goto-char st-point)
7654 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
7655 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
7656 (goto-char st-point)
7657 (while (re-search-forward "\\s *(?\\s *// Inouts" end-inst-point t)
7658 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
7659 (goto-char st-point)
7660 (while (re-search-forward "\\s *(?\\s *// Inputs" end-inst-point t)
7661 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
7662 )))))))
7663 ;; Combine duplicate bits
7664 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
7665 (verilog-subdecls-new
7666 (verilog-signals-combine-bus (nreverse sigs-out))
7667 (verilog-signals-combine-bus (nreverse sigs-inout))
7668 (verilog-signals-combine-bus (nreverse sigs-in))
7669 (verilog-signals-combine-bus (nreverse sigs-intf))
7670 (verilog-signals-combine-bus (nreverse sigs-intfd))))))
7671
7672 (defun verilog-read-inst-pins ()
7673 "Return an array of [ pins ] for the current instantiation at point.
7674 For example if declare A A (.B(SIG)) then B will be included in the list."
7675 (save-excursion
7676 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
7677 pins pin)
7678 (verilog-backward-open-paren)
7679 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
7680 (setq pin (match-string 1))
7681 (unless (verilog-inside-comment-p)
7682 (setq pins (cons (list pin) pins))
7683 (when (looking-at "(")
7684 (forward-sexp 1))))
7685 (vector pins))))
7686
7687 (defun verilog-read-arg-pins ()
7688 "Return an array of [ pins ] for the current argument declaration at point."
7689 (save-excursion
7690 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
7691 pins pin)
7692 (verilog-backward-open-paren)
7693 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
7694 (setq pin (match-string 1))
7695 (unless (verilog-inside-comment-p)
7696 (setq pins (cons (list pin) pins))))
7697 (vector pins))))
7698
7699 (defun verilog-read-auto-constants (beg end-mod-point)
7700 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
7701 ;; Insert new
7702 (save-excursion
7703 (let (sig-list tpl-end-pt)
7704 (goto-char beg)
7705 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
7706 (if (not (looking-at "\\s *("))
7707 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
7708 (search-forward "(" end-mod-point)
7709 (setq tpl-end-pt (save-excursion
7710 (backward-char 1)
7711 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7712 (backward-char 1)
7713 (point)))
7714 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
7715 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
7716 sig-list)))
7717
7718 (defvar verilog-cache-has-lisp nil "True if any AUTO_LISP in buffer.")
7719 (make-variable-buffer-local 'verilog-cache-has-lisp)
7720
7721 (defun verilog-read-auto-lisp-present ()
7722 "Set `verilog-cache-has-lisp' if any AUTO_LISP in this buffer."
7723 (save-excursion
7724 (setq verilog-cache-has-lisp (re-search-forward "\\<AUTO_LISP(" nil t))))
7725
7726 (defun verilog-read-auto-lisp (start end)
7727 "Look for and evaluate a AUTO_LISP between START and END.
7728 Must call `verilog-read-auto-lisp-present' before this function."
7729 ;; This function is expensive for large buffers, so we cache if any AUTO_LISP exists
7730 (when verilog-cache-has-lisp
7731 (save-excursion
7732 (goto-char start)
7733 (while (re-search-forward "\\<AUTO_LISP(" end t)
7734 (backward-char)
7735 (let* ((beg-pt (prog1 (point)
7736 (forward-sexp 1))) ;; Closing paren
7737 (end-pt (point)))
7738 (eval-region beg-pt end-pt nil))))))
7739
7740 (eval-when-compile
7741 ;; Prevent compile warnings; these are let's, not globals
7742 ;; Do not remove the eval-when-compile
7743 ;; - we want a error when we are debugging this code if they are refed.
7744 (defvar sigs-in)
7745 (defvar sigs-out)
7746 (defvar sigs-temp)
7747 (defvar uses-delayed)
7748 (defvar vector-skip-list))
7749
7750 (defun verilog-read-always-signals-recurse
7751 (exit-keywd rvalue temp-next)
7752 "Recursive routine for parentheses/bracket matching.
7753 EXIT-KEYWD is expression to stop at, nil if top level.
7754 RVALUE is true if at right hand side of equal.
7755 IGNORE-NEXT is true to ignore next token, fake from inside case statement."
7756 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
7757 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-list end-else-check
7758 ignore-next)
7759 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue temp-next))))
7760 (while (not (or (eobp) gotend))
7761 (cond
7762 ((looking-at "//")
7763 (search-forward "\n"))
7764 ((looking-at "/\\*")
7765 (or (search-forward "*/")
7766 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7767 ((looking-at "(\\*")
7768 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7769 (search-forward "*)")
7770 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7771 (t (setq keywd (buffer-substring-no-properties
7772 (point)
7773 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7774 (forward-char 1))
7775 (point)))
7776 sig-last-tolk sig-tolk
7777 sig-tolk nil)
7778 ;;(if dbg (setq dbg (concat dbg (format "\tPt=%S %S\trv=%S in=%S ee=%S gs=%S\n" (point) keywd rvalue ignore-next end-else-check got-sig))))
7779 (cond
7780 ((equal keywd "\"")
7781 (or (re-search-forward "[^\\]\"" nil t)
7782 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
7783 ;; else at top level loop, keep parsing
7784 ((and end-else-check (equal keywd "else"))
7785 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
7786 ;; no forward movement, want to see else in lower loop
7787 (setq end-else-check nil))
7788 ;; End at top level loop
7789 ((and end-else-check (looking-at "[^ \t\n\f]"))
7790 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
7791 (setq gotend t))
7792 ;; Final statement?
7793 ((and exit-keywd (equal keywd exit-keywd))
7794 (setq gotend t)
7795 (forward-char (length keywd)))
7796 ;; Standard tokens...
7797 ((equal keywd ";")
7798 (setq ignore-next nil rvalue semi-rvalue)
7799 ;; Final statement at top level loop?
7800 (when (not exit-keywd)
7801 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
7802 (setq end-else-check t))
7803 (forward-char 1))
7804 ((equal keywd "'")
7805 (if (looking-at "'[sS]?[hdxboHDXBO]?[ \t]*[0-9a-fA-F_xzXZ?]+")
7806 (goto-char (match-end 0))
7807 (forward-char 1)))
7808 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
7809 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
7810 (setq ignore-next nil rvalue nil))
7811 ((equal "?" exit-keywd) ;; x?y:z rvalue
7812 ) ;; NOP
7813 ((equal "]" exit-keywd) ;; [x:y] rvalue
7814 ) ;; NOP
7815 (got-sig ;; label: statement
7816 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
7817 ((not rvalue) ;; begin label
7818 (setq ignore-next t rvalue nil)))
7819 (forward-char 1))
7820 ((equal keywd "=")
7821 (if (and (eq (char-before) ?< )
7822 (not rvalue))
7823 (setq uses-delayed 1))
7824 (setq ignore-next nil rvalue t)
7825 (forward-char 1))
7826 ((equal keywd "?")
7827 (forward-char 1)
7828 (verilog-read-always-signals-recurse ":" rvalue nil))
7829 ((equal keywd "[")
7830 (forward-char 1)
7831 (verilog-read-always-signals-recurse "]" t nil))
7832 ((equal keywd "(")
7833 (forward-char 1)
7834 (cond (sig-last-tolk ;; Function call; zap last signal
7835 (setq got-sig nil)))
7836 (cond ((equal last-keywd "for")
7837 ;; temp-next: Variables on LHS are lvalues, but generally we want
7838 ;; to ignore them, assuming they are loop increments
7839 (verilog-read-always-signals-recurse ";" nil t)
7840 (verilog-read-always-signals-recurse ";" t nil)
7841 (verilog-read-always-signals-recurse ")" nil nil))
7842 (t (verilog-read-always-signals-recurse ")" t nil))))
7843 ((equal keywd "begin")
7844 (skip-syntax-forward "w_")
7845 (verilog-read-always-signals-recurse "end" nil nil)
7846 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
7847 (setq ignore-next nil rvalue semi-rvalue)
7848 (if (not exit-keywd) (setq end-else-check t)))
7849 ((member keywd '("case" "casex" "casez"))
7850 (skip-syntax-forward "w_")
7851 (verilog-read-always-signals-recurse "endcase" t nil)
7852 (setq ignore-next nil rvalue semi-rvalue)
7853 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
7854 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
7855 (cond ((member keywd '("`ifdef" "`ifndef" "`elsif"))
7856 (setq ignore-next t))
7857 ((or ignore-next
7858 (member keywd verilog-keywords)
7859 (string-match "^\\$" keywd)) ;; PLI task
7860 (setq ignore-next nil))
7861 (t
7862 (setq keywd (verilog-symbol-detick-denumber keywd))
7863 (when got-sig
7864 (set got-list (cons got-sig (symbol-value got-list)))
7865 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S got-list=%S\n" got-sig got-list))))
7866 )
7867 (setq got-list (cond (temp-next 'sigs-temp)
7868 (rvalue 'sigs-in)
7869 (t 'sigs-out))
7870 got-sig (if (or (not keywd)
7871 (assoc keywd (symbol-value got-list)))
7872 nil (list keywd nil nil))
7873 temp-next nil
7874 sig-tolk t)))
7875 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7876 (t
7877 (forward-char 1)))
7878 ;; End of non-comment token
7879 (setq last-keywd keywd)))
7880 (skip-syntax-forward " "))
7881 ;; Append the final pending signal
7882 (when got-sig
7883 ;;(if dbg (setq dbg (concat dbg (format "\t\tfinal got-sig=%S got-list=%s\n" got-sig got-list))))
7884 (set got-list (cons got-sig (symbol-value got-list)))
7885 (setq got-sig nil))
7886 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
7887 ))
7888
7889 (defun verilog-read-always-signals ()
7890 "Parse always block at point and return list of (outputs inout inputs)."
7891 (save-excursion
7892 (let* (;;(dbg "")
7893 sigs-out sigs-temp sigs-in
7894 uses-delayed) ;; Found signal/rvalue; push if not function
7895 (search-forward ")")
7896 (verilog-read-always-signals-recurse nil nil nil)
7897 ;;(if dbg (with-current-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg ""))
7898 ;; Return what was found
7899 (verilog-alw-new sigs-out sigs-temp sigs-in uses-delayed))))
7900
7901 (defun verilog-read-instants ()
7902 "Parse module at point and return list of ( ( file instance ) ... )."
7903 (verilog-beg-of-defun)
7904 (let* ((end-mod-point (verilog-get-end-of-defun t))
7905 (state nil)
7906 (instants-list nil))
7907 (save-excursion
7908 (while (< (point) end-mod-point)
7909 ;; Stay at level 0, no comments
7910 (while (progn
7911 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
7912 (or (> (car state) 0) ; in parens
7913 (nth 5 state) ; comment
7914 ))
7915 (forward-line 1))
7916 (beginning-of-line)
7917 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
7918 ;;(if (looking-at "^\\(.+\\)$")
7919 (let ((module (match-string 1))
7920 (instant (match-string 2)))
7921 (if (not (member module verilog-keywords))
7922 (setq instants-list (cons (list module instant) instants-list)))))
7923 (forward-line 1)))
7924 instants-list))
7925
7926
7927 (defun verilog-read-auto-template (module)
7928 "Look for a auto_template for the instantiation of the given MODULE.
7929 If found returns the signal name connections. Return REGEXP and
7930 list of ( (signal_name connection_name)... )."
7931 (save-excursion
7932 ;; Find beginning
7933 (let ((tpl-regexp "\\([0-9]+\\)")
7934 (lineno 0)
7935 (templateno 0)
7936 (pt (point))
7937 tpl-sig-list tpl-wild-list tpl-end-pt rep)
7938 ;; Note this search is expensive, as we hunt from mod-begin to point
7939 ;; for every instantiation. Likewise in verilog-read-auto-lisp.
7940 ;; So, we look first for an exact string rather than a slow regexp.
7941 ;; Someday we may keep a cache of every template, but this would also
7942 ;; need to record the relative position of each AUTOINST, as multiple
7943 ;; templates exist for each module, and we're inserting lines.
7944 (cond ((or
7945 (verilog-re-search-backward-substr
7946 "AUTO_TEMPLATE"
7947 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
7948 ;; Also try forward of this AUTOINST
7949 ;; This is for historical support; this isn't speced as working
7950 (progn
7951 (goto-char pt)
7952 (verilog-re-search-forward-substr
7953 "AUTO_TEMPLATE"
7954 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
7955 (goto-char (match-end 0))
7956 ;; Parse "REGEXP"
7957 ;; We reserve @"..." for future lisp expressions that evaluate
7958 ;; once-per-AUTOINST
7959 (when (looking-at "\\s-*\"\\([^\"]*\\)\"")
7960 (setq tpl-regexp (match-string 1))
7961 (goto-char (match-end 0)))
7962 (search-forward "(")
7963 ;; Parse lines in the template
7964 (when verilog-auto-inst-template-numbers
7965 (save-excursion
7966 (goto-char (point-min))
7967 (while (search-forward "AUTO_TEMPLATE" nil t)
7968 (setq templateno (1+ templateno)))))
7969 (setq tpl-end-pt (save-excursion
7970 (backward-char 1)
7971 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7972 (backward-char 1)
7973 (point)))
7974 ;;
7975 (while (< (point) tpl-end-pt)
7976 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7977 (setq tpl-sig-list (cons (list
7978 (match-string-no-properties 1)
7979 (match-string-no-properties 2)
7980 templateno lineno)
7981 tpl-sig-list))
7982 (goto-char (match-end 0)))
7983 ;; Regexp form??
7984 ((looking-at
7985 ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
7986 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7987 (setq rep (match-string-no-properties 3))
7988 (goto-char (match-end 0))
7989 (setq tpl-wild-list
7990 (cons (list
7991 (concat "^"
7992 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
7993 (match-string 1))
7994 "$")
7995 rep
7996 templateno lineno)
7997 tpl-wild-list)))
7998 ((looking-at "[ \t\f]+")
7999 (goto-char (match-end 0)))
8000 ((looking-at "\n")
8001 (setq lineno (1+ lineno))
8002 (goto-char (match-end 0)))
8003 ((looking-at "//")
8004 (search-forward "\n"))
8005 ((looking-at "/\\*")
8006 (forward-char 2)
8007 (or (search-forward "*/")
8008 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8009 (t
8010 (error "%s: AUTO_TEMPLATE parsing error: %s"
8011 (verilog-point-text)
8012 (progn (looking-at ".*$") (match-string 0))))))
8013 ;; Return
8014 (vector tpl-regexp
8015 (list tpl-sig-list tpl-wild-list)))
8016 ;; If no template found
8017 (t (vector tpl-regexp nil))))))
8018 ;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
8019
8020 (defun verilog-set-define (defname defvalue &optional buffer enumname)
8021 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
8022 Optionally associate it with the specified enumeration ENUMNAME."
8023 (with-current-buffer (or buffer (current-buffer))
8024 (let ((mac (intern (concat "vh-" defname))))
8025 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
8026 ;; Need to define to a constant if no value given
8027 (set (make-local-variable mac)
8028 (if (equal defvalue "") "1" defvalue)))
8029 (if enumname
8030 (let ((enumvar (intern (concat "venum-" enumname))))
8031 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
8032 (unless (boundp enumvar) (set enumvar nil))
8033 (add-to-list (make-local-variable enumvar) defname)))))
8034
8035 (defun verilog-read-defines (&optional filename recurse subcall)
8036 "Read `defines and parameters for the current file, or optional FILENAME.
8037 If the filename is provided, `verilog-library-flags' will be used to
8038 resolve it. If optional RECURSE is non-nil, recurse through `includes.
8039
8040 Parameters must be simple assignments to constants, or have their own
8041 \"parameter\" label rather than a list of parameters. Thus:
8042
8043 parameter X = 5, Y = 10; // Ok
8044 parameter X = {1'b1, 2'h2}; // Ok
8045 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
8046
8047 Defines must be simple text substitutions, one on a line, starting
8048 at the beginning of the line. Any ifdefs or multiline comments around the
8049 define are ignored.
8050
8051 Defines are stored inside Emacs variables using the name vh-{definename}.
8052
8053 This function is useful for setting vh-* variables. The file variables
8054 feature can be used to set defines that `verilog-mode' can see; put at the
8055 *END* of your file something like:
8056
8057 // Local Variables:
8058 // vh-macro:\"macro_definition\"
8059 // End:
8060
8061 If macros are defined earlier in the same file and you want their values,
8062 you can read them automatically (provided `enable-local-eval' is on):
8063
8064 // Local Variables:
8065 // eval:(verilog-read-defines)
8066 // eval:(verilog-read-defines \"group_standard_includes.v\")
8067 // End:
8068
8069 Note these are only read when the file is first visited, you must use
8070 \\[find-alternate-file] RET to have these take effect after editing them!
8071
8072 If you want to disable the \"Process `eval' or hook local variables\"
8073 warning message, you need to add to your .emacs file:
8074
8075 (setq enable-local-eval t)"
8076 (let ((origbuf (current-buffer)))
8077 (save-excursion
8078 (unless subcall (verilog-getopt-flags))
8079 (when filename
8080 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
8081 (if fns
8082 (set-buffer (find-file-noselect (car fns)))
8083 (error (concat (verilog-point-text)
8084 ": Can't find verilog-read-defines file: " filename)))))
8085 (when recurse
8086 (goto-char (point-min))
8087 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
8088 (let ((inc (verilog-string-replace-matches
8089 "\"" "" nil nil (match-string-no-properties 1))))
8090 (unless (verilog-inside-comment-p)
8091 (verilog-read-defines inc recurse t)))))
8092 ;; Read `defines
8093 ;; note we don't use verilog-re... it's faster this way, and that
8094 ;; function has problems when comments are at the end of the define
8095 (goto-char (point-min))
8096 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
8097 (let ((defname (match-string-no-properties 1))
8098 (defvalue (match-string-no-properties 2)))
8099 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
8100 (verilog-set-define defname defvalue origbuf)))
8101 ;; Hack: Read parameters
8102 (goto-char (point-min))
8103 (while (re-search-forward
8104 "^\\s-*\\(parameter\\|localparam\\)\\(\\s-*\\[[^]]*\\]\\)?\\s-+" nil t)
8105 (let (enumname)
8106 ;; The primary way of getting defines is verilog-read-decls
8107 ;; However, that isn't called yet for included files, so we'll add another scheme
8108 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
8109 (setq enumname (match-string-no-properties 1)))
8110 (forward-comment 999)
8111 (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
8112 (verilog-set-define (match-string-no-properties 1)
8113 (match-string-no-properties 2) origbuf enumname)
8114 (goto-char (match-end 0))
8115 (forward-comment 999)))))))
8116
8117 (defun verilog-read-includes ()
8118 "Read `includes for the current file.
8119 This will find all of the `includes which are at the beginning of lines,
8120 ignoring any ifdefs or multiline comments around them.
8121 `verilog-read-defines' is then performed on the current and each included
8122 file.
8123
8124 It is often useful put at the *END* of your file something like:
8125
8126 // Local Variables:
8127 // eval:(verilog-read-defines)
8128 // eval:(verilog-read-includes)
8129 // End:
8130
8131 Note includes are only read when the file is first visited, you must use
8132 \\[find-alternate-file] RET to have these take effect after editing them!
8133
8134 It is good to get in the habit of including all needed files in each .v
8135 file that needs it, rather than waiting for compile time. This will aid
8136 this process, Verilint, and readability. To prevent defining the same
8137 variable over and over when many modules are compiled together, put a test
8138 around the inside each include file:
8139
8140 foo.v (a include):
8141 `ifdef _FOO_V // include if not already included
8142 `else
8143 `define _FOO_V
8144 ... contents of file
8145 `endif // _FOO_V"
8146 ;;slow: (verilog-read-defines nil t))
8147 (save-excursion
8148 (verilog-getopt-flags)
8149 (goto-char (point-min))
8150 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
8151 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
8152 (verilog-read-defines inc nil t)))))
8153
8154 (defun verilog-read-signals (&optional start end)
8155 "Return a simple list of all possible signals in the file.
8156 Bounded by optional region from START to END. Overly aggressive but fast.
8157 Some macros and such are also found and included. For dinotrace.el."
8158 (let (sigs-all keywd)
8159 (progn;save-excursion
8160 (goto-char (or start (point-min)))
8161 (setq end (or end (point-max)))
8162 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
8163 (forward-char -1)
8164 (cond
8165 ((looking-at "//")
8166 (search-forward "\n"))
8167 ((looking-at "/\\*")
8168 (search-forward "*/"))
8169 ((looking-at "(\\*")
8170 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
8171 (search-forward "*)")))
8172 ((eq ?\" (following-char))
8173 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
8174 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
8175 (goto-char (match-end 0))
8176 (setq keywd (match-string-no-properties 1))
8177 (or (member keywd verilog-keywords)
8178 (member keywd sigs-all)
8179 (setq sigs-all (cons keywd sigs-all))))
8180 (t (forward-char 1))))
8181 ;; Return list
8182 sigs-all)))
8183
8184 ;;
8185 ;; Argument file parsing
8186 ;;
8187
8188 (defun verilog-getopt (arglist)
8189 "Parse -f, -v etc arguments in ARGLIST list or string."
8190 (unless (listp arglist) (setq arglist (list arglist)))
8191 (let ((space-args '())
8192 arg next-param)
8193 ;; Split on spaces, so users can pass whole command lines
8194 (while arglist
8195 (setq arg (car arglist)
8196 arglist (cdr arglist))
8197 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
8198 (setq space-args (append space-args
8199 (list (match-string-no-properties 1 arg))))
8200 (setq arg (match-string 2 arg))))
8201 ;; Parse arguments
8202 (while space-args
8203 (setq arg (car space-args)
8204 space-args (cdr space-args))
8205 (cond
8206 ;; Need another arg
8207 ((equal arg "-f")
8208 (setq next-param arg))
8209 ((equal arg "-v")
8210 (setq next-param arg))
8211 ((equal arg "-y")
8212 (setq next-param arg))
8213 ;; +libext+(ext1)+(ext2)...
8214 ((string-match "^\\+libext\\+\\(.*\\)" arg)
8215 (setq arg (match-string 1 arg))
8216 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
8217 (verilog-add-list-unique `verilog-library-extensions
8218 (match-string 1 arg))
8219 (setq arg (match-string 2 arg))))
8220 ;;
8221 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
8222 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
8223 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
8224 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
8225 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
8226 ;;
8227 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
8228 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
8229 (verilog-add-list-unique `verilog-library-directories
8230 (match-string 1 (substitute-in-file-name arg))))
8231 ;; Ignore
8232 ((equal "+librescan" arg))
8233 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
8234 ;; Second parameters
8235 ((equal next-param "-f")
8236 (setq next-param nil)
8237 (verilog-getopt-file (substitute-in-file-name arg)))
8238 ((equal next-param "-v")
8239 (setq next-param nil)
8240 (verilog-add-list-unique `verilog-library-files
8241 (substitute-in-file-name arg)))
8242 ((equal next-param "-y")
8243 (setq next-param nil)
8244 (verilog-add-list-unique `verilog-library-directories
8245 (substitute-in-file-name arg)))
8246 ;; Filename
8247 ((string-match "^[^-+]" arg)
8248 (verilog-add-list-unique `verilog-library-files
8249 (substitute-in-file-name arg)))
8250 ;; Default - ignore; no warning
8251 ))))
8252 ;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
8253
8254 (defun verilog-getopt-file (filename)
8255 "Read Verilog options from the specified FILENAME."
8256 (save-excursion
8257 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
8258 (orig-buffer (current-buffer))
8259 line)
8260 (if fns
8261 (set-buffer (find-file-noselect (car fns)))
8262 (error (concat (verilog-point-text)
8263 ": Can't find verilog-getopt-file -f file: " filename)))
8264 (goto-char (point-min))
8265 (while (not (eobp))
8266 (setq line (buffer-substring (point) (point-at-eol)))
8267 (forward-line 1)
8268 (when (string-match "//" line)
8269 (setq line (substring line 0 (match-beginning 0))))
8270 (with-current-buffer orig-buffer ; Variables are buffer-local, so need right context.
8271 (verilog-getopt line))))))
8272
8273 (defun verilog-getopt-flags ()
8274 "Convert `verilog-library-flags' into standard library variables."
8275 ;; If the flags are local, then all the outputs should be local also
8276 (when (local-variable-p `verilog-library-flags (current-buffer))
8277 (mapc 'make-local-variable '(verilog-library-extensions
8278 verilog-library-directories
8279 verilog-library-files
8280 verilog-library-flags)))
8281 ;; Allow user to customize
8282 (run-hooks 'verilog-before-getopt-flags-hook)
8283 ;; Process arguments
8284 (verilog-getopt verilog-library-flags)
8285 ;; Allow user to customize
8286 (run-hooks 'verilog-getopt-flags-hook))
8287
8288 (defun verilog-add-list-unique (varref object)
8289 "Append to VARREF list the given OBJECT,
8290 unless it is already a member of the variable's list."
8291 (unless (member object (symbol-value varref))
8292 (set varref (append (symbol-value varref) (list object))))
8293 varref)
8294 ;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
8295
8296 (defun verilog-current-flags ()
8297 "Convert `verilog-library-flags' and similar variables to command line.
8298 Used for __FLAGS__ in `verilog-expand-command'."
8299 (let ((cmd (mapconcat `concat verilog-library-flags " ")))
8300 (when (equal cmd "")
8301 (setq cmd (concat
8302 "+libext+" (mapconcat `concat verilog-library-extensions "+")
8303 (mapconcat (lambda (i) (concat " -y " i " +incdir+" i))
8304 verilog-library-directories "")
8305 (mapconcat (lambda (i) (concat " -v " i))
8306 verilog-library-files ""))))
8307 cmd))
8308 ;;(verilog-current-flags)
8309
8310 \f
8311 ;;
8312 ;; Cached directory support
8313 ;;
8314
8315 (defvar verilog-dir-cache-preserving nil
8316 "If set, the directory cache is enabled, and file system changes are ignored.
8317 See `verilog-dir-exists-p' and `verilog-dir-files'.")
8318
8319 ;; If adding new cached variable, add also to verilog-preserve-dir-cache
8320 (defvar verilog-dir-cache-list nil
8321 "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
8322 (defvar verilog-dir-cache-lib-filenames nil
8323 "Cached data for `verilog-library-filenames'.")
8324
8325 (defmacro verilog-preserve-dir-cache (&rest body)
8326 "Execute the BODY forms, allowing directory cache preservation within BODY.
8327 This means that changes inside BODY made to the file system will not be
8328 seen by the `verilog-dir-files' and related functions."
8329 `(let ((verilog-dir-cache-preserving (current-buffer))
8330 verilog-dir-cache-list
8331 verilog-dir-cache-lib-filenames)
8332 (progn ,@body)))
8333
8334 (defun verilog-dir-files (dirname)
8335 "Return all filenames in the DIRNAME directory.
8336 Relative paths depend on the `default-directory'.
8337 Results are cached if inside `verilog-preserve-dir-cache'."
8338 (unless verilog-dir-cache-preserving
8339 (setq verilog-dir-cache-list nil)) ;; Cache disabled
8340 ;; We don't use expand-file-name on the dirname to make key, as it's slow
8341 (let* ((cache-key (list dirname default-directory))
8342 (fass (assoc cache-key verilog-dir-cache-list))
8343 exp-dirname data)
8344 (cond (fass ;; Return data from cache hit
8345 (nth 1 fass))
8346 (t
8347 (setq exp-dirname (expand-file-name dirname)
8348 data (and (file-directory-p exp-dirname)
8349 (directory-files exp-dirname nil nil nil)))
8350 ;; Note we also encache nil for non-existing dirs.
8351 (setq verilog-dir-cache-list (cons (list cache-key data)
8352 verilog-dir-cache-list))
8353 data))))
8354 ;; Miss-and-hit test:
8355 ;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
8356 ;; (prin1 (verilog-dir-files ".")) nil)
8357
8358 (defun verilog-dir-file-exists-p (filename)
8359 "Return true if FILENAME exists.
8360 Like `file-exists-p' but results are cached if inside
8361 `verilog-preserve-dir-cache'."
8362 (let* ((dirname (file-name-directory filename))
8363 ;; Correct for file-name-nondirectory returning same if no slash.
8364 (dirnamed (if (or (not dirname) (equal dirname filename))
8365 default-directory dirname))
8366 (flist (verilog-dir-files dirnamed)))
8367 (and flist
8368 (member (file-name-nondirectory filename) flist)
8369 t)))
8370 ;;(verilog-dir-file-exists-p "verilog-mode.el")
8371 ;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
8372
8373 \f
8374 ;;
8375 ;; Module name lookup
8376 ;;
8377
8378 (defun verilog-module-inside-filename-p (module filename)
8379 "Return modi if MODULE is specified inside FILENAME, else nil.
8380 Allows version control to check out the file if need be."
8381 (and (or (file-exists-p filename)
8382 (and (fboundp 'vc-backend)
8383 (vc-backend filename)))
8384 (let (modi type)
8385 (with-current-buffer (find-file-noselect filename)
8386 (save-excursion
8387 (goto-char (point-min))
8388 (while (and
8389 ;; It may be tempting to look for verilog-defun-re,
8390 ;; don't, it slows things down a lot!
8391 (verilog-re-search-forward-quick "\\<\\(module\\|interface\\)\\>" nil t)
8392 (setq type (match-string-no-properties 0))
8393 (verilog-re-search-forward-quick "[(;]" nil t))
8394 (if (equal module (verilog-read-module-name))
8395 (setq modi (verilog-modi-new module filename (point) type))))
8396 modi)))))
8397
8398 (defun verilog-is-number (symbol)
8399 "Return true if SYMBOL is number-like."
8400 (or (string-match "^[0-9 \t:]+$" symbol)
8401 (string-match "^[---]*[0-9]+$" symbol)
8402 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
8403
8404 (defun verilog-symbol-detick (symbol wing-it)
8405 "Return an expanded SYMBOL name without any defines.
8406 If the variable vh-{symbol} is defined, return that value.
8407 If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
8408 (while (and symbol (string-match "^`" symbol))
8409 (setq symbol (substring symbol 1))
8410 (setq symbol
8411 (if (boundp (intern (concat "vh-" symbol)))
8412 ;; Emacs has a bug where boundp on a buffer-local
8413 ;; variable in only one buffer returns t in another.
8414 ;; This can confuse, so check for nil.
8415 (let ((val (eval (intern (concat "vh-" symbol)))))
8416 (if (eq val nil)
8417 (if wing-it symbol nil)
8418 val))
8419 (if wing-it symbol nil))))
8420 symbol)
8421 ;;(verilog-symbol-detick "`mod" nil)
8422
8423 (defun verilog-symbol-detick-denumber (symbol)
8424 "Return SYMBOL with defines converted and any numbers dropped to nil."
8425 (when (string-match "^`" symbol)
8426 ;; This only will work if the define is a simple signal, not
8427 ;; something like a[b]. Sorry, it should be substituted into the parser
8428 (setq symbol
8429 (verilog-string-replace-matches
8430 "\[[^0-9: \t]+\]" "" nil nil
8431 (or (verilog-symbol-detick symbol nil)
8432 (if verilog-auto-sense-defines-constant
8433 "0"
8434 symbol)))))
8435 (if (verilog-is-number symbol)
8436 nil
8437 symbol))
8438
8439 (defun verilog-symbol-detick-text (text)
8440 "Return TEXT without any known defines.
8441 If the variable vh-{symbol} is defined, substitute that value."
8442 (let ((ok t) symbol val)
8443 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
8444 (setq symbol (match-string 1 text))
8445 ;;(message symbol)
8446 (cond ((and
8447 (boundp (intern (concat "vh-" symbol)))
8448 ;; Emacs has a bug where boundp on a buffer-local
8449 ;; variable in only one buffer returns t in another.
8450 ;; This can confuse, so check for nil.
8451 (setq val (eval (intern (concat "vh-" symbol)))))
8452 (setq text (replace-match val nil nil text)))
8453 (t (setq ok nil)))))
8454 text)
8455 ;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
8456
8457 (defun verilog-expand-dirnames (&optional dirnames)
8458 "Return a list of existing directories given a list of wildcarded DIRNAMES.
8459 Or, just the existing dirnames themselves if there are no wildcards."
8460 ;; Note this function is performance critical.
8461 ;; Do not call anything that requires disk access that cannot be cached.
8462 (interactive)
8463 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
8464 (setq dirnames (reverse dirnames)) ; not nreverse
8465 (let ((dirlist nil)
8466 pattern dirfile dirfiles dirname root filename rest basefile)
8467 (while dirnames
8468 (setq dirname (substitute-in-file-name (car dirnames))
8469 dirnames (cdr dirnames))
8470 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
8471 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
8472 "\\(.*\\)") ;; rest
8473 dirname)
8474 (setq root (match-string 1 dirname)
8475 filename (match-string 2 dirname)
8476 rest (match-string 3 dirname)
8477 pattern filename)
8478 ;; now replace those * and ? with .+ and .
8479 ;; use ^ and /> to get only whole file names
8480 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
8481 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
8482 pattern (concat "^" pattern "$")
8483 dirfiles (verilog-dir-files root))
8484 (while dirfiles
8485 (setq basefile (car dirfiles)
8486 dirfile (expand-file-name (concat root basefile rest))
8487 dirfiles (cdr dirfiles))
8488 (if (and (string-match pattern basefile)
8489 ;; Don't allow abc/*/rtl to match abc/rtl via ..
8490 (not (equal basefile "."))
8491 (not (equal basefile ".."))
8492 (file-directory-p dirfile))
8493 (setq dirlist (cons dirfile dirlist)))))
8494 ;; Defaults
8495 (t
8496 (if (file-directory-p dirname)
8497 (setq dirlist (cons dirname dirlist))))))
8498 dirlist))
8499 ;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
8500
8501 (defun verilog-library-filenames (filename &optional current check-ext)
8502 "Return a search path to find the given FILENAME or module name.
8503 Uses the optional CURRENT filename or buffer-file-name, plus
8504 `verilog-library-directories' and `verilog-library-extensions'
8505 variables to build the path. With optional CHECK-EXT also check
8506 `verilog-library-extensions'."
8507 (unless current (setq current (buffer-file-name)))
8508 (unless verilog-dir-cache-preserving
8509 (setq verilog-dir-cache-lib-filenames nil))
8510 (let* ((cache-key (list filename current check-ext))
8511 (fass (assoc cache-key verilog-dir-cache-lib-filenames))
8512 chkdirs chkdir chkexts fn outlist)
8513 (cond (fass ;; Return data from cache hit
8514 (nth 1 fass))
8515 (t
8516 ;; Note this expand can't be easily cached, as we need to
8517 ;; pick up buffer-local variables for newly read sub-module files
8518 (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
8519 (while chkdirs
8520 (setq chkdir (expand-file-name (car chkdirs)
8521 (file-name-directory current))
8522 chkexts (if check-ext verilog-library-extensions `("")))
8523 (while chkexts
8524 (setq fn (expand-file-name (concat filename (car chkexts))
8525 chkdir))
8526 ;;(message "Check for %s" fn)
8527 (if (verilog-dir-file-exists-p fn)
8528 (setq outlist (cons (expand-file-name
8529 fn (file-name-directory current))
8530 outlist)))
8531 (setq chkexts (cdr chkexts)))
8532 (setq chkdirs (cdr chkdirs)))
8533 (setq outlist (nreverse outlist))
8534 (setq verilog-dir-cache-lib-filenames
8535 (cons (list cache-key outlist)
8536 verilog-dir-cache-lib-filenames))
8537 outlist))))
8538
8539 (defun verilog-module-filenames (module current)
8540 "Return a search path to find the given MODULE name.
8541 Uses the CURRENT filename, `verilog-library-extensions',
8542 `verilog-library-directories' and `verilog-library-files'
8543 variables to build the path."
8544 ;; Return search locations for it
8545 (append (list current) ; first, current buffer
8546 (verilog-library-filenames module current t)
8547 verilog-library-files)) ; finally, any libraries
8548
8549 ;;
8550 ;; Module Information
8551 ;;
8552 ;; Many of these functions work on "modi" a module information structure
8553 ;; A modi is: [module-name-string file-name begin-point]
8554
8555 (defvar verilog-cache-enabled t
8556 "If true, enable caching of signals, etc. Set to nil for debugging to make things SLOW!")
8557
8558 (defvar verilog-modi-cache-list nil
8559 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
8560 For speeding up verilog-modi-get-* commands.
8561 Buffer-local.")
8562 (make-variable-buffer-local 'verilog-modi-cache-list)
8563
8564 (defvar verilog-modi-cache-preserve-tick nil
8565 "Modification tick after which the cache is still considered valid.
8566 Use `verilog-preserve-modi-cache' to set it.")
8567 (defvar verilog-modi-cache-preserve-buffer nil
8568 "Modification tick after which the cache is still considered valid.
8569 Use `verilog-preserve-modi-cache' to set it.")
8570 (defvar verilog-modi-cache-current-enable nil
8571 "If true, allow caching `verilog-modi-current', set by let().")
8572 (defvar verilog-modi-cache-current nil
8573 "Currently active `verilog-modi-current', if any, set by let().")
8574 (defvar verilog-modi-cache-current-max nil
8575 "Current endmodule point for `verilog-modi-cache-current', if any.")
8576
8577 (defun verilog-modi-current ()
8578 "Return the modi structure for the module currently at point, possibly cached."
8579 (cond ((and verilog-modi-cache-current
8580 (>= (point) (verilog-modi-get-point verilog-modi-cache-current))
8581 (<= (point) verilog-modi-cache-current-max))
8582 ;; Slow assertion, for debugging the cache:
8583 ;;(or (equal verilog-modi-cache-current (verilog-modi-current-get)) (debug))
8584 verilog-modi-cache-current)
8585 (verilog-modi-cache-current-enable
8586 (setq verilog-modi-cache-current (verilog-modi-current-get)
8587 verilog-modi-cache-current-max
8588 ;; The cache expires when we pass "endmodule" as then the
8589 ;; current modi may change to the next module
8590 ;; This relies on the AUTOs generally inserting, not deleting text
8591 (save-excursion
8592 (verilog-re-search-forward-quick verilog-end-defun-re nil nil)))
8593 verilog-modi-cache-current)
8594 (t
8595 (verilog-modi-current-get))))
8596
8597 (defun verilog-modi-current-get ()
8598 "Return the modi structure for the module currently at point."
8599 (let* (name type pt)
8600 ;; read current module's name
8601 (save-excursion
8602 (verilog-re-search-backward-quick verilog-defun-re nil nil)
8603 (setq type (match-string-no-properties 0))
8604 (verilog-re-search-forward-quick "(" nil nil)
8605 (setq name (verilog-read-module-name))
8606 (setq pt (point)))
8607 ;; return modi - note this vector built two places
8608 (verilog-modi-new name (or (buffer-file-name) (current-buffer)) pt type)))
8609
8610 (defvar verilog-modi-lookup-cache nil "Hash of (modulename modi).")
8611 (make-variable-buffer-local 'verilog-modi-lookup-cache)
8612 (defvar verilog-modi-lookup-last-current nil "Cache of `current-buffer' at last lookup.")
8613 (defvar verilog-modi-lookup-last-tick nil "Cache of `buffer-chars-modified-tick' at last lookup.")
8614
8615 (defun verilog-modi-lookup (module allow-cache &optional ignore-error)
8616 "Find the file and point at which MODULE is defined.
8617 If ALLOW-CACHE is set, check and remember cache of previous lookups.
8618 Return modi if successful, else print message unless IGNORE-ERROR is true."
8619 (let* ((current (or (buffer-file-name) (current-buffer)))
8620 modi)
8621 ;; Check cache
8622 ;;(message "verilog-modi-lookup: %s" module)
8623 (cond ((and verilog-modi-lookup-cache
8624 verilog-cache-enabled
8625 allow-cache
8626 (setq modi (gethash module verilog-modi-lookup-cache))
8627 (equal verilog-modi-lookup-last-current current)
8628 ;; Iff hit is in current buffer, then tick must match
8629 (or (equal verilog-modi-lookup-last-tick (buffer-chars-modified-tick))
8630 (not (equal current (verilog-modi-file-or-buffer modi)))))
8631 ;;(message "verilog-modi-lookup: HIT %S" modi)
8632 modi)
8633 ;; Miss
8634 (t (let* ((realmod (verilog-symbol-detick module t))
8635 (orig-filenames (verilog-module-filenames realmod current))
8636 (filenames orig-filenames)
8637 mif)
8638 (while (and filenames (not mif))
8639 (if (not (setq mif (verilog-module-inside-filename-p realmod (car filenames))))
8640 (setq filenames (cdr filenames))))
8641 ;; mif has correct form to become later elements of modi
8642 (cond (mif (setq modi mif))
8643 (t (setq modi nil)
8644 (or ignore-error
8645 (error (concat (verilog-point-text)
8646 ": Can't locate " module " module definition"
8647 (if (not (equal module realmod))
8648 (concat " (Expanded macro to " realmod ")")
8649 "")
8650 "\n Check the verilog-library-directories variable."
8651 "\n I looked in (if not listed, doesn't exist):\n\t"
8652 (mapconcat 'concat orig-filenames "\n\t"))))))
8653 (when (eval-when-compile (fboundp 'make-hash-table))
8654 (unless verilog-modi-lookup-cache
8655 (setq verilog-modi-lookup-cache
8656 (make-hash-table :test 'equal :rehash-size 4.0)))
8657 (puthash module modi verilog-modi-lookup-cache))
8658 (setq verilog-modi-lookup-last-current current
8659 verilog-modi-lookup-last-tick (buffer-chars-modified-tick)))))
8660 modi))
8661
8662 (defun verilog-modi-filename (modi)
8663 "Filename of MODI, or name of buffer if it's never been saved."
8664 (if (bufferp (verilog-modi-file-or-buffer modi))
8665 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
8666 (buffer-name (verilog-modi-file-or-buffer modi)))
8667 (verilog-modi-file-or-buffer modi)))
8668
8669 (defun verilog-modi-goto (modi)
8670 "Move point/buffer to specified MODI."
8671 (or modi (error "Passed unfound modi to goto, check earlier"))
8672 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
8673 (verilog-modi-file-or-buffer modi)
8674 (find-file-noselect (verilog-modi-file-or-buffer modi))))
8675 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
8676 (verilog-mode))
8677 (goto-char (verilog-modi-get-point modi)))
8678
8679 (defun verilog-goto-defun-file (module)
8680 "Move point to the file at which a given MODULE is defined."
8681 (interactive "sGoto File for Module: ")
8682 (let* ((modi (verilog-modi-lookup module nil)))
8683 (when modi
8684 (verilog-modi-goto modi)
8685 (switch-to-buffer (current-buffer)))))
8686
8687 (defun verilog-modi-cache-results (modi function)
8688 "Run on MODI the given FUNCTION. Locate the module in a file.
8689 Cache the output of function so next call may have faster access."
8690 (let (fass)
8691 (save-excursion ;; Cache is buffer-local so can't avoid this.
8692 (verilog-modi-goto modi)
8693 (if (and (setq fass (assoc (list modi function)
8694 verilog-modi-cache-list))
8695 ;; Destroy caching when incorrect; Modified or file changed
8696 (not (and verilog-cache-enabled
8697 (or (equal (buffer-chars-modified-tick) (nth 1 fass))
8698 (and verilog-modi-cache-preserve-tick
8699 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
8700 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
8701 (equal (visited-file-modtime) (nth 2 fass)))))
8702 (setq verilog-modi-cache-list nil
8703 fass nil))
8704 (cond (fass
8705 ;; Return data from cache hit
8706 (nth 3 fass))
8707 (t
8708 ;; Read from file
8709 ;; Clear then restore any highlighting to make emacs19 happy
8710 (let ((fontlocked (when (and (boundp 'font-lock-mode)
8711 font-lock-mode)
8712 (font-lock-mode 0)
8713 t))
8714 func-returns)
8715 (setq func-returns (funcall function))
8716 (when fontlocked (font-lock-mode t))
8717 ;; Cache for next time
8718 (setq verilog-modi-cache-list
8719 (cons (list (list modi function)
8720 (buffer-chars-modified-tick)
8721 (visited-file-modtime)
8722 func-returns)
8723 verilog-modi-cache-list))
8724 func-returns))))))
8725
8726 (defun verilog-modi-cache-add (modi function element sig-list)
8727 "Add function return results to the module cache.
8728 Update MODI's cache for given FUNCTION so that the return ELEMENT of that
8729 function now contains the additional SIG-LIST parameters."
8730 (let (fass)
8731 (save-excursion
8732 (verilog-modi-goto modi)
8733 (if (setq fass (assoc (list modi function)
8734 verilog-modi-cache-list))
8735 (let ((func-returns (nth 3 fass)))
8736 (aset func-returns element
8737 (append sig-list (aref func-returns element))))))))
8738
8739 (defmacro verilog-preserve-modi-cache (&rest body)
8740 "Execute the BODY forms, allowing cache preservation within BODY.
8741 This means that changes to the buffer will not result in the cache being
8742 flushed. If the changes affect the modsig state, they must call the
8743 modsig-cache-add-* function, else the results of later calls may be
8744 incorrect. Without this, changes are assumed to be adding/removing signals
8745 and invalidating the cache."
8746 `(let ((verilog-modi-cache-preserve-tick (buffer-chars-modified-tick))
8747 (verilog-modi-cache-preserve-buffer (current-buffer)))
8748 (progn ,@body)))
8749
8750
8751 (defun verilog-signals-matching-enum (in-list enum)
8752 "Return all signals in IN-LIST matching the given ENUM."
8753 (let (out-list)
8754 (while in-list
8755 (if (equal (verilog-sig-enum (car in-list)) enum)
8756 (setq out-list (cons (car in-list) out-list)))
8757 (setq in-list (cdr in-list)))
8758 ;; New scheme
8759 (let* ((enumvar (intern (concat "venum-" enum)))
8760 (enumlist (and (boundp enumvar) (eval enumvar))))
8761 (while enumlist
8762 (add-to-list 'out-list (list (car enumlist)))
8763 (setq enumlist (cdr enumlist))))
8764 (nreverse out-list)))
8765
8766 (defun verilog-signals-matching-regexp (in-list regexp)
8767 "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
8768 (if (or (not regexp) (equal regexp ""))
8769 in-list
8770 (let (out-list)
8771 (while in-list
8772 (if (string-match regexp (verilog-sig-name (car in-list)))
8773 (setq out-list (cons (car in-list) out-list)))
8774 (setq in-list (cdr in-list)))
8775 (nreverse out-list))))
8776
8777 (defun verilog-signals-not-matching-regexp (in-list regexp)
8778 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
8779 (if (or (not regexp) (equal regexp ""))
8780 in-list
8781 (let (out-list)
8782 (while in-list
8783 (if (not (string-match regexp (verilog-sig-name (car in-list))))
8784 (setq out-list (cons (car in-list) out-list)))
8785 (setq in-list (cdr in-list)))
8786 (nreverse out-list))))
8787
8788 (defun verilog-signals-matching-dir-re (in-list decl-type regexp)
8789 "Return all signals in IN-LIST matching the given DECL-TYPE and REGEXP,
8790 if non-nil."
8791 (if (or (not regexp) (equal regexp ""))
8792 in-list
8793 (let (out-list to-match)
8794 (while in-list
8795 ;; Note verilog-insert-one-definition matches on this order
8796 (setq to-match (concat
8797 decl-type
8798 " " (verilog-sig-signed (car in-list))
8799 " " (verilog-sig-multidim (car in-list))
8800 (verilog-sig-bits (car in-list))))
8801 (if (string-match regexp to-match)
8802 (setq out-list (cons (car in-list) out-list)))
8803 (setq in-list (cdr in-list)))
8804 (nreverse out-list))))
8805
8806 ;; Combined
8807 (defun verilog-decls-get-signals (decls)
8808 (append
8809 (verilog-decls-get-outputs decls)
8810 (verilog-decls-get-inouts decls)
8811 (verilog-decls-get-inputs decls)
8812 (verilog-decls-get-wires decls)
8813 (verilog-decls-get-regs decls)
8814 (verilog-decls-get-assigns decls)
8815 (verilog-decls-get-consts decls)
8816 (verilog-decls-get-gparams decls)))
8817
8818 (defun verilog-decls-get-ports (decls)
8819 (append
8820 (verilog-decls-get-outputs decls)
8821 (verilog-decls-get-inouts decls)
8822 (verilog-decls-get-inputs decls)))
8823
8824 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
8825 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
8826 (defsubst verilog-modi-cache-add-inouts (modi sig-list)
8827 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
8828 (defsubst verilog-modi-cache-add-inputs (modi sig-list)
8829 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
8830 (defsubst verilog-modi-cache-add-wires (modi sig-list)
8831 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
8832 (defsubst verilog-modi-cache-add-regs (modi sig-list)
8833 (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
8834
8835 (defun verilog-signals-from-signame (signame-list)
8836 "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
8837 (mapcar (function (lambda (name) (list name nil nil)))
8838 signame-list))
8839 \f
8840 ;;
8841 ;; Auto creation utilities
8842 ;;
8843
8844 (defun verilog-auto-re-search-do (search-for func)
8845 "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
8846 (goto-char (point-min))
8847 (while (verilog-re-search-forward search-for nil t)
8848 (funcall func)))
8849
8850 (defun verilog-insert-one-definition (sig type indent-pt)
8851 "Print out a definition for SIG of the given TYPE,
8852 with appropriate INDENT-PT indentation."
8853 (indent-to indent-pt)
8854 ;; Note verilog-signals-matching-dir-re matches on this order
8855 (insert type)
8856 (when (verilog-sig-modport sig)
8857 (insert "." (verilog-sig-modport sig)))
8858 (when (verilog-sig-signed sig)
8859 (insert " " (verilog-sig-signed sig)))
8860 (when (verilog-sig-multidim sig)
8861 (insert " " (verilog-sig-multidim-string sig)))
8862 (when (verilog-sig-bits sig)
8863 (insert " " (verilog-sig-bits sig)))
8864 (indent-to (max 24 (+ indent-pt 16)))
8865 (unless (= (char-syntax (preceding-char)) ?\ )
8866 (insert " ")) ; Need space between "]name" if indent-to did nothing
8867 (insert (verilog-sig-name sig))
8868 (when (verilog-sig-memory sig)
8869 (insert " " (verilog-sig-memory sig))))
8870
8871 (defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
8872 "Print out a definition for a list of SIGS of the given DIRECTION,
8873 with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
8874 format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output."
8875 (or dont-sort
8876 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
8877 (while sigs
8878 (let ((sig (car sigs)))
8879 (verilog-insert-one-definition
8880 sig
8881 ;; Want "type x" or "output type x", not "wire type x"
8882 (cond ((verilog-sig-type sig)
8883 (concat
8884 (if (not (member direction '("wire" "interface")))
8885 (concat direction " "))
8886 (verilog-sig-type sig)))
8887 (t direction))
8888 indent-pt)
8889 (insert (if v2k "," ";"))
8890 (if (or (not (verilog-sig-comment sig))
8891 (equal "" (verilog-sig-comment sig)))
8892 (insert "\n")
8893 (indent-to (max 48 (+ indent-pt 40)))
8894 (verilog-insert "// " (verilog-sig-comment sig) "\n"))
8895 (setq sigs (cdr sigs)))))
8896
8897 (eval-when-compile
8898 (if (not (boundp 'indent-pt))
8899 (defvar indent-pt nil "Local used by insert-indent")))
8900
8901 (defun verilog-insert-indent (&rest stuff)
8902 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
8903 Presumes that any newlines end a list element."
8904 (let ((need-indent t))
8905 (while stuff
8906 (if need-indent (indent-to indent-pt))
8907 (setq need-indent nil)
8908 (verilog-insert (car stuff))
8909 (setq need-indent (string-match "\n$" (car stuff))
8910 stuff (cdr stuff)))))
8911 ;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
8912
8913 (defun verilog-repair-open-comma ()
8914 "Insert comma if previous argument is other than a open parenthesis or endif."
8915 ;; We can't just search backward for ) as it might be inside another expression.
8916 ;; Also want "`ifdef X input foo `endif" to just leave things to the human to deal with
8917 (save-excursion
8918 (verilog-backward-syntactic-ws)
8919 (when (and (not (save-excursion ;; Not beginning (, or existing ,
8920 (backward-char 1)
8921 (looking-at "[(,]")))
8922 (not (save-excursion ;; Not `endif, or user define
8923 (backward-char 1)
8924 (skip-chars-backward "[a-zA-Z0-9_`]")
8925 (looking-at "`"))))
8926 (insert ","))))
8927
8928 (defun verilog-repair-close-comma ()
8929 "If point is at a comma followed by a close parenthesis, fix it.
8930 This repairs those mis-inserted by a AUTOARG."
8931 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
8932 (save-excursion
8933 (verilog-forward-close-paren)
8934 (backward-char 1)
8935 (verilog-backward-syntactic-ws)
8936 (backward-char 1)
8937 (when (looking-at ",")
8938 (delete-char 1))))
8939
8940 (defun verilog-get-list (start end)
8941 "Return the elements of a comma separated list between START and END."
8942 (interactive)
8943 (let ((my-list (list))
8944 my-string)
8945 (save-excursion
8946 (while (< (point) end)
8947 (when (re-search-forward "\\([^,{]+\\)" end t)
8948 (setq my-string (verilog-string-remove-spaces (match-string 1)))
8949 (setq my-list (nconc my-list (list my-string) ))
8950 (goto-char (match-end 0))))
8951 my-list)))
8952
8953 (defun verilog-make-width-expression (range-exp)
8954 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
8955 ;; strip off the []
8956 (cond ((not range-exp)
8957 "1")
8958 (t
8959 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
8960 (setq range-exp (match-string 1 range-exp)))
8961 (cond ((not range-exp)
8962 "1")
8963 ;; [#:#] We can compute a numeric result
8964 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
8965 range-exp)
8966 (int-to-string
8967 (1+ (abs (- (string-to-number (match-string 1 range-exp))
8968 (string-to-number (match-string 2 range-exp)))))))
8969 ;; [PARAM-1:0] can just return PARAM
8970 ((string-match "^\\s *\\([a-zA-Z_][a-zA-Z0-9_]*\\)\\s *-\\s *1\\s *:\\s *0\\s *$" range-exp)
8971 (match-string 1 range-exp))
8972 ;; [arbitrary] need math
8973 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
8974 (concat "(1+(" (match-string 1 range-exp) ")"
8975 (if (equal "0" (match-string 2 range-exp))
8976 "" ;; Don't bother with -(0)
8977 (concat "-(" (match-string 2 range-exp) ")"))
8978 ")"))
8979 (t nil)))))
8980 ;;(verilog-make-width-expression "`A:`B")
8981
8982 (defun verilog-simplify-range-expression (range-exp)
8983 "Return a simplified range expression with constants eliminated from RANGE-EXP."
8984 (let ((out range-exp)
8985 (last-pass ""))
8986 (while (not (equal last-pass out))
8987 (setq last-pass out)
8988 (while (string-match "(\\<\\([0-9A-Z-az_]+\\)\\>)" out)
8989 (setq out (replace-match "\\1" nil nil out)))
8990 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\+\\s *\\<\\([0-9]+\\)\\>" out)
8991 (setq out (replace-match
8992 (int-to-string (+ (string-to-number (match-string 1 out))
8993 (string-to-number (match-string 2 out))))
8994 nil nil out)))
8995 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\-\\s *\\<\\([0-9]+\\)\\>" out)
8996 (setq out (replace-match
8997 (int-to-string (- (string-to-number (match-string 1 out))
8998 (string-to-number (match-string 2 out))))
8999 nil nil out))))
9000 out))
9001 ;;(verilog-simplify-range-expression "1")
9002 ;;(verilog-simplify-range-expression "(((16)+1)-3)")
9003
9004 (defun verilog-typedef-name-p (variable-name)
9005 "Return true if the VARIABLE-NAME is a type definition."
9006 (when verilog-typedef-regexp
9007 (string-match verilog-typedef-regexp variable-name)))
9008 \f
9009 ;;
9010 ;; Auto deletion
9011 ;;
9012
9013 (defun verilog-delete-autos-lined ()
9014 "Delete autos that occupy multiple lines, between begin and end comments."
9015 (let ((pt (point)))
9016 (forward-line 1)
9017 (when (and
9018 (looking-at "\\s-*// Beginning")
9019 (search-forward "// End of automatic" nil t))
9020 ;; End exists
9021 (end-of-line)
9022 (delete-region pt (point))
9023 (forward-line 1))))
9024
9025 (defun verilog-delete-empty-auto-pair ()
9026 "Delete begin/end auto pair at point, if empty."
9027 (forward-line 0)
9028 (when (looking-at (concat "\\s-*// Beginning of automatic.*\n"
9029 "\\s-*// End of automatics\n"))
9030 (delete-region (point) (save-excursion (forward-line 2) (point)))))
9031
9032 (defun verilog-forward-close-paren ()
9033 "Find the close parenthesis that match the current point.
9034 Ignore other close parenthesis with matching open parens."
9035 (let ((parens 1))
9036 (while (> parens 0)
9037 (unless (verilog-re-search-forward-quick "[()]" nil t)
9038 (error "%s: Mismatching ()" (verilog-point-text)))
9039 (cond ((= (preceding-char) ?\( )
9040 (setq parens (1+ parens)))
9041 ((= (preceding-char) ?\) )
9042 (setq parens (1- parens)))))))
9043
9044 (defun verilog-backward-open-paren ()
9045 "Find the open parenthesis that match the current point.
9046 Ignore other open parenthesis with matching close parens."
9047 (let ((parens 1))
9048 (while (> parens 0)
9049 (unless (verilog-re-search-backward-quick "[()]" nil t)
9050 (error "%s: Mismatching ()" (verilog-point-text)))
9051 (cond ((= (following-char) ?\) )
9052 (setq parens (1+ parens)))
9053 ((= (following-char) ?\( )
9054 (setq parens (1- parens)))))))
9055
9056 (defun verilog-backward-open-bracket ()
9057 "Find the open bracket that match the current point.
9058 Ignore other open bracket with matching close bracket."
9059 (let ((parens 1))
9060 (while (> parens 0)
9061 (unless (verilog-re-search-backward-quick "[][]" nil t)
9062 (error "%s: Mismatching []" (verilog-point-text)))
9063 (cond ((= (following-char) ?\] )
9064 (setq parens (1+ parens)))
9065 ((= (following-char) ?\[ )
9066 (setq parens (1- parens)))))))
9067
9068 (defun verilog-delete-to-paren ()
9069 "Delete the automatic inst/sense/arg created by autos.
9070 Deletion stops at the matching end parenthesis."
9071 (delete-region (point)
9072 (save-excursion
9073 (verilog-backward-open-paren)
9074 (forward-sexp 1) ;; Moves to paren that closes argdecl's
9075 (backward-char 1)
9076 (point))))
9077
9078 (defun verilog-auto-star-safe ()
9079 "Return if a .* AUTOINST is safe to delete or expand.
9080 It was created by the AUTOS themselves, or by the user."
9081 (and verilog-auto-star-expand
9082 (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\|Interfaces\\)\\)")))
9083
9084 (defun verilog-delete-auto-star-all ()
9085 "Delete a .* AUTOINST, if it is safe."
9086 (when (verilog-auto-star-safe)
9087 (verilog-delete-to-paren)))
9088
9089 (defun verilog-delete-auto-star-implicit ()
9090 "Delete all .* implicit connections created by `verilog-auto-star'.
9091 This function will be called automatically at save unless
9092 `verilog-auto-star-save' is set, any non-templated expanded pins will be
9093 removed."
9094 (interactive)
9095 (let (paren-pt indent have-close-paren)
9096 (save-excursion
9097 (goto-char (point-min))
9098 ;; We need to match these even outside of comments.
9099 ;; For reasonable performance, we don't check if inside comments, sorry.
9100 (while (re-search-forward "// Implicit \\.\\*" nil t)
9101 (setq paren-pt (point))
9102 (beginning-of-line)
9103 (setq have-close-paren
9104 (save-excursion
9105 (when (search-forward ");" paren-pt t)
9106 (setq indent (current-indentation))
9107 t)))
9108 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
9109 (when have-close-paren
9110 ;; Delete extra commentary
9111 (save-excursion
9112 (while (progn
9113 (forward-line -1)
9114 (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\|Interfaces\\)\n"))
9115 (delete-region (match-beginning 0) (match-end 0))))
9116 ;; If it is simple, we can put the ); on the same line as the last text
9117 (let ((rtn-pt (point)))
9118 (save-excursion
9119 (while (progn (backward-char 1)
9120 (looking-at "[ \t\n\f]")))
9121 (when (looking-at ",")
9122 (delete-region (+ 1 (point)) rtn-pt))))
9123 (when (bolp)
9124 (indent-to indent))
9125 (insert ");\n")
9126 ;; Still need to kill final comma - always is one as we put one after the .*
9127 (re-search-backward ",")
9128 (delete-char 1))))))
9129
9130 (defun verilog-delete-auto ()
9131 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
9132 Use \\[verilog-auto] to re-insert the updated AUTOs.
9133
9134 The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
9135 called before and after this function, respectively."
9136 (interactive)
9137 (save-excursion
9138 (if (buffer-file-name)
9139 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
9140 (verilog-save-no-change-functions
9141 (verilog-save-scan-cache
9142 ;; Allow user to customize
9143 (run-hooks 'verilog-before-delete-auto-hook)
9144
9145 ;; Remove those that have multi-line insertions, possibly with parameters
9146 (verilog-auto-re-search-do
9147 (concat "/\\*"
9148 (eval-when-compile
9149 (verilog-regexp-words
9150 `("AUTOASCIIENUM" "AUTOCONCATCOMMENT" "AUTODEFINEVALUE"
9151 "AUTOINOUT" "AUTOINOUTCOMP" "AUTOINOUTMODULE"
9152 "AUTOINPUT" "AUTOINSERTLISP" "AUTOOUTPUT" "AUTOOUTPUTEVERY"
9153 "AUTOREG" "AUTOREGINPUT" "AUTORESET" "AUTOTIEOFF"
9154 "AUTOUNUSED" "AUTOWIRE")))
9155 ;; Optional parens or quoted parameter or .* for (((...)))
9156 "\\(\\|([^)]*)\\|(\"[^\"]*\")\\).*?"
9157 "\\*/")
9158 'verilog-delete-autos-lined)
9159 ;; Remove those that are in parenthesis
9160 (verilog-auto-re-search-do
9161 (concat "/\\*"
9162 (eval-when-compile
9163 (verilog-regexp-words
9164 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
9165 "AUTOSENSE")))
9166 "\\*/")
9167 'verilog-delete-to-paren)
9168 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
9169 (verilog-auto-re-search-do "\\.\\*"
9170 'verilog-delete-auto-star-all)
9171 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
9172 (goto-char (point-min))
9173 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
9174 (replace-match ""))
9175
9176 ;; Final customize
9177 (run-hooks 'verilog-delete-auto-hook)))))
9178 \f
9179 ;;
9180 ;; Auto inject
9181 ;;
9182
9183 (defun verilog-inject-auto ()
9184 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
9185
9186 Any always @ blocks with sensitivity lists that match computed lists will
9187 be replaced with /*AS*/ comments.
9188
9189 Any cells will get /*AUTOINST*/ added to the end of the pin list.
9190 Pins with have identical names will be deleted.
9191
9192 Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
9193 support adding new ports. You may wish to delete older ports yourself.
9194
9195 For example:
9196
9197 module ExampInject (i, o);
9198 input i;
9199 input j;
9200 output o;
9201 always @ (i or j)
9202 o = i | j;
9203 InstModule instName
9204 (.foobar(baz),
9205 j(j));
9206 endmodule
9207
9208 Typing \\[verilog-inject-auto] will make this into:
9209
9210 module ExampInject (i, o/*AUTOARG*/
9211 // Inputs
9212 j);
9213 input i;
9214 output o;
9215 always @ (/*AS*/i or j)
9216 o = i | j;
9217 InstModule instName
9218 (.foobar(baz),
9219 /*AUTOINST*/
9220 // Outputs
9221 j(j));
9222 endmodule"
9223 (interactive)
9224 (verilog-auto t))
9225
9226 (defun verilog-inject-arg ()
9227 "Inject AUTOARG into new code. See `verilog-inject-auto'."
9228 ;; Presume one module per file.
9229 (save-excursion
9230 (goto-char (point-min))
9231 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
9232 (let ((endmodp (save-excursion
9233 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
9234 (point))))
9235 ;; See if there's already a comment .. inside a comment so not verilog-re-search
9236 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
9237 (verilog-re-search-forward-quick ";" nil t)
9238 (backward-char 1)
9239 (verilog-backward-syntactic-ws)
9240 (backward-char 1) ; Moves to paren that closes argdecl's
9241 (when (looking-at ")")
9242 (verilog-insert "/*AUTOARG*/")))))))
9243
9244 (defun verilog-inject-sense ()
9245 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
9246 (save-excursion
9247 (goto-char (point-min))
9248 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
9249 (let* ((start-pt (point))
9250 (modi (verilog-modi-current))
9251 (moddecls (verilog-modi-get-decls modi))
9252 pre-sigs
9253 got-sigs)
9254 (backward-char 1)
9255 (forward-sexp 1)
9256 (backward-char 1) ;; End )
9257 (when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
9258 (setq pre-sigs (verilog-signals-from-signame
9259 (verilog-read-signals start-pt (point)))
9260 got-sigs (verilog-auto-sense-sigs moddecls nil))
9261 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
9262 (verilog-signals-not-in got-sigs pre-sigs)))
9263 (delete-region start-pt (point))
9264 (verilog-insert "/*AS*/")))))))
9265
9266 (defun verilog-inject-inst ()
9267 "Inject AUTOINST into new code. See `verilog-inject-auto'."
9268 (save-excursion
9269 (goto-char (point-min))
9270 ;; It's hard to distinguish modules; we'll instead search for pins.
9271 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
9272 (verilog-backward-open-paren) ;; Inst start
9273 (cond
9274 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
9275 (forward-char 1)
9276 (verilog-forward-close-paren)) ;; Parameters done
9277 (t
9278 (forward-char 1)
9279 (let ((indent-pt (+ (current-column)))
9280 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
9281 (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
9282 (goto-char end-pt)) ;; Already there, continue search with next instance
9283 (t
9284 ;; Delete identical interconnect
9285 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
9286 (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
9287 (delete-region (match-beginning 0) (match-end 0))
9288 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
9289 (while (or (looking-at "[ \t\n\f,]+")
9290 (looking-at "//[^\n]*"))
9291 (delete-region (match-beginning 0) (match-end 0))
9292 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
9293 (verilog-forward-close-paren)
9294 (backward-char 1)
9295 ;; Not verilog-re-search, as we don't want to strip comments
9296 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
9297 (delete-region (match-beginning 0) (match-end 0)))
9298 (verilog-insert "\n")
9299 (verilog-insert-indent "/*AUTOINST*/")))))))))
9300 \f
9301 ;;
9302 ;; Auto save
9303 ;;
9304
9305 (defun verilog-auto-save-check ()
9306 "On saving see if we need auto update."
9307 (cond ((not verilog-auto-save-policy)) ; disabled
9308 ((not (save-excursion
9309 (save-match-data
9310 (let ((case-fold-search nil))
9311 (goto-char (point-min))
9312 (re-search-forward "AUTO" nil t))))))
9313 ((eq verilog-auto-save-policy 'force)
9314 (verilog-auto))
9315 ((not (buffer-modified-p)))
9316 ((eq verilog-auto-update-tick (buffer-chars-modified-tick))) ; up-to-date
9317 ((eq verilog-auto-save-policy 'detect)
9318 (verilog-auto))
9319 (t
9320 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
9321 (verilog-auto))
9322 ;; Don't ask again if didn't update
9323 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))))
9324 (when (not verilog-auto-star-save)
9325 (verilog-delete-auto-star-implicit))
9326 nil) ;; Always return nil -- we don't write the file ourselves
9327
9328 (defun verilog-auto-read-locals ()
9329 "Return file local variable segment at bottom of file."
9330 (save-excursion
9331 (goto-char (point-max))
9332 (if (re-search-backward "Local Variables:" nil t)
9333 (buffer-substring-no-properties (point) (point-max))
9334 "")))
9335
9336 (defun verilog-auto-reeval-locals (&optional force)
9337 "Read file local variable segment at bottom of file if it has changed.
9338 If FORCE, always reread it."
9339 (let ((curlocal (verilog-auto-read-locals)))
9340 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
9341 (set (make-local-variable 'verilog-auto-last-file-locals) curlocal)
9342 ;; Note this may cause this function to be recursively invoked,
9343 ;; because hack-local-variables may call (verilog-mode)
9344 ;; The above when statement will prevent it from recursing forever.
9345 (hack-local-variables)
9346 t)))
9347 \f
9348 ;;
9349 ;; Auto creation
9350 ;;
9351
9352 (defun verilog-auto-arg-ports (sigs message indent-pt)
9353 "Print a list of ports for a AUTOINST.
9354 Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
9355 (when sigs
9356 (when verilog-auto-arg-sort
9357 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
9358 (insert "\n")
9359 (indent-to indent-pt)
9360 (insert message)
9361 (insert "\n")
9362 (let ((space ""))
9363 (indent-to indent-pt)
9364 (while sigs
9365 (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
9366 (insert "\n")
9367 (indent-to indent-pt))
9368 (t (insert space)))
9369 (insert (verilog-sig-name (car sigs)) ",")
9370 (setq sigs (cdr sigs)
9371 space " ")))))
9372
9373 (defun verilog-auto-arg ()
9374 "Expand AUTOARG statements.
9375 Replace the argument declarations at the beginning of the
9376 module with ones automatically derived from input and output
9377 statements. This can be dangerous if the module is instantiated
9378 using position-based connections, so use only name-based when
9379 instantiating the resulting module. Long lines are split based
9380 on the `fill-column', see \\[set-fill-column].
9381
9382 Limitations:
9383 Concatenation and outputting partial busses is not supported.
9384
9385 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9386
9387 For example:
9388
9389 module ExampArg (/*AUTOARG*/);
9390 input i;
9391 output o;
9392 endmodule
9393
9394 Typing \\[verilog-auto] will make this into:
9395
9396 module ExampArg (/*AUTOARG*/
9397 // Outputs
9398 o,
9399 // Inputs
9400 i
9401 );
9402 input i;
9403 output o;
9404 endmodule
9405
9406 The argument declarations may be printed in declaration order to best suit
9407 order based instantiations, or alphabetically, based on the
9408 `verilog-auto-arg-sort' variable.
9409
9410 Any ports declared between the ( and /*AUTOARG*/ are presumed to be
9411 predeclared and are not redeclared by AUTOARG. AUTOARG will make a
9412 conservative guess on adding a comma for the first signal, if you have
9413 any ifdefs or complicated expressions before the AUTOARG you will need
9414 to choose the comma yourself.
9415
9416 Avoid declaring ports manually, as it makes code harder to maintain."
9417 (save-excursion
9418 (let* ((modi (verilog-modi-current))
9419 (moddecls (verilog-modi-get-decls modi))
9420 (skip-pins (aref (verilog-read-arg-pins) 0)))
9421 (verilog-repair-open-comma)
9422 (verilog-auto-arg-ports (verilog-signals-not-in
9423 (verilog-decls-get-outputs moddecls)
9424 skip-pins)
9425 "// Outputs"
9426 verilog-indent-level-declaration)
9427 (verilog-auto-arg-ports (verilog-signals-not-in
9428 (verilog-decls-get-inouts moddecls)
9429 skip-pins)
9430 "// Inouts"
9431 verilog-indent-level-declaration)
9432 (verilog-auto-arg-ports (verilog-signals-not-in
9433 (verilog-decls-get-inputs moddecls)
9434 skip-pins)
9435 "// Inputs"
9436 verilog-indent-level-declaration)
9437 (verilog-repair-close-comma)
9438 (unless (eq (char-before) ?/ )
9439 (insert "\n"))
9440 (indent-to verilog-indent-level-declaration))))
9441
9442 (defun verilog-auto-inst-port-map (port-st)
9443 nil)
9444
9445 (defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
9446 (defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
9447 (defvar vl-modport nil "See `verilog-auto-inst'.") ; Prevent compile warning
9448 (defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
9449 (defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
9450 (defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
9451 (defvar vl-bits nil "See `verilog-auto-inst'.") ; Prevent compile warning
9452 (defvar vl-mbits nil "See `verilog-auto-inst'.") ; Prevent compile warning
9453
9454 (defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
9455 "Print out a instantiation connection for this PORT-ST.
9456 Insert to INDENT-PT, use template TPL-LIST.
9457 @ are instantiation numbers, replaced with TPL-NUM.
9458 @\"(expression @)\" are evaluated, with @ as a variable.
9459 If FOR-STAR add comment it is a .* expansion.
9460 If PAR-VALUES replace final strings with these parameter values."
9461 (let* ((port (verilog-sig-name port-st))
9462 (tpl-ass (or (assoc port (car tpl-list))
9463 (verilog-auto-inst-port-map port-st)))
9464 ;; vl-* are documented for user use
9465 (vl-name (verilog-sig-name port-st))
9466 (vl-width (verilog-sig-width port-st))
9467 (vl-modport (verilog-sig-modport port-st))
9468 (vl-mbits (if (verilog-sig-multidim port-st)
9469 (verilog-sig-multidim-string port-st) ""))
9470 (vl-bits (if (or verilog-auto-inst-vector
9471 (not (assoc port vector-skip-list))
9472 (not (equal (verilog-sig-bits port-st)
9473 (verilog-sig-bits (assoc port vector-skip-list)))))
9474 (or (verilog-sig-bits port-st) "")
9475 ""))
9476 (case-fold-search nil)
9477 (check-values par-values)
9478 tpl-net)
9479 ;; Replace parameters in bit-width
9480 (when (and check-values
9481 (not (equal vl-bits "")))
9482 (while check-values
9483 (setq vl-bits (verilog-string-replace-matches
9484 (concat "\\<" (nth 0 (car check-values)) "\\>")
9485 (concat "(" (nth 1 (car check-values)) ")")
9486 t t vl-bits)
9487 check-values (cdr check-values)))
9488 (setq vl-bits (verilog-simplify-range-expression vl-bits))) ; Not in the loop for speed
9489 ;; Default net value if not found
9490 (setq tpl-net (concat port
9491 (if vl-modport (concat "." vl-modport) "")
9492 (if (verilog-sig-multidim port-st)
9493 (concat "/*" (verilog-sig-multidim-string port-st)
9494 vl-bits "*/")
9495 (concat vl-bits))))
9496 ;; Find template
9497 (cond (tpl-ass ; Template of exact port name
9498 (setq tpl-net (nth 1 tpl-ass)))
9499 ((nth 1 tpl-list) ; Wildcards in template, search them
9500 (let ((wildcards (nth 1 tpl-list)))
9501 (while wildcards
9502 (when (string-match (nth 0 (car wildcards)) port)
9503 (setq tpl-ass (car wildcards) ; so allow @ parsing
9504 tpl-net (replace-match (nth 1 (car wildcards))
9505 t nil port)))
9506 (setq wildcards (cdr wildcards))))))
9507 ;; Parse Templated variable
9508 (when tpl-ass
9509 ;; Evaluate @"(lispcode)"
9510 (when (string-match "@\".*[^\\]\"" tpl-net)
9511 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
9512 (setq tpl-net
9513 (concat
9514 (substring tpl-net 0 (match-beginning 0))
9515 (save-match-data
9516 (let* ((expr (match-string 1 tpl-net))
9517 (value
9518 (progn
9519 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
9520 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
9521 (prin1 (eval (car (read-from-string expr)))
9522 (lambda (ch) ())))))
9523 (if (numberp value) (setq value (number-to-string value)))
9524 value))
9525 (substring tpl-net (match-end 0))))))
9526 ;; Replace @ and [] magic variables in final output
9527 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
9528 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
9529 ;; Insert it
9530 (indent-to indent-pt)
9531 (insert "." port)
9532 (unless (and verilog-auto-inst-dot-name
9533 (equal port tpl-net))
9534 (indent-to verilog-auto-inst-column)
9535 (insert "(" tpl-net ")"))
9536 (insert ",")
9537 (cond (tpl-ass
9538 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
9539 verilog-auto-inst-column))
9540 (if verilog-auto-inst-template-numbers
9541 (verilog-insert " // Templated"
9542 " T" (int-to-string (nth 2 tpl-ass))
9543 " L" (int-to-string (nth 3 tpl-ass)))
9544 (verilog-insert " // Templated")))
9545 (for-star
9546 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
9547 verilog-auto-inst-column))
9548 (verilog-insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
9549 (insert "\n")))
9550 ;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
9551 ;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
9552 ;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
9553
9554 (defun verilog-auto-inst-first ()
9555 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
9556 ;; Do we need a trailing comma?
9557 ;; There maybe a ifdef or something similar before us. What a mess. Thus
9558 ;; to avoid trouble we only insert on preceding ) or *.
9559 ;; Insert first port on new line
9560 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
9561 (save-excursion
9562 (verilog-re-search-backward "[^ \t\n\f]" nil nil)
9563 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
9564 (forward-char 1)
9565 (insert ","))))
9566
9567 (defun verilog-auto-star ()
9568 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
9569
9570 If `verilog-auto-star-expand' is set, .* pins are treated if they were
9571 AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
9572 will also ignore any .* that are not last in your pin list (this prevents
9573 it from deleting pins following the .* when it expands the AUTOINST.)
9574
9575 On writing your file, unless `verilog-auto-star-save' is set, any
9576 non-templated expanded pins will be removed. You may do this at any time
9577 with \\[verilog-delete-auto-star-implicit].
9578
9579 If you are converting a module to use .* for the first time, you may wish
9580 to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
9581
9582 See `verilog-auto-inst' for examples, templates, and more information."
9583 (when (verilog-auto-star-safe)
9584 (verilog-auto-inst)))
9585
9586 (defun verilog-auto-inst ()
9587 "Expand AUTOINST statements, as part of \\[verilog-auto].
9588 Replace the pin connections to an instantiation or interface
9589 declaration with ones automatically derived from the module or
9590 interface header of the instantiated item.
9591
9592 If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
9593 and delete them before saving unless `verilog-auto-star-save' is set.
9594 See `verilog-auto-star' for more information.
9595
9596 Limitations:
9597 Module names must be resolvable to filenames by adding a
9598 `verilog-library-extensions', and being found in the same directory, or
9599 by changing the variable `verilog-library-flags' or
9600 `verilog-library-directories'. Macros `modname are translated through the
9601 vh-{name} Emacs variable, if that is not found, it just ignores the `.
9602
9603 In templates you must have one signal per line, ending in a ), or ));,
9604 and have proper () nesting, including a final ); to end the template.
9605
9606 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9607
9608 SystemVerilog multidimensional input/output has only experimental support.
9609
9610 SystemVerilog .name syntax is used if `verilog-auto-inst-dot-name' is set.
9611
9612 Parameters referenced by the instantiation will remain symbolic, unless
9613 `verilog-auto-inst-param-value' is set.
9614
9615 Gate primitives (and/or) may have AUTOINST for the purpose of
9616 AUTOWIRE declarations, etc. Gates are the only case when
9617 position based connections are passed.
9618
9619 For example, first take the submodule InstModule.v:
9620
9621 module InstModule (o,i);
9622 output [31:0] o;
9623 input i;
9624 wire [31:0] o = {32{i}};
9625 endmodule
9626
9627 This is then used in a upper level module:
9628
9629 module ExampInst (o,i);
9630 output o;
9631 input i;
9632 InstModule instName
9633 (/*AUTOINST*/);
9634 endmodule
9635
9636 Typing \\[verilog-auto] will make this into:
9637
9638 module ExampInst (o,i);
9639 output o;
9640 input i;
9641 InstModule instName
9642 (/*AUTOINST*/
9643 // Outputs
9644 .ov (ov[31:0]),
9645 // Inputs
9646 .i (i));
9647 endmodule
9648
9649 Where the list of inputs and outputs came from the inst module.
9650 \f
9651 Exceptions:
9652
9653 Unless you are instantiating a module multiple times, or the module is
9654 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
9655 It just makes for unmaintainable code. To sanitize signal names, try
9656 vrename from URL `http://www.veripool.org'.
9657
9658 When you need to violate this suggestion there are two ways to list
9659 exceptions, placing them before the AUTOINST, or using templates.
9660
9661 Any ports defined before the /*AUTOINST*/ are not included in the list of
9662 automatics. This is similar to making a template as described below, but
9663 is restricted to simple connections just like you normally make. Also note
9664 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
9665 you have the appropriate // Input or // Output comment, and exactly the
9666 same line formatting as AUTOINST itself uses.
9667
9668 InstModule instName
9669 (// Inputs
9670 .i (my_i_dont_mess_with_it),
9671 /*AUTOINST*/
9672 // Outputs
9673 .ov (ov[31:0]));
9674
9675 \f
9676 Templates:
9677
9678 For multiple instantiations based upon a single template, create a
9679 commented out template:
9680
9681 /* InstModule AUTO_TEMPLATE (
9682 .sig3 (sigz[]),
9683 );
9684 */
9685
9686 Templates go ABOVE the instantiation(s). When an instantiation is
9687 expanded `verilog-mode' simply searches up for the closest template.
9688 Thus you can have multiple templates for the same module, just alternate
9689 between the template for an instantiation and the instantiation itself.
9690
9691 The module name must be the same as the name of the module in the
9692 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
9693 words and capitalized. Only signals that must be different for each
9694 instantiation need to be listed.
9695
9696 Inside a template, a [] in a connection name (with nothing else inside
9697 the brackets) will be replaced by the same bus subscript as it is being
9698 connected to, or the [] will be removed if it is a single bit signal.
9699 Generally it is a good idea to do this for all connections in a template,
9700 as then they will work for any width signal, and with AUTOWIRE. See
9701 PTL_BUS becoming PTL_BUSNEW below.
9702
9703 If you have a complicated template, set `verilog-auto-inst-template-numbers'
9704 to see which regexps are matching. Don't leave that mode set after
9705 debugging is completed though, it will result in lots of extra differences
9706 and merge conflicts.
9707
9708 For example:
9709
9710 /* InstModule AUTO_TEMPLATE (
9711 .ptl_bus (ptl_busnew[]),
9712 );
9713 */
9714 InstModule ms2m (/*AUTOINST*/);
9715
9716 Typing \\[verilog-auto] will make this into:
9717
9718 InstModule ms2m (/*AUTOINST*/
9719 // Outputs
9720 .NotInTemplate (NotInTemplate),
9721 .ptl_bus (ptl_busnew[3:0]), // Templated
9722 ....
9723 \f
9724 @ Templates:
9725
9726 It is common to instantiate a cell multiple times, so templates make it
9727 trivial to substitute part of the cell name into the connection name.
9728
9729 /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
9730 .sig1 (sigx[@]),
9731 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
9732 );
9733 */
9734
9735 If no regular expression is provided immediately after the AUTO_TEMPLATE
9736 keyword, then the @ character in any connection names will be replaced
9737 with the instantiation number; the first digits found in the cell's
9738 instantiation name.
9739
9740 If a regular expression is provided, the @ character will be replaced
9741 with the first \(\) grouping that matches against the cell name. Using a
9742 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
9743 regexp is provided. If you use multiple layers of parenthesis,
9744 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
9745 characters after test and before _, whereas
9746 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
9747 match.
9748
9749 For example:
9750
9751 /* InstModule AUTO_TEMPLATE (
9752 .ptl_mapvalidx (ptl_mapvalid[@]),
9753 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
9754 );
9755 */
9756 InstModule ms2m (/*AUTOINST*/);
9757
9758 Typing \\[verilog-auto] will make this into:
9759
9760 InstModule ms2m (/*AUTOINST*/
9761 // Outputs
9762 .ptl_mapvalidx (ptl_mapvalid[2]),
9763 .ptl_mapvalidp1x (ptl_mapvalid[3]));
9764
9765 Note the @ character was replaced with the 2 from \"ms2m\".
9766
9767 Alternatively, using a regular expression for @:
9768
9769 /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
9770 .ptl_mapvalidx (@_ptl_mapvalid),
9771 .ptl_mapvalidp1x (ptl_mapvalid_@),
9772 );
9773 */
9774 InstModule ms2_FOO (/*AUTOINST*/);
9775 InstModule ms2_BAR (/*AUTOINST*/);
9776
9777 Typing \\[verilog-auto] will make this into:
9778
9779 InstModule ms2_FOO (/*AUTOINST*/
9780 // Outputs
9781 .ptl_mapvalidx (FOO_ptl_mapvalid),
9782 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
9783 InstModule ms2_BAR (/*AUTOINST*/
9784 // Outputs
9785 .ptl_mapvalidx (BAR_ptl_mapvalid),
9786 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
9787
9788 \f
9789 Regexp Templates:
9790
9791 A template entry of the form
9792
9793 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
9794
9795 will apply an Emacs style regular expression search for any port beginning
9796 in pci_req followed by numbers and ending in _l and connecting that to
9797 the pci_req_jtag_[] net, with the bus subscript coming from what matches
9798 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
9799
9800 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
9801 does the same thing. (Note a @ in the connection/replacement text is
9802 completely different -- still use \\1 there!) Thus this is the same as
9803 the above template:
9804
9805 .pci_req@_l (pci_req_jtag_[\\1]),
9806
9807 Here's another example to remove the _l, useful when naming conventions
9808 specify _ alone to mean active low. Note the use of [] to keep the bus
9809 subscript:
9810
9811 .\\(.*\\)_l (\\1_[]),
9812 \f
9813 Lisp Templates:
9814
9815 First any regular expression template is expanded.
9816
9817 If the syntax @\"( ... )\" is found in a connection, the expression in
9818 quotes will be evaluated as a Lisp expression, with @ replaced by the
9819 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
9820 4 into the brackets. Quote all double-quotes inside the expression with
9821 a leading backslash (\\\"...\\\"); or if the Lisp template is also a
9822 regexp template backslash the backslash quote (\\\\\"...\\\\\").
9823
9824 There are special variables defined that are useful in these
9825 Lisp functions:
9826
9827 vl-name Name portion of the input/output port.
9828 vl-bits Bus bits portion of the input/output port ('[2:0]').
9829 vl-mbits Multidimensional array bits for port ('[2:0][3:0]').
9830 vl-width Width of the input/output port ('3' for [2:0]).
9831 May be a (...) expression if bits isn't a constant.
9832 vl-dir Direction of the pin input/output/inout/interface.
9833 vl-modport The modport, if an interface with a modport.
9834 vl-cell-type Module name/type of the cell ('InstModule').
9835 vl-cell-name Instance name of the cell ('instName').
9836
9837 Normal Lisp variables may be used in expressions. See
9838 `verilog-read-defines' which can set vh-{definename} variables for use
9839 here. Also, any comments of the form:
9840
9841 /*AUTO_LISP(setq foo 1)*/
9842
9843 will evaluate any Lisp expression inside the parenthesis between the
9844 beginning of the buffer and the point of the AUTOINST. This allows
9845 functions to be defined or variables to be changed between instantiations.
9846 (See also `verilog-auto-insert-lisp' if you want the output from your
9847 lisp function to be inserted.)
9848
9849 Note that when using lisp expressions errors may occur when @ is not a
9850 number; you may need to use the standard Emacs Lisp functions
9851 `number-to-string' and `string-to-number'.
9852
9853 After the evaluation is completed, @ substitution and [] substitution
9854 occur.
9855
9856 For more information see the \\[verilog-faq] and forums at URL
9857 `http://www.veripool.org'."
9858 (save-excursion
9859 ;; Find beginning
9860 (let* ((pt (point))
9861 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
9862 (indent-pt (save-excursion (verilog-backward-open-paren)
9863 (1+ (current-column))))
9864 (verilog-auto-inst-column (max verilog-auto-inst-column
9865 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
9866 (modi (verilog-modi-current))
9867 (moddecls (verilog-modi-get-decls modi))
9868 (vector-skip-list (unless verilog-auto-inst-vector
9869 (verilog-decls-get-signals moddecls)))
9870 submod submodi submoddecls
9871 inst skip-pins tpl-list tpl-num did-first par-values)
9872
9873 ;; Find module name that is instantiated
9874 (setq submod (verilog-read-inst-module)
9875 inst (verilog-read-inst-name)
9876 vl-cell-type submod
9877 vl-cell-name inst
9878 skip-pins (aref (verilog-read-inst-pins) 0))
9879
9880 ;; Parse any AUTO_LISP() before here
9881 (verilog-read-auto-lisp (point-min) pt)
9882
9883 ;; Read parameters (after AUTO_LISP)
9884 (setq par-values (and verilog-auto-inst-param-value
9885 (verilog-read-inst-param-value)))
9886
9887 ;; Lookup position, etc of submodule
9888 ;; Note this may raise an error
9889 (when (and (not (member submod verilog-gate-keywords))
9890 (setq submodi (verilog-modi-lookup submod t)))
9891 (setq submoddecls (verilog-modi-get-decls submodi))
9892 ;; If there's a number in the instantiation, it may be a argument to the
9893 ;; automatic variable instantiation program.
9894 (let* ((tpl-info (verilog-read-auto-template submod))
9895 (tpl-regexp (aref tpl-info 0)))
9896 (setq tpl-num (if (string-match tpl-regexp inst)
9897 (match-string 1 inst)
9898 "")
9899 tpl-list (aref tpl-info 1)))
9900 ;; Find submodule's signals and dump
9901 (let ((sig-list (and (equal (verilog-modi-get-type submodi) "interface")
9902 (verilog-signals-not-in
9903 (append (verilog-decls-get-wires submoddecls)
9904 (verilog-decls-get-regs submoddecls))
9905 skip-pins)))
9906 (vl-dir "interfaced"))
9907 (when sig-list
9908 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9909 ;; Note these are searched for in verilog-read-sub-decls.
9910 (verilog-insert-indent "// Interfaced\n")
9911 (mapc (lambda (port)
9912 (verilog-auto-inst-port port indent-pt
9913 tpl-list tpl-num for-star par-values))
9914 sig-list)))
9915 (let ((sig-list (verilog-signals-not-in
9916 (verilog-decls-get-interfaces submoddecls)
9917 skip-pins))
9918 (vl-dir "interface"))
9919 (when sig-list
9920 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9921 ;; Note these are searched for in verilog-read-sub-decls.
9922 (verilog-insert-indent "// Interfaces\n")
9923 (mapc (lambda (port)
9924 (verilog-auto-inst-port port indent-pt
9925 tpl-list tpl-num for-star par-values))
9926 sig-list)))
9927 (let ((sig-list (verilog-signals-not-in
9928 (verilog-decls-get-outputs submoddecls)
9929 skip-pins))
9930 (vl-dir "output"))
9931 (when sig-list
9932 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9933 (verilog-insert-indent "// Outputs\n")
9934 (mapc (lambda (port)
9935 (verilog-auto-inst-port port indent-pt
9936 tpl-list tpl-num for-star par-values))
9937 sig-list)))
9938 (let ((sig-list (verilog-signals-not-in
9939 (verilog-decls-get-inouts submoddecls)
9940 skip-pins))
9941 (vl-dir "inout"))
9942 (when sig-list
9943 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9944 (verilog-insert-indent "// Inouts\n")
9945 (mapc (lambda (port)
9946 (verilog-auto-inst-port port indent-pt
9947 tpl-list tpl-num for-star par-values))
9948 sig-list)))
9949 (let ((sig-list (verilog-signals-not-in
9950 (verilog-decls-get-inputs submoddecls)
9951 skip-pins))
9952 (vl-dir "input"))
9953 (when sig-list
9954 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9955 (verilog-insert-indent "// Inputs\n")
9956 (mapc (lambda (port)
9957 (verilog-auto-inst-port port indent-pt
9958 tpl-list tpl-num for-star par-values))
9959 sig-list)))
9960 ;; Kill extra semi
9961 (save-excursion
9962 (cond (did-first
9963 (re-search-backward "," pt t)
9964 (delete-char 1)
9965 (insert ");")
9966 (search-forward "\n") ;; Added by inst-port
9967 (delete-char -1)
9968 (if (search-forward ")" nil t) ;; From user, moved up a line
9969 (delete-char -1))
9970 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
9971 (delete-char -1)))))))))
9972
9973 (defun verilog-auto-inst-param ()
9974 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
9975 Replace the parameter connections to an instantiation with ones
9976 automatically derived from the module header of the instantiated netlist.
9977
9978 See \\[verilog-auto-inst] for limitations, and templates to customize the
9979 output.
9980
9981 For example, first take the submodule InstModule.v:
9982
9983 module InstModule (o,i);
9984 parameter PAR;
9985 endmodule
9986
9987 This is then used in a upper level module:
9988
9989 module ExampInst (o,i);
9990 parameter PAR;
9991 InstModule #(/*AUTOINSTPARAM*/)
9992 instName (/*AUTOINST*/);
9993 endmodule
9994
9995 Typing \\[verilog-auto] will make this into:
9996
9997 module ExampInst (o,i);
9998 output o;
9999 input i;
10000 InstModule #(/*AUTOINSTPARAM*/
10001 // Parameters
10002 .PAR (PAR));
10003 instName (/*AUTOINST*/);
10004 endmodule
10005
10006 Where the list of parameter connections come from the inst module.
10007 \f
10008 Templates:
10009
10010 You can customize the parameter connections using AUTO_TEMPLATEs,
10011 just as you would with \\[verilog-auto-inst]."
10012 (save-excursion
10013 ;; Find beginning
10014 (let* ((pt (point))
10015 (indent-pt (save-excursion (verilog-backward-open-paren)
10016 (1+ (current-column))))
10017 (verilog-auto-inst-column (max verilog-auto-inst-column
10018 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
10019 (modi (verilog-modi-current))
10020 (moddecls (verilog-modi-get-decls modi))
10021 (vector-skip-list (unless verilog-auto-inst-vector
10022 (verilog-decls-get-signals moddecls)))
10023 submod submodi submoddecls
10024 inst skip-pins tpl-list tpl-num did-first)
10025 ;; Find module name that is instantiated
10026 (setq submod (save-excursion
10027 ;; Get to the point where AUTOINST normally is to read the module
10028 (verilog-re-search-forward-quick "[(;]" nil nil)
10029 (verilog-read-inst-module))
10030 inst (save-excursion
10031 ;; Get to the point where AUTOINST normally is to read the module
10032 (verilog-re-search-forward-quick "[(;]" nil nil)
10033 (verilog-read-inst-name))
10034 vl-cell-type submod
10035 vl-cell-name inst
10036 skip-pins (aref (verilog-read-inst-pins) 0))
10037
10038 ;; Parse any AUTO_LISP() before here
10039 (verilog-read-auto-lisp (point-min) pt)
10040
10041 ;; Lookup position, etc of submodule
10042 ;; Note this may raise an error
10043 (when (setq submodi (verilog-modi-lookup submod t))
10044 (setq submoddecls (verilog-modi-get-decls submodi))
10045 ;; If there's a number in the instantiation, it may be a argument to the
10046 ;; automatic variable instantiation program.
10047 (let* ((tpl-info (verilog-read-auto-template submod))
10048 (tpl-regexp (aref tpl-info 0)))
10049 (setq tpl-num (if (string-match tpl-regexp inst)
10050 (match-string 1 inst)
10051 "")
10052 tpl-list (aref tpl-info 1)))
10053 ;; Find submodule's signals and dump
10054 (let ((sig-list (verilog-signals-not-in
10055 (verilog-decls-get-gparams submoddecls)
10056 skip-pins))
10057 (vl-dir "parameter"))
10058 (when sig-list
10059 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
10060 ;; Note these are searched for in verilog-read-sub-decls.
10061 (verilog-insert-indent "// Parameters\n")
10062 (mapc (lambda (port)
10063 (verilog-auto-inst-port port indent-pt
10064 tpl-list tpl-num nil nil))
10065 sig-list)))
10066 ;; Kill extra semi
10067 (save-excursion
10068 (cond (did-first
10069 (re-search-backward "," pt t)
10070 (delete-char 1)
10071 (insert ")")
10072 (search-forward "\n") ;; Added by inst-port
10073 (delete-char -1)
10074 (if (search-forward ")" nil t) ;; From user, moved up a line
10075 (delete-char -1)))))))))
10076
10077 (defun verilog-auto-reg ()
10078 "Expand AUTOREG statements, as part of \\[verilog-auto].
10079 Make reg statements for any output that isn't already declared,
10080 and isn't a wire output from a block.
10081
10082 Limitations:
10083 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10084
10085 This does NOT work on memories, declare those yourself.
10086
10087 An example:
10088
10089 module ExampReg (o,i);
10090 output o;
10091 input i;
10092 /*AUTOREG*/
10093 always o = i;
10094 endmodule
10095
10096 Typing \\[verilog-auto] will make this into:
10097
10098 module ExampReg (o,i);
10099 output o;
10100 input i;
10101 /*AUTOREG*/
10102 // Beginning of automatic regs (for this module's undeclared outputs)
10103 reg o;
10104 // End of automatics
10105 always o = i;
10106 endmodule"
10107 (save-excursion
10108 ;; Point must be at insertion point.
10109 (let* ((indent-pt (current-indentation))
10110 (modi (verilog-modi-current))
10111 (moddecls (verilog-modi-get-decls modi))
10112 (modsubdecls (verilog-modi-get-sub-decls modi))
10113 (sig-list (verilog-signals-not-in
10114 (verilog-decls-get-outputs moddecls)
10115 (append (verilog-decls-get-wires moddecls)
10116 (verilog-decls-get-regs moddecls)
10117 (verilog-decls-get-assigns moddecls)
10118 (verilog-decls-get-consts moddecls)
10119 (verilog-decls-get-gparams moddecls)
10120 (verilog-subdecls-get-interfaced modsubdecls)
10121 (verilog-subdecls-get-outputs modsubdecls)
10122 (verilog-subdecls-get-inouts modsubdecls)))))
10123 (forward-line 1)
10124 (when sig-list
10125 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
10126 (verilog-insert-definition sig-list "reg" indent-pt nil)
10127 (verilog-modi-cache-add-regs modi sig-list)
10128 (verilog-insert-indent "// End of automatics\n")))))
10129
10130 (defun verilog-auto-reg-input ()
10131 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
10132 Make reg statements instantiation inputs that aren't already declared.
10133 This is useful for making a top level shell for testing the module that is
10134 to be instantiated.
10135
10136 Limitations:
10137 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
10138
10139 This does NOT work on memories, declare those yourself.
10140
10141 An example (see `verilog-auto-inst' for what else is going on here):
10142
10143 module ExampRegInput (o,i);
10144 output o;
10145 input i;
10146 /*AUTOREGINPUT*/
10147 InstModule instName
10148 (/*AUTOINST*/);
10149 endmodule
10150
10151 Typing \\[verilog-auto] will make this into:
10152
10153 module ExampRegInput (o,i);
10154 output o;
10155 input i;
10156 /*AUTOREGINPUT*/
10157 // Beginning of automatic reg inputs (for undeclared ...
10158 reg [31:0] iv; // From inst of inst.v
10159 // End of automatics
10160 InstModule instName
10161 (/*AUTOINST*/
10162 // Outputs
10163 .o (o[31:0]),
10164 // Inputs
10165 .iv (iv));
10166 endmodule"
10167 (save-excursion
10168 ;; Point must be at insertion point.
10169 (let* ((indent-pt (current-indentation))
10170 (modi (verilog-modi-current))
10171 (moddecls (verilog-modi-get-decls modi))
10172 (modsubdecls (verilog-modi-get-sub-decls modi))
10173 (sig-list (verilog-signals-combine-bus
10174 (verilog-signals-not-in
10175 (append (verilog-subdecls-get-inputs modsubdecls)
10176 (verilog-subdecls-get-inouts modsubdecls))
10177 (verilog-decls-get-signals moddecls)))))
10178 (forward-line 1)
10179 (when sig-list
10180 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
10181 (verilog-insert-definition sig-list "reg" indent-pt nil)
10182 (verilog-modi-cache-add-regs modi sig-list)
10183 (verilog-insert-indent "// End of automatics\n")))))
10184
10185 (defun verilog-auto-wire ()
10186 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
10187 Make wire statements for instantiations outputs that aren't
10188 already declared.
10189
10190 Limitations:
10191 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
10192 and all busses must have widths, such as those from AUTOINST, or using []
10193 in AUTO_TEMPLATEs.
10194
10195 This does NOT work on memories or SystemVerilog .name connections,
10196 declare those yourself.
10197
10198 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
10199 determine how to bus together. This occurs when you have ports with
10200 non-numeric or non-sequential bus subscripts. If Verilog mode
10201 mis-guessed, you'll have to declare them yourself.
10202
10203 An example (see `verilog-auto-inst' for what else is going on here):
10204
10205 module ExampWire (o,i);
10206 output o;
10207 input i;
10208 /*AUTOWIRE*/
10209 InstModule instName
10210 (/*AUTOINST*/);
10211 endmodule
10212
10213 Typing \\[verilog-auto] will make this into:
10214
10215 module ExampWire (o,i);
10216 output o;
10217 input i;
10218 /*AUTOWIRE*/
10219 // Beginning of automatic wires
10220 wire [31:0] ov; // From inst of inst.v
10221 // End of automatics
10222 InstModule instName
10223 (/*AUTOINST*/
10224 // Outputs
10225 .ov (ov[31:0]),
10226 // Inputs
10227 .i (i));
10228 wire o = | ov;
10229 endmodule"
10230 (save-excursion
10231 ;; Point must be at insertion point.
10232 (let* ((indent-pt (current-indentation))
10233 (modi (verilog-modi-current))
10234 (moddecls (verilog-modi-get-decls modi))
10235 (modsubdecls (verilog-modi-get-sub-decls modi))
10236 (sig-list (verilog-signals-combine-bus
10237 (verilog-signals-not-in
10238 (append (verilog-subdecls-get-outputs modsubdecls)
10239 (verilog-subdecls-get-inouts modsubdecls))
10240 (verilog-decls-get-signals moddecls)))))
10241 (forward-line 1)
10242 (when sig-list
10243 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
10244 (verilog-insert-definition sig-list "wire" indent-pt nil)
10245 (verilog-modi-cache-add-wires modi sig-list)
10246 (verilog-insert-indent "// End of automatics\n")
10247 (when nil ;; Too slow on huge modules, plus makes everyone's module change
10248 (beginning-of-line)
10249 (setq pnt (point))
10250 (verilog-pretty-declarations quiet)
10251 (goto-char pnt)
10252 (verilog-pretty-expr t "//"))))))
10253
10254 (defun verilog-auto-output (&optional with-params)
10255 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
10256 Make output statements for any output signal from an /*AUTOINST*/ that
10257 isn't a input to another AUTOINST. This is useful for modules which
10258 only instantiate other modules.
10259
10260 Limitations:
10261 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10262
10263 If placed inside the parenthesis of a module declaration, it creates
10264 Verilog 2001 style, else uses Verilog 1995 style.
10265
10266 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10267 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10268
10269 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10270
10271 Signals matching `verilog-auto-output-ignore-regexp' are not included.
10272
10273 An example (see `verilog-auto-inst' for what else is going on here):
10274
10275 module ExampOutput (ov,i);
10276 input i;
10277 /*AUTOOUTPUT*/
10278 InstModule instName
10279 (/*AUTOINST*/);
10280 endmodule
10281
10282 Typing \\[verilog-auto] will make this into:
10283
10284 module ExampOutput (ov,i);
10285 input i;
10286 /*AUTOOUTPUT*/
10287 // Beginning of automatic outputs (from unused autoinst outputs)
10288 output [31:0] ov; // From inst of inst.v
10289 // End of automatics
10290 InstModule instName
10291 (/*AUTOINST*/
10292 // Outputs
10293 .ov (ov[31:0]),
10294 // Inputs
10295 .i (i));
10296 endmodule
10297
10298 You may also provide an optional regular expression, in which case only
10299 signals matching the regular expression will be included. For example the
10300 same expansion will result from only extracting outputs starting with ov:
10301
10302 /*AUTOOUTPUT(\"^ov\")*/"
10303 (save-excursion
10304 ;; Point must be at insertion point.
10305 (let* ((indent-pt (current-indentation))
10306 (regexp (and with-params
10307 (nth 0 (verilog-read-auto-params 1))))
10308 (v2k (verilog-in-paren))
10309 (modi (verilog-modi-current))
10310 (moddecls (verilog-modi-get-decls modi))
10311 (modsubdecls (verilog-modi-get-sub-decls modi))
10312 (sig-list (verilog-signals-not-in
10313 (verilog-subdecls-get-outputs modsubdecls)
10314 (append (verilog-decls-get-outputs moddecls)
10315 (verilog-decls-get-inouts moddecls)
10316 (verilog-subdecls-get-inputs modsubdecls)
10317 (verilog-subdecls-get-inouts modsubdecls)))))
10318 (when regexp
10319 (setq sig-list (verilog-signals-matching-regexp
10320 sig-list regexp)))
10321 (setq sig-list (verilog-signals-not-matching-regexp
10322 sig-list verilog-auto-output-ignore-regexp))
10323 (forward-line 1)
10324 (when v2k (verilog-repair-open-comma))
10325 (when sig-list
10326 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
10327 (verilog-insert-definition sig-list "output" indent-pt v2k)
10328 (verilog-modi-cache-add-outputs modi sig-list)
10329 (verilog-insert-indent "// End of automatics\n"))
10330 (when v2k (verilog-repair-close-comma)))))
10331
10332 (defun verilog-auto-output-every ()
10333 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
10334 Make output statements for any signals that aren't primary inputs or
10335 outputs already. This makes every signal in the design a output. This is
10336 useful to get Synopsys to preserve every signal in the design, since it
10337 won't optimize away the outputs.
10338
10339 An example:
10340
10341 module ExampOutputEvery (o,i,tempa,tempb);
10342 output o;
10343 input i;
10344 /*AUTOOUTPUTEVERY*/
10345 wire tempa = i;
10346 wire tempb = tempa;
10347 wire o = tempb;
10348 endmodule
10349
10350 Typing \\[verilog-auto] will make this into:
10351
10352 module ExampOutputEvery (o,i,tempa,tempb);
10353 output o;
10354 input i;
10355 /*AUTOOUTPUTEVERY*/
10356 // Beginning of automatic outputs (every signal)
10357 output tempb;
10358 output tempa;
10359 // End of automatics
10360 wire tempa = i;
10361 wire tempb = tempa;
10362 wire o = tempb;
10363 endmodule"
10364 (save-excursion
10365 ;;Point must be at insertion point
10366 (let* ((indent-pt (current-indentation))
10367 (v2k (verilog-in-paren))
10368 (modi (verilog-modi-current))
10369 (moddecls (verilog-modi-get-decls modi))
10370 (sig-list (verilog-signals-combine-bus
10371 (verilog-signals-not-in
10372 (verilog-decls-get-signals moddecls)
10373 (verilog-decls-get-ports moddecls)))))
10374 (forward-line 1)
10375 (when v2k (verilog-repair-open-comma))
10376 (when sig-list
10377 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
10378 (verilog-insert-definition sig-list "output" indent-pt v2k)
10379 (verilog-modi-cache-add-outputs modi sig-list)
10380 (verilog-insert-indent "// End of automatics\n"))
10381 (when v2k (verilog-repair-close-comma)))))
10382
10383 (defun verilog-auto-input (&optional with-params)
10384 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
10385 Make input statements for any input signal into an /*AUTOINST*/ that
10386 isn't declared elsewhere inside the module. This is useful for modules which
10387 only instantiate other modules.
10388
10389 Limitations:
10390 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10391
10392 If placed inside the parenthesis of a module declaration, it creates
10393 Verilog 2001 style, else uses Verilog 1995 style.
10394
10395 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10396 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10397
10398 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10399
10400 Signals matching `verilog-auto-input-ignore-regexp' are not included.
10401
10402 An example (see `verilog-auto-inst' for what else is going on here):
10403
10404 module ExampInput (ov,i);
10405 output [31:0] ov;
10406 /*AUTOINPUT*/
10407 InstModule instName
10408 (/*AUTOINST*/);
10409 endmodule
10410
10411 Typing \\[verilog-auto] will make this into:
10412
10413 module ExampInput (ov,i);
10414 output [31:0] ov;
10415 /*AUTOINPUT*/
10416 // Beginning of automatic inputs (from unused autoinst inputs)
10417 input i; // From inst of inst.v
10418 // End of automatics
10419 InstModule instName
10420 (/*AUTOINST*/
10421 // Outputs
10422 .ov (ov[31:0]),
10423 // Inputs
10424 .i (i));
10425 endmodule
10426
10427 You may also provide an optional regular expression, in which case only
10428 signals matching the regular expression will be included. For example the
10429 same expansion will result from only extracting inputs starting with i:
10430
10431 /*AUTOINPUT(\"^i\")*/"
10432 (save-excursion
10433 (let* ((indent-pt (current-indentation))
10434 (regexp (and with-params
10435 (nth 0 (verilog-read-auto-params 1))))
10436 (v2k (verilog-in-paren))
10437 (modi (verilog-modi-current))
10438 (moddecls (verilog-modi-get-decls modi))
10439 (modsubdecls (verilog-modi-get-sub-decls modi))
10440 (sig-list (verilog-signals-not-in
10441 (verilog-subdecls-get-inputs modsubdecls)
10442 (append (verilog-decls-get-inputs moddecls)
10443 (verilog-decls-get-inouts moddecls)
10444 (verilog-decls-get-wires moddecls)
10445 (verilog-decls-get-regs moddecls)
10446 (verilog-decls-get-consts moddecls)
10447 (verilog-decls-get-gparams moddecls)
10448 (verilog-subdecls-get-interfaced modsubdecls)
10449 (verilog-subdecls-get-outputs modsubdecls)
10450 (verilog-subdecls-get-inouts modsubdecls)))))
10451 (when regexp
10452 (setq sig-list (verilog-signals-matching-regexp
10453 sig-list regexp)))
10454 (setq sig-list (verilog-signals-not-matching-regexp
10455 sig-list verilog-auto-input-ignore-regexp))
10456 (forward-line 1)
10457 (when v2k (verilog-repair-open-comma))
10458 (when sig-list
10459 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
10460 (verilog-insert-definition sig-list "input" indent-pt v2k)
10461 (verilog-modi-cache-add-inputs modi sig-list)
10462 (verilog-insert-indent "// End of automatics\n"))
10463 (when v2k (verilog-repair-close-comma)))))
10464
10465 (defun verilog-auto-inout (&optional with-params)
10466 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
10467 Make inout statements for any inout signal in an /*AUTOINST*/ that
10468 isn't declared elsewhere inside the module.
10469
10470 Limitations:
10471 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10472
10473 If placed inside the parenthesis of a module declaration, it creates
10474 Verilog 2001 style, else uses Verilog 1995 style.
10475
10476 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10477 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10478
10479 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10480
10481 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
10482
10483 An example (see `verilog-auto-inst' for what else is going on here):
10484
10485 module ExampInout (ov,i);
10486 input i;
10487 /*AUTOINOUT*/
10488 InstModule instName
10489 (/*AUTOINST*/);
10490 endmodule
10491
10492 Typing \\[verilog-auto] will make this into:
10493
10494 module ExampInout (ov,i);
10495 input i;
10496 /*AUTOINOUT*/
10497 // Beginning of automatic inouts (from unused autoinst inouts)
10498 inout [31:0] ov; // From inst of inst.v
10499 // End of automatics
10500 InstModule instName
10501 (/*AUTOINST*/
10502 // Inouts
10503 .ov (ov[31:0]),
10504 // Inputs
10505 .i (i));
10506 endmodule
10507
10508 You may also provide an optional regular expression, in which case only
10509 signals matching the regular expression will be included. For example the
10510 same expansion will result from only extracting inouts starting with i:
10511
10512 /*AUTOINOUT(\"^i\")*/"
10513 (save-excursion
10514 ;; Point must be at insertion point.
10515 (let* ((indent-pt (current-indentation))
10516 (regexp (and with-params
10517 (nth 0 (verilog-read-auto-params 1))))
10518 (v2k (verilog-in-paren))
10519 (modi (verilog-modi-current))
10520 (moddecls (verilog-modi-get-decls modi))
10521 (modsubdecls (verilog-modi-get-sub-decls modi))
10522 (sig-list (verilog-signals-not-in
10523 (verilog-subdecls-get-inouts modsubdecls)
10524 (append (verilog-decls-get-outputs moddecls)
10525 (verilog-decls-get-inouts moddecls)
10526 (verilog-decls-get-inputs moddecls)
10527 (verilog-subdecls-get-inputs modsubdecls)
10528 (verilog-subdecls-get-outputs modsubdecls)))))
10529 (when regexp
10530 (setq sig-list (verilog-signals-matching-regexp
10531 sig-list regexp)))
10532 (setq sig-list (verilog-signals-not-matching-regexp
10533 sig-list verilog-auto-inout-ignore-regexp))
10534 (forward-line 1)
10535 (when v2k (verilog-repair-open-comma))
10536 (when sig-list
10537 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
10538 (verilog-insert-definition sig-list "inout" indent-pt v2k)
10539 (verilog-modi-cache-add-inouts modi sig-list)
10540 (verilog-insert-indent "// End of automatics\n"))
10541 (when v2k (verilog-repair-close-comma)))))
10542
10543 (defun verilog-auto-inout-module (&optional complement)
10544 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
10545 Take input/output/inout statements from the specified module and insert
10546 into the current module. This is useful for making null templates and
10547 shell modules which need to have identical I/O with another module.
10548 Any I/O which are already defined in this module will not be redefined.
10549 For the complement of this function, see `verilog-auto-inout-comp'.
10550
10551 Limitations:
10552 If placed inside the parenthesis of a module declaration, it creates
10553 Verilog 2001 style, else uses Verilog 1995 style.
10554
10555 Concatenation and outputting partial busses is not supported.
10556
10557 Module names must be resolvable to filenames. See `verilog-auto-inst'.
10558
10559 Signals are not inserted in the same order as in the original module,
10560 though they will appear to be in the same order to a AUTOINST
10561 instantiating either module.
10562
10563 An example:
10564
10565 module ExampShell (/*AUTOARG*/);
10566 /*AUTOINOUTMODULE(\"ExampMain\")*/
10567 endmodule
10568
10569 module ExampMain (i,o,io);
10570 input i;
10571 output o;
10572 inout io;
10573 endmodule
10574
10575 Typing \\[verilog-auto] will make this into:
10576
10577 module ExampShell (/*AUTOARG*/i,o,io);
10578 /*AUTOINOUTMODULE(\"ExampMain\")*/
10579 // Beginning of automatic in/out/inouts (from specific module)
10580 output o;
10581 inout io;
10582 input i;
10583 // End of automatics
10584 endmodule
10585
10586 You may also provide an optional regular expression, in which case only
10587 signals matching the regular expression will be included. For example the
10588 same expansion will result from only extracting signals starting with i:
10589
10590 /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/
10591
10592 You may also provide an optional second regular expression, in
10593 which case only signals which have that pin direction and data
10594 type will be included. This matches against everything before
10595 the signal name in the declaration, for example against
10596 \"input\" (single bit), \"output logic\" (direction and type) or
10597 \"output [1:0]\" (direction and implicit type). You also
10598 probably want to skip spaces in your regexp.
10599
10600 For example, the below will result in matching the output \"o\"
10601 against the previous example's module:
10602
10603 /*AUTOINOUTMODULE(\"ExampMain\",\"\",\"^output.*\")*/"
10604 (save-excursion
10605 (let* ((params (verilog-read-auto-params 1 3))
10606 (submod (nth 0 params))
10607 (regexp (nth 1 params))
10608 (direction-re (nth 2 params))
10609 submodi)
10610 ;; Lookup position, etc of co-module
10611 ;; Note this may raise an error
10612 (when (setq submodi (verilog-modi-lookup submod t))
10613 (let* ((indent-pt (current-indentation))
10614 (v2k (verilog-in-paren))
10615 (modi (verilog-modi-current))
10616 (moddecls (verilog-modi-get-decls modi))
10617 (submoddecls (verilog-modi-get-decls submodi))
10618 (sig-list-i (verilog-signals-not-in
10619 (if complement
10620 (verilog-decls-get-outputs submoddecls)
10621 (verilog-decls-get-inputs submoddecls))
10622 (append (verilog-decls-get-inputs moddecls))))
10623 (sig-list-o (verilog-signals-not-in
10624 (if complement
10625 (verilog-decls-get-inputs submoddecls)
10626 (verilog-decls-get-outputs submoddecls))
10627 (append (verilog-decls-get-outputs moddecls))))
10628 (sig-list-io (verilog-signals-not-in
10629 (verilog-decls-get-inouts submoddecls)
10630 (append (verilog-decls-get-inouts moddecls))))
10631 (sig-list-if (verilog-signals-not-in
10632 (verilog-decls-get-interfaces submoddecls)
10633 (append (verilog-decls-get-interfaces moddecls)))))
10634 (forward-line 1)
10635 (setq sig-list-i (verilog-signals-matching-dir-re
10636 (verilog-signals-matching-regexp sig-list-i regexp)
10637 "input" direction-re)
10638 sig-list-o (verilog-signals-matching-dir-re
10639 (verilog-signals-matching-regexp sig-list-o regexp)
10640 "output" direction-re)
10641 sig-list-io (verilog-signals-matching-dir-re
10642 (verilog-signals-matching-regexp sig-list-io regexp)
10643 "inout" direction-re)
10644 sig-list-if (verilog-signals-matching-dir-re
10645 (verilog-signals-matching-regexp sig-list-if regexp)
10646 "interface" direction-re))
10647 (when v2k (verilog-repair-open-comma))
10648 (when (or sig-list-i sig-list-o sig-list-io)
10649 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
10650 ;; Don't sort them so a upper AUTOINST will match the main module
10651 (verilog-insert-definition sig-list-o "output" indent-pt v2k t)
10652 (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
10653 (verilog-insert-definition sig-list-i "input" indent-pt v2k t)
10654 (verilog-insert-definition sig-list-if "interface" indent-pt v2k t)
10655 (verilog-modi-cache-add-inputs modi sig-list-i)
10656 (verilog-modi-cache-add-outputs modi sig-list-o)
10657 (verilog-modi-cache-add-inouts modi sig-list-io)
10658 (verilog-insert-indent "// End of automatics\n"))
10659 (when v2k (verilog-repair-close-comma)))))))
10660
10661 (defun verilog-auto-inout-comp ()
10662 "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
10663 Take input/output/inout statements from the specified module and
10664 insert the inverse into the current module (inputs become outputs
10665 and vice-versa.) This is useful for making test and stimulus
10666 modules which need to have complementing I/O with another module.
10667 Any I/O which are already defined in this module will not be
10668 redefined. For the complement of this function, see
10669 `verilog-auto-inout-module'.
10670
10671 Limitations:
10672 If placed inside the parenthesis of a module declaration, it creates
10673 Verilog 2001 style, else uses Verilog 1995 style.
10674
10675 Concatenation and outputting partial busses is not supported.
10676
10677 Module names must be resolvable to filenames. See `verilog-auto-inst'.
10678
10679 Signals are not inserted in the same order as in the original module,
10680 though they will appear to be in the same order to a AUTOINST
10681 instantiating either module.
10682
10683 An example:
10684
10685 module ExampShell (/*AUTOARG*/);
10686 /*AUTOINOUTCOMP(\"ExampMain\")*/
10687 endmodule
10688
10689 module ExampMain (i,o,io);
10690 input i;
10691 output o;
10692 inout io;
10693 endmodule
10694
10695 Typing \\[verilog-auto] will make this into:
10696
10697 module ExampShell (/*AUTOARG*/i,o,io);
10698 /*AUTOINOUTCOMP(\"ExampMain\")*/
10699 // Beginning of automatic in/out/inouts (from specific module)
10700 output i;
10701 inout io;
10702 input o;
10703 // End of automatics
10704 endmodule
10705
10706 You may also provide an optional regular expression, in which case only
10707 signals matching the regular expression will be included. For example the
10708 same expansion will result from only extracting signals starting with i:
10709
10710 /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/"
10711 (verilog-auto-inout-module t))
10712
10713 (defun verilog-auto-insert-lisp ()
10714 "Expand AUTOINSERTLISP statements, as part of \\[verilog-auto].
10715 The Lisp code provided is called, and the Lisp code calls
10716 `insert` to insert text into the current file beginning on the
10717 line after the AUTOINSERTLISP.
10718
10719 See also AUTO_LISP, which takes a Lisp expression and evaluates
10720 it during `verilog-auto-inst' but does not insert any text.
10721
10722 An example:
10723
10724 module ExampInsertLisp;
10725 /*AUTOINSERTLISP(my-verilog-insert-hello \"world\")*/
10726 endmodule
10727
10728 // For this example we declare the function in the
10729 // module's file itself. Often you'd define it instead
10730 // in a site-start.el or .emacs file.
10731 /*
10732 Local Variables:
10733 eval:
10734 (defun my-verilog-insert-hello (who)
10735 (insert (concat \"initial $write(\\\"hello \" who \"\\\");\\n\")))
10736 End:
10737 */
10738
10739 Typing \\[verilog-auto] will call my-verilog-insert-hello and
10740 expand the above into:
10741
10742 // Beginning of automatic insert lisp
10743 initial $write(\"hello world\");
10744 // End of automatics
10745
10746 You can also call an external program and insert the returned
10747 text:
10748
10749 /*AUTOINSERTLISP(insert (shell-command-to-string \"echo //hello\"))*/
10750 // Beginning of automatic insert lisp
10751 //hello
10752 // End of automatics"
10753 (save-excursion
10754 ;; Point is at end of /*AUTO...*/
10755 (let* ((indent-pt (current-indentation))
10756 (cmd-end-pt (save-excursion (search-backward ")")
10757 (forward-char)
10758 (point))) ;; Closing paren
10759 (cmd-beg-pt (save-excursion (goto-char cmd-end-pt)
10760 (backward-sexp 1)
10761 (point))) ;; Beginning paren
10762 (cmd (buffer-substring-no-properties cmd-beg-pt cmd-end-pt)))
10763 (forward-line 1)
10764 ;; Some commands don't move point (like insert-file) so we always
10765 ;; add the begin/end comments, then delete it if not needed
10766 (verilog-insert-indent "// Beginning of automatic insert lisp\n")
10767 (verilog-insert-indent "// End of automatics\n")
10768 (forward-line -1)
10769 (eval (read cmd))
10770 (forward-line -1)
10771 (setq verilog-scan-cache-tick nil) ;; Clear cache; inserted unknown text
10772 (verilog-delete-empty-auto-pair))))
10773
10774 (defun verilog-auto-sense-sigs (moddecls presense-sigs)
10775 "Return list of signals for current AUTOSENSE block."
10776 (let* ((sigss (verilog-read-always-signals))
10777 (sig-list (verilog-signals-not-params
10778 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
10779 (append (and (not verilog-auto-sense-include-inputs)
10780 (verilog-alw-get-outputs sigss))
10781 (verilog-alw-get-temps sigss)
10782 (verilog-decls-get-consts moddecls)
10783 (verilog-decls-get-gparams moddecls)
10784 presense-sigs)))))
10785 sig-list))
10786
10787 (defun verilog-auto-sense ()
10788 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
10789 Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
10790 with one automatically derived from all inputs declared in the always
10791 statement. Signals that are generated within the same always block are NOT
10792 placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
10793 Long lines are split based on the `fill-column', see \\[set-fill-column].
10794
10795 Limitations:
10796 Verilog does not allow memories (multidimensional arrays) in sensitivity
10797 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
10798
10799 Constant signals:
10800 AUTOSENSE cannot always determine if a `define is a constant or a signal
10801 (it could be in a include file for example). If a `define or other signal
10802 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
10803 declaration anywhere in the module (parenthesis are required):
10804
10805 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
10806
10807 Better yet, use a parameter, which will be understood to be constant
10808 automatically.
10809
10810 OOps!
10811 If AUTOSENSE makes a mistake, please report it. (First try putting
10812 a begin/end after your always!) As a workaround, if a signal that
10813 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
10814 If a signal should be in the sensitivity list wasn't, placing it before
10815 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
10816 autos are updated (or added if it occurs there already).
10817
10818 An example:
10819
10820 always @ (/*AS*/) begin
10821 /* AUTO_CONSTANT (`constant) */
10822 outin = ina | inb | `constant;
10823 out = outin;
10824 end
10825
10826 Typing \\[verilog-auto] will make this into:
10827
10828 always @ (/*AS*/ina or inb) begin
10829 /* AUTO_CONSTANT (`constant) */
10830 outin = ina | inb | `constant;
10831 out = outin;
10832 end
10833
10834 Note in Verilog 2001, you can often get the same result from the new @*
10835 operator. (This was added to the language in part due to AUTOSENSE!)
10836
10837 always @* begin
10838 outin = ina | inb | `constant;
10839 out = outin;
10840 end"
10841 (save-excursion
10842 ;; Find beginning
10843 (let* ((start-pt (save-excursion
10844 (verilog-re-search-backward "(" nil t)
10845 (point)))
10846 (indent-pt (save-excursion
10847 (or (and (goto-char start-pt) (1+ (current-column)))
10848 (current-indentation))))
10849 (modi (verilog-modi-current))
10850 (moddecls (verilog-modi-get-decls modi))
10851 (sig-memories (verilog-signals-memory
10852 (append
10853 (verilog-decls-get-regs moddecls)
10854 (verilog-decls-get-wires moddecls))))
10855 sig-list not-first presense-sigs)
10856 ;; Read signals in always, eliminate outputs from sense list
10857 (setq presense-sigs (verilog-signals-from-signame
10858 (save-excursion
10859 (verilog-read-signals start-pt (point)))))
10860 (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
10861 (when sig-memories
10862 (let ((tlen (length sig-list)))
10863 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
10864 (if (not (eq tlen (length sig-list))) (verilog-insert " /*memory or*/ "))))
10865 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
10866 (save-excursion (goto-char (point))
10867 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10868 (verilog-re-search-backward "\\s-" start-pt t)
10869 (while (looking-at "\\s-`endif")
10870 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10871 (verilog-re-search-backward "\\s-" start-pt t))
10872 (not (looking-at "\\s-or\\b"))))
10873 (setq not-first t))
10874 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10875 (while sig-list
10876 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
10877 (insert "\n")
10878 (indent-to indent-pt)
10879 (if not-first (insert "or ")))
10880 (not-first (insert " or ")))
10881 (insert (verilog-sig-name (car sig-list)))
10882 (setq sig-list (cdr sig-list)
10883 not-first t)))))
10884
10885 (defun verilog-auto-reset ()
10886 "Expand AUTORESET statements, as part of \\[verilog-auto].
10887 Replace the /*AUTORESET*/ comment with code to initialize all
10888 registers set elsewhere in the always block.
10889
10890 Limitations:
10891 AUTORESET will not clear memories.
10892
10893 AUTORESET uses <= if there are any <= assignments in the block,
10894 else it uses =.
10895
10896 /*AUTORESET*/ presumes that any signals mentioned between the previous
10897 begin/case/if statement and the AUTORESET comment are being reset manually
10898 and should not be automatically reset. This includes omitting any signals
10899 used on the right hand side of assignments.
10900
10901 By default, AUTORESET will include the width of the signal in the autos,
10902 this is a recent change. To control this behavior, see
10903 `verilog-auto-reset-widths'.
10904
10905 AUTORESET ties signals to deasserted, which is presumed to be zero.
10906 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
10907 them to a one.
10908
10909 An example:
10910
10911 always @(posedge clk or negedge reset_l) begin
10912 if (!reset_l) begin
10913 c <= 1;
10914 /*AUTORESET*/
10915 end
10916 else begin
10917 a <= in_a;
10918 b <= in_b;
10919 c <= in_c;
10920 end
10921 end
10922
10923 Typing \\[verilog-auto] will make this into:
10924
10925 always @(posedge core_clk or negedge reset_l) begin
10926 if (!reset_l) begin
10927 c <= 1;
10928 /*AUTORESET*/
10929 // Beginning of autoreset for uninitialized flops
10930 a <= 0;
10931 b <= 0;
10932 // End of automatics
10933 end
10934 else begin
10935 a <= in_a;
10936 b <= in_b;
10937 c <= in_c;
10938 end
10939 end"
10940
10941 (interactive)
10942 (save-excursion
10943 ;; Find beginning
10944 (let* ((indent-pt (current-indentation))
10945 (modi (verilog-modi-current))
10946 (moddecls (verilog-modi-get-decls modi))
10947 (all-list (verilog-decls-get-signals moddecls))
10948 sigss sig-list prereset-sigs assignment-str)
10949 ;; Read signals in always, eliminate outputs from reset list
10950 (setq prereset-sigs (verilog-signals-from-signame
10951 (save-excursion
10952 (verilog-read-signals
10953 (save-excursion
10954 (verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
10955 (point))
10956 (point)))))
10957 (save-excursion
10958 (verilog-re-search-backward "@" nil t)
10959 (setq sigss (verilog-read-always-signals)))
10960 (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
10961 (concat " <= " verilog-assignment-delay)
10962 " = "))
10963 (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
10964 (append
10965 (verilog-alw-get-temps sigss)
10966 prereset-sigs)))
10967 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10968 (when sig-list
10969 (insert "\n");
10970 (verilog-insert-indent "// Beginning of autoreset for uninitialized flops\n");
10971 (indent-to indent-pt)
10972 (while sig-list
10973 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
10974 (car sig-list))))
10975 (insert (verilog-sig-name sig)
10976 assignment-str
10977 (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
10978 ";\n")
10979 (indent-to indent-pt)
10980 (setq sig-list (cdr sig-list))))
10981 (verilog-insert "// End of automatics")))))
10982
10983 (defun verilog-auto-tieoff ()
10984 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
10985 Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
10986 signals to deasserted.
10987
10988 /*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
10989 input/output list as another module, but no internals. Specifically, it
10990 finds all outputs in the module, and if that input is not otherwise declared
10991 as a register or wire, creates a tieoff.
10992
10993 AUTORESET ties signals to deasserted, which is presumed to be zero.
10994 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
10995 them to a one.
10996
10997 You can add signals you do not want included in AUTOTIEOFF with
10998 `verilog-auto-tieoff-ignore-regexp'.
10999
11000 An example of making a stub for another module:
11001
11002 module ExampStub (/*AUTOINST*/);
11003 /*AUTOINOUTMODULE(\"Foo\")*/
11004 /*AUTOTIEOFF*/
11005 // verilator lint_off UNUSED
11006 wire _unused_ok = &{1'b0,
11007 /*AUTOUNUSED*/
11008 1'b0};
11009 // verilator lint_on UNUSED
11010 endmodule
11011
11012 Typing \\[verilog-auto] will make this into:
11013
11014 module ExampStub (/*AUTOINST*/...);
11015 /*AUTOINOUTMODULE(\"Foo\")*/
11016 // Beginning of autotieoff
11017 output [2:0] foo;
11018 // End of automatics
11019
11020 /*AUTOTIEOFF*/
11021 // Beginning of autotieoff
11022 wire [2:0] foo = 3'b0;
11023 // End of automatics
11024 ...
11025 endmodule"
11026 (interactive)
11027 (save-excursion
11028 ;; Find beginning
11029 (let* ((indent-pt (current-indentation))
11030 (modi (verilog-modi-current))
11031 (moddecls (verilog-modi-get-decls modi))
11032 (modsubdecls (verilog-modi-get-sub-decls modi))
11033 (sig-list (verilog-signals-not-in
11034 (verilog-decls-get-outputs moddecls)
11035 (append (verilog-decls-get-wires moddecls)
11036 (verilog-decls-get-regs moddecls)
11037 (verilog-decls-get-assigns moddecls)
11038 (verilog-decls-get-consts moddecls)
11039 (verilog-decls-get-gparams moddecls)
11040 (verilog-subdecls-get-interfaced modsubdecls)
11041 (verilog-subdecls-get-outputs modsubdecls)
11042 (verilog-subdecls-get-inouts modsubdecls)))))
11043 (setq sig-list (verilog-signals-not-matching-regexp
11044 sig-list verilog-auto-tieoff-ignore-regexp))
11045 (when sig-list
11046 (forward-line 1)
11047 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
11048 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
11049 (verilog-modi-cache-add-wires modi sig-list) ; Before we trash list
11050 (while sig-list
11051 (let ((sig (car sig-list)))
11052 (verilog-insert-one-definition sig "wire" indent-pt)
11053 (indent-to (max 48 (+ indent-pt 40)))
11054 (insert "= " (verilog-sig-tieoff sig)
11055 ";\n")
11056 (setq sig-list (cdr sig-list))))
11057 (verilog-insert-indent "// End of automatics\n")))))
11058
11059 (defun verilog-auto-unused ()
11060 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
11061 Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
11062 input and inout signals.
11063
11064 /*AUTOUNUSED*/ is used to make stub modules; modules that have the same
11065 input/output list as another module, but no internals. Specifically, it
11066 finds all inputs and inouts in the module, and if that input is not otherwise
11067 used, adds it to a comma separated list.
11068
11069 The comma separated list is intended to be used to create a _unused_ok
11070 signal. Using the exact name \"_unused_ok\" for name of the temporary
11071 signal is recommended as it will insure maximum forward compatibility, it
11072 also makes lint warnings easy to understand; ignore any unused warnings
11073 with \"unused\" in the signal name.
11074
11075 To reduce simulation time, the _unused_ok signal should be forced to a
11076 constant to prevent wiggling. The easiest thing to do is use a
11077 reduction-and with 1'b0 as shown.
11078
11079 This way all unused signals are in one place, making it convenient to add
11080 your tool's specific pragmas around the assignment to disable any unused
11081 warnings.
11082
11083 You can add signals you do not want included in AUTOUNUSED with
11084 `verilog-auto-unused-ignore-regexp'.
11085
11086 An example of making a stub for another module:
11087
11088 module ExampStub (/*AUTOINST*/);
11089 /*AUTOINOUTMODULE(\"Examp\")*/
11090 /*AUTOTIEOFF*/
11091 // verilator lint_off UNUSED
11092 wire _unused_ok = &{1'b0,
11093 /*AUTOUNUSED*/
11094 1'b0};
11095 // verilator lint_on UNUSED
11096 endmodule
11097
11098 Typing \\[verilog-auto] will make this into:
11099
11100 ...
11101 // verilator lint_off UNUSED
11102 wire _unused_ok = &{1'b0,
11103 /*AUTOUNUSED*/
11104 // Beginning of automatics
11105 unused_input_a,
11106 unused_input_b,
11107 unused_input_c,
11108 // End of automatics
11109 1'b0};
11110 // verilator lint_on UNUSED
11111 endmodule"
11112 (interactive)
11113 (save-excursion
11114 ;; Find beginning
11115 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
11116 (modi (verilog-modi-current))
11117 (moddecls (verilog-modi-get-decls modi))
11118 (modsubdecls (verilog-modi-get-sub-decls modi))
11119 (sig-list (verilog-signals-not-in
11120 (append (verilog-decls-get-inputs moddecls)
11121 (verilog-decls-get-inouts moddecls))
11122 (append (verilog-subdecls-get-inputs modsubdecls)
11123 (verilog-subdecls-get-inouts modsubdecls)))))
11124 (setq sig-list (verilog-signals-not-matching-regexp
11125 sig-list verilog-auto-unused-ignore-regexp))
11126 (when sig-list
11127 (forward-line 1)
11128 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
11129 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
11130 (while sig-list
11131 (let ((sig (car sig-list)))
11132 (indent-to indent-pt)
11133 (insert (verilog-sig-name sig) ",\n")
11134 (setq sig-list (cdr sig-list))))
11135 (verilog-insert-indent "// End of automatics\n")))))
11136
11137 (defun verilog-enum-ascii (signm elim-regexp)
11138 "Convert an enum name SIGNM to an ascii string for insertion.
11139 Remove user provided prefix ELIM-REGEXP."
11140 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
11141 (let ((case-fold-search t))
11142 ;; All upper becomes all lower for readability
11143 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
11144
11145 (defun verilog-auto-ascii-enum ()
11146 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
11147 Create a register to contain the ASCII decode of a enumerated signal type.
11148 This will allow trace viewers to show the ASCII name of states.
11149
11150 First, parameters are built into a enumeration using the synopsys enum
11151 comment. The comment must be between the keyword and the symbol.
11152 \(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
11153
11154 Next, registers which that enum applies to are also tagged with the same
11155 enum. Synopsys also suggests labeling state vectors, but `verilog-mode'
11156 doesn't care.
11157
11158 Finally, a AUTOASCIIENUM command is used.
11159
11160 The first parameter is the name of the signal to be decoded.
11161 If and only if the first parameter width is 2^(number of states
11162 in enum) and does NOT match the width of the enum, the signal
11163 is assumed to be a one hot decode. Otherwise, it's a normal
11164 encoded state vector.
11165
11166 The second parameter is the name to store the ASCII code into. For the
11167 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
11168 a signal that is just for simulation, and the magic characters _ascii
11169 tell viewers like Dinotrace to display in ASCII format.
11170
11171 The final optional parameter is a string which will be removed from the
11172 state names.
11173
11174 An example:
11175
11176 //== State enumeration
11177 parameter [2:0] // synopsys enum state_info
11178 SM_IDLE = 3'b000,
11179 SM_SEND = 3'b001,
11180 SM_WAIT1 = 3'b010;
11181 //== State variables
11182 reg [2:0] /* synopsys enum state_info */
11183 state_r; /* synopsys state_vector state_r */
11184 reg [2:0] /* synopsys enum state_info */
11185 state_e1;
11186
11187 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
11188
11189 Typing \\[verilog-auto] will make this into:
11190
11191 ... same front matter ...
11192
11193 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
11194 // Beginning of automatic ASCII enum decoding
11195 reg [39:0] state_ascii_r; // Decode of state_r
11196 always @(state_r) begin
11197 case ({state_r})
11198 SM_IDLE: state_ascii_r = \"idle \";
11199 SM_SEND: state_ascii_r = \"send \";
11200 SM_WAIT1: state_ascii_r = \"wait1\";
11201 default: state_ascii_r = \"%Erro\";
11202 endcase
11203 end
11204 // End of automatics"
11205 (save-excursion
11206 (let* ((params (verilog-read-auto-params 2 3))
11207 (undecode-name (nth 0 params))
11208 (ascii-name (nth 1 params))
11209 (elim-regexp (nth 2 params))
11210 ;;
11211 (indent-pt (current-indentation))
11212 (modi (verilog-modi-current))
11213 (moddecls (verilog-modi-get-decls modi))
11214 ;;
11215 (sig-list-consts (append (verilog-decls-get-consts moddecls)
11216 (verilog-decls-get-gparams moddecls)))
11217 (sig-list-all (append (verilog-decls-get-regs moddecls)
11218 (verilog-decls-get-outputs moddecls)
11219 (verilog-decls-get-inouts moddecls)
11220 (verilog-decls-get-inputs moddecls)
11221 (verilog-decls-get-wires moddecls)))
11222 ;;
11223 (undecode-sig (or (assoc undecode-name sig-list-all)
11224 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
11225 (undecode-enum (or (verilog-sig-enum undecode-sig)
11226 (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
11227 ;;
11228 (enum-sigs (verilog-signals-not-in
11229 (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
11230 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum))
11231 nil))
11232 ;;
11233 (one-hot (and ;; width(enum) != width(sig)
11234 (or (not (verilog-sig-bits (car enum-sigs)))
11235 (not (equal (verilog-sig-width (car enum-sigs))
11236 (verilog-sig-width undecode-sig))))
11237 ;; count(enums) == width(sig)
11238 (equal (number-to-string (length enum-sigs))
11239 (verilog-sig-width undecode-sig))))
11240 (enum-chars 0)
11241 (ascii-chars 0))
11242 ;;
11243 ;; Find number of ascii chars needed
11244 (let ((tmp-sigs enum-sigs))
11245 (while tmp-sigs
11246 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
11247 ascii-chars (max ascii-chars (length (verilog-enum-ascii
11248 (verilog-sig-name (car tmp-sigs))
11249 elim-regexp)))
11250 tmp-sigs (cdr tmp-sigs))))
11251 ;;
11252 (forward-line 1)
11253 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
11254 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
11255 (concat "Decode of " undecode-name) nil nil))))
11256 (verilog-insert-definition decode-sig-list "reg" indent-pt nil)
11257 (verilog-modi-cache-add-regs modi decode-sig-list))
11258 ;;
11259 (verilog-insert-indent "always @(" undecode-name ") begin\n")
11260 (setq indent-pt (+ indent-pt verilog-indent-level))
11261 (indent-to indent-pt)
11262 (insert "case ({" undecode-name "})\n")
11263 (setq indent-pt (+ indent-pt verilog-case-indent))
11264 ;;
11265 (let ((tmp-sigs enum-sigs)
11266 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n"
11267 (+ (if one-hot 9 1) (max 8 enum-chars))
11268 ascii-name ascii-chars))
11269 (errname (substring "%Error" 0 (min 6 ascii-chars))))
11270 (while tmp-sigs
11271 (verilog-insert-indent
11272 (concat
11273 (format chrfmt
11274 (concat (if one-hot "(")
11275 (if one-hot (verilog-sig-width undecode-sig))
11276 ;; We use a shift instead of var[index]
11277 ;; so that a non-one hot value will show as error.
11278 (if one-hot "'b1<<")
11279 (verilog-sig-name (car tmp-sigs))
11280 (if one-hot ")") ":")
11281 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
11282 elim-regexp))))
11283 (setq tmp-sigs (cdr tmp-sigs)))
11284 (verilog-insert-indent (format chrfmt "default:" errname)))
11285 ;;
11286 (setq indent-pt (- indent-pt verilog-case-indent))
11287 (verilog-insert-indent "endcase\n")
11288 (setq indent-pt (- indent-pt verilog-indent-level))
11289 (verilog-insert-indent "end\n"
11290 "// End of automatics\n"))))
11291
11292 (defun verilog-auto-templated-rel ()
11293 "Replace Templated relative line numbers with absolute line numbers.
11294 Internal use only. This hacks around the line numbers in AUTOINST Templates
11295 being different from the final output's line numbering."
11296 (let ((templateno 0) (template-line (list 0)) (buf-line 1))
11297 ;; Find line number each template is on
11298 ;; Count lines as we go, as otherwise it's O(n^2) to use count-lines
11299 (goto-char (point-min))
11300 (while (not (eobp))
11301 (when (looking-at ".*AUTO_TEMPLATE")
11302 (setq templateno (1+ templateno))
11303 (setq template-line (cons buf-line template-line)))
11304 (setq buf-line (1+ buf-line))
11305 (forward-line 1))
11306 (setq template-line (nreverse template-line))
11307 ;; Replace T# L# with absolute line number
11308 (goto-char (point-min))
11309 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
11310 (replace-match
11311 (concat " Templated "
11312 (int-to-string (+ (nth (string-to-number (match-string 1))
11313 template-line)
11314 (string-to-number (match-string 2)))))
11315 t t))))
11316
11317 \f
11318 ;;
11319 ;; Auto top level
11320 ;;
11321
11322 (defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing a arg
11323 "Expand AUTO statements.
11324 Look for any /*AUTO...*/ commands in the code, as used in
11325 instantiations or argument headers. Update the list of signals
11326 following the /*AUTO...*/ command.
11327
11328 Use \\[verilog-delete-auto] to remove the AUTOs.
11329
11330 Use \\[verilog-inject-auto] to insert AUTOs for the first time.
11331
11332 Use \\[verilog-faq] for a pointer to frequently asked questions.
11333
11334 The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
11335 called before and after this function, respectively.
11336
11337 For example:
11338 module ModuleName (/*AUTOARG*/);
11339 /*AUTOINPUT*/
11340 /*AUTOOUTPUT*/
11341 /*AUTOWIRE*/
11342 /*AUTOREG*/
11343 InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
11344
11345 You can also update the AUTOs from the shell using:
11346 emacs --batch <filenames.v> -f verilog-batch-auto
11347 Or fix indentation with:
11348 emacs --batch <filenames.v> -f verilog-batch-indent
11349 Likewise, you can delete or inject AUTOs with:
11350 emacs --batch <filenames.v> -f verilog-batch-delete-auto
11351 emacs --batch <filenames.v> -f verilog-batch-inject-auto
11352
11353 Using \\[describe-function], see also:
11354 `verilog-auto-arg' for AUTOARG module instantiations
11355 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
11356 `verilog-auto-inout-comp' for AUTOINOUTCOMP copy complemented i/o
11357 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
11358 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
11359 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
11360 `verilog-auto-insert-lisp' for AUTOINSERTLISP insert code from lisp function
11361 `verilog-auto-inst' for AUTOINST instantiation pins
11362 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
11363 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
11364 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
11365 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
11366 `verilog-auto-reg' for AUTOREG registers
11367 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
11368 `verilog-auto-reset' for AUTORESET flop resets
11369 `verilog-auto-sense' for AUTOSENSE always sensitivity lists
11370 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
11371 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
11372 `verilog-auto-wire' for AUTOWIRE instantiation wires
11373
11374 `verilog-read-defines' for reading `define values
11375 `verilog-read-includes' for reading `includes
11376
11377 If you have bugs with these autos, please file an issue at
11378 URL `http://www.veripool.org/verilog-mode' or contact the AUTOAUTHOR
11379 Wilson Snyder (wsnyder@wsnyder.org)."
11380 (interactive)
11381 (unless noninteractive (message "Updating AUTOs..."))
11382 (if (fboundp 'dinotrace-unannotate-all)
11383 (dinotrace-unannotate-all))
11384 (let ((oldbuf (if (not (buffer-modified-p))
11385 (buffer-string)))
11386 ;; Before version 20, match-string with font-lock returns a
11387 ;; vector that is not equal to the string. IE if on "input"
11388 ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
11389 (fontlocked (when (and (boundp 'font-lock-mode)
11390 font-lock-mode)
11391 (font-lock-mode 0)
11392 t))
11393 ;; Cache directories; we don't write new files, so can't change
11394 (verilog-dir-cache-preserving t)
11395 ;; Cache current module
11396 (verilog-modi-cache-current-enable t)
11397 (verilog-modi-cache-current-max (point-min)) ; IE it's invalid
11398 verilog-modi-cache-current)
11399 (unwind-protect
11400 ;; Disable change hooks for speed
11401 ;; This let can't be part of above let; must restore
11402 ;; after-change-functions before font-lock resumes
11403 (verilog-save-no-change-functions
11404 (verilog-save-scan-cache
11405 (save-excursion
11406 ;; If we're not in verilog-mode, change syntax table so parsing works right
11407 (unless (eq major-mode `verilog-mode) (verilog-mode))
11408 ;; Allow user to customize
11409 (run-hooks 'verilog-before-auto-hook)
11410 ;; Try to save the user from needing to revert-file to reread file local-variables
11411 (verilog-auto-reeval-locals)
11412 (verilog-read-auto-lisp-present)
11413 (verilog-read-auto-lisp (point-min) (point-max))
11414 (verilog-getopt-flags)
11415 ;; From here on out, we can cache anything we read from disk
11416 (verilog-preserve-dir-cache
11417 ;; These two may seem obvious to do always, but on large includes it can be way too slow
11418 (when verilog-auto-read-includes
11419 (verilog-read-includes)
11420 (verilog-read-defines nil nil t))
11421 ;; This particular ordering is important
11422 ;; INST: Lower modules correct, no internal dependencies, FIRST
11423 (verilog-preserve-modi-cache
11424 ;; Clear existing autos else we'll be screwed by existing ones
11425 (verilog-delete-auto)
11426 ;; Injection if appropriate
11427 (when inject
11428 (verilog-inject-inst)
11429 (verilog-inject-sense)
11430 (verilog-inject-arg))
11431 ;;
11432 ;; Do user inserts first, so their code can insert AUTOs
11433 ;; We may provide a AUTOINSERTLISPLAST if another cleanup pass is needed
11434 (verilog-auto-re-search-do "/\\*AUTOINSERTLISP(.*?)\\*/"
11435 'verilog-auto-insert-lisp)
11436 ;; Expand instances before need the signals the instances input/output
11437 (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
11438 (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
11439 (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
11440 ;; Doesn't matter when done, but combine it with a common changer
11441 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
11442 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
11443 ;; Must be done before autoin/out as creates a reg
11444 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
11445 ;;
11446 ;; first in/outs from other files
11447 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
11448 (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP([^)]*)\\*/" 'verilog-auto-inout-comp)
11449 ;; next in/outs which need previous sucked inputs first
11450 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((\"[^\"]*\")\\)\\*/"
11451 '(lambda () (verilog-auto-output t)))
11452 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\*/" 'verilog-auto-output)
11453 (verilog-auto-re-search-do "/\\*AUTOINPUT\\((\"[^\"]*\")\\)\\*/"
11454 '(lambda () (verilog-auto-input t)))
11455 (verilog-auto-re-search-do "/\\*AUTOINPUT\\*/" 'verilog-auto-input)
11456 (verilog-auto-re-search-do "/\\*AUTOINOUT\\((\"[^\"]*\")\\)\\*/"
11457 '(lambda () (verilog-auto-inout t)))
11458 (verilog-auto-re-search-do "/\\*AUTOINOUT\\*/" 'verilog-auto-inout)
11459 ;; Then tie off those in/outs
11460 (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
11461 ;; Wires/regs must be after inputs/outputs
11462 (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
11463 (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
11464 (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
11465 ;; outputevery needs AUTOOUTPUTs done first
11466 (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\*/" 'verilog-auto-output-every)
11467 ;; After we've created all new variables
11468 (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
11469 ;; Must be after all inputs outputs are generated
11470 (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
11471 ;; Fix line numbers (comments only)
11472 (when verilog-auto-inst-template-numbers
11473 (verilog-auto-templated-rel))))
11474 ;;
11475 (run-hooks 'verilog-auto-hook)
11476 ;;
11477 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))
11478 ;;
11479 ;; If end result is same as when started, clear modified flag
11480 (cond ((and oldbuf (equal oldbuf (buffer-string)))
11481 (set-buffer-modified-p nil)
11482 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
11483 (t (unless noninteractive (message "Updating AUTOs...done"))))
11484 ;; End of after-change protection
11485 )))
11486 ;; Unwind forms
11487 (progn
11488 ;; Restore font-lock
11489 (when fontlocked (font-lock-mode t))))))
11490 \f
11491
11492 ;;
11493 ;; Skeleton based code insertion
11494 ;;
11495 (defvar verilog-template-map
11496 (let ((map (make-sparse-keymap)))
11497 (define-key map "a" 'verilog-sk-always)
11498 (define-key map "b" 'verilog-sk-begin)
11499 (define-key map "c" 'verilog-sk-case)
11500 (define-key map "f" 'verilog-sk-for)
11501 (define-key map "g" 'verilog-sk-generate)
11502 (define-key map "h" 'verilog-sk-header)
11503 (define-key map "i" 'verilog-sk-initial)
11504 (define-key map "j" 'verilog-sk-fork)
11505 (define-key map "m" 'verilog-sk-module)
11506 (define-key map "p" 'verilog-sk-primitive)
11507 (define-key map "r" 'verilog-sk-repeat)
11508 (define-key map "s" 'verilog-sk-specify)
11509 (define-key map "t" 'verilog-sk-task)
11510 (define-key map "w" 'verilog-sk-while)
11511 (define-key map "x" 'verilog-sk-casex)
11512 (define-key map "z" 'verilog-sk-casez)
11513 (define-key map "?" 'verilog-sk-if)
11514 (define-key map ":" 'verilog-sk-else-if)
11515 (define-key map "/" 'verilog-sk-comment)
11516 (define-key map "A" 'verilog-sk-assign)
11517 (define-key map "F" 'verilog-sk-function)
11518 (define-key map "I" 'verilog-sk-input)
11519 (define-key map "O" 'verilog-sk-output)
11520 (define-key map "S" 'verilog-sk-state-machine)
11521 (define-key map "=" 'verilog-sk-inout)
11522 (define-key map "W" 'verilog-sk-wire)
11523 (define-key map "R" 'verilog-sk-reg)
11524 (define-key map "D" 'verilog-sk-define-signal)
11525 map)
11526 "Keymap used in Verilog mode for smart template operations.")
11527
11528
11529 ;;
11530 ;; Place the templates into Verilog Mode. They may be inserted under any key.
11531 ;; C-c C-t will be the default. If you use templates a lot, you
11532 ;; may want to consider moving the binding to another key in your .emacs
11533 ;; file.
11534 ;;
11535 ;(define-key verilog-mode-map "\C-ct" verilog-template-map)
11536 (define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
11537
11538 ;;; ---- statement skeletons ------------------------------------------
11539
11540 (define-skeleton verilog-sk-prompt-condition
11541 "Prompt for the loop condition."
11542 "[condition]: " str )
11543
11544 (define-skeleton verilog-sk-prompt-init
11545 "Prompt for the loop init statement."
11546 "[initial statement]: " str )
11547
11548 (define-skeleton verilog-sk-prompt-inc
11549 "Prompt for the loop increment statement."
11550 "[increment statement]: " str )
11551
11552 (define-skeleton verilog-sk-prompt-name
11553 "Prompt for the name of something."
11554 "[name]: " str)
11555
11556 (define-skeleton verilog-sk-prompt-clock
11557 "Prompt for the name of something."
11558 "name and edge of clock(s): " str)
11559
11560 (defvar verilog-sk-reset nil)
11561 (defun verilog-sk-prompt-reset ()
11562 "Prompt for the name of a state machine reset."
11563 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
11564
11565
11566 (define-skeleton verilog-sk-prompt-state-selector
11567 "Prompt for the name of a state machine selector."
11568 "name of selector (eg {a,b,c,d}): " str )
11569
11570 (define-skeleton verilog-sk-prompt-output
11571 "Prompt for the name of something."
11572 "output: " str)
11573
11574 (define-skeleton verilog-sk-prompt-msb
11575 "Prompt for least significant bit specification."
11576 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
11577
11578 (define-skeleton verilog-sk-prompt-lsb
11579 "Prompt for least significant bit specification."
11580 "lsb:" str )
11581
11582 (defvar verilog-sk-p nil)
11583 (define-skeleton verilog-sk-prompt-width
11584 "Prompt for a width specification."
11585 ()
11586 (progn
11587 (setq verilog-sk-p (point))
11588 (verilog-sk-prompt-msb)
11589 (if (> (point) verilog-sk-p) "] " " ")))
11590
11591 (defun verilog-sk-header ()
11592 "Insert a descriptive header at the top of the file.
11593 See also `verilog-header' for an alternative format."
11594 (interactive "*")
11595 (save-excursion
11596 (goto-char (point-min))
11597 (verilog-sk-header-tmpl)))
11598
11599 (define-skeleton verilog-sk-header-tmpl
11600 "Insert a comment block containing the module title, author, etc."
11601 "[Description]: "
11602 "// -*- Mode: Verilog -*-"
11603 "\n// Filename : " (buffer-name)
11604 "\n// Description : " str
11605 "\n// Author : " (user-full-name)
11606 "\n// Created On : " (current-time-string)
11607 "\n// Last Modified By: " (user-full-name)
11608 "\n// Last Modified On: " (current-time-string)
11609 "\n// Update Count : 0"
11610 "\n// Status : Unknown, Use with caution!"
11611 "\n")
11612
11613 (define-skeleton verilog-sk-module
11614 "Insert a module definition."
11615 ()
11616 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
11617 > _ \n
11618 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
11619
11620 (define-skeleton verilog-sk-primitive
11621 "Insert a task definition."
11622 ()
11623 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
11624 > _ \n
11625 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
11626
11627 (define-skeleton verilog-sk-task
11628 "Insert a task definition."
11629 ()
11630 > "task " '(verilog-sk-prompt-name) & ?; \n
11631 > _ \n
11632 > "begin" \n
11633 > \n
11634 > (- verilog-indent-level-behavioral) "end" \n
11635 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
11636
11637 (define-skeleton verilog-sk-function
11638 "Insert a function definition."
11639 ()
11640 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
11641 > _ \n
11642 > "begin" \n
11643 > \n
11644 > (- verilog-indent-level-behavioral) "end" \n
11645 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
11646
11647 (define-skeleton verilog-sk-always
11648 "Insert always block. Uses the minibuffer to prompt
11649 for sensitivity list."
11650 ()
11651 > "always @ ( /*AUTOSENSE*/ ) begin\n"
11652 > _ \n
11653 > (- verilog-indent-level-behavioral) "end" \n >
11654 )
11655
11656 (define-skeleton verilog-sk-initial
11657 "Insert an initial block."
11658 ()
11659 > "initial begin\n"
11660 > _ \n
11661 > (- verilog-indent-level-behavioral) "end" \n > )
11662
11663 (define-skeleton verilog-sk-specify
11664 "Insert specify block. "
11665 ()
11666 > "specify\n"
11667 > _ \n
11668 > (- verilog-indent-level-behavioral) "endspecify" \n > )
11669
11670 (define-skeleton verilog-sk-generate
11671 "Insert generate block. "
11672 ()
11673 > "generate\n"
11674 > _ \n
11675 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
11676
11677 (define-skeleton verilog-sk-begin
11678 "Insert begin end block. Uses the minibuffer to prompt for name."
11679 ()
11680 > "begin" '(verilog-sk-prompt-name) \n
11681 > _ \n
11682 > (- verilog-indent-level-behavioral) "end"
11683 )
11684
11685 (define-skeleton verilog-sk-fork
11686 "Insert a fork join block."
11687 ()
11688 > "fork\n"
11689 > "begin" \n
11690 > _ \n
11691 > (- verilog-indent-level-behavioral) "end" \n
11692 > "begin" \n
11693 > \n
11694 > (- verilog-indent-level-behavioral) "end" \n
11695 > (- verilog-indent-level-behavioral) "join" \n
11696 > )
11697
11698
11699 (define-skeleton verilog-sk-case
11700 "Build skeleton case statement, prompting for the selector expression,
11701 and the case items."
11702 "[selector expression]: "
11703 > "case (" str ") " \n
11704 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
11705 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11706
11707 (define-skeleton verilog-sk-casex
11708 "Build skeleton casex statement, prompting for the selector expression,
11709 and the case items."
11710 "[selector expression]: "
11711 > "casex (" str ") " \n
11712 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
11713 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11714
11715 (define-skeleton verilog-sk-casez
11716 "Build skeleton casez statement, prompting for the selector expression,
11717 and the case items."
11718 "[selector expression]: "
11719 > "casez (" str ") " \n
11720 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
11721 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11722
11723 (define-skeleton verilog-sk-if
11724 "Insert a skeleton if statement."
11725 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
11726 > _ \n
11727 > (- verilog-indent-level-behavioral) "end " \n )
11728
11729 (define-skeleton verilog-sk-else-if
11730 "Insert a skeleton else if statement."
11731 > (verilog-indent-line) "else if ("
11732 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
11733 > _ \n
11734 > "end" (progn (electric-verilog-terminate-line) nil))
11735
11736 (define-skeleton verilog-sk-datadef
11737 "Common routine to get data definition."
11738 ()
11739 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
11740
11741 (define-skeleton verilog-sk-input
11742 "Insert an input definition."
11743 ()
11744 > "input [" '(verilog-sk-datadef))
11745
11746 (define-skeleton verilog-sk-output
11747 "Insert an output definition."
11748 ()
11749 > "output [" '(verilog-sk-datadef))
11750
11751 (define-skeleton verilog-sk-inout
11752 "Insert an inout definition."
11753 ()
11754 > "inout [" '(verilog-sk-datadef))
11755
11756 (defvar verilog-sk-signal nil)
11757 (define-skeleton verilog-sk-def-reg
11758 "Insert a reg definition."
11759 ()
11760 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
11761
11762 (defun verilog-sk-define-signal ()
11763 "Insert a definition of signal under point at top of module."
11764 (interactive "*")
11765 (let* ((sig-re "[a-zA-Z0-9_]*")
11766 (v1 (buffer-substring
11767 (save-excursion
11768 (skip-chars-backward sig-re)
11769 (point))
11770 (save-excursion
11771 (skip-chars-forward sig-re)
11772 (point)))))
11773 (if (not (member v1 verilog-keywords))
11774 (save-excursion
11775 (setq verilog-sk-signal v1)
11776 (verilog-beg-of-defun)
11777 (verilog-end-of-statement)
11778 (verilog-forward-syntactic-ws)
11779 (verilog-sk-def-reg)
11780 (message "signal at point is %s" v1))
11781 (message "object at point (%s) is a keyword" v1))))
11782
11783 (define-skeleton verilog-sk-wire
11784 "Insert a wire definition."
11785 ()
11786 > "wire [" '(verilog-sk-datadef))
11787
11788 (define-skeleton verilog-sk-reg
11789 "Insert a reg definition."
11790 ()
11791 > "reg [" '(verilog-sk-datadef))
11792
11793 (define-skeleton verilog-sk-assign
11794 "Insert a skeleton assign statement."
11795 ()
11796 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
11797
11798 (define-skeleton verilog-sk-while
11799 "Insert a skeleton while loop statement."
11800 ()
11801 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
11802 > _ \n
11803 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11804
11805 (define-skeleton verilog-sk-repeat
11806 "Insert a skeleton repeat loop statement."
11807 ()
11808 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
11809 > _ \n
11810 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11811
11812 (define-skeleton verilog-sk-for
11813 "Insert a skeleton while loop statement."
11814 ()
11815 > "for ("
11816 '(verilog-sk-prompt-init) "; "
11817 '(verilog-sk-prompt-condition) "; "
11818 '(verilog-sk-prompt-inc)
11819 ") begin" \n
11820 > _ \n
11821 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11822
11823 (define-skeleton verilog-sk-comment
11824 "Inserts three comment lines, making a display comment."
11825 ()
11826 > "/*\n"
11827 > "* " _ \n
11828 > "*/")
11829
11830 (define-skeleton verilog-sk-state-machine
11831 "Insert a state machine definition."
11832 "Name of state variable: "
11833 '(setq input "state")
11834 > "// State registers for " str | -23 \n
11835 '(setq verilog-sk-state str)
11836 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
11837 '(setq input nil)
11838 > \n
11839 > "// State FF for " verilog-sk-state \n
11840 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
11841 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
11842 > verilog-sk-state " = next_" verilog-sk-state ?; \n
11843 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
11844 > \n
11845 > "// Next State Logic for " verilog-sk-state \n
11846 > "always @ ( /*AUTOSENSE*/ ) begin\n"
11847 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
11848 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
11849 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
11850 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
11851 \f
11852
11853 ;;
11854 ;; Include file loading with mouse/return event
11855 ;;
11856 ;; idea & first impl.: M. Rouat (eldo-mode.el)
11857 ;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
11858
11859 (if (featurep 'xemacs)
11860 (require 'overlay))
11861
11862 (defconst verilog-include-file-regexp
11863 "^`include\\s-+\"\\([^\n\"]*\\)\""
11864 "Regexp that matches the include file.")
11865
11866 (defvar verilog-mode-mouse-map
11867 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
11868 (set-keymap-parent map verilog-mode-map)
11869 ;; mouse button bindings
11870 (define-key map "\r" 'verilog-load-file-at-point)
11871 (if (featurep 'xemacs)
11872 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
11873 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
11874 (if (featurep 'xemacs)
11875 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
11876 (define-key map [S-mouse-2] 'mouse-yank-at-click))
11877 map)
11878 "Map containing mouse bindings for `verilog-mode'.")
11879
11880
11881 (defun verilog-highlight-region (beg end old-len)
11882 "Colorize included files and modules in the (changed?) region.
11883 Clicking on the middle-mouse button loads them in a buffer (as in dired)."
11884 (when (or verilog-highlight-includes
11885 verilog-highlight-modules)
11886 (save-excursion
11887 (save-match-data ;; A query-replace may call this function - do not disturb
11888 (verilog-save-buffer-state
11889 (verilog-save-scan-cache
11890 (let (end-point)
11891 (goto-char end)
11892 (setq end-point (point-at-eol))
11893 (goto-char beg)
11894 (beginning-of-line) ; scan entire line
11895 ;; delete overlays existing on this line
11896 (let ((overlays (overlays-in (point) end-point)))
11897 (while overlays
11898 (if (and
11899 (overlay-get (car overlays) 'detachable)
11900 (or (overlay-get (car overlays) 'verilog-include-file)
11901 (overlay-get (car overlays) 'verilog-inst-module)))
11902 (delete-overlay (car overlays)))
11903 (setq overlays (cdr overlays))))
11904 ;;
11905 ;; make new include overlays
11906 (when verilog-highlight-includes
11907 (while (search-forward-regexp verilog-include-file-regexp end-point t)
11908 (goto-char (match-beginning 1))
11909 (let ((ov (make-overlay (match-beginning 1) (match-end 1))))
11910 (overlay-put ov 'start-closed 't)
11911 (overlay-put ov 'end-closed 't)
11912 (overlay-put ov 'evaporate 't)
11913 (overlay-put ov 'verilog-include-file 't)
11914 (overlay-put ov 'mouse-face 'highlight)
11915 (overlay-put ov 'local-map verilog-mode-mouse-map))))
11916 ;;
11917 ;; make new module overlays
11918 (goto-char beg)
11919 ;; This scanner is syntax-fragile, so don't get bent
11920 (when verilog-highlight-modules
11921 (condition-case nil
11922 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-point t)
11923 (save-excursion
11924 (goto-char (match-beginning 0))
11925 (unless (verilog-inside-comment-p)
11926 (verilog-read-inst-module-matcher) ;; sets match 0
11927 (let* ((ov (make-overlay (match-beginning 0) (match-end 0))))
11928 (overlay-put ov 'start-closed 't)
11929 (overlay-put ov 'end-closed 't)
11930 (overlay-put ov 'evaporate 't)
11931 (overlay-put ov 'verilog-inst-module 't)
11932 (overlay-put ov 'mouse-face 'highlight)
11933 (overlay-put ov 'local-map verilog-mode-mouse-map)))))
11934 (error nil)))
11935 ;;
11936 ;; Future highlights:
11937 ;; variables - make an Occur buffer of where referenced
11938 ;; pins - make an Occur buffer of the sig in the declaration module
11939 )))))))
11940
11941 (defun verilog-highlight-buffer ()
11942 "Colorize included files and modules across the whole buffer."
11943 ;; Invoked via verilog-mode calling font-lock then `font-lock-mode-hook'
11944 (interactive)
11945 ;; delete and remake overlays
11946 (verilog-highlight-region (point-min) (point-max) nil))
11947
11948 ;; Deprecated, but was interactive, so we'll keep it around
11949 (defalias 'verilog-colorize-include-files-buffer 'verilog-highlight-buffer)
11950
11951 ;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
11952 ;; so define this function to do more or less the same as ffap-at-mouse
11953 ;; but first resolve filename...
11954 (defun verilog-load-file-at-mouse (event)
11955 "Load file under button 2 click's EVENT.
11956 Files are checked based on `verilog-library-flags'."
11957 (interactive "@e")
11958 (save-excursion ;; implement a Verilog specific ffap-at-mouse
11959 (mouse-set-point event)
11960 (verilog-load-file-at-point t)))
11961
11962 ;; ffap isn't useable for Verilog mode. It uses library paths.
11963 ;; so define this function to do more or less the same as ffap
11964 ;; but first resolve filename...
11965 (defun verilog-load-file-at-point (&optional warn)
11966 "Load file under point.
11967 If WARN, throw warning if not found.
11968 Files are checked based on `verilog-library-flags'."
11969 (interactive)
11970 (save-excursion ;; implement a Verilog specific ffap
11971 (let ((overlays (overlays-in (point) (point)))
11972 hit)
11973 (while (and overlays (not hit))
11974 (when (overlay-get (car overlays) 'verilog-inst-module)
11975 (verilog-goto-defun-file (buffer-substring
11976 (overlay-start (car overlays))
11977 (overlay-end (car overlays))))
11978 (setq hit t))
11979 (setq overlays (cdr overlays)))
11980 ;; Include?
11981 (beginning-of-line)
11982 (when (and (not hit)
11983 (looking-at verilog-include-file-regexp))
11984 (if (and (car (verilog-library-filenames
11985 (match-string 1) (buffer-file-name)))
11986 (file-readable-p (car (verilog-library-filenames
11987 (match-string 1) (buffer-file-name)))))
11988 (find-file (car (verilog-library-filenames
11989 (match-string 1) (buffer-file-name))))
11990 (when warn
11991 (message
11992 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
11993 (match-string 1))))))))
11994
11995 ;;
11996 ;; Bug reporting
11997 ;;
11998
11999 (defun verilog-faq ()
12000 "Tell the user their current version, and where to get the FAQ etc."
12001 (interactive)
12002 (with-output-to-temp-buffer "*verilog-mode help*"
12003 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
12004 (princ "\n")
12005 (princ "For new releases, see http://www.verilog.com\n")
12006 (princ "\n")
12007 (princ "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
12008 (princ "\n")
12009 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
12010 (princ "\n")))
12011
12012 (autoload 'reporter-submit-bug-report "reporter")
12013 (defvar reporter-prompt-for-summary-p)
12014
12015 (defun verilog-submit-bug-report ()
12016 "Submit via mail a bug report on verilog-mode.el."
12017 (interactive)
12018 (let ((reporter-prompt-for-summary-p t))
12019 (reporter-submit-bug-report
12020 "mac@verilog.com, wsnyder@wsnyder.org"
12021 (concat "verilog-mode v" verilog-mode-version)
12022 '(
12023 verilog-active-low-regexp
12024 verilog-align-ifelse
12025 verilog-assignment-delay
12026 verilog-auto-arg-sort
12027 verilog-auto-endcomments
12028 verilog-auto-hook
12029 verilog-auto-ignore-concat
12030 verilog-auto-indent-on-newline
12031 verilog-auto-inout-ignore-regexp
12032 verilog-auto-input-ignore-regexp
12033 verilog-auto-inst-column
12034 verilog-auto-inst-dot-name
12035 verilog-auto-inst-param-value
12036 verilog-auto-inst-template-numbers
12037 verilog-auto-inst-vector
12038 verilog-auto-lineup
12039 verilog-auto-newline
12040 verilog-auto-output-ignore-regexp
12041 verilog-auto-read-includes
12042 verilog-auto-reset-widths
12043 verilog-auto-save-policy
12044 verilog-auto-sense-defines-constant
12045 verilog-auto-sense-include-inputs
12046 verilog-auto-star-expand
12047 verilog-auto-star-save
12048 verilog-auto-unused-ignore-regexp
12049 verilog-before-auto-hook
12050 verilog-before-delete-auto-hook
12051 verilog-before-getopt-flags-hook
12052 verilog-case-indent
12053 verilog-cexp-indent
12054 verilog-compiler
12055 verilog-coverage
12056 verilog-delete-auto-hook
12057 verilog-getopt-flags-hook
12058 verilog-highlight-grouping-keywords
12059 verilog-highlight-p1800-keywords
12060 verilog-highlight-translate-off
12061 verilog-indent-begin-after-if
12062 verilog-indent-declaration-macros
12063 verilog-indent-level
12064 verilog-indent-level-behavioral
12065 verilog-indent-level-declaration
12066 verilog-indent-level-directive
12067 verilog-indent-level-module
12068 verilog-indent-lists
12069 verilog-library-directories
12070 verilog-library-extensions
12071 verilog-library-files
12072 verilog-library-flags
12073 verilog-linter
12074 verilog-minimum-comment-distance
12075 verilog-mode-hook
12076 verilog-preprocessor
12077 verilog-simulator
12078 verilog-tab-always-indent
12079 verilog-tab-to-comment
12080 verilog-typedef-regexp
12081 )
12082 nil nil
12083 (concat "Hi Mac,
12084
12085 I want to report a bug.
12086
12087 Before I go further, I want to say that Verilog mode has changed my life.
12088 I save so much time, my files are colored nicely, my co workers respect
12089 my coding ability... until now. I'd really appreciate anything you
12090 could do to help me out with this minor deficiency in the product.
12091
12092 I've taken a look at the Verilog-Mode FAQ at
12093 http://www.veripool.org/verilog-mode-faq.html.
12094
12095 And, I've considered filing the bug on the issue tracker at
12096 http://www.veripool.org/verilog-mode-bugs
12097 since I realize that public bugs are easier for you to track,
12098 and for others to search, but would prefer to email.
12099
12100 So, to reproduce the bug, start a fresh Emacs via " invocation-name "
12101 -no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
12102 the code included below.
12103
12104 Given those lines, I expected [[Fill in here]] to happen;
12105 but instead, [[Fill in here]] happens!.
12106
12107 == The code: =="))))
12108
12109 (provide 'verilog-mode)
12110
12111 ;; Local Variables:
12112 ;; checkdoc-permit-comma-termination-flag:t
12113 ;; checkdoc-force-docstrings-flag:nil
12114 ;; End:
12115
12116 ;;; verilog-mode.el ends here