]> code.delx.au - gnu-emacs/blob - lisp/progmodes/verilog-mode.el
e7fcf223bc1353078731659cb7fb846db515085e
[gnu-emacs] / lisp / progmodes / verilog-mode.el
1 ;;; verilog-mode.el --- major mode for editing verilog source in Emacs
2
3 ;; Copyright (C) 1996-2014 Free Software Foundation, Inc.
4
5 ;; Author: Michael McNamara <mac@verilog.com>
6 ;; Wilson Snyder <wsnyder@wsnyder.org>
7 ;; http://www.verilog.com
8 ;; http://www.veripool.org
9 ;; Created: 3 Jan 1996
10 ;; Keywords: languages
11
12 ;; Yoni Rabkin <yoni@rabkins.net> contacted the maintainer of this
13 ;; file on 19/3/2008, and the maintainer agreed that when a bug is
14 ;; filed in the Emacs bug reporting system against this file, a copy
15 ;; of the bug report be sent to the maintainer's email address.
16
17 ;; This code supports Emacs 21.1 and later
18 ;; And XEmacs 21.1 and later
19 ;; Please do not make changes that break Emacs 21. Thanks!
20 ;;
21 ;;
22
23 ;; This file is part of GNU Emacs.
24
25 ;; GNU Emacs is free software: you can redistribute it and/or modify
26 ;; it under the terms of the GNU General Public License as published by
27 ;; the Free Software Foundation, either version 3 of the License, or
28 ;; (at your option) any later version.
29
30 ;; GNU Emacs is distributed in the hope that it will be useful,
31 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
32 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 ;; GNU General Public License for more details.
34
35 ;; You should have received a copy of the GNU General Public License
36 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
37
38 ;;; Commentary:
39
40 ;; USAGE
41 ;; =====
42
43 ;; A major mode for editing Verilog and SystemVerilog HDL source code (IEEE
44 ;; 1364-2005 and IEEE 1800-2012 standards). When you have entered Verilog
45 ;; mode, you may get more info by pressing C-h m. You may also get online
46 ;; help describing various functions by: C-h f <Name of function you want
47 ;; described>
48
49 ;; KNOWN BUGS / BUG REPORTS
50 ;; =======================
51
52 ;; SystemVerilog is a rapidly evolving language, and hence this mode is
53 ;; under continuous development. Please report any issues to the issue
54 ;; tracker at
55 ;;
56 ;; http://www.veripool.org/verilog-mode
57 ;;
58 ;; Please use verilog-submit-bug-report to submit a report; type C-c
59 ;; C-b to invoke this and as a result we will have a much easier time
60 ;; of reproducing the bug you find, and hence fixing it.
61
62 ;; INSTALLING THE MODE
63 ;; ===================
64
65 ;; An older version of this mode may be already installed as a part of
66 ;; your environment, and one method of updating would be to update
67 ;; your Emacs environment. Sometimes this is difficult for local
68 ;; political/control reasons, and hence you can always install a
69 ;; private copy (or even a shared copy) which overrides the system
70 ;; default.
71
72 ;; You can get step by step help in installing this file by going to
73 ;; <http://www.verilog.com/emacs_install.html>
74
75 ;; The short list of installation instructions are: To set up
76 ;; automatic Verilog mode, put this file in your load path, and put
77 ;; the following in code (please un comment it first!) in your
78 ;; .emacs, or in your site's site-load.el
79
80 ; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
81 ; (add-to-list 'auto-mode-alist '("\\.[ds]?vh?\\'" . verilog-mode))
82
83 ;; Be sure to examine at the help for verilog-auto, and the other
84 ;; verilog-auto-* functions for some major coding time savers.
85 ;;
86 ;; If you want to customize Verilog mode to fit your needs better,
87 ;; you may add the below lines (the values of the variables presented
88 ;; here are the defaults). Note also that if you use an Emacs that
89 ;; supports custom, it's probably better to use the custom menu to
90 ;; edit these. If working as a member of a large team these settings
91 ;; should be common across all users (in a site-start file), or set
92 ;; in Local Variables in every file. Otherwise, different people's
93 ;; AUTO expansion may result different whitespace changes.
94 ;;
95 ; ;; Enable syntax highlighting of **all** languages
96 ; (global-font-lock-mode t)
97 ;
98 ; ;; User customization for Verilog mode
99 ; (setq verilog-indent-level 3
100 ; verilog-indent-level-module 3
101 ; verilog-indent-level-declaration 3
102 ; verilog-indent-level-behavioral 3
103 ; verilog-indent-level-directive 1
104 ; verilog-case-indent 2
105 ; verilog-auto-newline t
106 ; verilog-auto-indent-on-newline t
107 ; verilog-tab-always-indent t
108 ; verilog-auto-endcomments t
109 ; verilog-minimum-comment-distance 40
110 ; verilog-indent-begin-after-if t
111 ; verilog-auto-lineup 'declarations
112 ; verilog-highlight-p1800-keywords nil
113 ; verilog-linter "my_lint_shell_command"
114 ; )
115
116 ;; \f
117
118 ;;; History:
119 ;;
120 ;; See commit history at http://www.veripool.org/verilog-mode.html
121 ;; (This section is required to appease checkdoc.)
122
123 ;;; Code:
124
125 ;; This variable will always hold the version number of the mode
126 (defconst verilog-mode-version "2014-11-12-aa4b777-vpo"
127 "Version of this Verilog mode.")
128 (defconst verilog-mode-release-emacs t
129 "If non-nil, this version of Verilog mode was released with Emacs itself.")
130
131 (defun verilog-version ()
132 "Inform caller of the version of this file."
133 (interactive)
134 (message "Using verilog-mode version %s" verilog-mode-version))
135
136 ;; Insure we have certain packages, and deal with it if we don't
137 ;; Be sure to note which Emacs flavor and version added each feature.
138 (eval-when-compile
139 ;; Provide stuff if we are XEmacs
140 (when (featurep 'xemacs)
141 (condition-case nil
142 (require 'easymenu)
143 (error nil))
144 (condition-case nil
145 (require 'regexp-opt)
146 (error nil))
147 ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
148 (condition-case nil
149 (load "skeleton")
150 (error nil))
151 (condition-case nil
152 (if (fboundp 'when)
153 nil ;; fab
154 (defmacro when (cond &rest body)
155 (list 'if cond (cons 'progn body))))
156 (error nil))
157 (condition-case nil
158 (if (fboundp 'unless)
159 nil ;; fab
160 (defmacro unless (cond &rest body)
161 (cons 'if (cons cond (cons nil body)))))
162 (error nil))
163 (condition-case nil
164 (if (fboundp 'store-match-data)
165 nil ;; fab
166 (defmacro store-match-data (&rest _args) nil))
167 (error nil))
168 (condition-case nil
169 (if (fboundp 'char-before)
170 nil ;; great
171 (defmacro char-before (&rest _body)
172 (char-after (1- (point)))))
173 (error nil))
174 (condition-case nil
175 (if (fboundp 'when)
176 nil ;; fab
177 (defsubst point-at-bol (&optional N)
178 (save-excursion (beginning-of-line N) (point))))
179 (error nil))
180 (condition-case nil
181 (if (fboundp 'when)
182 nil ;; fab
183 (defsubst point-at-eol (&optional N)
184 (save-excursion (end-of-line N) (point))))
185 (error nil))
186 (condition-case nil
187 (require 'custom)
188 (error nil))
189 (condition-case nil
190 (if (fboundp 'match-string-no-properties)
191 nil ;; great
192 (defsubst match-string-no-properties (num &optional string)
193 "Return string of text matched by last search, without text properties.
194 NUM specifies which parenthesized expression in the last regexp.
195 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
196 Zero means the entire text matched by the whole regexp or whole string.
197 STRING should be given if the last search was by `string-match' on STRING."
198 (if (match-beginning num)
199 (if string
200 (let ((result
201 (substring string
202 (match-beginning num) (match-end num))))
203 (set-text-properties 0 (length result) nil result)
204 result)
205 (buffer-substring-no-properties (match-beginning num)
206 (match-end num)
207 (current-buffer)))))
208 )
209 (error nil))
210 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
211 nil ;; We've got what we needed
212 ;; We have the old custom-library, hack around it!
213 (defmacro defgroup (&rest _args) nil)
214 (defmacro customize (&rest _args)
215 (message
216 "Sorry, Customize is not available with this version of Emacs"))
217 (defmacro defcustom (var value doc &rest _args)
218 `(defvar ,var ,value ,doc))
219 )
220 (if (fboundp 'defface)
221 nil ; great!
222 (defmacro defface (var values doc &rest _args)
223 `(make-face ,var))
224 )
225
226 (if (and (featurep 'custom) (fboundp 'customize-group))
227 nil ;; We've got what we needed
228 ;; We have an intermediate custom-library, hack around it!
229 (defmacro customize-group (var &rest _args)
230 `(customize ,var))
231 )
232
233 (unless (boundp 'inhibit-point-motion-hooks)
234 (defvar inhibit-point-motion-hooks nil))
235 (unless (boundp 'deactivate-mark)
236 (defvar deactivate-mark nil))
237 )
238 ;;
239 ;; OK, do this stuff if we are NOT XEmacs:
240 (unless (featurep 'xemacs)
241 (unless (fboundp 'region-active-p)
242 (defmacro region-active-p ()
243 `(and transient-mark-mode mark-active))))
244 )
245
246 ;; Provide a regular expression optimization routine, using regexp-opt
247 ;; if provided by the user's elisp libraries
248 (eval-and-compile
249 ;; The below were disabled when GNU Emacs 22 was released;
250 ;; perhaps some still need to be there to support Emacs 21.
251 (if (featurep 'xemacs)
252 (if (fboundp 'regexp-opt)
253 ;; regexp-opt is defined, does it take 3 or 2 arguments?
254 (if (fboundp 'function-max-args)
255 (let ((args (function-max-args `regexp-opt)))
256 (cond
257 ((eq args 3) ;; It takes 3
258 (condition-case nil ; Hide this defun from emacses
259 ;with just a two input regexp
260 (defun verilog-regexp-opt (a b)
261 "Deal with differing number of required arguments for `regexp-opt'.
262 Call `regexp-opt' on A and B."
263 (regexp-opt a b t))
264 (error nil))
265 )
266 ((eq args 2) ;; It takes 2
267 (defun verilog-regexp-opt (a b)
268 "Call `regexp-opt' on A and B."
269 (regexp-opt a b))
270 )
271 (t nil)))
272 ;; We can't tell; assume it takes 2
273 (defun verilog-regexp-opt (a b)
274 "Call `regexp-opt' on A and B."
275 (regexp-opt a b))
276 )
277 ;; There is no regexp-opt, provide our own
278 (defun verilog-regexp-opt (strings &optional paren _shy)
279 (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
280 (concat open (mapconcat 'regexp-quote strings "\\|") close)))
281 )
282 ;; Emacs.
283 (defalias 'verilog-regexp-opt 'regexp-opt)))
284
285 (eval-and-compile
286 ;; Both xemacs and emacs
287 (condition-case nil
288 (require 'diff) ;; diff-command and diff-switches
289 (error nil))
290 (condition-case nil
291 (require 'compile) ;; compilation-error-regexp-alist-alist
292 (error nil))
293 (condition-case nil
294 (unless (fboundp 'buffer-chars-modified-tick) ;; Emacs 22 added
295 (defmacro buffer-chars-modified-tick () (buffer-modified-tick)))
296 (error nil))
297 ;; Added in Emacs 24.1
298 (condition-case nil
299 (unless (fboundp 'prog-mode)
300 (define-derived-mode prog-mode fundamental-mode "Prog"))
301 (error nil)))
302
303 (eval-when-compile
304 (defun verilog-regexp-words (a)
305 "Call 'regexp-opt' with word delimiters for the words A."
306 (concat "\\<" (verilog-regexp-opt a t) "\\>")))
307 (defun verilog-regexp-words (a)
308 "Call 'regexp-opt' with word delimiters for the words A."
309 ;; The FAQ references this function, so user LISP sometimes calls it
310 (concat "\\<" (verilog-regexp-opt a t) "\\>"))
311
312 (defun verilog-easy-menu-filter (menu)
313 "Filter `easy-menu-define' MENU to support new features."
314 (cond ((not (featurep 'xemacs))
315 menu) ;; GNU Emacs - passthru
316 ;; XEmacs doesn't support :help. Strip it.
317 ;; Recursively filter the a submenu
318 ((listp menu)
319 (mapcar 'verilog-easy-menu-filter menu))
320 ;; Look for [:help "blah"] and remove
321 ((vectorp menu)
322 (let ((i 0) (out []))
323 (while (< i (length menu))
324 (if (equal `:help (aref menu i))
325 (setq i (+ 2 i))
326 (setq out (vconcat out (vector (aref menu i)))
327 i (1+ i))))
328 out))
329 (t menu))) ;; Default - ok
330 ;;(verilog-easy-menu-filter
331 ;; `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
332 ;; "----" ["MB" nil :help "Help MB"]))
333
334 (defun verilog-define-abbrev (table name expansion &optional hook)
335 "Filter `define-abbrev' TABLE NAME EXPANSION and call HOOK.
336 Provides SYSTEM-FLAG in newer Emacs."
337 (condition-case nil
338 (define-abbrev table name expansion hook 0 t)
339 (error
340 (define-abbrev table name expansion hook))))
341
342 (defun verilog-customize ()
343 "Customize variables and other settings used by Verilog-Mode."
344 (interactive)
345 (customize-group 'verilog-mode))
346
347 (defun verilog-font-customize ()
348 "Customize fonts used by Verilog-Mode."
349 (interactive)
350 (if (fboundp 'customize-apropos)
351 (customize-apropos "font-lock-*" 'faces)))
352
353 (defun verilog-booleanp (value)
354 "Return t if VALUE is boolean.
355 This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
356 This function may be removed when Emacs 21 is no longer supported."
357 (or (equal value t) (equal value nil)))
358
359 (defun verilog-insert-last-command-event ()
360 "Insert the `last-command-event'."
361 (insert (if (featurep 'xemacs)
362 ;; XEmacs 21.5 doesn't like last-command-event
363 last-command-char
364 ;; And GNU Emacs 22 has obsoleted last-command-char
365 last-command-event)))
366
367 (defvar verilog-no-change-functions nil
368 "True if `after-change-functions' is disabled.
369 Use of `syntax-ppss' may break, as ppss's cache may get corrupted.")
370
371 (defvar verilog-in-hooks nil
372 "True when within a `verilog-run-hooks' block.")
373
374 (defmacro verilog-run-hooks (&rest hooks)
375 "Run each hook in HOOKS using `run-hooks'.
376 Set `verilog-in-hooks' during this time, to assist AUTO caches."
377 `(let ((verilog-in-hooks t))
378 (run-hooks ,@hooks)))
379
380 (defun verilog-syntax-ppss (&optional pos)
381 (when verilog-no-change-functions
382 (if verilog-in-hooks
383 (verilog-scan-cache-flush)
384 ;; else don't let the AUTO code itself get away with flushing the cache,
385 ;; as that'll make things very slow
386 (backtrace)
387 (error "%s: Internal problem; use of syntax-ppss when cache may be corrupt"
388 (verilog-point-text))))
389 (if (fboundp 'syntax-ppss)
390 (syntax-ppss pos)
391 (parse-partial-sexp (point-min) (or pos (point)))))
392
393 (defgroup verilog-mode nil
394 "Major mode for Verilog source code."
395 :version "22.2"
396 :group 'languages)
397
398 ; (defgroup verilog-mode-fonts nil
399 ; "Facilitates easy customization fonts used in Verilog source text"
400 ; :link '(customize-apropos "font-lock-*" 'faces)
401 ; :group 'verilog-mode)
402
403 (defgroup verilog-mode-indent nil
404 "Customize indentation and highlighting of Verilog source text."
405 :group 'verilog-mode)
406
407 (defgroup verilog-mode-actions nil
408 "Customize actions on Verilog source text."
409 :group 'verilog-mode)
410
411 (defgroup verilog-mode-auto nil
412 "Customize AUTO actions when expanding Verilog source text."
413 :group 'verilog-mode)
414
415 (defvar verilog-debug nil
416 "Non-nil means enable debug messages for `verilog-mode' internals.")
417
418 (defvar verilog-warn-fatal nil
419 "Non-nil means `verilog-warn-error' warnings are fatal `error's.")
420
421 (defcustom verilog-linter
422 "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
423 "Unix program and arguments to call to run a lint checker on Verilog source.
424 Depending on the `verilog-set-compile-command', this may be invoked when
425 you type \\[compile]. When the compile completes, \\[next-error] will take
426 you to the next lint error."
427 :type 'string
428 :group 'verilog-mode-actions)
429 ;; We don't mark it safe, as it's used as a shell command
430
431 (defcustom verilog-coverage
432 "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
433 "Program and arguments to use to annotate for coverage Verilog source.
434 Depending on the `verilog-set-compile-command', this may be invoked when
435 you type \\[compile]. When the compile completes, \\[next-error] will take
436 you to the next lint error."
437 :type 'string
438 :group 'verilog-mode-actions)
439 ;; We don't mark it safe, as it's used as a shell command
440
441 (defcustom verilog-simulator
442 "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
443 "Program and arguments to use to interpret Verilog source.
444 Depending on the `verilog-set-compile-command', this may be invoked when
445 you type \\[compile]. When the compile completes, \\[next-error] will take
446 you to the next lint error."
447 :type 'string
448 :group 'verilog-mode-actions)
449 ;; We don't mark it safe, as it's used as a shell command
450
451 (defcustom verilog-compiler
452 "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
453 "Program and arguments to use to compile Verilog source.
454 Depending on the `verilog-set-compile-command', this may be invoked when
455 you type \\[compile]. When the compile completes, \\[next-error] will take
456 you to the next lint error."
457 :type 'string
458 :group 'verilog-mode-actions)
459 ;; We don't mark it safe, as it's used as a shell command
460
461 (defcustom verilog-preprocessor
462 ;; Very few tools give preprocessed output, so we'll default to Verilog-Perl
463 "vppreproc __FLAGS__ __FILE__"
464 "Program and arguments to use to preprocess Verilog source.
465 This is invoked with `verilog-preprocess', and depending on the
466 `verilog-set-compile-command', may also be invoked when you type
467 \\[compile]. When the compile completes, \\[next-error] will
468 take you to the next lint error."
469 :type 'string
470 :group 'verilog-mode-actions)
471 ;; We don't mark it safe, as it's used as a shell command
472
473 (defvar verilog-preprocess-history nil
474 "History for `verilog-preprocess'.")
475
476 (defvar verilog-tool 'verilog-linter
477 "Which tool to use for building compiler-command.
478 Either nil, `verilog-linter, `verilog-compiler,
479 `verilog-coverage, `verilog-preprocessor, or `verilog-simulator.
480 Alternatively use the \"Choose Compilation Action\" menu. See
481 `verilog-set-compile-command' for more information.")
482
483 (defcustom verilog-highlight-translate-off nil
484 "Non-nil means background-highlight code excluded from translation.
485 That is, all code between \"// synopsys translate_off\" and
486 \"// synopsys translate_on\" is highlighted using a different background color
487 \(face `verilog-font-lock-translate-off-face').
488
489 Note: This will slow down on-the-fly fontification (and thus editing).
490
491 Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
492 entry \"Fontify Buffer\"). XEmacs: turn off and on font locking."
493 :type 'boolean
494 :group 'verilog-mode-indent)
495 ;; Note we don't use :safe, as that would break on Emacsen before 22.0.
496 (put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
497
498 (defcustom verilog-auto-lineup 'declarations
499 "Type of statements to lineup across multiple lines.
500 If 'all' is selected, then all line ups described below are done.
501
502 If 'declarations', then just declarations are lined up with any
503 preceding declarations, taking into account widths and the like,
504 so or example the code:
505 reg [31:0] a;
506 reg b;
507 would become
508 reg [31:0] a;
509 reg b;
510
511 If 'assignment', then assignments are lined up with any preceding
512 assignments, so for example the code
513 a_long_variable <= b + c;
514 d = e + f;
515 would become
516 a_long_variable <= b + c;
517 d = e + f;
518
519 In order to speed up editing, large blocks of statements are lined up
520 only when a \\[verilog-pretty-expr] is typed; and large blocks of declarations
521 are lineup only when \\[verilog-pretty-declarations] is typed."
522
523 :type '(radio (const :tag "Line up Assignments and Declarations" all)
524 (const :tag "Line up Assignment statements" assignments )
525 (const :tag "Line up Declarations" declarations)
526 (function :tag "Other"))
527 :group 'verilog-mode-indent )
528 (put 'verilog-auto-lineup 'safe-local-variable
529 '(lambda (x) (memq x '(nil all assignments declarations))))
530
531 (defcustom verilog-indent-level 3
532 "Indentation of Verilog statements with respect to containing block."
533 :group 'verilog-mode-indent
534 :type 'integer)
535 (put 'verilog-indent-level 'safe-local-variable 'integerp)
536
537 (defcustom verilog-indent-level-module 3
538 "Indentation of Module level Verilog statements (eg always, initial).
539 Set to 0 to get initial and always statements lined up on the left side of
540 your screen."
541 :group 'verilog-mode-indent
542 :type 'integer)
543 (put 'verilog-indent-level-module 'safe-local-variable 'integerp)
544
545 (defcustom verilog-indent-level-declaration 3
546 "Indentation of declarations with respect to containing block.
547 Set to 0 to get them list right under containing block."
548 :group 'verilog-mode-indent
549 :type 'integer)
550 (put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
551
552 (defcustom verilog-indent-declaration-macros nil
553 "How to treat macro expansions in a declaration.
554 If nil, indent as:
555 input [31:0] a;
556 input `CP;
557 output c;
558 If non nil, treat as:
559 input [31:0] a;
560 input `CP ;
561 output c;"
562 :group 'verilog-mode-indent
563 :type 'boolean)
564 (put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
565
566 (defcustom verilog-indent-lists t
567 "How to treat indenting items in a list.
568 If t (the default), indent as:
569 always @( posedge a or
570 reset ) begin
571
572 If nil, treat as:
573 always @( posedge a or
574 reset ) begin"
575 :group 'verilog-mode-indent
576 :type 'boolean)
577 (put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
578
579 (defcustom verilog-indent-level-behavioral 3
580 "Absolute indentation of first begin in a task or function block.
581 Set to 0 to get such code to start at the left side of the screen."
582 :group 'verilog-mode-indent
583 :type 'integer)
584 (put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
585
586 (defcustom verilog-indent-level-directive 1
587 "Indentation to add to each level of `ifdef declarations.
588 Set to 0 to have all directives start at the left side of the screen."
589 :group 'verilog-mode-indent
590 :type 'integer)
591 (put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
592
593 (defcustom verilog-cexp-indent 2
594 "Indentation of Verilog statements split across lines."
595 :group 'verilog-mode-indent
596 :type 'integer)
597 (put 'verilog-cexp-indent 'safe-local-variable 'integerp)
598
599 (defcustom verilog-case-indent 2
600 "Indentation for case statements."
601 :group 'verilog-mode-indent
602 :type 'integer)
603 (put 'verilog-case-indent 'safe-local-variable 'integerp)
604
605 (defcustom verilog-auto-newline t
606 "Non-nil means automatically newline after semicolons."
607 :group 'verilog-mode-indent
608 :type 'boolean)
609 (put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
610
611 (defcustom verilog-auto-indent-on-newline t
612 "Non-nil means automatically indent line after newline."
613 :group 'verilog-mode-indent
614 :type 'boolean)
615 (put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
616
617 (defcustom verilog-tab-always-indent t
618 "Non-nil means TAB should always re-indent the current line.
619 A nil value means TAB will only reindent when at the beginning of the line."
620 :group 'verilog-mode-indent
621 :type 'boolean)
622 (put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
623
624 (defcustom verilog-tab-to-comment nil
625 "Non-nil means TAB moves to the right hand column in preparation for a comment."
626 :group 'verilog-mode-actions
627 :type 'boolean)
628 (put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
629
630 (defcustom verilog-indent-begin-after-if t
631 "Non-nil means indent begin statements following if, else, while, etc.
632 Otherwise, line them up."
633 :group 'verilog-mode-indent
634 :type 'boolean)
635 (put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
636
637 (defcustom verilog-align-ifelse nil
638 "Non-nil means align `else' under matching `if'.
639 Otherwise else is lined up with first character on line holding matching if."
640 :group 'verilog-mode-indent
641 :type 'boolean)
642 (put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
643
644 (defcustom verilog-minimum-comment-distance 10
645 "Minimum distance (in lines) between begin and end required before a comment.
646 Setting this variable to zero results in every end acquiring a comment; the
647 default avoids too many redundant comments in tight quarters."
648 :group 'verilog-mode-indent
649 :type 'integer)
650 (put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
651
652 (defcustom verilog-highlight-p1800-keywords nil
653 "Non-nil means highlight words newly reserved by IEEE-1800.
654 These will appear in `verilog-font-lock-p1800-face' in order to gently
655 suggest changing where these words are used as variables to something else.
656 A nil value means highlight these words as appropriate for the SystemVerilog
657 IEEE-1800 standard. Note that changing this will require restarting Emacs
658 to see the effect as font color choices are cached by Emacs."
659 :group 'verilog-mode-indent
660 :type 'boolean)
661 (put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
662
663 (defcustom verilog-highlight-grouping-keywords nil
664 "Non-nil means highlight grouping keywords more dramatically.
665 If false, these words are in the `font-lock-type-face'; if True then they are in
666 `verilog-font-lock-ams-face'. Some find that special highlighting on these
667 grouping constructs allow the structure of the code to be understood at a glance."
668 :group 'verilog-mode-indent
669 :type 'boolean)
670 (put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
671
672 (defcustom verilog-highlight-modules nil
673 "Non-nil means highlight module statements for `verilog-load-file-at-point'.
674 When true, mousing over module names will allow jumping to the
675 module definition. If false, this is not supported. Setting
676 this is experimental, and may lead to bad performance."
677 :group 'verilog-mode-indent
678 :type 'boolean)
679 (put 'verilog-highlight-modules 'safe-local-variable 'verilog-booleanp)
680
681 (defcustom verilog-highlight-includes t
682 "Non-nil means highlight module statements for `verilog-load-file-at-point'.
683 When true, mousing over include file names will allow jumping to the
684 file referenced. If false, this is not supported."
685 :group 'verilog-mode-indent
686 :type 'boolean)
687 (put 'verilog-highlight-includes 'safe-local-variable 'verilog-booleanp)
688
689 (defcustom verilog-auto-declare-nettype nil
690 "Non-nil specifies the data type to use with `verilog-auto-input' etc.
691 Set this to \"wire\" if the Verilog code uses \"`default_nettype
692 none\". Note using `default_nettype none isn't recommended practice; this
693 mode is experimental."
694 :version "24.1" ;; rev670
695 :group 'verilog-mode-actions
696 :type 'boolean)
697 (put 'verilog-auto-declare-nettype 'safe-local-variable `stringp)
698
699 (defcustom verilog-auto-wire-type nil
700 "Non-nil specifies the data type to use with `verilog-auto-wire' etc.
701 Set this to \"logic\" for SystemVerilog code, or use `verilog-auto-logic'."
702 :version "24.1" ;; rev673
703 :group 'verilog-mode-actions
704 :type 'boolean)
705 (put 'verilog-auto-wire-type 'safe-local-variable `stringp)
706
707 (defcustom verilog-auto-endcomments t
708 "Non-nil means insert a comment /* ... */ after 'end's.
709 The name of the function or case will be set between the braces."
710 :group 'verilog-mode-actions
711 :type 'boolean)
712 (put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
713
714 (defcustom verilog-auto-delete-trailing-whitespace nil
715 "Non-nil means to `delete-trailing-whitespace' in `verilog-auto'."
716 :version "24.1" ;; rev703
717 :group 'verilog-mode-actions
718 :type 'boolean)
719 (put 'verilog-auto-delete-trailing-whitespace 'safe-local-variable 'verilog-booleanp)
720
721 (defcustom verilog-auto-ignore-concat nil
722 "Non-nil means ignore signals in {...} concatenations for AUTOWIRE etc.
723 This will exclude signals referenced as pin connections in {...}
724 from AUTOWIRE, AUTOOUTPUT and friends. This flag should be set
725 for backward compatibility only and not set in new designs; it
726 may be removed in future versions."
727 :group 'verilog-mode-actions
728 :type 'boolean)
729 (put 'verilog-auto-ignore-concat 'safe-local-variable 'verilog-booleanp)
730
731 (defcustom verilog-auto-read-includes nil
732 "Non-nil means to automatically read includes before AUTOs.
733 This will do a `verilog-read-defines' and `verilog-read-includes' before
734 each AUTO expansion. This makes it easier to embed defines and includes,
735 but can result in very slow reading times if there are many or large
736 include files."
737 :group 'verilog-mode-actions
738 :type 'boolean)
739 (put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
740
741 (defcustom verilog-auto-save-policy nil
742 "Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
743 A value of `force' will always do a \\[verilog-auto] automatically if
744 needed on every save. A value of `detect' will do \\[verilog-auto]
745 automatically when it thinks necessary. A value of `ask' will query the
746 user when it thinks updating is needed.
747
748 You should not rely on the 'ask or 'detect policies, they are safeguards
749 only. They do not detect when AUTOINSTs need to be updated because a
750 sub-module's port list has changed."
751 :group 'verilog-mode-actions
752 :type '(choice (const nil) (const ask) (const detect) (const force)))
753
754 (defcustom verilog-auto-star-expand t
755 "Non-nil means to expand SystemVerilog .* instance ports.
756 They will be expanded in the same way as if there was an AUTOINST in the
757 instantiation. See also `verilog-auto-star' and `verilog-auto-star-save'."
758 :group 'verilog-mode-actions
759 :type 'boolean)
760 (put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
761
762 (defcustom verilog-auto-star-save nil
763 "Non-nil means save to disk SystemVerilog .* instance expansions.
764 A nil value indicates direct connections will be removed before saving.
765 Only meaningful to those created due to `verilog-auto-star-expand' being set.
766
767 Instead of setting this, you may want to use /*AUTOINST*/, which will
768 always be saved."
769 :group 'verilog-mode-actions
770 :type 'boolean)
771 (put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
772
773 (defvar verilog-auto-update-tick nil
774 "Modification tick at which autos were last performed.")
775
776 (defvar verilog-auto-last-file-locals nil
777 "Text from file-local-variables during last evaluation.")
778
779 (defvar verilog-diff-function 'verilog-diff-report
780 "Function to run when `verilog-diff-auto' detects differences.
781 Function takes three arguments, the original buffer, the
782 difference buffer, and the point in original buffer with the
783 first difference.")
784
785 ;;; Compile support
786 (require 'compile)
787 (defvar verilog-error-regexp-added nil)
788
789 (defvar verilog-error-regexp-emacs-alist
790 '(
791 (verilog-xl-1
792 "\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
793 (verilog-xl-2
794 "([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 3)
795 (verilog-IES
796 ".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)" 2 3)
797 (verilog-surefire-1
798 "[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
799 (verilog-surefire-2
800 "\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\),\\s-+\\(line \\)?\\([0-9]+\\):" 2 4 )
801 (verilog-verbose
802 "\
803 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
804 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
805 (verilog-xsim
806 "\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
807 (verilog-vcs-1
808 "\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
809 (verilog-vcs-2
810 "Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
811 (verilog-vcs-3
812 "\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
813 (verilog-vcs-4
814 "syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
815 (verilog-verilator
816 "%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
817 (verilog-leda
818 "^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 2)
819 )
820 "List of regexps for Verilog compilers.
821 See `compilation-error-regexp-alist' for the formatting. For Emacs 22+.")
822
823 (defvar verilog-error-regexp-xemacs-alist
824 ;; Emacs form is '((v-tool "re" 1 2) ...)
825 ;; XEmacs form is '(verilog ("re" 1 2) ...)
826 ;; So we can just map from Emacs to XEmacs
827 (cons 'verilog (mapcar 'cdr verilog-error-regexp-emacs-alist))
828 "List of regexps for Verilog compilers.
829 See `compilation-error-regexp-alist-alist' for the formatting. For XEmacs.")
830
831 (defvar verilog-error-font-lock-keywords
832 '(
833 ;; verilog-xl-1
834 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
835 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
836 ;; verilog-xl-2
837 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 bold t)
838 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 3 bold t)
839 ;; verilog-IES (nc-verilog)
840 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
841 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 3 bold t)
842 ;; verilog-surefire-1
843 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
844 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
845 ;; verilog-surefire-2
846 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
847 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
848 ;; verilog-verbose
849 ("\
850 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
851 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
852 ("\
853 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
854 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
855 ;; verilog-vcs-1
856 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
857 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
858 ;; verilog-vcs-2
859 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
860 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
861 ;; verilog-vcs-3
862 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
863 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
864 ;; verilog-vcs-4
865 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
866 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
867 ;; verilog-verilator
868 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
869 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
870 ;; verilog-leda
871 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 bold t)
872 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 2 bold t)
873 )
874 "Keywords to also highlight in Verilog *compilation* buffers.
875 Only used in XEmacs; GNU Emacs uses `verilog-error-regexp-emacs-alist'.")
876
877 (defcustom verilog-library-flags '("")
878 "List of standard Verilog arguments to use for /*AUTOINST*/.
879 These arguments are used to find files for `verilog-auto', and match
880 the flags accepted by a standard Verilog-XL simulator.
881
882 -f filename Reads more `verilog-library-flags' from the filename.
883 +incdir+dir Adds the directory to `verilog-library-directories'.
884 -Idir Adds the directory to `verilog-library-directories'.
885 -y dir Adds the directory to `verilog-library-directories'.
886 +libext+.v Adds the extensions to `verilog-library-extensions'.
887 -v filename Adds the filename to `verilog-library-files'.
888
889 filename Adds the filename to `verilog-library-files'.
890 This is not recommended, -v is a better choice.
891
892 You might want these defined in each file; put at the *END* of your file
893 something like:
894
895 // Local Variables:
896 // verilog-library-flags:(\"-y dir -y otherdir\")
897 // End:
898
899 Verilog-mode attempts to detect changes to this local variable, but they
900 are only insured to be correct when the file is first visited. Thus if you
901 have problems, use \\[find-alternate-file] RET to have these take effect.
902
903 See also the variables mentioned above."
904 :group 'verilog-mode-auto
905 :type '(repeat string))
906 (put 'verilog-library-flags 'safe-local-variable 'listp)
907
908 (defcustom verilog-library-directories '(".")
909 "List of directories when looking for files for /*AUTOINST*/.
910 The directory may be relative to the current file, or absolute.
911 Environment variables are also expanded in the directory names.
912 Having at least the current directory is a good idea.
913
914 You might want these defined in each file; put at the *END* of your file
915 something like:
916
917 // Local Variables:
918 // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
919 // End:
920
921 Verilog-mode attempts to detect changes to this local variable, but they
922 are only insured to be correct when the file is first visited. Thus if you
923 have problems, use \\[find-alternate-file] RET to have these take effect.
924
925 See also `verilog-library-flags', `verilog-library-files'
926 and `verilog-library-extensions'."
927 :group 'verilog-mode-auto
928 :type '(repeat file))
929 (put 'verilog-library-directories 'safe-local-variable 'listp)
930
931 (defcustom verilog-library-files '()
932 "List of files to search for modules.
933 AUTOINST will use this when it needs to resolve a module name.
934 This is a complete path, usually to a technology file with many standard
935 cells defined in it.
936
937 You might want these defined in each file; put at the *END* of your file
938 something like:
939
940 // Local Variables:
941 // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
942 // End:
943
944 Verilog-mode attempts to detect changes to this local variable, but they
945 are only insured to be correct when the file is first visited. Thus if you
946 have problems, use \\[find-alternate-file] RET to have these take effect.
947
948 See also `verilog-library-flags', `verilog-library-directories'."
949 :group 'verilog-mode-auto
950 :type '(repeat directory))
951 (put 'verilog-library-files 'safe-local-variable 'listp)
952
953 (defcustom verilog-library-extensions '(".v" ".sv")
954 "List of extensions to use when looking for files for /*AUTOINST*/.
955 See also `verilog-library-flags', `verilog-library-directories'."
956 :type '(repeat string)
957 :group 'verilog-mode-auto)
958 (put 'verilog-library-extensions 'safe-local-variable 'listp)
959
960 (defcustom verilog-active-low-regexp nil
961 "If true, treat signals matching this regexp as active low.
962 This is used for AUTORESET and AUTOTIEOFF. For proper behavior,
963 you will probably also need `verilog-auto-reset-widths' set."
964 :group 'verilog-mode-auto
965 :type '(choice (const nil) regexp))
966 (put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
967
968 (defcustom verilog-auto-sense-include-inputs nil
969 "Non-nil means AUTOSENSE should include all inputs.
970 If nil, only inputs that are NOT output signals in the same block are
971 included."
972 :group 'verilog-mode-auto
973 :type 'boolean)
974 (put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
975
976 (defcustom verilog-auto-sense-defines-constant nil
977 "Non-nil means AUTOSENSE should assume all defines represent constants.
978 When true, the defines will not be included in sensitivity lists. To
979 maintain compatibility with other sites, this should be set at the bottom
980 of each Verilog file that requires it, rather than being set globally."
981 :group 'verilog-mode-auto
982 :type 'boolean)
983 (put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
984
985 (defcustom verilog-auto-reset-blocking-in-non t
986 "Non-nil means AUTORESET will reset blocking statements.
987 When true, AUTORESET will reset in blocking statements those
988 signals which were assigned with blocking assignments (=) even in
989 a block with non-blocking assignments (<=).
990
991 If nil, all blocking assigned signals are ignored when any
992 non-blocking assignment is in the AUTORESET block. This allows
993 blocking assignments to be used for temporary values and not have
994 those temporaries reset. See example in `verilog-auto-reset'."
995 :version "24.1" ;; rev718
996 :type 'boolean
997 :group 'verilog-mode-auto)
998 (put 'verilog-auto-reset-blocking-in-non 'safe-local-variable 'verilog-booleanp)
999
1000 (defcustom verilog-auto-reset-widths t
1001 "True means AUTORESET should determine the width of signals.
1002 This is then used to set the width of the zero (32'h0 for example). This
1003 is required by some lint tools that aren't smart enough to ignore widths of
1004 the constant zero. This may result in ugly code when parameters determine
1005 the MSB or LSB of a signal inside an AUTORESET.
1006
1007 If nil, AUTORESET uses \"0\" as the constant.
1008
1009 If 'unbased', AUTORESET used the unbased unsized literal \"'0\"
1010 as the constant. This setting is strongly recommended for
1011 SystemVerilog designs."
1012 :type 'boolean
1013 :group 'verilog-mode-auto)
1014 (put 'verilog-auto-reset-widths 'safe-local-variable
1015 '(lambda (x) (memq x '(nil t unbased))))
1016
1017 (defcustom verilog-assignment-delay ""
1018 "Text used for delays in delayed assignments. Add a trailing space if set."
1019 :group 'verilog-mode-auto
1020 :type 'string)
1021 (put 'verilog-assignment-delay 'safe-local-variable 'stringp)
1022
1023 (defcustom verilog-auto-arg-format 'packed
1024 "Formatting to use for AUTOARG signal names.
1025 If 'packed', then as many inputs and outputs that fit within
1026 `fill-column' will be put onto one line.
1027
1028 If 'single', then a single input or output will be put onto each
1029 line."
1030 :version "25.1"
1031 :type '(radio (const :tag "Line up Assignments and Declarations" packed)
1032 (const :tag "Line up Assignment statements" single))
1033 :group 'verilog-mode-auto)
1034 (put 'verilog-auto-arg-format 'safe-local-variable
1035 '(lambda (x) (memq x '(packed single))))
1036
1037 (defcustom verilog-auto-arg-sort nil
1038 "Non-nil means AUTOARG signal names will be sorted, not in declaration order.
1039 Declaration order is advantageous with order based instantiations
1040 and is the default for backward compatibility. Sorted order
1041 reduces changes when declarations are moved around in a file, and
1042 it's bad practice to rely on order based instantiations anyhow.
1043
1044 See also `verilog-auto-inst-sort'."
1045 :group 'verilog-mode-auto
1046 :type 'boolean)
1047 (put 'verilog-auto-arg-sort 'safe-local-variable 'verilog-booleanp)
1048
1049 (defcustom verilog-auto-inst-dot-name nil
1050 "Non-nil means when creating ports with AUTOINST, use .name syntax.
1051 This will use \".port\" instead of \".port(port)\" when possible.
1052 This is only legal in SystemVerilog files, and will confuse older
1053 simulators. Setting `verilog-auto-inst-vector' to nil may also
1054 be desirable to increase how often .name will be used."
1055 :group 'verilog-mode-auto
1056 :type 'boolean)
1057 (put 'verilog-auto-inst-dot-name 'safe-local-variable 'verilog-booleanp)
1058
1059 (defcustom verilog-auto-inst-param-value nil
1060 "Non-nil means AUTOINST will replace parameters with the parameter value.
1061 If nil, leave parameters as symbolic names.
1062
1063 Parameters must be in Verilog 2001 format #(...), and if a parameter is not
1064 listed as such there (as when the default value is acceptable), it will not
1065 be replaced, and will remain symbolic.
1066
1067 For example, imagine a submodule uses parameters to declare the size of its
1068 inputs. This is then used by an upper module:
1069
1070 module InstModule (o,i);
1071 parameter WIDTH;
1072 input [WIDTH-1:0] i;
1073 endmodule
1074
1075 module ExampInst;
1076 InstModule
1077 #(.PARAM(10))
1078 instName
1079 (/*AUTOINST*/
1080 .i (i[PARAM-1:0]));
1081
1082 Note even though PARAM=10, the AUTOINST has left the parameter as a
1083 symbolic name. If `verilog-auto-inst-param-value' is set, this will
1084 instead expand to:
1085
1086 module ExampInst;
1087 InstModule
1088 #(.PARAM(10))
1089 instName
1090 (/*AUTOINST*/
1091 .i (i[9:0]));"
1092 :group 'verilog-mode-auto
1093 :type 'boolean)
1094 (put 'verilog-auto-inst-param-value 'safe-local-variable 'verilog-booleanp)
1095
1096 (defcustom verilog-auto-inst-sort nil
1097 "Non-nil means AUTOINST signals will be sorted, not in declaration order.
1098 Also affects AUTOINSTPARAM. Declaration order is the default for
1099 backward compatibility, and as some teams prefer signals that are
1100 declared together to remain together. Sorted order reduces
1101 changes when declarations are moved around in a file.
1102
1103 See also `verilog-auto-arg-sort'."
1104 :version "24.1" ;; rev688
1105 :group 'verilog-mode-auto
1106 :type 'boolean)
1107 (put 'verilog-auto-inst-sort 'safe-local-variable 'verilog-booleanp)
1108
1109 (defcustom verilog-auto-inst-vector t
1110 "Non-nil means when creating default ports with AUTOINST, use bus subscripts.
1111 If nil, skip the subscript when it matches the entire bus as declared in
1112 the module (AUTOWIRE signals always are subscripted, you must manually
1113 declare the wire to have the subscripts removed.) Setting this to nil may
1114 speed up some simulators, but is less general and harder to read, so avoid."
1115 :group 'verilog-mode-auto
1116 :type 'boolean)
1117 (put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
1118
1119 (defcustom verilog-auto-inst-template-numbers nil
1120 "If true, when creating templated ports with AUTOINST, add a comment.
1121
1122 If t, the comment will add the line number of the template that
1123 was used for that port declaration. This setting is suggested
1124 only for debugging use, as regular use may cause a large numbers
1125 of merge conflicts.
1126
1127 If 'lhs', the comment will show the left hand side of the
1128 AUTO_TEMPLATE rule that is matched. This is less precise than
1129 numbering (t) when multiple rules have the same pin name, but
1130 won't merge conflict."
1131 :group 'verilog-mode-auto
1132 :type '(choice (const nil) (const t) (const lhs)))
1133 (put 'verilog-auto-inst-template-numbers 'safe-local-variable
1134 '(lambda (x) (memq x '(nil t lhs))))
1135
1136 (defcustom verilog-auto-inst-column 40
1137 "Indent-to column number for net name part of AUTOINST created pin."
1138 :group 'verilog-mode-indent
1139 :type 'integer)
1140 (put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
1141
1142 (defcustom verilog-auto-inst-interfaced-ports nil
1143 "Non-nil means include interfaced ports in AUTOINST expansions."
1144 :version "24.3" ;; rev773, default change rev815
1145 :group 'verilog-mode-auto
1146 :type 'boolean)
1147 (put 'verilog-auto-inst-interfaced-ports 'safe-local-variable 'verilog-booleanp)
1148
1149 (defcustom verilog-auto-input-ignore-regexp nil
1150 "If non-nil, when creating AUTOINPUT, ignore signals matching this regexp.
1151 See the \\[verilog-faq] for examples on using this."
1152 :group 'verilog-mode-auto
1153 :type '(choice (const nil) regexp))
1154 (put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
1155
1156 (defcustom verilog-auto-inout-ignore-regexp nil
1157 "If non-nil, when creating AUTOINOUT, ignore signals matching this regexp.
1158 See the \\[verilog-faq] for examples on using this."
1159 :group 'verilog-mode-auto
1160 :type '(choice (const nil) regexp))
1161 (put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
1162
1163 (defcustom verilog-auto-output-ignore-regexp nil
1164 "If non-nil, when creating AUTOOUTPUT, ignore signals matching this regexp.
1165 See the \\[verilog-faq] for examples on using this."
1166 :group 'verilog-mode-auto
1167 :type '(choice (const nil) regexp))
1168 (put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
1169
1170 (defcustom verilog-auto-template-warn-unused nil
1171 "Non-nil means report warning if an AUTO_TEMPLATE line is not used.
1172 This feature is not supported before Emacs 21.1 or XEmacs 21.4."
1173 :version "24.3" ;;rev787
1174 :group 'verilog-mode-auto
1175 :type 'boolean)
1176 (put 'verilog-auto-template-warn-unused 'safe-local-variable 'verilog-booleanp)
1177
1178 (defcustom verilog-auto-tieoff-declaration "wire"
1179 "Data type used for the declaration for AUTOTIEOFF.
1180 If \"wire\" then create a wire, if \"assign\" create an
1181 assignment, else the data type for variable creation."
1182 :version "24.1" ;; rev713
1183 :group 'verilog-mode-auto
1184 :type 'string)
1185 (put 'verilog-auto-tieoff-declaration 'safe-local-variable 'stringp)
1186
1187 (defcustom verilog-auto-tieoff-ignore-regexp nil
1188 "If non-nil, when creating AUTOTIEOFF, ignore signals matching this regexp.
1189 See the \\[verilog-faq] for examples on using this."
1190 :group 'verilog-mode-auto
1191 :type '(choice (const nil) regexp))
1192 (put 'verilog-auto-tieoff-ignore-regexp 'safe-local-variable 'stringp)
1193
1194 (defcustom verilog-auto-unused-ignore-regexp nil
1195 "If non-nil, when creating AUTOUNUSED, ignore signals matching this regexp.
1196 See the \\[verilog-faq] for examples on using this."
1197 :group 'verilog-mode-auto
1198 :type '(choice (const nil) regexp))
1199 (put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
1200
1201 (defcustom verilog-case-fold t
1202 "Non-nil means `verilog-mode' regexps should ignore case.
1203 This variable is t for backward compatibility; nil is suggested."
1204 :version "24.4"
1205 :group 'verilog-mode
1206 :type 'boolean)
1207 (put 'verilog-case-fold 'safe-local-variable 'verilog-booleanp)
1208
1209 (defcustom verilog-typedef-regexp nil
1210 "If non-nil, regular expression that matches Verilog-2001 typedef names.
1211 For example, \"_t$\" matches typedefs named with _t, as in the C language.
1212 See also `verilog-case-fold'."
1213 :group 'verilog-mode-auto
1214 :type '(choice (const nil) regexp))
1215 (put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
1216
1217 (defcustom verilog-mode-hook 'verilog-set-compile-command
1218 "Hook run after Verilog mode is loaded."
1219 :type 'hook
1220 :group 'verilog-mode)
1221
1222 (defcustom verilog-auto-hook nil
1223 "Hook run after `verilog-mode' updates AUTOs."
1224 :group 'verilog-mode-auto
1225 :type 'hook)
1226
1227 (defcustom verilog-before-auto-hook nil
1228 "Hook run before `verilog-mode' updates AUTOs."
1229 :group 'verilog-mode-auto
1230 :type 'hook)
1231
1232 (defcustom verilog-delete-auto-hook nil
1233 "Hook run after `verilog-mode' deletes AUTOs."
1234 :group 'verilog-mode-auto
1235 :type 'hook)
1236
1237 (defcustom verilog-before-delete-auto-hook nil
1238 "Hook run before `verilog-mode' deletes AUTOs."
1239 :group 'verilog-mode-auto
1240 :type 'hook)
1241
1242 (defcustom verilog-getopt-flags-hook nil
1243 "Hook run after `verilog-getopt-flags' determines the Verilog option lists."
1244 :group 'verilog-mode-auto
1245 :type 'hook)
1246
1247 (defcustom verilog-before-getopt-flags-hook nil
1248 "Hook run before `verilog-getopt-flags' determines the Verilog option lists."
1249 :group 'verilog-mode-auto
1250 :type 'hook)
1251
1252 (defcustom verilog-before-save-font-hook nil
1253 "Hook run before `verilog-save-font-mods' removes highlighting."
1254 :version "24.3" ;;rev735
1255 :group 'verilog-mode-auto
1256 :type 'hook)
1257
1258 (defcustom verilog-after-save-font-hook nil
1259 "Hook run after `verilog-save-font-mods' restores highlighting."
1260 :version "24.3" ;;rev735
1261 :group 'verilog-mode-auto
1262 :type 'hook)
1263
1264 (defvar verilog-imenu-generic-expression
1265 '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
1266 ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
1267 "Imenu expression for Verilog mode. See `imenu-generic-expression'.")
1268
1269 ;;
1270 ;; provide a verilog-header function.
1271 ;; Customization variables:
1272 ;;
1273 (defvar verilog-date-scientific-format nil
1274 "If non-nil, dates are written in scientific format (e.g. 1997/09/17).
1275 If nil, in European format (e.g. 17.09.1997). The brain-dead American
1276 format (e.g. 09/17/1997) is not supported.")
1277
1278 (defvar verilog-company nil
1279 "Default name of Company for Verilog header.
1280 If set will become buffer local.")
1281 (make-variable-buffer-local 'verilog-company)
1282
1283 (defvar verilog-project nil
1284 "Default name of Project for Verilog header.
1285 If set will become buffer local.")
1286 (make-variable-buffer-local 'verilog-project)
1287
1288 (defvar verilog-mode-map
1289 (let ((map (make-sparse-keymap)))
1290 (define-key map ";" 'electric-verilog-semi)
1291 (define-key map [(control 59)] 'electric-verilog-semi-with-comment)
1292 (define-key map ":" 'electric-verilog-colon)
1293 ;;(define-key map "=" 'electric-verilog-equal)
1294 (define-key map "\`" 'electric-verilog-tick)
1295 (define-key map "\t" 'electric-verilog-tab)
1296 (define-key map "\r" 'electric-verilog-terminate-line)
1297 ;; backspace/delete key bindings
1298 (define-key map [backspace] 'backward-delete-char-untabify)
1299 (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
1300 (define-key map [delete] 'delete-char)
1301 (define-key map [(meta delete)] 'kill-word))
1302 (define-key map "\M-\C-b" 'electric-verilog-backward-sexp)
1303 (define-key map "\M-\C-f" 'electric-verilog-forward-sexp)
1304 (define-key map "\M-\r" `electric-verilog-terminate-and-indent)
1305 (define-key map "\M-\t" 'verilog-complete-word)
1306 (define-key map "\M-?" 'verilog-show-completions)
1307 ;; Note \C-c and letter are reserved for users
1308 (define-key map "\C-c\`" 'verilog-lint-off)
1309 (define-key map "\C-c\*" 'verilog-delete-auto-star-implicit)
1310 (define-key map "\C-c\?" 'verilog-diff-auto)
1311 (define-key map "\C-c\C-r" 'verilog-label-be)
1312 (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
1313 (define-key map "\C-c=" 'verilog-pretty-expr)
1314 (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
1315 (define-key map "\M-*" 'verilog-star-comment)
1316 (define-key map "\C-c\C-c" 'verilog-comment-region)
1317 (define-key map "\C-c\C-u" 'verilog-uncomment-region)
1318 (when (featurep 'xemacs)
1319 (define-key map [(meta control h)] 'verilog-mark-defun)
1320 (define-key map "\M-\C-a" 'verilog-beg-of-defun)
1321 (define-key map "\M-\C-e" 'verilog-end-of-defun))
1322 (define-key map "\C-c\C-d" 'verilog-goto-defun)
1323 (define-key map "\C-c\C-k" 'verilog-delete-auto)
1324 (define-key map "\C-c\C-a" 'verilog-auto)
1325 (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
1326 (define-key map "\C-c\C-p" 'verilog-preprocess)
1327 (define-key map "\C-c\C-z" 'verilog-inject-auto)
1328 (define-key map "\C-c\C-e" 'verilog-expand-vector)
1329 (define-key map "\C-c\C-h" 'verilog-header)
1330 map)
1331 "Keymap used in Verilog mode.")
1332
1333 ;; menus
1334 (easy-menu-define
1335 verilog-menu verilog-mode-map "Menu for Verilog mode"
1336 (verilog-easy-menu-filter
1337 '("Verilog"
1338 ("Choose Compilation Action"
1339 ["None"
1340 (progn
1341 (setq verilog-tool nil)
1342 (verilog-set-compile-command))
1343 :style radio
1344 :selected (equal verilog-tool nil)
1345 :help "When invoking compilation, use compile-command"]
1346 ["Lint"
1347 (progn
1348 (setq verilog-tool 'verilog-linter)
1349 (verilog-set-compile-command))
1350 :style radio
1351 :selected (equal verilog-tool `verilog-linter)
1352 :help "When invoking compilation, use lint checker"]
1353 ["Coverage"
1354 (progn
1355 (setq verilog-tool 'verilog-coverage)
1356 (verilog-set-compile-command))
1357 :style radio
1358 :selected (equal verilog-tool `verilog-coverage)
1359 :help "When invoking compilation, annotate for coverage"]
1360 ["Simulator"
1361 (progn
1362 (setq verilog-tool 'verilog-simulator)
1363 (verilog-set-compile-command))
1364 :style radio
1365 :selected (equal verilog-tool `verilog-simulator)
1366 :help "When invoking compilation, interpret Verilog source"]
1367 ["Compiler"
1368 (progn
1369 (setq verilog-tool 'verilog-compiler)
1370 (verilog-set-compile-command))
1371 :style radio
1372 :selected (equal verilog-tool `verilog-compiler)
1373 :help "When invoking compilation, compile Verilog source"]
1374 ["Preprocessor"
1375 (progn
1376 (setq verilog-tool 'verilog-preprocessor)
1377 (verilog-set-compile-command))
1378 :style radio
1379 :selected (equal verilog-tool `verilog-preprocessor)
1380 :help "When invoking compilation, preprocess Verilog source, see also `verilog-preprocess'"]
1381 )
1382 ("Move"
1383 ["Beginning of function" verilog-beg-of-defun
1384 :keys "C-M-a"
1385 :help "Move backward to the beginning of the current function or procedure"]
1386 ["End of function" verilog-end-of-defun
1387 :keys "C-M-e"
1388 :help "Move forward to the end of the current function or procedure"]
1389 ["Mark function" verilog-mark-defun
1390 :keys "C-M-h"
1391 :help "Mark the current Verilog function or procedure"]
1392 ["Goto function/module" verilog-goto-defun
1393 :help "Move to specified Verilog module/task/function"]
1394 ["Move to beginning of block" electric-verilog-backward-sexp
1395 :help "Move backward over one balanced expression"]
1396 ["Move to end of block" electric-verilog-forward-sexp
1397 :help "Move forward over one balanced expression"]
1398 )
1399 ("Comments"
1400 ["Comment Region" verilog-comment-region
1401 :help "Put marked area into a comment"]
1402 ["UnComment Region" verilog-uncomment-region
1403 :help "Uncomment an area commented with Comment Region"]
1404 ["Multi-line comment insert" verilog-star-comment
1405 :help "Insert Verilog /* */ comment at point"]
1406 ["Lint error to comment" verilog-lint-off
1407 :help "Convert a Verilog linter warning line into a disable statement"]
1408 )
1409 "----"
1410 ["Compile" compile
1411 :help "Perform compilation-action (above) on the current buffer"]
1412 ["AUTO, Save, Compile" verilog-auto-save-compile
1413 :help "Recompute AUTOs, save buffer, and compile"]
1414 ["Next Compile Error" next-error
1415 :help "Visit next compilation error message and corresponding source code"]
1416 ["Ignore Lint Warning at point" verilog-lint-off
1417 :help "Convert a Verilog linter warning line into a disable statement"]
1418 "----"
1419 ["Line up declarations around point" verilog-pretty-declarations
1420 :help "Line up declarations around point"]
1421 ["Line up equations around point" verilog-pretty-expr
1422 :help "Line up expressions around point"]
1423 ["Redo/insert comments on every end" verilog-label-be
1424 :help "Label matching begin ... end statements"]
1425 ["Expand [x:y] vector line" verilog-expand-vector
1426 :help "Take a signal vector on the current line and expand it to multiple lines"]
1427 ["Insert begin-end block" verilog-insert-block
1428 :help "Insert begin ... end"]
1429 ["Complete word" verilog-complete-word
1430 :help "Complete word at point"]
1431 "----"
1432 ["Recompute AUTOs" verilog-auto
1433 :help "Expand AUTO meta-comment statements"]
1434 ["Kill AUTOs" verilog-delete-auto
1435 :help "Remove AUTO expansions"]
1436 ["Diff AUTOs" verilog-diff-auto
1437 :help "Show differences in AUTO expansions"]
1438 ["Inject AUTOs" verilog-inject-auto
1439 :help "Inject AUTOs into legacy non-AUTO buffer"]
1440 ("AUTO Help..."
1441 ["AUTO General" (describe-function 'verilog-auto)
1442 :help "Help introduction on AUTOs"]
1443 ["AUTO Library Flags" (describe-variable 'verilog-library-flags)
1444 :help "Help on verilog-library-flags"]
1445 ["AUTO Library Path" (describe-variable 'verilog-library-directories)
1446 :help "Help on verilog-library-directories"]
1447 ["AUTO Library Files" (describe-variable 'verilog-library-files)
1448 :help "Help on verilog-library-files"]
1449 ["AUTO Library Extensions" (describe-variable 'verilog-library-extensions)
1450 :help "Help on verilog-library-extensions"]
1451 ["AUTO `define Reading" (describe-function 'verilog-read-defines)
1452 :help "Help on reading `defines"]
1453 ["AUTO `include Reading" (describe-function 'verilog-read-includes)
1454 :help "Help on parsing `includes"]
1455 ["AUTOARG" (describe-function 'verilog-auto-arg)
1456 :help "Help on AUTOARG - declaring module port list"]
1457 ["AUTOASCIIENUM" (describe-function 'verilog-auto-ascii-enum)
1458 :help "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
1459 ["AUTOASSIGNMODPORT" (describe-function 'verilog-auto-assign-modport)
1460 :help "Help on AUTOASSIGNMODPORT - creating assignments to/from modports"]
1461 ["AUTOINOUT" (describe-function 'verilog-auto-inout)
1462 :help "Help on AUTOINOUT - adding inouts from cells"]
1463 ["AUTOINOUTCOMP" (describe-function 'verilog-auto-inout-comp)
1464 :help "Help on AUTOINOUTCOMP - copying complemented i/o from another file"]
1465 ["AUTOINOUTIN" (describe-function 'verilog-auto-inout-in)
1466 :help "Help on AUTOINOUTIN - copying i/o from another file as all inputs"]
1467 ["AUTOINOUTMODPORT" (describe-function 'verilog-auto-inout-modport)
1468 :help "Help on AUTOINOUTMODPORT - copying i/o from an interface modport"]
1469 ["AUTOINOUTMODULE" (describe-function 'verilog-auto-inout-module)
1470 :help "Help on AUTOINOUTMODULE - copying i/o from another file"]
1471 ["AUTOINOUTPARAM" (describe-function 'verilog-auto-inout-param)
1472 :help "Help on AUTOINOUTPARAM - copying parameters from another file"]
1473 ["AUTOINPUT" (describe-function 'verilog-auto-input)
1474 :help "Help on AUTOINPUT - adding inputs from cells"]
1475 ["AUTOINSERTLISP" (describe-function 'verilog-auto-insert-lisp)
1476 :help "Help on AUTOINSERTLISP - insert text from a lisp function"]
1477 ["AUTOINSERTLAST" (describe-function 'verilog-auto-insert-last)
1478 :help "Help on AUTOINSERTLISPLAST - insert text from a lisp function"]
1479 ["AUTOINST" (describe-function 'verilog-auto-inst)
1480 :help "Help on AUTOINST - adding pins for cells"]
1481 ["AUTOINST (.*)" (describe-function 'verilog-auto-star)
1482 :help "Help on expanding Verilog-2001 .* pins"]
1483 ["AUTOINSTPARAM" (describe-function 'verilog-auto-inst-param)
1484 :help "Help on AUTOINSTPARAM - adding parameter pins to cells"]
1485 ["AUTOLOGIC" (describe-function 'verilog-auto-logic)
1486 :help "Help on AUTOLOGIC - declaring logic signals"]
1487 ["AUTOOUTPUT" (describe-function 'verilog-auto-output)
1488 :help "Help on AUTOOUTPUT - adding outputs from cells"]
1489 ["AUTOOUTPUTEVERY" (describe-function 'verilog-auto-output-every)
1490 :help "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
1491 ["AUTOREG" (describe-function 'verilog-auto-reg)
1492 :help "Help on AUTOREG - declaring registers for non-wires"]
1493 ["AUTOREGINPUT" (describe-function 'verilog-auto-reg-input)
1494 :help "Help on AUTOREGINPUT - declaring inputs for non-wires"]
1495 ["AUTORESET" (describe-function 'verilog-auto-reset)
1496 :help "Help on AUTORESET - resetting always blocks"]
1497 ["AUTOSENSE or AS" (describe-function 'verilog-auto-sense)
1498 :help "Help on AUTOSENSE - sensitivity lists for always blocks"]
1499 ["AUTOTIEOFF" (describe-function 'verilog-auto-tieoff)
1500 :help "Help on AUTOTIEOFF - tying off unused outputs"]
1501 ["AUTOUNDEF" (describe-function 'verilog-auto-undef)
1502 :help "Help on AUTOUNDEF - undefine all local defines"]
1503 ["AUTOUNUSED" (describe-function 'verilog-auto-unused)
1504 :help "Help on AUTOUNUSED - terminating unused inputs"]
1505 ["AUTOWIRE" (describe-function 'verilog-auto-wire)
1506 :help "Help on AUTOWIRE - declaring wires for cells"]
1507 )
1508 "----"
1509 ["Submit bug report" verilog-submit-bug-report
1510 :help "Submit via mail a bug report on verilog-mode.el"]
1511 ["Version and FAQ" verilog-faq
1512 :help "Show the current version, and where to get the FAQ etc"]
1513 ["Customize Verilog Mode..." verilog-customize
1514 :help "Customize variables and other settings used by Verilog-Mode"]
1515 ["Customize Verilog Fonts & Colors" verilog-font-customize
1516 :help "Customize fonts used by Verilog-Mode."])))
1517
1518 (easy-menu-define
1519 verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
1520 (verilog-easy-menu-filter
1521 '("Statements"
1522 ["Header" verilog-sk-header
1523 :help "Insert a header block at the top of file"]
1524 ["Comment" verilog-sk-comment
1525 :help "Insert a comment block"]
1526 "----"
1527 ["Module" verilog-sk-module
1528 :help "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
1529 ["OVM Class" verilog-sk-ovm-class
1530 :help "Insert an OVM class block"]
1531 ["UVM Object" verilog-sk-uvm-object
1532 :help "Insert an UVM object block"]
1533 ["UVM Component" verilog-sk-uvm-component
1534 :help "Insert an UVM component block"]
1535 ["Primitive" verilog-sk-primitive
1536 :help "Insert a primitive .. (.. );.. endprimitive block"]
1537 "----"
1538 ["Input" verilog-sk-input
1539 :help "Insert an input declaration"]
1540 ["Output" verilog-sk-output
1541 :help "Insert an output declaration"]
1542 ["Inout" verilog-sk-inout
1543 :help "Insert an inout declaration"]
1544 ["Wire" verilog-sk-wire
1545 :help "Insert a wire declaration"]
1546 ["Reg" verilog-sk-reg
1547 :help "Insert a register declaration"]
1548 ["Define thing under point as a register" verilog-sk-define-signal
1549 :help "Define signal under point as a register at the top of the module"]
1550 "----"
1551 ["Initial" verilog-sk-initial
1552 :help "Insert an initial begin .. end block"]
1553 ["Always" verilog-sk-always
1554 :help "Insert an always @(AS) begin .. end block"]
1555 ["Function" verilog-sk-function
1556 :help "Insert a function .. begin .. end endfunction block"]
1557 ["Task" verilog-sk-task
1558 :help "Insert a task .. begin .. end endtask block"]
1559 ["Specify" verilog-sk-specify
1560 :help "Insert a specify .. endspecify block"]
1561 ["Generate" verilog-sk-generate
1562 :help "Insert a generate .. endgenerate block"]
1563 "----"
1564 ["Begin" verilog-sk-begin
1565 :help "Insert a begin .. end block"]
1566 ["If" verilog-sk-if
1567 :help "Insert an if (..) begin .. end block"]
1568 ["(if) else" verilog-sk-else-if
1569 :help "Insert an else if (..) begin .. end block"]
1570 ["For" verilog-sk-for
1571 :help "Insert a for (...) begin .. end block"]
1572 ["While" verilog-sk-while
1573 :help "Insert a while (...) begin .. end block"]
1574 ["Fork" verilog-sk-fork
1575 :help "Insert a fork begin .. end .. join block"]
1576 ["Repeat" verilog-sk-repeat
1577 :help "Insert a repeat (..) begin .. end block"]
1578 ["Case" verilog-sk-case
1579 :help "Insert a case block, prompting for details"]
1580 ["Casex" verilog-sk-casex
1581 :help "Insert a casex (...) item: begin.. end endcase block"]
1582 ["Casez" verilog-sk-casez
1583 :help "Insert a casez (...) item: begin.. end endcase block"])))
1584
1585 (defvar verilog-mode-abbrev-table nil
1586 "Abbrev table in use in Verilog-mode buffers.")
1587
1588 (define-abbrev-table 'verilog-mode-abbrev-table ())
1589 (verilog-define-abbrev verilog-mode-abbrev-table "class" "" 'verilog-sk-ovm-class)
1590 (verilog-define-abbrev verilog-mode-abbrev-table "always" "" 'verilog-sk-always)
1591 (verilog-define-abbrev verilog-mode-abbrev-table "begin" nil `verilog-sk-begin)
1592 (verilog-define-abbrev verilog-mode-abbrev-table "case" "" `verilog-sk-case)
1593 (verilog-define-abbrev verilog-mode-abbrev-table "for" "" `verilog-sk-for)
1594 (verilog-define-abbrev verilog-mode-abbrev-table "generate" "" `verilog-sk-generate)
1595 (verilog-define-abbrev verilog-mode-abbrev-table "initial" "" `verilog-sk-initial)
1596 (verilog-define-abbrev verilog-mode-abbrev-table "fork" "" `verilog-sk-fork)
1597 (verilog-define-abbrev verilog-mode-abbrev-table "module" "" `verilog-sk-module)
1598 (verilog-define-abbrev verilog-mode-abbrev-table "primitive" "" `verilog-sk-primitive)
1599 (verilog-define-abbrev verilog-mode-abbrev-table "repeat" "" `verilog-sk-repeat)
1600 (verilog-define-abbrev verilog-mode-abbrev-table "specify" "" `verilog-sk-specify)
1601 (verilog-define-abbrev verilog-mode-abbrev-table "task" "" `verilog-sk-task)
1602 (verilog-define-abbrev verilog-mode-abbrev-table "while" "" `verilog-sk-while)
1603 (verilog-define-abbrev verilog-mode-abbrev-table "casex" "" `verilog-sk-casex)
1604 (verilog-define-abbrev verilog-mode-abbrev-table "casez" "" `verilog-sk-casez)
1605 (verilog-define-abbrev verilog-mode-abbrev-table "if" "" `verilog-sk-if)
1606 (verilog-define-abbrev verilog-mode-abbrev-table "else if" "" `verilog-sk-else-if)
1607 (verilog-define-abbrev verilog-mode-abbrev-table "assign" "" `verilog-sk-assign)
1608 (verilog-define-abbrev verilog-mode-abbrev-table "function" "" `verilog-sk-function)
1609 (verilog-define-abbrev verilog-mode-abbrev-table "input" "" `verilog-sk-input)
1610 (verilog-define-abbrev verilog-mode-abbrev-table "output" "" `verilog-sk-output)
1611 (verilog-define-abbrev verilog-mode-abbrev-table "inout" "" `verilog-sk-inout)
1612 (verilog-define-abbrev verilog-mode-abbrev-table "wire" "" `verilog-sk-wire)
1613 (verilog-define-abbrev verilog-mode-abbrev-table "reg" "" `verilog-sk-reg)
1614
1615 ;;
1616 ;; Macros
1617 ;;
1618
1619 (defsubst verilog-within-string ()
1620 (nth 3 (parse-partial-sexp (point-at-bol) (point))))
1621
1622 (defsubst verilog-string-match-fold (regexp string &optional start)
1623 "Like `string-match', but use `verilog-case-fold'.
1624 Return index of start of first match for REGEXP in STRING, or nil.
1625 Matching ignores case if `verilog-case-fold' is non-nil.
1626 If third arg START is non-nil, start search at that index in STRING."
1627 (let ((case-fold-search verilog-case-fold))
1628 (string-match regexp string start)))
1629
1630 (defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1631 "Replace occurrences of FROM-STRING with TO-STRING.
1632 FIXEDCASE and LITERAL as in `replace-match`. STRING is what to replace.
1633 The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1634 will break, as the o's continuously replace. xa -> x works ok though."
1635 ;; Hopefully soon to an Emacs built-in
1636 ;; Also note \ in the replacement prevent multiple replacements; IE
1637 ;; (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil "wire@_@")
1638 ;; Gives "wire\([0-9]+\)_@" not "wire\([0-9]+\)_\([0-9]+\)"
1639 (let ((start 0))
1640 (while (string-match from-string string start)
1641 (setq string (replace-match to-string fixedcase literal string)
1642 start (min (length string) (+ (match-beginning 0) (length to-string)))))
1643 string))
1644
1645 (defsubst verilog-string-remove-spaces (string)
1646 "Remove spaces surrounding STRING."
1647 (save-match-data
1648 (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1649 (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1650 string))
1651
1652 (defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1653 ;; checkdoc-params: (REGEXP BOUND NOERROR)
1654 "Like `re-search-forward', but skips over match in comments or strings."
1655 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1656 (while (and
1657 (re-search-forward REGEXP BOUND NOERROR)
1658 (setq mdata (match-data))
1659 (and (verilog-skip-forward-comment-or-string)
1660 (progn
1661 (setq mdata '(nil nil))
1662 (if BOUND
1663 (< (point) BOUND)
1664 t)))))
1665 (store-match-data mdata)
1666 (match-end 0)))
1667
1668 (defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1669 ;; checkdoc-params: (REGEXP BOUND NOERROR)
1670 "Like `re-search-backward', but skips over match in comments or strings."
1671 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1672 (while (and
1673 (re-search-backward REGEXP BOUND NOERROR)
1674 (setq mdata (match-data))
1675 (and (verilog-skip-backward-comment-or-string)
1676 (progn
1677 (setq mdata '(nil nil))
1678 (if BOUND
1679 (> (point) BOUND)
1680 t)))))
1681 (store-match-data mdata)
1682 (match-end 0)))
1683
1684 (defsubst verilog-re-search-forward-quick (regexp bound noerror)
1685 "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1686 but trashes match data and is faster for REGEXP that doesn't match often.
1687 This uses `verilog-scan' and text properties to ignore comments,
1688 so there may be a large up front penalty for the first search."
1689 (let (pt)
1690 (while (and (not pt)
1691 (re-search-forward regexp bound noerror))
1692 (if (verilog-inside-comment-or-string-p)
1693 (re-search-forward "[/\"\n]" nil t) ;; Only way a comment or quote can end
1694 (setq pt (match-end 0))))
1695 pt))
1696
1697 (defsubst verilog-re-search-backward-quick (regexp bound noerror)
1698 ;; checkdoc-params: (REGEXP BOUND NOERROR)
1699 "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1700 but trashes match data and is faster for REGEXP that doesn't match often.
1701 This uses `verilog-scan' and text properties to ignore comments,
1702 so there may be a large up front penalty for the first search."
1703 (let (pt)
1704 (while (and (not pt)
1705 (re-search-backward regexp bound noerror))
1706 (if (verilog-inside-comment-or-string-p)
1707 (re-search-backward "[/\"]" nil t) ;; Only way a comment or quote can begin
1708 (setq pt (match-beginning 0))))
1709 pt))
1710
1711 (defsubst verilog-re-search-forward-substr (substr regexp bound noerror)
1712 "Like `re-search-forward', but first search for SUBSTR constant.
1713 Then searched for the normal REGEXP (which contains SUBSTR), with given
1714 BOUND and NOERROR. The REGEXP must fit within a single line.
1715 This speeds up complicated regexp matches."
1716 ;; Problem with overlap: search-forward BAR then FOOBARBAZ won't match.
1717 ;; thus require matches to be on one line, and use beginning-of-line.
1718 (let (done)
1719 (while (and (not done)
1720 (search-forward substr bound noerror))
1721 (save-excursion
1722 (beginning-of-line)
1723 (setq done (re-search-forward regexp (point-at-eol) noerror)))
1724 (unless (and (<= (match-beginning 0) (point))
1725 (>= (match-end 0) (point)))
1726 (setq done nil)))
1727 (when done (goto-char done))
1728 done))
1729 ;;(verilog-re-search-forward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1730
1731 (defsubst verilog-re-search-backward-substr (substr regexp bound noerror)
1732 "Like `re-search-backward', but first search for SUBSTR constant.
1733 Then searched for the normal REGEXP (which contains SUBSTR), with given
1734 BOUND and NOERROR. The REGEXP must fit within a single line.
1735 This speeds up complicated regexp matches."
1736 ;; Problem with overlap: search-backward BAR then FOOBARBAZ won't match.
1737 ;; thus require matches to be on one line, and use beginning-of-line.
1738 (let (done)
1739 (while (and (not done)
1740 (search-backward substr bound noerror))
1741 (save-excursion
1742 (end-of-line)
1743 (setq done (re-search-backward regexp (point-at-bol) noerror)))
1744 (unless (and (<= (match-beginning 0) (point))
1745 (>= (match-end 0) (point)))
1746 (setq done nil)))
1747 (when done (goto-char done))
1748 done))
1749 ;;(verilog-re-search-backward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1750
1751 (defun verilog-delete-trailing-whitespace ()
1752 "Delete trailing spaces or tabs, but not newlines nor linefeeds.
1753 Also add missing final newline.
1754
1755 To call this from the command line, see \\[verilog-batch-diff-auto].
1756
1757 To call on \\[verilog-auto], set `verilog-auto-delete-trailing-whitespace'."
1758 ;; Similar to `delete-trailing-whitespace' but that's not present in XEmacs
1759 (save-excursion
1760 (goto-char (point-min))
1761 (while (re-search-forward "[ \t]+$" nil t) ;; Not syntactic WS as no formfeed
1762 (replace-match "" nil nil))
1763 (goto-char (point-max))
1764 (unless (bolp) (insert "\n"))))
1765
1766 (defvar compile-command)
1767 (defvar create-lockfiles) ;; Emacs 24
1768
1769 ;; compilation program
1770 (defun verilog-set-compile-command ()
1771 "Function to compute shell command to compile Verilog.
1772
1773 This reads `verilog-tool' and sets `compile-command'. This specifies the
1774 program that executes when you type \\[compile] or
1775 \\[verilog-auto-save-compile].
1776
1777 By default `verilog-tool' uses a Makefile if one exists in the
1778 current directory. If not, it is set to the `verilog-linter',
1779 `verilog-compiler', `verilog-coverage', `verilog-preprocessor',
1780 or `verilog-simulator' variables, as selected with the Verilog ->
1781 \"Choose Compilation Action\" menu.
1782
1783 You should set `verilog-tool' or the other variables to the path and
1784 arguments for your Verilog simulator. For example:
1785 \"vcs -p123 -O\"
1786 or a string like:
1787 \"(cd /tmp; surecov %s)\".
1788
1789 In the former case, the path to the current buffer is concat'ed to the
1790 value of `verilog-tool'; in the later, the path to the current buffer is
1791 substituted for the %s.
1792
1793 Where __FLAGS__ appears in the string `verilog-current-flags'
1794 will be substituted.
1795
1796 Where __FILE__ appears in the string, the variable
1797 `buffer-file-name' of the current buffer, without the directory
1798 portion, will be substituted."
1799 (interactive)
1800 (cond
1801 ((or (file-exists-p "makefile") ;If there is a makefile, use it
1802 (file-exists-p "Makefile"))
1803 (set (make-local-variable 'compile-command) "make "))
1804 (t
1805 (set (make-local-variable 'compile-command)
1806 (if verilog-tool
1807 (if (string-match "%s" (eval verilog-tool))
1808 (format (eval verilog-tool) (or buffer-file-name ""))
1809 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1810 ""))))
1811 (verilog-modify-compile-command))
1812
1813 (defun verilog-expand-command (command)
1814 "Replace meta-information in COMMAND and return it.
1815 Where __FLAGS__ appears in the string `verilog-current-flags'
1816 will be substituted. Where __FILE__ appears in the string, the
1817 current buffer's file-name, without the directory portion, will
1818 be substituted."
1819 (setq command (verilog-string-replace-matches
1820 ;; Note \\b only works if under verilog syntax table
1821 "\\b__FLAGS__\\b" (verilog-current-flags)
1822 t t command))
1823 (setq command (verilog-string-replace-matches
1824 "\\b__FILE__\\b" (file-name-nondirectory
1825 (or (buffer-file-name) ""))
1826 t t command))
1827 command)
1828
1829 (defun verilog-modify-compile-command ()
1830 "Update `compile-command' using `verilog-expand-command'."
1831 (when (and
1832 (stringp compile-command)
1833 (string-match "\\b\\(__FLAGS__\\|__FILE__\\)\\b" compile-command))
1834 (set (make-local-variable 'compile-command)
1835 (verilog-expand-command compile-command))))
1836
1837 (if (featurep 'xemacs)
1838 ;; Following code only gets called from compilation-mode-hook on XEmacs to add error handling.
1839 (defun verilog-error-regexp-add-xemacs ()
1840 "Teach XEmacs about verilog errors.
1841 Called by `compilation-mode-hook'. This allows \\[next-error] to
1842 find the errors."
1843 (interactive)
1844 (if (boundp 'compilation-error-regexp-systems-alist)
1845 (if (and
1846 (not (equal compilation-error-regexp-systems-list 'all))
1847 (not (member compilation-error-regexp-systems-list 'verilog)))
1848 (push 'verilog compilation-error-regexp-systems-list)))
1849 (if (boundp 'compilation-error-regexp-alist-alist)
1850 (if (not (assoc 'verilog compilation-error-regexp-alist-alist))
1851 (setcdr compilation-error-regexp-alist-alist
1852 (cons verilog-error-regexp-xemacs-alist
1853 (cdr compilation-error-regexp-alist-alist)))))
1854 (if (boundp 'compilation-font-lock-keywords)
1855 (progn
1856 (set (make-local-variable 'compilation-font-lock-keywords)
1857 verilog-error-font-lock-keywords)
1858 (font-lock-set-defaults)))
1859 ;; Need to re-run compilation-error-regexp builder
1860 (if (fboundp 'compilation-build-compilation-error-regexp-alist)
1861 (compilation-build-compilation-error-regexp-alist))
1862 ))
1863
1864 ;; Following code only gets called from compilation-mode-hook on Emacs to add error handling.
1865 (defun verilog-error-regexp-add-emacs ()
1866 "Tell Emacs compile that we are Verilog.
1867 Called by `compilation-mode-hook'. This allows \\[next-error] to
1868 find the errors."
1869 (interactive)
1870 (if (boundp 'compilation-error-regexp-alist-alist)
1871 (progn
1872 (if (not (assoc 'verilog-xl-1 compilation-error-regexp-alist-alist))
1873 (mapcar
1874 (lambda (item)
1875 (push (car item) compilation-error-regexp-alist)
1876 (push item compilation-error-regexp-alist-alist)
1877 )
1878 verilog-error-regexp-emacs-alist)))))
1879
1880 (if (featurep 'xemacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-xemacs))
1881 (if (featurep 'emacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-emacs))
1882
1883 (defconst verilog-directive-re
1884 (eval-when-compile
1885 (verilog-regexp-words
1886 '(
1887 "`case" "`default" "`define" "`else" "`elsif" "`endfor" "`endif"
1888 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1889 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1890 "`time_scale" "`undef" "`while" ))))
1891
1892 (defconst verilog-directive-re-1
1893 (concat "[ \t]*" verilog-directive-re))
1894
1895 (defconst verilog-directive-begin
1896 "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1897
1898 (defconst verilog-directive-middle
1899 "\\<`\\(else\\|elsif\\|default\\|case\\)\\>")
1900
1901 (defconst verilog-directive-end
1902 "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1903
1904 (defconst verilog-ovm-begin-re
1905 (eval-when-compile
1906 (verilog-regexp-opt
1907 '(
1908 "`ovm_component_utils_begin"
1909 "`ovm_component_param_utils_begin"
1910 "`ovm_field_utils_begin"
1911 "`ovm_object_utils_begin"
1912 "`ovm_object_param_utils_begin"
1913 "`ovm_sequence_utils_begin"
1914 "`ovm_sequencer_utils_begin"
1915 ) nil )))
1916
1917 (defconst verilog-ovm-end-re
1918 (eval-when-compile
1919 (verilog-regexp-opt
1920 '(
1921 "`ovm_component_utils_end"
1922 "`ovm_field_utils_end"
1923 "`ovm_object_utils_end"
1924 "`ovm_sequence_utils_end"
1925 "`ovm_sequencer_utils_end"
1926 ) nil )))
1927
1928 (defconst verilog-uvm-begin-re
1929 (eval-when-compile
1930 (verilog-regexp-opt
1931 '(
1932 "`uvm_component_utils_begin"
1933 "`uvm_component_param_utils_begin"
1934 "`uvm_field_utils_begin"
1935 "`uvm_object_utils_begin"
1936 "`uvm_object_param_utils_begin"
1937 "`uvm_sequence_utils_begin"
1938 "`uvm_sequencer_utils_begin"
1939 ) nil )))
1940
1941 (defconst verilog-uvm-end-re
1942 (eval-when-compile
1943 (verilog-regexp-opt
1944 '(
1945 "`uvm_component_utils_end"
1946 "`uvm_field_utils_end"
1947 "`uvm_object_utils_end"
1948 "`uvm_sequence_utils_end"
1949 "`uvm_sequencer_utils_end"
1950 ) nil )))
1951
1952 (defconst verilog-vmm-begin-re
1953 (eval-when-compile
1954 (verilog-regexp-opt
1955 '(
1956 "`vmm_data_member_begin"
1957 "`vmm_env_member_begin"
1958 "`vmm_scenario_member_begin"
1959 "`vmm_subenv_member_begin"
1960 "`vmm_xactor_member_begin"
1961 ) nil ) ) )
1962
1963 (defconst verilog-vmm-end-re
1964 (eval-when-compile
1965 (verilog-regexp-opt
1966 '(
1967 "`vmm_data_member_end"
1968 "`vmm_env_member_end"
1969 "`vmm_scenario_member_end"
1970 "`vmm_subenv_member_end"
1971 "`vmm_xactor_member_end"
1972 ) nil ) ) )
1973
1974 (defconst verilog-vmm-statement-re
1975 (eval-when-compile
1976 (verilog-regexp-opt
1977 '(
1978 ;; "`vmm_xactor_member_enum_array"
1979 "`vmm_\\(data\\|env\\|scenario\\|subenv\\|xactor\\)_member_\\(scalar\\|string\\|enum\\|vmm_data\\|channel\\|xactor\\|subenv\\|user_defined\\)\\(_array\\)?"
1980 ;; "`vmm_xactor_member_scalar_array"
1981 ;; "`vmm_xactor_member_scalar"
1982 ) nil )))
1983
1984 (defconst verilog-ovm-statement-re
1985 (eval-when-compile
1986 (verilog-regexp-opt
1987 '(
1988 ;; Statements
1989 "`DUT_ERROR"
1990 "`MESSAGE"
1991 "`dut_error"
1992 "`message"
1993 "`ovm_analysis_imp_decl"
1994 "`ovm_blocking_get_imp_decl"
1995 "`ovm_blocking_get_peek_imp_decl"
1996 "`ovm_blocking_master_imp_decl"
1997 "`ovm_blocking_peek_imp_decl"
1998 "`ovm_blocking_put_imp_decl"
1999 "`ovm_blocking_slave_imp_decl"
2000 "`ovm_blocking_transport_imp_decl"
2001 "`ovm_component_registry"
2002 "`ovm_component_registry_param"
2003 "`ovm_component_utils"
2004 "`ovm_create"
2005 "`ovm_create_seq"
2006 "`ovm_declare_sequence_lib"
2007 "`ovm_do"
2008 "`ovm_do_seq"
2009 "`ovm_do_seq_with"
2010 "`ovm_do_with"
2011 "`ovm_error"
2012 "`ovm_fatal"
2013 "`ovm_field_aa_int_byte"
2014 "`ovm_field_aa_int_byte_unsigned"
2015 "`ovm_field_aa_int_int"
2016 "`ovm_field_aa_int_int_unsigned"
2017 "`ovm_field_aa_int_integer"
2018 "`ovm_field_aa_int_integer_unsigned"
2019 "`ovm_field_aa_int_key"
2020 "`ovm_field_aa_int_longint"
2021 "`ovm_field_aa_int_longint_unsigned"
2022 "`ovm_field_aa_int_shortint"
2023 "`ovm_field_aa_int_shortint_unsigned"
2024 "`ovm_field_aa_int_string"
2025 "`ovm_field_aa_object_int"
2026 "`ovm_field_aa_object_string"
2027 "`ovm_field_aa_string_int"
2028 "`ovm_field_aa_string_string"
2029 "`ovm_field_array_int"
2030 "`ovm_field_array_object"
2031 "`ovm_field_array_string"
2032 "`ovm_field_enum"
2033 "`ovm_field_event"
2034 "`ovm_field_int"
2035 "`ovm_field_object"
2036 "`ovm_field_queue_int"
2037 "`ovm_field_queue_object"
2038 "`ovm_field_queue_string"
2039 "`ovm_field_sarray_int"
2040 "`ovm_field_string"
2041 "`ovm_field_utils"
2042 "`ovm_file"
2043 "`ovm_get_imp_decl"
2044 "`ovm_get_peek_imp_decl"
2045 "`ovm_info"
2046 "`ovm_info1"
2047 "`ovm_info2"
2048 "`ovm_info3"
2049 "`ovm_info4"
2050 "`ovm_line"
2051 "`ovm_master_imp_decl"
2052 "`ovm_msg_detail"
2053 "`ovm_non_blocking_transport_imp_decl"
2054 "`ovm_nonblocking_get_imp_decl"
2055 "`ovm_nonblocking_get_peek_imp_decl"
2056 "`ovm_nonblocking_master_imp_decl"
2057 "`ovm_nonblocking_peek_imp_decl"
2058 "`ovm_nonblocking_put_imp_decl"
2059 "`ovm_nonblocking_slave_imp_decl"
2060 "`ovm_object_registry"
2061 "`ovm_object_registry_param"
2062 "`ovm_object_utils"
2063 "`ovm_peek_imp_decl"
2064 "`ovm_phase_func_decl"
2065 "`ovm_phase_task_decl"
2066 "`ovm_print_aa_int_object"
2067 "`ovm_print_aa_string_int"
2068 "`ovm_print_aa_string_object"
2069 "`ovm_print_aa_string_string"
2070 "`ovm_print_array_int"
2071 "`ovm_print_array_object"
2072 "`ovm_print_array_string"
2073 "`ovm_print_object_queue"
2074 "`ovm_print_queue_int"
2075 "`ovm_print_string_queue"
2076 "`ovm_put_imp_decl"
2077 "`ovm_rand_send"
2078 "`ovm_rand_send_with"
2079 "`ovm_send"
2080 "`ovm_sequence_utils"
2081 "`ovm_slave_imp_decl"
2082 "`ovm_transport_imp_decl"
2083 "`ovm_update_sequence_lib"
2084 "`ovm_update_sequence_lib_and_item"
2085 "`ovm_warning"
2086 "`static_dut_error"
2087 "`static_message") nil )))
2088
2089 (defconst verilog-uvm-statement-re
2090 (eval-when-compile
2091 (verilog-regexp-opt
2092 '(
2093 ;; Statements
2094 "`uvm_analysis_imp_decl"
2095 "`uvm_blocking_get_imp_decl"
2096 "`uvm_blocking_get_peek_imp_decl"
2097 "`uvm_blocking_master_imp_decl"
2098 "`uvm_blocking_peek_imp_decl"
2099 "`uvm_blocking_put_imp_decl"
2100 "`uvm_blocking_slave_imp_decl"
2101 "`uvm_blocking_transport_imp_decl"
2102 "`uvm_component_param_utils"
2103 "`uvm_component_registry"
2104 "`uvm_component_registry_param"
2105 "`uvm_component_utils"
2106 "`uvm_create"
2107 "`uvm_create_on"
2108 "`uvm_create_seq" ;; Undocumented in 1.1
2109 "`uvm_declare_p_sequencer"
2110 "`uvm_declare_sequence_lib" ;; Deprecated in 1.1
2111 "`uvm_do"
2112 "`uvm_do_callbacks"
2113 "`uvm_do_callbacks_exit_on"
2114 "`uvm_do_obj_callbacks"
2115 "`uvm_do_obj_callbacks_exit_on"
2116 "`uvm_do_on"
2117 "`uvm_do_on_pri"
2118 "`uvm_do_on_pri_with"
2119 "`uvm_do_on_with"
2120 "`uvm_do_pri"
2121 "`uvm_do_pri_with"
2122 "`uvm_do_seq" ;; Undocumented in 1.1
2123 "`uvm_do_seq_with" ;; Undocumented in 1.1
2124 "`uvm_do_with"
2125 "`uvm_error"
2126 "`uvm_error_context"
2127 "`uvm_fatal"
2128 "`uvm_fatal_context"
2129 "`uvm_field_aa_int_byte"
2130 "`uvm_field_aa_int_byte_unsigned"
2131 "`uvm_field_aa_int_enum"
2132 "`uvm_field_aa_int_int"
2133 "`uvm_field_aa_int_int_unsigned"
2134 "`uvm_field_aa_int_integer"
2135 "`uvm_field_aa_int_integer_unsigned"
2136 "`uvm_field_aa_int_key"
2137 "`uvm_field_aa_int_longint"
2138 "`uvm_field_aa_int_longint_unsigned"
2139 "`uvm_field_aa_int_shortint"
2140 "`uvm_field_aa_int_shortint_unsigned"
2141 "`uvm_field_aa_int_string"
2142 "`uvm_field_aa_object_int"
2143 "`uvm_field_aa_object_string"
2144 "`uvm_field_aa_string_int"
2145 "`uvm_field_aa_string_string"
2146 "`uvm_field_array_enum"
2147 "`uvm_field_array_int"
2148 "`uvm_field_array_object"
2149 "`uvm_field_array_string"
2150 "`uvm_field_enum"
2151 "`uvm_field_event"
2152 "`uvm_field_int"
2153 "`uvm_field_object"
2154 "`uvm_field_queue_enum"
2155 "`uvm_field_queue_int"
2156 "`uvm_field_queue_object"
2157 "`uvm_field_queue_string"
2158 "`uvm_field_real"
2159 "`uvm_field_sarray_enum"
2160 "`uvm_field_sarray_int"
2161 "`uvm_field_sarray_object"
2162 "`uvm_field_sarray_string"
2163 "`uvm_field_string"
2164 "`uvm_field_utils"
2165 "`uvm_file" ;; Undocumented in 1.1, use `__FILE__
2166 "`uvm_get_imp_decl"
2167 "`uvm_get_peek_imp_decl"
2168 "`uvm_info"
2169 "`uvm_info_context"
2170 "`uvm_line" ;; Undocumented in 1.1, use `__LINE__
2171 "`uvm_master_imp_decl"
2172 "`uvm_non_blocking_transport_imp_decl" ;; Deprecated in 1.1
2173 "`uvm_nonblocking_get_imp_decl"
2174 "`uvm_nonblocking_get_peek_imp_decl"
2175 "`uvm_nonblocking_master_imp_decl"
2176 "`uvm_nonblocking_peek_imp_decl"
2177 "`uvm_nonblocking_put_imp_decl"
2178 "`uvm_nonblocking_slave_imp_decl"
2179 "`uvm_nonblocking_transport_imp_decl"
2180 "`uvm_object_param_utils"
2181 "`uvm_object_registry"
2182 "`uvm_object_registry_param" ;; Undocumented in 1.1
2183 "`uvm_object_utils"
2184 "`uvm_pack_array"
2185 "`uvm_pack_arrayN"
2186 "`uvm_pack_enum"
2187 "`uvm_pack_enumN"
2188 "`uvm_pack_int"
2189 "`uvm_pack_intN"
2190 "`uvm_pack_queue"
2191 "`uvm_pack_queueN"
2192 "`uvm_pack_real"
2193 "`uvm_pack_sarray"
2194 "`uvm_pack_sarrayN"
2195 "`uvm_pack_string"
2196 "`uvm_peek_imp_decl"
2197 "`uvm_put_imp_decl"
2198 "`uvm_rand_send"
2199 "`uvm_rand_send_pri"
2200 "`uvm_rand_send_pri_with"
2201 "`uvm_rand_send_with"
2202 "`uvm_record_attribute"
2203 "`uvm_record_field"
2204 "`uvm_register_cb"
2205 "`uvm_send"
2206 "`uvm_send_pri"
2207 "`uvm_sequence_utils" ;; Deprecated in 1.1
2208 "`uvm_set_super_type"
2209 "`uvm_slave_imp_decl"
2210 "`uvm_transport_imp_decl"
2211 "`uvm_unpack_array"
2212 "`uvm_unpack_arrayN"
2213 "`uvm_unpack_enum"
2214 "`uvm_unpack_enumN"
2215 "`uvm_unpack_int"
2216 "`uvm_unpack_intN"
2217 "`uvm_unpack_queue"
2218 "`uvm_unpack_queueN"
2219 "`uvm_unpack_real"
2220 "`uvm_unpack_sarray"
2221 "`uvm_unpack_sarrayN"
2222 "`uvm_unpack_string"
2223 "`uvm_update_sequence_lib" ;; Deprecated in 1.1
2224 "`uvm_update_sequence_lib_and_item" ;; Deprecated in 1.1
2225 "`uvm_warning"
2226 "`uvm_warning_context") nil )))
2227
2228
2229 ;;
2230 ;; Regular expressions used to calculate indent, etc.
2231 ;;
2232 (defconst verilog-symbol-re "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
2233 ;; Want to match
2234 ;; aa :
2235 ;; aa,bb :
2236 ;; a[34:32] :
2237 ;; a,
2238 ;; b :
2239 (defconst verilog-assignment-operator-re
2240 (eval-when-compile
2241 (verilog-regexp-opt
2242 `(
2243 ;; blocking assignment_operator
2244 "=" "+=" "-=" "*=" "/=" "%=" "&=" "|=" "^=" "<<=" ">>=" "<<<=" ">>>="
2245 ;; non blocking assignment operator
2246 "<="
2247 ;; comparison
2248 "==" "!=" "===" "!===" "<=" ">=" "==\?" "!=\?"
2249 ;; event_trigger
2250 "->" "->>"
2251 ;; property_expr
2252 "|->" "|=>"
2253 ;; Is this a legal verilog operator?
2254 ":="
2255 ) 't
2256 )))
2257 (defconst verilog-assignment-operation-re
2258 (concat
2259 ; "\\(^\\s-*[A-Za-z0-9_]+\\(\\[\\([A-Za-z0-9_]+\\)\\]\\)*\\s-*\\)"
2260 ; "\\(^\\s-*[^=<>+-*/%&|^:\\s-]+[^=<>+-*/%&|^\n]*?\\)"
2261 "\\(^.*?\\)" "\\B" verilog-assignment-operator-re "\\B" ))
2262
2263 (defconst verilog-label-re (concat verilog-symbol-re "\\s-*:\\s-*"))
2264 (defconst verilog-property-re
2265 (concat "\\(" verilog-label-re "\\)?"
2266 "\\(\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(assert\\)"))
2267 ;; "\\(assert\\|assume\\|cover\\)\\s-+property\\>"
2268
2269 (defconst verilog-no-indent-begin-re
2270 (eval-when-compile
2271 (verilog-regexp-words
2272 '("always" "always_comb" "always_ff" "always_latch" "initial" "final" ;; procedural blocks
2273 "if" "else" ;; conditional statements
2274 "while" "for" "foreach" "repeat" "do" "forever" )))) ;; loop statements
2275
2276 (defconst verilog-ends-re
2277 ;; Parenthesis indicate type of keyword found
2278 (concat
2279 "\\(\\<else\\>\\)\\|" ; 1
2280 "\\(\\<if\\>\\)\\|" ; 2
2281 "\\(\\<assert\\>\\)\\|" ; 3
2282 "\\(\\<end\\>\\)\\|" ; 3.1
2283 "\\(\\<endcase\\>\\)\\|" ; 4
2284 "\\(\\<endfunction\\>\\)\\|" ; 5
2285 "\\(\\<endtask\\>\\)\\|" ; 6
2286 "\\(\\<endspecify\\>\\)\\|" ; 7
2287 "\\(\\<endtable\\>\\)\\|" ; 8
2288 "\\(\\<endgenerate\\>\\)\\|" ; 9
2289 "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
2290 "\\(\\<endclass\\>\\)\\|" ; 11
2291 "\\(\\<endgroup\\>\\)\\|" ; 12
2292 ;; VMM
2293 "\\(\\<`vmm_data_member_end\\>\\)\\|"
2294 "\\(\\<`vmm_env_member_end\\>\\)\\|"
2295 "\\(\\<`vmm_scenario_member_end\\>\\)\\|"
2296 "\\(\\<`vmm_subenv_member_end\\>\\)\\|"
2297 "\\(\\<`vmm_xactor_member_end\\>\\)\\|"
2298 ;; OVM
2299 "\\(\\<`ovm_component_utils_end\\>\\)\\|"
2300 "\\(\\<`ovm_field_utils_end\\>\\)\\|"
2301 "\\(\\<`ovm_object_utils_end\\>\\)\\|"
2302 "\\(\\<`ovm_sequence_utils_end\\>\\)\\|"
2303 "\\(\\<`ovm_sequencer_utils_end\\>\\)"
2304 ;; UVM
2305 "\\(\\<`uvm_component_utils_end\\>\\)\\|"
2306 "\\(\\<`uvm_field_utils_end\\>\\)\\|"
2307 "\\(\\<`uvm_object_utils_end\\>\\)\\|"
2308 "\\(\\<`uvm_sequence_utils_end\\>\\)\\|"
2309 "\\(\\<`uvm_sequencer_utils_end\\>\\)"
2310 ))
2311
2312 (defconst verilog-auto-end-comment-lines-re
2313 ;; Matches to names in this list cause auto-end-commenting
2314 (concat "\\("
2315 verilog-directive-re "\\)\\|\\("
2316 (eval-when-compile
2317 (verilog-regexp-words
2318 `( "begin"
2319 "else"
2320 "end"
2321 "endcase"
2322 "endclass"
2323 "endclocking"
2324 "endgroup"
2325 "endfunction"
2326 "endmodule"
2327 "endprogram"
2328 "endprimitive"
2329 "endinterface"
2330 "endpackage"
2331 "endsequence"
2332 "endproperty"
2333 "endspecify"
2334 "endtable"
2335 "endtask"
2336 "join"
2337 "join_any"
2338 "join_none"
2339 "module"
2340 "macromodule"
2341 "primitive"
2342 "interface"
2343 "package")))
2344 "\\)"))
2345
2346 ;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
2347 ;;; verilog-end-block-ordered-re matches exactly the same strings.
2348 (defconst verilog-end-block-ordered-re
2349 ;; Parenthesis indicate type of keyword found
2350 (concat "\\(\\<endcase\\>\\)\\|" ; 1
2351 "\\(\\<end\\>\\)\\|" ; 2
2352 "\\(\\<end" ; 3, but not used
2353 "\\(" ; 4, but not used
2354 "\\(function\\)\\|" ; 5
2355 "\\(task\\)\\|" ; 6
2356 "\\(module\\)\\|" ; 7
2357 "\\(primitive\\)\\|" ; 8
2358 "\\(interface\\)\\|" ; 9
2359 "\\(package\\)\\|" ; 10
2360 "\\(class\\)\\|" ; 11
2361 "\\(group\\)\\|" ; 12
2362 "\\(program\\)\\|" ; 13
2363 "\\(sequence\\)\\|" ; 14
2364 "\\(clocking\\)\\|" ; 15
2365 "\\(property\\)\\|" ; 16
2366 "\\)\\>\\)"))
2367 (defconst verilog-end-block-re
2368 (eval-when-compile
2369 (verilog-regexp-words
2370
2371 `("end" ;; closes begin
2372 "endcase" ;; closes any of case, casex casez or randcase
2373 "join" "join_any" "join_none" ;; closes fork
2374 "endclass"
2375 "endtable"
2376 "endspecify"
2377 "endfunction"
2378 "endgenerate"
2379 "endtask"
2380 "endgroup"
2381 "endproperty"
2382 "endinterface"
2383 "endpackage"
2384 "endprogram"
2385 "endsequence"
2386 "endclocking"
2387 ;; OVM
2388 "`ovm_component_utils_end"
2389 "`ovm_field_utils_end"
2390 "`ovm_object_utils_end"
2391 "`ovm_sequence_utils_end"
2392 "`ovm_sequencer_utils_end"
2393 ;; UVM
2394 "`uvm_component_utils_end"
2395 "`uvm_field_utils_end"
2396 "`uvm_object_utils_end"
2397 "`uvm_sequence_utils_end"
2398 "`uvm_sequencer_utils_end"
2399 ;; VMM
2400 "`vmm_data_member_end"
2401 "`vmm_env_member_end"
2402 "`vmm_scenario_member_end"
2403 "`vmm_subenv_member_end"
2404 "`vmm_xactor_member_end"
2405 ))))
2406
2407
2408 (defconst verilog-endcomment-reason-re
2409 ;; Parenthesis indicate type of keyword found
2410 (concat
2411 "\\(\\<begin\\>\\)\\|" ; 1
2412 "\\(\\<else\\>\\)\\|" ; 2
2413 "\\(\\<end\\>\\s-+\\<else\\>\\)\\|" ; 3
2414 "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|" ; 4
2415 "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|" ; 5
2416 "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|" ; 6
2417 "\\(\\<fork\\>\\)\\|" ; 7
2418 "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
2419 "\\(\\<if\\>\\)\\|"
2420 verilog-property-re "\\|"
2421 "\\(\\(" verilog-label-re "\\)?\\<assert\\>\\)\\|"
2422 "\\(\\<clocking\\>\\)\\|"
2423 "\\(\\<task\\>\\)\\|"
2424 "\\(\\<function\\>\\)\\|"
2425 "\\(\\<initial\\>\\)\\|"
2426 "\\(\\<interface\\>\\)\\|"
2427 "\\(\\<package\\>\\)\\|"
2428 "\\(\\<final\\>\\)\\|"
2429 "\\(@\\)\\|"
2430 "\\(\\<while\\>\\)\\|\\(\\<do\\>\\)\\|"
2431 "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
2432 "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
2433 "#"))
2434
2435 (defconst verilog-named-block-re "begin[ \t]*:")
2436
2437 ;; These words begin a block which can occur inside a module which should be indented,
2438 ;; and closed with the respective word from the end-block list
2439
2440 (defconst verilog-beg-block-re
2441 (eval-when-compile
2442 (verilog-regexp-words
2443 `("begin"
2444 "case" "casex" "casez" "randcase"
2445 "clocking"
2446 "generate"
2447 "fork"
2448 "function"
2449 "property"
2450 "specify"
2451 "table"
2452 "task"
2453 ;; OVM
2454 "`ovm_component_utils_begin"
2455 "`ovm_component_param_utils_begin"
2456 "`ovm_field_utils_begin"
2457 "`ovm_object_utils_begin"
2458 "`ovm_object_param_utils_begin"
2459 "`ovm_sequence_utils_begin"
2460 "`ovm_sequencer_utils_begin"
2461 ;; UVM
2462 "`uvm_component_utils_begin"
2463 "`uvm_component_param_utils_begin"
2464 "`uvm_field_utils_begin"
2465 "`uvm_object_utils_begin"
2466 "`uvm_object_param_utils_begin"
2467 "`uvm_sequence_utils_begin"
2468 "`uvm_sequencer_utils_begin"
2469 ;; VMM
2470 "`vmm_data_member_begin"
2471 "`vmm_env_member_begin"
2472 "`vmm_scenario_member_begin"
2473 "`vmm_subenv_member_begin"
2474 "`vmm_xactor_member_begin"
2475 ))))
2476 ;; These are the same words, in a specific order in the regular
2477 ;; expression so that matching will work nicely for
2478 ;; verilog-forward-sexp and verilog-calc-indent
2479 (defconst verilog-beg-block-re-ordered
2480 ( concat "\\(\\<begin\\>\\)" ;1
2481 "\\|\\(\\<randcase\\>\\|\\(\\<unique0?\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
2482 "\\|\\(\\(\\<disable\\>\\s-+\\|\\<wait\\>\\s-+\\)?fork\\>\\)" ;4,5
2483 "\\|\\(\\<class\\>\\)" ;6
2484 "\\|\\(\\<table\\>\\)" ;7
2485 "\\|\\(\\<specify\\>\\)" ;8
2486 "\\|\\(\\<function\\>\\)" ;9
2487 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<function\\>\\)" ;10
2488 "\\|\\(\\<task\\>\\)" ;14
2489 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)" ;15
2490 "\\|\\(\\<generate\\>\\)" ;18
2491 "\\|\\(\\<covergroup\\>\\)" ;16 20
2492 "\\|\\(\\(\\(\\<cover\\>\\s-+\\)\\|\\(\\<assert\\>\\s-+\\)\\)*\\<property\\>\\)" ;17 21
2493 "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;21 25
2494 "\\|\\(\\<clocking\\>\\)" ;22 27
2495 "\\|\\(\\<`[ou]vm_[a-z_]+_begin\\>\\)" ;28
2496 "\\|\\(\\<`vmm_[a-z_]+_member_begin\\>\\)"
2497 ;;
2498 ))
2499
2500 (defconst verilog-end-block-ordered-rry
2501 [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2502 "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
2503 "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2504 "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
2505 "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
2506 "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
2507 "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
2508 "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
2509 "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
2510 "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
2511 "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
2512 "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
2513 "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
2514 ] )
2515
2516 (defconst verilog-nameable-item-re
2517 (eval-when-compile
2518 (verilog-regexp-words
2519 `("begin"
2520 "fork"
2521 "join" "join_any" "join_none"
2522 "end"
2523 "endcase"
2524 "endchecker"
2525 "endclass"
2526 "endclocking"
2527 "endconfig"
2528 "endfunction"
2529 "endgenerate"
2530 "endgroup"
2531 "endmodule"
2532 "endprimitive"
2533 "endinterface"
2534 "endpackage"
2535 "endprogram"
2536 "endproperty"
2537 "endsequence"
2538 "endspecify"
2539 "endtable"
2540 "endtask" )
2541 )))
2542
2543 (defconst verilog-declaration-opener
2544 (eval-when-compile
2545 (verilog-regexp-words
2546 `("module" "begin" "task" "function"))))
2547
2548 (defconst verilog-declaration-prefix-re
2549 (eval-when-compile
2550 (verilog-regexp-words
2551 `(
2552 ;; port direction
2553 "inout" "input" "output" "ref"
2554 ;; changeableness
2555 "const" "static" "protected" "local"
2556 ;; parameters
2557 "localparam" "parameter" "var"
2558 ;; type creation
2559 "typedef"
2560 ))))
2561 (defconst verilog-declaration-core-re
2562 (eval-when-compile
2563 (verilog-regexp-words
2564 `(
2565 ;; port direction (by themselves)
2566 "inout" "input" "output"
2567 ;; integer_atom_type
2568 "byte" "shortint" "int" "longint" "integer" "time"
2569 ;; integer_vector_type
2570 "bit" "logic" "reg"
2571 ;; non_integer_type
2572 "shortreal" "real" "realtime"
2573 ;; net_type
2574 "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
2575 ;; misc
2576 "string" "event" "chandle" "virtual" "enum" "genvar"
2577 "struct" "union"
2578 ;; builtin classes
2579 "mailbox" "semaphore"
2580 ))))
2581 (defconst verilog-declaration-re
2582 (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
2583 (defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
2584 (defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
2585 (defconst verilog-optional-signed-range-re
2586 (concat
2587 "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
2588 (defconst verilog-macroexp-re "`\\sw+")
2589
2590 (defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
2591 (defconst verilog-declaration-re-2-no-macro
2592 (concat "\\s-*" verilog-declaration-re
2593 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2594 "\\)?"))
2595 (defconst verilog-declaration-re-2-macro
2596 (concat "\\s-*" verilog-declaration-re
2597 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2598 "\\|\\(" verilog-macroexp-re "\\)"
2599 "\\)?"))
2600 (defconst verilog-declaration-re-1-macro
2601 (concat "^" verilog-declaration-re-2-macro))
2602
2603 (defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
2604
2605 (defconst verilog-defun-re
2606 (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
2607 (defconst verilog-end-defun-re
2608 (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
2609 (defconst verilog-zero-indent-re
2610 (concat verilog-defun-re "\\|" verilog-end-defun-re))
2611 (defconst verilog-inst-comment-re
2612 (eval-when-compile (verilog-regexp-words `("Outputs" "Inouts" "Inputs" "Interfaces" "Interfaced"))))
2613
2614 (defconst verilog-behavioral-block-beg-re
2615 (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
2616 "function" "task"))))
2617 (defconst verilog-coverpoint-re "\\w+\\s*:\\s*\\(coverpoint\\|cross\\constraint\\)" )
2618 (defconst verilog-in-constraint-re ;; keywords legal in constraint blocks starting a statement/block
2619 (eval-when-compile (verilog-regexp-words `("if" "else" "solve" "foreach"))))
2620
2621 (defconst verilog-indent-re
2622 (eval-when-compile
2623 (verilog-regexp-words
2624 `(
2625 "{"
2626 "always" "always_latch" "always_ff" "always_comb"
2627 "begin" "end"
2628 ; "unique" "priority"
2629 "case" "casex" "casez" "randcase" "endcase"
2630 "class" "endclass"
2631 "clocking" "endclocking"
2632 "config" "endconfig"
2633 "covergroup" "endgroup"
2634 "fork" "join" "join_any" "join_none"
2635 "function" "endfunction"
2636 "final"
2637 "generate" "endgenerate"
2638 "initial"
2639 "interface" "endinterface"
2640 "module" "macromodule" "endmodule"
2641 "package" "endpackage"
2642 "primitive" "endprimitive"
2643 "program" "endprogram"
2644 "property" "endproperty"
2645 "sequence" "randsequence" "endsequence"
2646 "specify" "endspecify"
2647 "table" "endtable"
2648 "task" "endtask"
2649 "virtual"
2650 "`case"
2651 "`default"
2652 "`define" "`undef"
2653 "`if" "`ifdef" "`ifndef" "`else" "`elsif" "`endif"
2654 "`while" "`endwhile"
2655 "`for" "`endfor"
2656 "`format"
2657 "`include"
2658 "`let"
2659 "`protect" "`endprotect"
2660 "`switch" "`endswitch"
2661 "`timescale"
2662 "`time_scale"
2663 ;; OVM Begin tokens
2664 "`ovm_component_utils_begin"
2665 "`ovm_component_param_utils_begin"
2666 "`ovm_field_utils_begin"
2667 "`ovm_object_utils_begin"
2668 "`ovm_object_param_utils_begin"
2669 "`ovm_sequence_utils_begin"
2670 "`ovm_sequencer_utils_begin"
2671 ;; OVM End tokens
2672 "`ovm_component_utils_end"
2673 "`ovm_field_utils_end"
2674 "`ovm_object_utils_end"
2675 "`ovm_sequence_utils_end"
2676 "`ovm_sequencer_utils_end"
2677 ;; UVM Begin tokens
2678 "`uvm_component_utils_begin"
2679 "`uvm_component_param_utils_begin"
2680 "`uvm_field_utils_begin"
2681 "`uvm_object_utils_begin"
2682 "`uvm_object_param_utils_begin"
2683 "`uvm_sequence_utils_begin"
2684 "`uvm_sequencer_utils_begin"
2685 ;; UVM End tokens
2686 "`uvm_component_utils_end" ;; Typo in spec, it's not uvm_component_end
2687 "`uvm_field_utils_end"
2688 "`uvm_object_utils_end"
2689 "`uvm_sequence_utils_end"
2690 "`uvm_sequencer_utils_end"
2691 ;; VMM Begin tokens
2692 "`vmm_data_member_begin"
2693 "`vmm_env_member_begin"
2694 "`vmm_scenario_member_begin"
2695 "`vmm_subenv_member_begin"
2696 "`vmm_xactor_member_begin"
2697 ;; VMM End tokens
2698 "`vmm_data_member_end"
2699 "`vmm_env_member_end"
2700 "`vmm_scenario_member_end"
2701 "`vmm_subenv_member_end"
2702 "`vmm_xactor_member_end"
2703 ))))
2704
2705 (defconst verilog-defun-level-not-generate-re
2706 (eval-when-compile
2707 (verilog-regexp-words
2708 `( "module" "macromodule" "primitive" "class" "program"
2709 "interface" "package" "config"))))
2710
2711 (defconst verilog-defun-level-re
2712 (eval-when-compile
2713 (verilog-regexp-words
2714 (append
2715 `( "module" "macromodule" "primitive" "class" "program"
2716 "interface" "package" "config")
2717 `( "initial" "final" "always" "always_comb" "always_ff"
2718 "always_latch" "endtask" "endfunction" )))))
2719
2720 (defconst verilog-defun-level-generate-only-re
2721 (eval-when-compile
2722 (verilog-regexp-words
2723 `( "initial" "final" "always" "always_comb" "always_ff"
2724 "always_latch" "endtask" "endfunction" ))))
2725
2726 (defconst verilog-cpp-level-re
2727 (eval-when-compile
2728 (verilog-regexp-words
2729 `(
2730 "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
2731 ))))
2732 (defconst verilog-disable-fork-re "\\(disable\\|wait\\)\\s-+fork\\>")
2733 (defconst verilog-extended-case-re "\\(\\(unique0?\\s-+\\|priority\\s-+\\)?case[xz]?\\)")
2734 (defconst verilog-extended-complete-re
2735 (concat "\\(\\(\\<extern\\s-+\\|\\<\\(\\<\\(pure\\|context\\)\\>\\s-+\\)?virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)\\)"
2736 "\\|\\(\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)\\)"
2737 "\\|\\(\\(\\<import\\>\\s-+\\)?\\(\"DPI-C\"\\s-+\\)?\\(\\<\\(pure\\|context\\)\\>\\s-+\\)?\\([A-Za-z_][A-Za-z0-9_]*\\s-+=\\s-+\\)?\\(function\\>\\|task\\>\\)\\)"
2738 "\\|" verilog-extended-case-re ))
2739 (defconst verilog-basic-complete-re
2740 (eval-when-compile
2741 (verilog-regexp-words
2742 `(
2743 "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
2744 "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
2745 "if" "for" "forever" "foreach" "else" "parameter" "do" "localparam" "assert"
2746 ))))
2747 (defconst verilog-complete-reg
2748 (concat
2749 verilog-extended-complete-re "\\|\\(" verilog-basic-complete-re "\\)"))
2750
2751 (defconst verilog-end-statement-re
2752 (concat "\\(" verilog-beg-block-re "\\)\\|\\("
2753 verilog-end-block-re "\\)"))
2754
2755 (defconst verilog-endcase-re
2756 (concat verilog-extended-case-re "\\|"
2757 "\\(endcase\\)\\|"
2758 verilog-defun-re
2759 ))
2760
2761 (defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
2762 "String used to mark beginning of excluded text.")
2763 (defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
2764 "String used to mark end of excluded text.")
2765 (defconst verilog-preprocessor-re
2766 (eval-when-compile
2767 (concat
2768 ;; single words
2769 "\\(?:"
2770 (verilog-regexp-words
2771 `("`__FILE__"
2772 "`__LINE__"
2773 "`celldefine"
2774 "`else"
2775 "`end_keywords"
2776 "`endcelldefine"
2777 "`endif"
2778 "`nounconnected_drive"
2779 "`resetall"
2780 "`unconnected_drive"
2781 "`undefineall"))
2782 "\\)\\|\\(?:"
2783 ;; two words: i.e. `ifdef DEFINE
2784 "\\<\\(`elsif\\|`ifn?def\\|`undef\\|`default_nettype\\|`begin_keywords\\)\\>\\s-"
2785 "\\)\\|\\(?:"
2786 ;; `line number "filename" level
2787 "\\<\\(`line\\)\\>\\s-+[0-9]+\\s-+\"[^\"]+\"\\s-+[012]"
2788 "\\)\\|\\(?:"
2789 ;;`include "file" or `include <file>
2790 "\\<\\(`include\\)\\>\\s-+\\(?:\"[^\"]+\"\\|<[^>]+>\\)"
2791 "\\)\\|\\(?:"
2792 ;; `pragma <stuff> (no mention in IEEE 1800-2012 that pragma can span multiple lines
2793 "\\<\\(`pragma\\)\\>\\s-+.+$"
2794 "\\)\\|\\(?:"
2795 ;; `timescale time_unit / time_precision
2796 "\\<\\(`timescale\\)\\>\\s-+10\\{0,2\\}\\s-*[munpf]?s\\s-*\\/\\s-*10\\{0,2\\}\\s-*[munpf]?s"
2797 "\\)\\|\\(?:"
2798 ;; `define and `if can span multiple lines if line ends in '\'. NOTE: `if is not IEEE 1800-2012
2799 ;; from http://www.emacswiki.org/emacs/MultilineRegexp
2800 (concat "\\<\\(`define\\|`if\\)\\>" ;; directive
2801 "\\s-+" ;; separator
2802 "\\(.*\\(?:\n.*\\)*?\\)" ;; definition: to tend of line, the maybe more lines (excludes any trailing \n)
2803 "\\(?:\n\\s-*\n\\|\\'\\)") ;; blank line or EOF
2804 "\\)"
2805 )))
2806
2807 (defconst verilog-keywords
2808 '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
2809 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
2810 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
2811 "`time_scale" "`undef" "`while"
2812
2813 "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
2814 "assert" "assign" "assume" "automatic" "before" "begin" "bind"
2815 "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
2816 "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
2817 "config" "const" "constraint" "context" "continue" "cover"
2818 "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
2819 "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
2820 "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
2821 "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
2822 "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
2823 "endtask" "enum" "event" "expect" "export" "extends" "extern"
2824 "final" "first_match" "for" "force" "foreach" "forever" "fork"
2825 "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
2826 "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
2827 "include" "initial" "inout" "input" "inside" "instance" "int"
2828 "integer" "interface" "intersect" "join" "join_any" "join_none"
2829 "large" "liblist" "library" "local" "localparam" "logic"
2830 "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
2831 "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
2832 "notif0" "notif1" "null" "or" "output" "package" "packed"
2833 "parameter" "pmos" "posedge" "primitive" "priority" "program"
2834 "property" "protected" "pull0" "pull1" "pulldown" "pullup"
2835 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2836 "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
2837 "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
2838 "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
2839 "showcancelled" "signed" "small" "solve" "specify" "specparam"
2840 "static" "string" "strong0" "strong1" "struct" "super" "supply0"
2841 "supply1" "table" "tagged" "task" "this" "throughout" "time"
2842 "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
2843 "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
2844 "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
2845 "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
2846 "wire" "with" "within" "wor" "xnor" "xor"
2847 ;; 1800-2009
2848 "accept_on" "checker" "endchecker" "eventually" "global" "implies"
2849 "let" "nexttime" "reject_on" "restrict" "s_always" "s_eventually"
2850 "s_nexttime" "s_until" "s_until_with" "strong" "sync_accept_on"
2851 "sync_reject_on" "unique0" "until" "until_with" "untyped" "weak"
2852 ;; 1800-2012
2853 "implements" "interconnect" "nettype" "soft"
2854 )
2855 "List of Verilog keywords.")
2856
2857 (defconst verilog-comment-start-regexp "//\\|/\\*"
2858 "Dual comment value for `comment-start-regexp'.")
2859
2860 (defvar verilog-mode-syntax-table
2861 (let ((table (make-syntax-table)))
2862 ;; Populate the syntax TABLE.
2863 (modify-syntax-entry ?\\ "\\" table)
2864 (modify-syntax-entry ?+ "." table)
2865 (modify-syntax-entry ?- "." table)
2866 (modify-syntax-entry ?= "." table)
2867 (modify-syntax-entry ?% "." table)
2868 (modify-syntax-entry ?< "." table)
2869 (modify-syntax-entry ?> "." table)
2870 (modify-syntax-entry ?& "." table)
2871 (modify-syntax-entry ?| "." table)
2872 ;; FIXME: This goes against Emacs conventions. Use "_" syntax instead and
2873 ;; then use regexps with things like "\\_<...\\_>".
2874 (modify-syntax-entry ?` "w" table) ;; ` is part of definition symbols in Verilog
2875 (modify-syntax-entry ?_ "w" table)
2876 (modify-syntax-entry ?\' "." table)
2877
2878 ;; Set up TABLE to handle block and line style comments.
2879 (if (featurep 'xemacs)
2880 (progn
2881 ;; XEmacs (formerly Lucid) has the best implementation
2882 (modify-syntax-entry ?/ ". 1456" table)
2883 (modify-syntax-entry ?* ". 23" table)
2884 (modify-syntax-entry ?\n "> b" table))
2885 ;; Emacs does things differently, but we can work with it
2886 (modify-syntax-entry ?/ ". 124b" table)
2887 (modify-syntax-entry ?* ". 23" table)
2888 (modify-syntax-entry ?\n "> b" table))
2889 table)
2890 "Syntax table used in Verilog mode buffers.")
2891
2892 (defvar verilog-font-lock-keywords nil
2893 "Default highlighting for Verilog mode.")
2894
2895 (defvar verilog-font-lock-keywords-1 nil
2896 "Subdued level highlighting for Verilog mode.")
2897
2898 (defvar verilog-font-lock-keywords-2 nil
2899 "Medium level highlighting for Verilog mode.
2900 See also `verilog-font-lock-extra-types'.")
2901
2902 (defvar verilog-font-lock-keywords-3 nil
2903 "Gaudy level highlighting for Verilog mode.
2904 See also `verilog-font-lock-extra-types'.")
2905
2906 (defvar verilog-font-lock-translate-off-face
2907 'verilog-font-lock-translate-off-face
2908 "Font to use for translated off regions.")
2909 (defface verilog-font-lock-translate-off-face
2910 '((((class color)
2911 (background light))
2912 (:background "gray90" :italic t ))
2913 (((class color)
2914 (background dark))
2915 (:background "gray10" :italic t ))
2916 (((class grayscale) (background light))
2917 (:foreground "DimGray" :italic t))
2918 (((class grayscale) (background dark))
2919 (:foreground "LightGray" :italic t))
2920 (t (:italis t)))
2921 "Font lock mode face used to background highlight translate-off regions."
2922 :group 'font-lock-highlighting-faces)
2923
2924 (defvar verilog-font-lock-p1800-face
2925 'verilog-font-lock-p1800-face
2926 "Font to use for p1800 keywords.")
2927 (defface verilog-font-lock-p1800-face
2928 '((((class color)
2929 (background light))
2930 (:foreground "DarkOrange3" :bold t ))
2931 (((class color)
2932 (background dark))
2933 (:foreground "orange1" :bold t ))
2934 (t (:italic t)))
2935 "Font lock mode face used to highlight P1800 keywords."
2936 :group 'font-lock-highlighting-faces)
2937
2938 (defvar verilog-font-lock-ams-face
2939 'verilog-font-lock-ams-face
2940 "Font to use for Analog/Mixed Signal keywords.")
2941 (defface verilog-font-lock-ams-face
2942 '((((class color)
2943 (background light))
2944 (:foreground "Purple" :bold t ))
2945 (((class color)
2946 (background dark))
2947 (:foreground "orange1" :bold t ))
2948 (t (:italic t)))
2949 "Font lock mode face used to highlight AMS keywords."
2950 :group 'font-lock-highlighting-faces)
2951
2952 (defvar verilog-font-grouping-keywords-face
2953 'verilog-font-lock-grouping-keywords-face
2954 "Font to use for Verilog Grouping Keywords (such as begin..end).")
2955 (defface verilog-font-lock-grouping-keywords-face
2956 '((((class color)
2957 (background light))
2958 (:foreground "red4" :bold t ))
2959 (((class color)
2960 (background dark))
2961 (:foreground "red4" :bold t ))
2962 (t (:italic t)))
2963 "Font lock mode face used to highlight verilog grouping keywords."
2964 :group 'font-lock-highlighting-faces)
2965
2966 (let* ((verilog-type-font-keywords
2967 (eval-when-compile
2968 (verilog-regexp-opt
2969 '(
2970 "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
2971 "event" "genvar" "inout" "input" "integer" "localparam"
2972 "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0" "notif1" "or"
2973 "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
2974 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
2975 "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
2976 "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
2977 "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
2978 "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
2979 ) nil )))
2980
2981 (verilog-pragma-keywords
2982 (eval-when-compile
2983 (verilog-regexp-opt
2984 '("surefire" "auto" "synopsys" "rtl_synthesis" "verilint" "leda" "0in"
2985 ) nil )))
2986
2987 (verilog-1800-2005-keywords
2988 (eval-when-compile
2989 (verilog-regexp-opt
2990 '("alias" "assert" "assume" "automatic" "before" "bind"
2991 "bins" "binsof" "break" "byte" "cell" "chandle" "class"
2992 "clocking" "config" "const" "constraint" "context" "continue"
2993 "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
2994 "dist" "do" "edge" "endclass" "endclocking" "endconfig"
2995 "endgroup" "endprogram" "endproperty" "endsequence" "enum"
2996 "expect" "export" "extends" "extern" "first_match" "foreach"
2997 "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
2998 "illegal_bins" "import" "incdir" "include" "inside" "instance"
2999 "int" "intersect" "large" "liblist" "library" "local" "longint"
3000 "matches" "medium" "modport" "new" "noshowcancelled" "null"
3001 "packed" "program" "property" "protected" "pull0" "pull1"
3002 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
3003 "randcase" "randsequence" "ref" "release" "return" "scalared"
3004 "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
3005 "specparam" "static" "string" "strong0" "strong1" "struct"
3006 "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
3007 "type" "union" "unsigned" "use" "var" "virtual" "void"
3008 "wait_order" "weak0" "weak1" "wildcard" "with" "within"
3009 ) nil )))
3010
3011 (verilog-1800-2009-keywords
3012 (eval-when-compile
3013 (verilog-regexp-opt
3014 '("accept_on" "checker" "endchecker" "eventually" "global"
3015 "implies" "let" "nexttime" "reject_on" "restrict" "s_always"
3016 "s_eventually" "s_nexttime" "s_until" "s_until_with" "strong"
3017 "sync_accept_on" "sync_reject_on" "unique0" "until"
3018 "until_with" "untyped" "weak" ) nil )))
3019
3020 (verilog-1800-2012-keywords
3021 (eval-when-compile
3022 (verilog-regexp-opt
3023 '("implements" "interconnect" "nettype" "soft" ) nil )))
3024
3025 (verilog-ams-keywords
3026 (eval-when-compile
3027 (verilog-regexp-opt
3028 '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
3029 "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
3030 "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
3031 "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
3032 "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
3033 "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
3034 "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
3035 "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
3036 "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
3037 "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
3038 "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
3039
3040 (verilog-font-keywords
3041 (eval-when-compile
3042 (verilog-regexp-opt
3043 '(
3044 "assign" "case" "casex" "casez" "randcase" "deassign"
3045 "default" "disable" "else" "endcase" "endfunction"
3046 "endgenerate" "endinterface" "endmodule" "endprimitive"
3047 "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
3048 "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
3049 "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
3050 "package" "endpackage" "always" "always_comb" "always_ff"
3051 "always_latch" "posedge" "primitive" "priority" "release"
3052 "repeat" "specify" "table" "task" "unique" "wait" "while"
3053 "class" "program" "endclass" "endprogram"
3054 ) nil )))
3055
3056 (verilog-font-grouping-keywords
3057 (eval-when-compile
3058 (verilog-regexp-opt
3059 '( "begin" "end" ) nil ))))
3060
3061 (setq verilog-font-lock-keywords
3062 (list
3063 ;; Fontify all builtin keywords
3064 (concat "\\<\\(" verilog-font-keywords "\\|"
3065 ;; And user/system tasks and functions
3066 "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
3067 "\\)\\>")
3068 ;; Fontify all types
3069 (if verilog-highlight-grouping-keywords
3070 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
3071 'verilog-font-lock-ams-face)
3072 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
3073 'font-lock-type-face))
3074 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
3075 'font-lock-type-face)
3076 ;; Fontify IEEE-1800-2005 keywords appropriately
3077 (if verilog-highlight-p1800-keywords
3078 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
3079 'verilog-font-lock-p1800-face)
3080 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
3081 'font-lock-type-face))
3082 ;; Fontify IEEE-1800-2009 keywords appropriately
3083 (if verilog-highlight-p1800-keywords
3084 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
3085 'verilog-font-lock-p1800-face)
3086 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
3087 'font-lock-type-face))
3088 ;; Fontify IEEE-1800-2012 keywords appropriately
3089 (if verilog-highlight-p1800-keywords
3090 (cons (concat "\\<\\(" verilog-1800-2012-keywords "\\)\\>")
3091 'verilog-font-lock-p1800-face)
3092 (cons (concat "\\<\\(" verilog-1800-2012-keywords "\\)\\>")
3093 'font-lock-type-face))
3094 ;; Fontify Verilog-AMS keywords
3095 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
3096 'verilog-font-lock-ams-face)))
3097
3098 (setq verilog-font-lock-keywords-1
3099 (append verilog-font-lock-keywords
3100 (list
3101 ;; Fontify module definitions
3102 (list
3103 "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
3104 '(1 font-lock-keyword-face)
3105 '(3 font-lock-function-name-face 'prepend))
3106 ;; Fontify function definitions
3107 (list
3108 (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
3109 '(1 font-lock-keyword-face)
3110 '(3 font-lock-constant-face prepend))
3111 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
3112 (1 font-lock-keyword-face)
3113 (2 font-lock-constant-face append))
3114 '("\\<function\\>\\s-+\\(\\sw+\\)"
3115 1 'font-lock-constant-face append))))
3116
3117 (setq verilog-font-lock-keywords-2
3118 (append verilog-font-lock-keywords-1
3119 (list
3120 ;; Fontify pragmas
3121 (concat "\\(//\\s-*\\(" verilog-pragma-keywords "\\)\\s-.*\\)")
3122 ;; Fontify escaped names
3123 '("\\(\\\\\\S-*\\s-\\)" 0 font-lock-function-name-face)
3124 ;; Fontify macro definitions/ uses
3125 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
3126 'font-lock-preprocessor-face
3127 'font-lock-type-face))
3128 ;; Fontify delays/numbers
3129 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
3130 0 font-lock-type-face append)
3131 ;; Fontify instantiation names
3132 '("\\([A-Za-z][A-Za-z0-9_]*\\)\\s-*(" 1 font-lock-function-name-face)
3133 )))
3134
3135 (setq verilog-font-lock-keywords-3
3136 (append verilog-font-lock-keywords-2
3137 (when verilog-highlight-translate-off
3138 (list
3139 ;; Fontify things in translate off regions
3140 '(verilog-match-translate-off
3141 (0 'verilog-font-lock-translate-off-face prepend))
3142 )))))
3143
3144 ;;
3145 ;; Buffer state preservation
3146
3147 (defmacro verilog-save-buffer-state (&rest body)
3148 "Execute BODY forms, saving state around insignificant change.
3149 Changes in text properties like `face' or `syntax-table' are
3150 considered insignificant. This macro allows text properties to
3151 be changed, even in a read-only buffer.
3152
3153 A change is considered significant if it affects the buffer text
3154 in any way that isn't completely restored again. Any
3155 user-visible changes to the buffer must not be within a
3156 `verilog-save-buffer-state'."
3157 ;; From c-save-buffer-state
3158 `(let* ((modified (buffer-modified-p))
3159 (buffer-undo-list t)
3160 (inhibit-read-only t)
3161 (inhibit-point-motion-hooks t)
3162 (verilog-no-change-functions t)
3163 before-change-functions
3164 after-change-functions
3165 deactivate-mark
3166 buffer-file-name ; Prevent primitives checking
3167 buffer-file-truename) ; for file modification
3168 (unwind-protect
3169 (progn ,@body)
3170 (and (not modified)
3171 (buffer-modified-p)
3172 (set-buffer-modified-p nil)))))
3173
3174 (defmacro verilog-save-no-change-functions (&rest body)
3175 "Execute BODY forms, disabling all change hooks in BODY.
3176 For insignificant changes, see instead `verilog-save-buffer-state'."
3177 `(let* ((inhibit-point-motion-hooks t)
3178 (verilog-no-change-functions t)
3179 before-change-functions
3180 after-change-functions)
3181 (progn ,@body)))
3182
3183 (defvar verilog-save-font-mod-hooked nil
3184 "Local variable when inside a `verilog-save-font-mods' block.")
3185 (make-variable-buffer-local 'verilog-save-font-mod-hooked)
3186
3187 (defmacro verilog-save-font-mods (&rest body)
3188 "Execute BODY forms, disabling text modifications to allow performing BODY.
3189 Includes temporary disabling of `font-lock' to restore the buffer
3190 to full text form for parsing. Additional actions may be specified with
3191 `verilog-before-save-font-hook' and `verilog-after-save-font-hook'."
3192 ;; Before version 20, match-string with font-lock returns a
3193 ;; vector that is not equal to the string. IE if on "input"
3194 ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
3195 `(let* ((hooked (unless verilog-save-font-mod-hooked
3196 (verilog-run-hooks 'verilog-before-save-font-hook)
3197 t))
3198 (verilog-save-font-mod-hooked t)
3199 (fontlocked (when (and (boundp 'font-lock-mode) font-lock-mode)
3200 (font-lock-mode 0)
3201 t)))
3202 (unwind-protect
3203 (progn ,@body)
3204 ;; Unwind forms
3205 (when fontlocked (font-lock-mode t))
3206 (when hooked (verilog-run-hooks 'verilog-after-save-font-hook)))))
3207
3208 ;;
3209 ;; Comment detection and caching
3210
3211 (defvar verilog-scan-cache-preserving nil
3212 "If true, the specified buffer's comment properties are static.
3213 Buffer changes will be ignored. See `verilog-inside-comment-or-string-p'
3214 and `verilog-scan'.")
3215
3216 (defvar verilog-scan-cache-tick nil
3217 "Modification tick at which `verilog-scan' was last completed.")
3218 (make-variable-buffer-local 'verilog-scan-cache-tick)
3219
3220 (defun verilog-scan-cache-flush ()
3221 "Flush the `verilog-scan' cache."
3222 (setq verilog-scan-cache-tick nil))
3223
3224 (defun verilog-scan-cache-ok-p ()
3225 "Return t if the scan cache is up to date."
3226 (or (and verilog-scan-cache-preserving
3227 (eq verilog-scan-cache-preserving (current-buffer))
3228 verilog-scan-cache-tick)
3229 (equal verilog-scan-cache-tick (buffer-chars-modified-tick))))
3230
3231 (defmacro verilog-save-scan-cache (&rest body)
3232 "Execute the BODY forms, allowing scan cache preservation within BODY.
3233 This requires that insertions must use `verilog-insert'."
3234 ;; If the buffer is out of date, trash it, as we'll not check later the tick
3235 ;; Note this must work properly if there's multiple layers of calls
3236 ;; to verilog-save-scan-cache even with differing ticks.
3237 `(progn
3238 (unless (verilog-scan-cache-ok-p) ;; Must be before let
3239 (setq verilog-scan-cache-tick nil))
3240 (let* ((verilog-scan-cache-preserving (current-buffer)))
3241 (progn ,@body))))
3242
3243 (defun verilog-scan-region (beg end)
3244 "Parse between BEG and END for `verilog-inside-comment-or-string-p'.
3245 This creates v-cmts properties where comments are in force."
3246 ;; Why properties and not overlays? Overlays have much slower non O(1)
3247 ;; lookup times.
3248 ;; This function is warm - called on every verilog-insert
3249 (save-excursion
3250 (save-match-data
3251 (verilog-save-buffer-state
3252 (let (pt)
3253 (goto-char beg)
3254 (while (< (point) end)
3255 (cond ((looking-at "//")
3256 (setq pt (point))
3257 (or (search-forward "\n" end t)
3258 (goto-char end))
3259 ;; "1+": The leading // or /* itself isn't considered as
3260 ;; being "inside" the comment, so that a (search-backward)
3261 ;; that lands at the start of the // won't mis-indicate
3262 ;; it's inside a comment. Also otherwise it would be
3263 ;; hard to find a commented out /*AS*/ vs one that isn't
3264 (put-text-property (1+ pt) (point) 'v-cmts t))
3265 ((looking-at "/\\*")
3266 (setq pt (point))
3267 (or (search-forward "*/" end t)
3268 ;; No error - let later code indicate it so we can
3269 ;; use inside functions on-the-fly
3270 ;;(error "%s: Unmatched /* */, at char %d"
3271 ;; (verilog-point-text) (point))
3272 (goto-char end))
3273 (put-text-property (1+ pt) (point) 'v-cmts t))
3274 ((looking-at "\"")
3275 (setq pt (point))
3276 (or (re-search-forward "[^\\]\"" end t) ;; don't forward-char first, since we look for a non backslash first
3277 ;; No error - let later code indicate it so we can
3278 (goto-char end))
3279 (put-text-property (1+ pt) (point) 'v-cmts t))
3280 (t
3281 (forward-char 1)
3282 (if (re-search-forward "[/\"]" end t)
3283 (backward-char 1)
3284 (goto-char end))))))))))
3285
3286 (defun verilog-scan ()
3287 "Parse the buffer, marking all comments with properties.
3288 Also assumes any text inserted since `verilog-scan-cache-tick'
3289 either is ok to parse as a non-comment, or `verilog-insert' was used."
3290 ;; See also `verilog-scan-debug' and `verilog-scan-and-debug'
3291 (unless (verilog-scan-cache-ok-p)
3292 (save-excursion
3293 (verilog-save-buffer-state
3294 (when verilog-debug
3295 (message "Scanning %s cache=%s cachetick=%S tick=%S" (current-buffer)
3296 verilog-scan-cache-preserving verilog-scan-cache-tick
3297 (buffer-chars-modified-tick)))
3298 (remove-text-properties (point-min) (point-max) '(v-cmts nil))
3299 (verilog-scan-region (point-min) (point-max))
3300 (setq verilog-scan-cache-tick (buffer-chars-modified-tick))
3301 (when verilog-debug (message "Scanning... done"))))))
3302
3303 (defun verilog-scan-debug ()
3304 "For debugging, show with display face results of `verilog-scan'."
3305 (font-lock-mode 0)
3306 ;;(if dbg (setq dbg (concat dbg (format "verilog-scan-debug\n"))))
3307 (save-excursion
3308 (goto-char (point-min))
3309 (remove-text-properties (point-min) (point-max) '(face nil))
3310 (while (not (eobp))
3311 (cond ((get-text-property (point) 'v-cmts)
3312 (put-text-property (point) (1+ (point)) `face 'underline)
3313 ;;(if dbg (setq dbg (concat dbg (format " v-cmts at %S\n" (point)))))
3314 (forward-char 1))
3315 (t
3316 (goto-char (or (next-property-change (point)) (point-max))))))))
3317
3318 (defun verilog-scan-and-debug ()
3319 "For debugging, run `verilog-scan' and `verilog-scan-debug'."
3320 (let (verilog-scan-cache-preserving
3321 verilog-scan-cache-tick)
3322 (goto-char (point-min))
3323 (verilog-scan)
3324 (verilog-scan-debug)))
3325
3326 (defun verilog-inside-comment-or-string-p (&optional pos)
3327 "Check if optional point POS is inside a comment.
3328 This may require a slow pre-parse of the buffer with `verilog-scan'
3329 to establish comment properties on all text."
3330 ;; This function is very hot
3331 (verilog-scan)
3332 (if pos
3333 (and (>= pos (point-min))
3334 (get-text-property pos 'v-cmts))
3335 (get-text-property (point) 'v-cmts)))
3336
3337 (defun verilog-insert (&rest stuff)
3338 "Insert STUFF arguments, tracking for `verilog-inside-comment-or-string-p'.
3339 Any insert that includes a comment must have the entire comment
3340 inserted using a single call to `verilog-insert'."
3341 (let ((pt (point)))
3342 (while stuff
3343 (insert (car stuff))
3344 (setq stuff (cdr stuff)))
3345 (verilog-scan-region pt (point))))
3346
3347 ;; More searching
3348
3349 (defun verilog-declaration-end ()
3350 (search-forward ";"))
3351
3352 (defun verilog-point-text (&optional pointnum)
3353 "Return text describing where POINTNUM or current point is (for errors).
3354 Use filename, if current buffer being edited shorten to just buffer name."
3355 (concat (or (and (equal (window-buffer) (current-buffer))
3356 (buffer-name))
3357 buffer-file-name
3358 (buffer-name))
3359 ":" (int-to-string (1+ (count-lines (point-min) (or pointnum (point)))))))
3360
3361 (defun electric-verilog-backward-sexp ()
3362 "Move backward over one balanced expression."
3363 (interactive)
3364 ;; before that see if we are in a comment
3365 (verilog-backward-sexp))
3366
3367 (defun electric-verilog-forward-sexp ()
3368 "Move forward over one balanced expression."
3369 (interactive)
3370 ;; before that see if we are in a comment
3371 (verilog-forward-sexp))
3372
3373 ;;;used by hs-minor-mode
3374 (defun verilog-forward-sexp-function (arg)
3375 (if (< arg 0)
3376 (verilog-backward-sexp)
3377 (verilog-forward-sexp)))
3378
3379
3380 (defun verilog-backward-sexp ()
3381 (let ((reg)
3382 (elsec 1)
3383 (found nil)
3384 (st (point)))
3385 (if (not (looking-at "\\<"))
3386 (forward-word -1))
3387 (cond
3388 ((verilog-skip-backward-comment-or-string))
3389 ((looking-at "\\<else\\>")
3390 (setq reg (concat
3391 verilog-end-block-re
3392 "\\|\\(\\<else\\>\\)"
3393 "\\|\\(\\<if\\>\\)"))
3394 (while (and (not found)
3395 (verilog-re-search-backward reg nil 'move))
3396 (cond
3397 ((match-end 1) ; matched verilog-end-block-re
3398 ;; try to leap back to matching outward block by striding across
3399 ;; indent level changing tokens then immediately
3400 ;; previous line governs indentation.
3401 (verilog-leap-to-head))
3402 ((match-end 2) ; else, we're in deep
3403 (setq elsec (1+ elsec)))
3404 ((match-end 3) ; found it
3405 (setq elsec (1- elsec))
3406 (if (= 0 elsec)
3407 ;; Now previous line describes syntax
3408 (setq found 't))))))
3409 ((looking-at verilog-end-block-re)
3410 (verilog-leap-to-head))
3411 ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
3412 (cond
3413 ((match-end 1)
3414 (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
3415 ((match-end 2)
3416 (verilog-re-search-backward "\\<primitive\\>" nil 'move))
3417 ((match-end 3)
3418 (verilog-re-search-backward "\\<class\\>" nil 'move))
3419 ((match-end 4)
3420 (verilog-re-search-backward "\\<program\\>" nil 'move))
3421 ((match-end 5)
3422 (verilog-re-search-backward "\\<interface\\>" nil 'move))
3423 ((match-end 6)
3424 (verilog-re-search-backward "\\<package\\>" nil 'move))
3425 (t
3426 (goto-char st)
3427 (backward-sexp 1))))
3428 (t
3429 (goto-char st)
3430 (backward-sexp)))))
3431
3432 (defun verilog-forward-sexp ()
3433 (let ((reg)
3434 (md 2)
3435 (st (point))
3436 (nest 'yes))
3437 (if (not (looking-at "\\<"))
3438 (forward-word -1))
3439 (cond
3440 ((verilog-skip-forward-comment-or-string)
3441 (verilog-forward-syntactic-ws))
3442 ((looking-at verilog-beg-block-re-ordered)
3443 (cond
3444 ((match-end 1);
3445 ;; Search forward for matching end
3446 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
3447 ((match-end 2)
3448 ;; Search forward for matching endcase
3449 (setq reg "\\(\\<randcase\\>\\|\\(\\<unique0?\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
3450 (setq md 3) ;; ender is third item in regexp
3451 )
3452 ((match-end 4)
3453 ;; might be "disable fork" or "wait fork"
3454 (let
3455 (here)
3456 (if (or
3457 (looking-at verilog-disable-fork-re)
3458 (and (looking-at "fork")
3459 (progn
3460 (setq here (point)) ;; sometimes a fork is just a fork
3461 (forward-word -1)
3462 (looking-at verilog-disable-fork-re))))
3463 (progn ;; it is a disable fork; ignore it
3464 (goto-char (match-end 0))
3465 (forward-word 1)
3466 (setq reg nil))
3467 (progn ;; it is a nice simple fork
3468 (goto-char here) ;; return from looking for "disable fork"
3469 ;; Search forward for matching join
3470 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))))
3471 ((match-end 6)
3472 ;; Search forward for matching endclass
3473 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
3474
3475 ((match-end 7)
3476 ;; Search forward for matching endtable
3477 (setq reg "\\<endtable\\>" )
3478 (setq nest 'no))
3479 ((match-end 8)
3480 ;; Search forward for matching endspecify
3481 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
3482 ((match-end 9)
3483 ;; Search forward for matching endfunction
3484 (setq reg "\\<endfunction\\>" )
3485 (setq nest 'no))
3486 ((match-end 10)
3487 ;; Search forward for matching endfunction
3488 (setq reg "\\<endfunction\\>" )
3489 (setq nest 'no))
3490 ((match-end 14)
3491 ;; Search forward for matching endtask
3492 (setq reg "\\<endtask\\>" )
3493 (setq nest 'no))
3494 ((match-end 15)
3495 ;; Search forward for matching endtask
3496 (setq reg "\\<endtask\\>" )
3497 (setq nest 'no))
3498 ((match-end 19)
3499 ;; Search forward for matching endgenerate
3500 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
3501 ((match-end 20)
3502 ;; Search forward for matching endgroup
3503 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
3504 ((match-end 21)
3505 ;; Search forward for matching endproperty
3506 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
3507 ((match-end 25)
3508 ;; Search forward for matching endsequence
3509 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
3510 (setq md 3)) ; 3 to get to endsequence in the reg above
3511 ((match-end 27)
3512 ;; Search forward for matching endclocking
3513 (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
3514 (if (and reg
3515 (forward-word 1))
3516 (catch 'skip
3517 (if (eq nest 'yes)
3518 (let ((depth 1)
3519 here)
3520 (while (verilog-re-search-forward reg nil 'move)
3521 (cond
3522 ((match-end md) ; a closer in regular expression, so we are climbing out
3523 (setq depth (1- depth))
3524 (if (= 0 depth) ; we are out!
3525 (throw 'skip 1)))
3526 ((match-end 1) ; an opener in the r-e, so we are in deeper now
3527 (setq here (point)) ; remember where we started
3528 (goto-char (match-beginning 1))
3529 (cond
3530 ((if (or
3531 (looking-at verilog-disable-fork-re)
3532 (and (looking-at "fork")
3533 (progn
3534 (forward-word -1)
3535 (looking-at verilog-disable-fork-re))))
3536 (progn ;; it is a disable fork; another false alarm
3537 (goto-char (match-end 0)))
3538 (progn ;; it is a simple fork (or has nothing to do with fork)
3539 (goto-char here)
3540 (setq depth (1+ depth))))))))))
3541 (if (verilog-re-search-forward reg nil 'move)
3542 (throw 'skip 1))))))
3543
3544 ((looking-at (concat
3545 "\\(\\<\\(macro\\)?module\\>\\)\\|"
3546 "\\(\\<primitive\\>\\)\\|"
3547 "\\(\\<class\\>\\)\\|"
3548 "\\(\\<program\\>\\)\\|"
3549 "\\(\\<interface\\>\\)\\|"
3550 "\\(\\<package\\>\\)"))
3551 (cond
3552 ((match-end 1)
3553 (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
3554 ((match-end 2)
3555 (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
3556 ((match-end 3)
3557 (verilog-re-search-forward "\\<endclass\\>" nil 'move))
3558 ((match-end 4)
3559 (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
3560 ((match-end 5)
3561 (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
3562 ((match-end 6)
3563 (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
3564 (t
3565 (goto-char st)
3566 (if (= (following-char) ?\) )
3567 (forward-char 1)
3568 (forward-sexp 1)))))
3569 (t
3570 (goto-char st)
3571 (if (= (following-char) ?\) )
3572 (forward-char 1)
3573 (forward-sexp 1))))))
3574
3575 (defun verilog-declaration-beg ()
3576 (verilog-re-search-backward verilog-declaration-re (bobp) t))
3577
3578 ;;
3579 ;;
3580 ;; Mode
3581 ;;
3582 (defvar verilog-which-tool 1)
3583 ;;;###autoload
3584 (define-derived-mode verilog-mode prog-mode "Verilog"
3585 "Major mode for editing Verilog code.
3586 \\<verilog-mode-map>
3587 See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
3588 AUTOs can improve coding efficiency.
3589
3590 Use \\[verilog-faq] for a pointer to frequently asked questions.
3591
3592 NEWLINE, TAB indents for Verilog code.
3593 Delete converts tabs to spaces as it moves back.
3594
3595 Supports highlighting.
3596
3597 Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
3598 with no args, if that value is non-nil.
3599
3600 Variables controlling indentation/edit style:
3601
3602 variable `verilog-indent-level' (default 3)
3603 Indentation of Verilog statements with respect to containing block.
3604 `verilog-indent-level-module' (default 3)
3605 Absolute indentation of Module level Verilog statements.
3606 Set to 0 to get initial and always statements lined up
3607 on the left side of your screen.
3608 `verilog-indent-level-declaration' (default 3)
3609 Indentation of declarations with respect to containing block.
3610 Set to 0 to get them list right under containing block.
3611 `verilog-indent-level-behavioral' (default 3)
3612 Indentation of first begin in a task or function block
3613 Set to 0 to get such code to lined up underneath the task or
3614 function keyword.
3615 `verilog-indent-level-directive' (default 1)
3616 Indentation of `ifdef/`endif blocks.
3617 `verilog-cexp-indent' (default 1)
3618 Indentation of Verilog statements broken across lines i.e.:
3619 if (a)
3620 begin
3621 `verilog-case-indent' (default 2)
3622 Indentation for case statements.
3623 `verilog-auto-newline' (default nil)
3624 Non-nil means automatically newline after semicolons and the punctuation
3625 mark after an end.
3626 `verilog-auto-indent-on-newline' (default t)
3627 Non-nil means automatically indent line after newline.
3628 `verilog-tab-always-indent' (default t)
3629 Non-nil means TAB in Verilog mode should always reindent the current line,
3630 regardless of where in the line point is when the TAB command is used.
3631 `verilog-indent-begin-after-if' (default t)
3632 Non-nil means to indent begin statements following a preceding
3633 if, else, while, for and repeat statements, if any. Otherwise,
3634 the begin is lined up with the preceding token. If t, you get:
3635 if (a)
3636 begin // amount of indent based on `verilog-cexp-indent'
3637 otherwise you get:
3638 if (a)
3639 begin
3640 `verilog-auto-endcomments' (default t)
3641 Non-nil means a comment /* ... */ is set after the ends which ends
3642 cases, tasks, functions and modules.
3643 The type and name of the object will be set between the braces.
3644 `verilog-minimum-comment-distance' (default 10)
3645 Minimum distance (in lines) between begin and end required before a comment
3646 will be inserted. Setting this variable to zero results in every
3647 end acquiring a comment; the default avoids too many redundant
3648 comments in tight quarters.
3649 `verilog-auto-lineup' (default 'declarations)
3650 List of contexts where auto lineup of code should be done.
3651
3652 Variables controlling other actions:
3653
3654 `verilog-linter' (default surelint)
3655 Unix program to call to run the lint checker. This is the default
3656 command for \\[compile-command] and \\[verilog-auto-save-compile].
3657
3658 See \\[customize] for the complete list of variables.
3659
3660 AUTO expansion functions are, in part:
3661
3662 \\[verilog-auto] Expand AUTO statements.
3663 \\[verilog-delete-auto] Remove the AUTOs.
3664 \\[verilog-inject-auto] Insert AUTOs for the first time.
3665
3666 Some other functions are:
3667
3668 \\[verilog-complete-word] Complete word with appropriate possibilities.
3669 \\[verilog-mark-defun] Mark function.
3670 \\[verilog-beg-of-defun] Move to beginning of current function.
3671 \\[verilog-end-of-defun] Move to end of current function.
3672 \\[verilog-label-be] Label matching begin ... end, fork ... join, etc statements.
3673
3674 \\[verilog-comment-region] Put marked area in a comment.
3675 \\[verilog-uncomment-region] Uncomment an area commented with \\[verilog-comment-region].
3676 \\[verilog-insert-block] Insert begin ... end.
3677 \\[verilog-star-comment] Insert /* ... */.
3678
3679 \\[verilog-sk-always] Insert an always @(AS) begin .. end block.
3680 \\[verilog-sk-begin] Insert a begin .. end block.
3681 \\[verilog-sk-case] Insert a case block, prompting for details.
3682 \\[verilog-sk-for] Insert a for (...) begin .. end block, prompting for details.
3683 \\[verilog-sk-generate] Insert a generate .. endgenerate block.
3684 \\[verilog-sk-header] Insert a header block at the top of file.
3685 \\[verilog-sk-initial] Insert an initial begin .. end block.
3686 \\[verilog-sk-fork] Insert a fork begin .. end .. join block.
3687 \\[verilog-sk-module] Insert a module .. (/*AUTOARG*/);.. endmodule block.
3688 \\[verilog-sk-ovm-class] Insert an OVM Class block.
3689 \\[verilog-sk-uvm-object] Insert an UVM Object block.
3690 \\[verilog-sk-uvm-component] Insert an UVM Component block.
3691 \\[verilog-sk-primitive] Insert a primitive .. (.. );.. endprimitive block.
3692 \\[verilog-sk-repeat] Insert a repeat (..) begin .. end block.
3693 \\[verilog-sk-specify] Insert a specify .. endspecify block.
3694 \\[verilog-sk-task] Insert a task .. begin .. end endtask block.
3695 \\[verilog-sk-while] Insert a while (...) begin .. end block, prompting for details.
3696 \\[verilog-sk-casex] Insert a casex (...) item: begin.. end endcase block, prompting for details.
3697 \\[verilog-sk-casez] Insert a casez (...) item: begin.. end endcase block, prompting for details.
3698 \\[verilog-sk-if] Insert an if (..) begin .. end block.
3699 \\[verilog-sk-else-if] Insert an else if (..) begin .. end block.
3700 \\[verilog-sk-comment] Insert a comment block.
3701 \\[verilog-sk-assign] Insert an assign .. = ..; statement.
3702 \\[verilog-sk-function] Insert a function .. begin .. end endfunction block.
3703 \\[verilog-sk-input] Insert an input declaration, prompting for details.
3704 \\[verilog-sk-output] Insert an output declaration, prompting for details.
3705 \\[verilog-sk-state-machine] Insert a state machine definition, prompting for details.
3706 \\[verilog-sk-inout] Insert an inout declaration, prompting for details.
3707 \\[verilog-sk-wire] Insert a wire declaration, prompting for details.
3708 \\[verilog-sk-reg] Insert a register declaration, prompting for details.
3709 \\[verilog-sk-define-signal] Define signal under point as a register at the top of the module.
3710
3711 All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
3712 Key bindings specific to `verilog-mode-map' are:
3713
3714 \\{verilog-mode-map}"
3715 :abbrev-table verilog-mode-abbrev-table
3716 (set (make-local-variable 'beginning-of-defun-function)
3717 'verilog-beg-of-defun)
3718 (set (make-local-variable 'end-of-defun-function)
3719 'verilog-end-of-defun)
3720 (set-syntax-table verilog-mode-syntax-table)
3721 (set (make-local-variable 'indent-line-function)
3722 #'verilog-indent-line-relative)
3723 (set (make-local-variable 'comment-indent-function) 'verilog-comment-indent)
3724 (set (make-local-variable 'parse-sexp-ignore-comments) nil)
3725 (set (make-local-variable 'comment-start) "// ")
3726 (set (make-local-variable 'comment-end) "")
3727 (set (make-local-variable 'comment-start-skip) "/\\*+ *\\|// *")
3728 (set (make-local-variable 'comment-multi-line) nil)
3729 ;; Set up for compilation
3730 (setq verilog-which-tool 1)
3731 (setq verilog-tool 'verilog-linter)
3732 (verilog-set-compile-command)
3733 (when (boundp 'hack-local-variables-hook) ;; Also modify any file-local-variables
3734 (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
3735
3736 ;; Setting up menus
3737 (when (featurep 'xemacs)
3738 (easy-menu-add verilog-stmt-menu)
3739 (easy-menu-add verilog-menu)
3740 (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
3741
3742 ;; Stuff for GNU Emacs
3743 (set (make-local-variable 'font-lock-defaults)
3744 `((verilog-font-lock-keywords
3745 verilog-font-lock-keywords-1
3746 verilog-font-lock-keywords-2
3747 verilog-font-lock-keywords-3)
3748 nil nil nil
3749 ,(if (functionp 'syntax-ppss)
3750 ;; verilog-beg-of-defun uses syntax-ppss, and syntax-ppss uses
3751 ;; font-lock-beginning-of-syntax-function, so
3752 ;; font-lock-beginning-of-syntax-function, can't use
3753 ;; verilog-beg-of-defun.
3754 nil
3755 'verilog-beg-of-defun)))
3756 ;;------------------------------------------------------------
3757 ;; now hook in 'verilog-highlight-include-files (eldo-mode.el&spice-mode.el)
3758 ;; all buffer local:
3759 (unless noninteractive ;; Else can't see the result, and change hooks are slow
3760 (when (featurep 'xemacs)
3761 (make-local-hook 'font-lock-mode-hook)
3762 (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
3763 (make-local-hook 'after-change-functions))
3764 (add-hook 'font-lock-mode-hook 'verilog-highlight-buffer t t)
3765 (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-highlight-buffer t t) ; not in Emacs
3766 (add-hook 'after-change-functions 'verilog-highlight-region t t))
3767
3768 ;; Tell imenu how to handle Verilog.
3769 (set (make-local-variable 'imenu-generic-expression)
3770 verilog-imenu-generic-expression)
3771 ;; Tell which-func-modes that imenu knows about verilog
3772 (when (and (boundp 'which-func-modes) (listp which-func-modes))
3773 (add-to-list 'which-func-modes 'verilog-mode))
3774 ;; hideshow support
3775 (when (boundp 'hs-special-modes-alist)
3776 (unless (assq 'verilog-mode hs-special-modes-alist)
3777 (setq hs-special-modes-alist
3778 (cons '(verilog-mode-mode "\\<begin\\>" "\\<end\\>" nil
3779 verilog-forward-sexp-function)
3780 hs-special-modes-alist))))
3781
3782 ;; Stuff for autos
3783 (add-hook 'write-contents-hooks 'verilog-auto-save-check nil 'local)
3784 ;; verilog-mode-hook call added by define-derived-mode
3785 )
3786 \f
3787
3788 ;;
3789 ;; Electric functions
3790 ;;
3791 (defun electric-verilog-terminate-line (&optional arg)
3792 "Terminate line and indent next line.
3793 With optional ARG, remove existing end of line comments."
3794 (interactive)
3795 ;; before that see if we are in a comment
3796 (let ((state (save-excursion (verilog-syntax-ppss))))
3797 (cond
3798 ((nth 7 state) ; Inside // comment
3799 (if (eolp)
3800 (progn
3801 (delete-horizontal-space)
3802 (newline))
3803 (progn
3804 (newline)
3805 (insert "// ")
3806 (beginning-of-line)))
3807 (verilog-indent-line))
3808 ((nth 4 state) ; Inside any comment (hence /**/)
3809 (newline)
3810 (verilog-more-comment))
3811 ((eolp)
3812 ;; First, check if current line should be indented
3813 (if (save-excursion
3814 (delete-horizontal-space)
3815 (beginning-of-line)
3816 (skip-chars-forward " \t")
3817 (if (looking-at verilog-auto-end-comment-lines-re)
3818 (let ((indent-str (verilog-indent-line)))
3819 ;; Maybe we should set some endcomments
3820 (if verilog-auto-endcomments
3821 (verilog-set-auto-endcomments indent-str arg))
3822 (end-of-line)
3823 (delete-horizontal-space)
3824 (if arg
3825 ()
3826 (newline))
3827 nil)
3828 (progn
3829 (end-of-line)
3830 (delete-horizontal-space)
3831 't)))
3832 ;; see if we should line up assignments
3833 (progn
3834 (if (or (eq 'all verilog-auto-lineup)
3835 (eq 'assignments verilog-auto-lineup))
3836 (verilog-pretty-expr t "\\(<\\|:\\)?=" ))
3837 (newline))
3838 (forward-line 1))
3839 ;; Indent next line
3840 (if verilog-auto-indent-on-newline
3841 (verilog-indent-line)))
3842 (t
3843 (newline)))))
3844
3845 (defun electric-verilog-terminate-and-indent ()
3846 "Insert a newline and indent for the next statement."
3847 (interactive)
3848 (electric-verilog-terminate-line 1))
3849
3850 (defun electric-verilog-semi ()
3851 "Insert `;' character and reindent the line."
3852 (interactive)
3853 (verilog-insert-last-command-event)
3854
3855 (if (or (verilog-in-comment-or-string-p)
3856 (verilog-in-escaped-name-p))
3857 ()
3858 (save-excursion
3859 (beginning-of-line)
3860 (verilog-forward-ws&directives)
3861 (verilog-indent-line))
3862 (if (and verilog-auto-newline
3863 (not (verilog-parenthesis-depth)))
3864 (electric-verilog-terminate-line))))
3865
3866 (defun electric-verilog-semi-with-comment ()
3867 "Insert `;' character, reindent the line and indent for comment."
3868 (interactive)
3869 (insert "\;")
3870 (save-excursion
3871 (beginning-of-line)
3872 (verilog-indent-line))
3873 (indent-for-comment))
3874
3875 (defun electric-verilog-colon ()
3876 "Insert `:' and do all indentations except line indent on this line."
3877 (interactive)
3878 (verilog-insert-last-command-event)
3879 ;; Do nothing if within string.
3880 (if (or
3881 (verilog-within-string)
3882 (not (verilog-in-case-region-p)))
3883 ()
3884 (save-excursion
3885 (let ((p (point))
3886 (lim (progn (verilog-beg-of-statement) (point))))
3887 (goto-char p)
3888 (verilog-backward-case-item lim)
3889 (verilog-indent-line)))
3890 ;; (let ((verilog-tab-always-indent nil))
3891 ;; (verilog-indent-line))
3892 ))
3893
3894 ;;(defun electric-verilog-equal ()
3895 ;; "Insert `=', and do indentation if within block."
3896 ;; (interactive)
3897 ;; (verilog-insert-last-command-event)
3898 ;; Could auto line up expressions, but not yet
3899 ;; (if (eq (car (verilog-calculate-indent)) 'block)
3900 ;; (let ((verilog-tab-always-indent nil))
3901 ;; (verilog-indent-command)))
3902 ;; )
3903
3904 (defun electric-verilog-tick ()
3905 "Insert back-tick, and indent to column 0 if this is a CPP directive."
3906 (interactive)
3907 (verilog-insert-last-command-event)
3908 (save-excursion
3909 (if (verilog-in-directive-p)
3910 (verilog-indent-line))))
3911
3912 (defun electric-verilog-tab ()
3913 "Function called when TAB is pressed in Verilog mode."
3914 (interactive)
3915 ;; If verilog-tab-always-indent, indent the beginning of the line.
3916 (cond
3917 ;; The region is active, indent it.
3918 ((and (region-active-p)
3919 (not (eq (region-beginning) (region-end))))
3920 (indent-region (region-beginning) (region-end) nil))
3921 ((or verilog-tab-always-indent
3922 (save-excursion
3923 (skip-chars-backward " \t")
3924 (bolp)))
3925 (let* ((oldpnt (point))
3926 (boi-point
3927 (save-excursion
3928 (beginning-of-line)
3929 (skip-chars-forward " \t")
3930 (verilog-indent-line)
3931 (back-to-indentation)
3932 (point))))
3933 (if (< (point) boi-point)
3934 (back-to-indentation)
3935 (cond ((not verilog-tab-to-comment))
3936 ((not (eolp))
3937 (end-of-line))
3938 (t
3939 (indent-for-comment)
3940 (when (and (eolp) (= oldpnt (point)))
3941 ; kill existing comment
3942 (beginning-of-line)
3943 (re-search-forward comment-start-skip oldpnt 'move)
3944 (goto-char (match-beginning 0))
3945 (skip-chars-backward " \t")
3946 (kill-region (point) oldpnt)))))))
3947 (t (progn (insert "\t")))))
3948
3949 \f
3950
3951 ;;
3952 ;; Interactive functions
3953 ;;
3954
3955 (defun verilog-indent-buffer ()
3956 "Indent-region the entire buffer as Verilog code.
3957 To call this from the command line, see \\[verilog-batch-indent]."
3958 (interactive)
3959 (verilog-mode)
3960 (indent-region (point-min) (point-max) nil))
3961
3962 (defun verilog-insert-block ()
3963 "Insert Verilog begin ... end; block in the code with right indentation."
3964 (interactive)
3965 (verilog-indent-line)
3966 (insert "begin")
3967 (electric-verilog-terminate-line)
3968 (save-excursion
3969 (electric-verilog-terminate-line)
3970 (insert "end")
3971 (beginning-of-line)
3972 (verilog-indent-line)))
3973
3974 (defun verilog-star-comment ()
3975 "Insert Verilog star comment at point."
3976 (interactive)
3977 (verilog-indent-line)
3978 (insert "/*")
3979 (save-excursion
3980 (newline)
3981 (insert " */"))
3982 (newline)
3983 (insert " * "))
3984
3985 (defun verilog-insert-1 (fmt max)
3986 "Use format string FMT to insert integers 0 to MAX - 1.
3987 Inserts one integer per line, at the current column. Stops early
3988 if it reaches the end of the buffer."
3989 (let ((col (current-column))
3990 (n 0))
3991 (save-excursion
3992 (while (< n max)
3993 (insert (format fmt n))
3994 (forward-line 1)
3995 ;; Note that this function does not bother to check for lines
3996 ;; shorter than col.
3997 (if (eobp)
3998 (setq n max)
3999 (setq n (1+ n))
4000 (move-to-column col))))))
4001
4002 (defun verilog-insert-indices (max)
4003 "Insert a set of indices into a rectangle.
4004 The upper left corner is defined by point. Indices begin with 0
4005 and extend to the MAX - 1. If no prefix arg is given, the user
4006 is prompted for a value. The indices are surrounded by square
4007 brackets \[]. For example, the following code with the point
4008 located after the first 'a' gives:
4009
4010 a = b a[ 0] = b
4011 a = b a[ 1] = b
4012 a = b a[ 2] = b
4013 a = b a[ 3] = b
4014 a = b ==> insert-indices ==> a[ 4] = b
4015 a = b a[ 5] = b
4016 a = b a[ 6] = b
4017 a = b a[ 7] = b
4018 a = b a[ 8] = b"
4019
4020 (interactive "NMAX: ")
4021 (verilog-insert-1 "[%3d]" max))
4022
4023 (defun verilog-generate-numbers (max)
4024 "Insert a set of generated numbers into a rectangle.
4025 The upper left corner is defined by point. The numbers are padded to three
4026 digits, starting with 000 and extending to (MAX - 1). If no prefix argument
4027 is supplied, then the user is prompted for the MAX number. Consider the
4028 following code fragment:
4029
4030 buf buf buf buf000
4031 buf buf buf buf001
4032 buf buf buf buf002
4033 buf buf buf buf003
4034 buf buf ==> generate-numbers ==> buf buf004
4035 buf buf buf buf005
4036 buf buf buf buf006
4037 buf buf buf buf007
4038 buf buf buf buf008"
4039
4040 (interactive "NMAX: ")
4041 (verilog-insert-1 "%3.3d" max))
4042
4043 (defun verilog-mark-defun ()
4044 "Mark the current Verilog function (or procedure).
4045 This puts the mark at the end, and point at the beginning."
4046 (interactive)
4047 (if (featurep 'xemacs)
4048 (progn
4049 (push-mark (point))
4050 (verilog-end-of-defun)
4051 (push-mark (point))
4052 (verilog-beg-of-defun)
4053 (if (fboundp 'zmacs-activate-region)
4054 (zmacs-activate-region)))
4055 (mark-defun)))
4056
4057 (defun verilog-comment-region (start end)
4058 ;; checkdoc-params: (start end)
4059 "Put the region into a Verilog comment.
4060 The comments that are in this area are \"deformed\":
4061 `*)' becomes `!(*' and `}' becomes `!{'.
4062 These deformed comments are returned to normal if you use
4063 \\[verilog-uncomment-region] to undo the commenting.
4064
4065 The commented area starts with `verilog-exclude-str-start', and ends with
4066 `verilog-exclude-str-end'. But if you change these variables,
4067 \\[verilog-uncomment-region] won't recognize the comments."
4068 (interactive "r")
4069 (save-excursion
4070 ;; Insert start and endcomments
4071 (goto-char end)
4072 (if (and (save-excursion (skip-chars-forward " \t") (eolp))
4073 (not (save-excursion (skip-chars-backward " \t") (bolp))))
4074 (forward-line 1)
4075 (beginning-of-line))
4076 (insert verilog-exclude-str-end)
4077 (setq end (point))
4078 (newline)
4079 (goto-char start)
4080 (beginning-of-line)
4081 (insert verilog-exclude-str-start)
4082 (newline)
4083 ;; Replace end-comments within commented area
4084 (goto-char end)
4085 (save-excursion
4086 (while (re-search-backward "\\*/" start t)
4087 (replace-match "*-/" t t)))
4088 (save-excursion
4089 (let ((s+1 (1+ start)))
4090 (while (re-search-backward "/\\*" s+1 t)
4091 (replace-match "/-*" t t))))))
4092
4093 (defun verilog-uncomment-region ()
4094 "Uncomment a commented area; change deformed comments back to normal.
4095 This command does nothing if the pointer is not in a commented
4096 area. See also `verilog-comment-region'."
4097 (interactive)
4098 (save-excursion
4099 (let ((start (point))
4100 (end (point)))
4101 ;; Find the boundaries of the comment
4102 (save-excursion
4103 (setq start (progn (search-backward verilog-exclude-str-start nil t)
4104 (point)))
4105 (setq end (progn (search-forward verilog-exclude-str-end nil t)
4106 (point))))
4107 ;; Check if we're really inside a comment
4108 (if (or (equal start (point)) (<= end (point)))
4109 (message "Not standing within commented area.")
4110 (progn
4111 ;; Remove endcomment
4112 (goto-char end)
4113 (beginning-of-line)
4114 (let ((pos (point)))
4115 (end-of-line)
4116 (delete-region pos (1+ (point))))
4117 ;; Change comments back to normal
4118 (save-excursion
4119 (while (re-search-backward "\\*-/" start t)
4120 (replace-match "*/" t t)))
4121 (save-excursion
4122 (while (re-search-backward "/-\\*" start t)
4123 (replace-match "/*" t t)))
4124 ;; Remove start comment
4125 (goto-char start)
4126 (beginning-of-line)
4127 (let ((pos (point)))
4128 (end-of-line)
4129 (delete-region pos (1+ (point)))))))))
4130
4131 (defun verilog-beg-of-defun ()
4132 "Move backward to the beginning of the current function or procedure."
4133 (interactive)
4134 (verilog-re-search-backward verilog-defun-re nil 'move))
4135
4136 (defun verilog-beg-of-defun-quick ()
4137 "Move backward to the beginning of the current function or procedure.
4138 Uses `verilog-scan' cache."
4139 (interactive)
4140 (verilog-re-search-backward-quick verilog-defun-re nil 'move))
4141
4142 (defun verilog-end-of-defun ()
4143 "Move forward to the end of the current function or procedure."
4144 (interactive)
4145 (verilog-re-search-forward verilog-end-defun-re nil 'move))
4146
4147 (defun verilog-get-end-of-defun ()
4148 (save-excursion
4149 (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
4150 (point))
4151 (t
4152 (error "%s: Can't find endmodule" (verilog-point-text))
4153 (point-max)))))
4154
4155 (defun verilog-label-be ()
4156 "Label matching begin ... end, fork ... join and case ... endcase statements."
4157 (interactive)
4158 (let ((cnt 0)
4159 (oldpos (point))
4160 (b (progn
4161 (verilog-beg-of-defun)
4162 (point-marker)))
4163 (e (progn
4164 (verilog-end-of-defun)
4165 (point-marker))))
4166 (goto-char (marker-position b))
4167 (if (> (- e b) 200)
4168 (message "Relabeling module..."))
4169 (while (and
4170 (> (marker-position e) (point))
4171 (verilog-re-search-forward
4172 verilog-auto-end-comment-lines-re
4173 nil 'move))
4174 (goto-char (match-beginning 0))
4175 (let ((indent-str (verilog-indent-line)))
4176 (verilog-set-auto-endcomments indent-str 't)
4177 (end-of-line)
4178 (delete-horizontal-space))
4179 (setq cnt (1+ cnt))
4180 (if (= 9 (% cnt 10))
4181 (message "%d..." cnt)))
4182 (goto-char oldpos)
4183 (if (or
4184 (> (- e b) 200)
4185 (> cnt 20))
4186 (message "%d lines auto commented" cnt))))
4187
4188 (defun verilog-beg-of-statement ()
4189 "Move backward to beginning of statement."
4190 (interactive)
4191 ;; Move back token by token until we see the end
4192 ;; of some earlier line.
4193 (let (h)
4194 (while
4195 ;; If the current point does not begin a new
4196 ;; statement, as in the character ahead of us is a ';', or SOF
4197 ;; or the string after us unambiguously starts a statement,
4198 ;; or the token before us unambiguously ends a statement,
4199 ;; then move back a token and test again.
4200 (not (or
4201 ;; stop if beginning of buffer
4202 (bobp)
4203 ;; stop if we find a ;
4204 (= (preceding-char) ?\;)
4205 ;; stop if we see a named coverpoint
4206 (looking-at "\\w+\\W*:\\W*\\(coverpoint\\|cross\\|constraint\\)")
4207 ;; keep going if we are in the middle of a word
4208 (not (or (looking-at "\\<") (forward-word -1)))
4209 ;; stop if we see an assertion (perhaps labeled)
4210 (and
4211 (looking-at "\\(\\<\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(\\<assert\\>\\)")
4212 (progn
4213 (setq h (point))
4214 (save-excursion
4215 (verilog-backward-token)
4216 (if (looking-at verilog-label-re)
4217 (setq h (point))))
4218 (goto-char h)))
4219 ;; stop if we see an extended complete reg, perhaps a complete one
4220 (and
4221 (looking-at verilog-complete-reg)
4222 (let* ((p (point)))
4223 (while (and (looking-at verilog-extended-complete-re)
4224 (progn (setq p (point))
4225 (verilog-backward-token)
4226 (/= p (point)))))
4227 (goto-char p)))
4228 ;; stop if we see a complete reg (previous found extended ones)
4229 (looking-at verilog-basic-complete-re)
4230 ;; stop if previous token is an ender
4231 (save-excursion
4232 (verilog-backward-token)
4233 (looking-at verilog-end-block-re))))
4234 (verilog-backward-syntactic-ws)
4235 (verilog-backward-token))
4236 ;; Now point is where the previous line ended.
4237 (verilog-forward-syntactic-ws)
4238 ;; Skip forward over any preprocessor directives, as they have wacky indentation
4239 (if (looking-at verilog-preprocessor-re)
4240 (progn (goto-char (match-end 0))
4241 (verilog-forward-syntactic-ws)))))
4242
4243 (defun verilog-beg-of-statement-1 ()
4244 "Move backward to beginning of statement."
4245 (interactive)
4246 (if (verilog-in-comment-p)
4247 (verilog-backward-syntactic-ws))
4248 (let ((pt (point)))
4249 (catch 'done
4250 (while (not (looking-at verilog-complete-reg))
4251 (setq pt (point))
4252 (verilog-backward-syntactic-ws)
4253 (if (or (bolp)
4254 (= (preceding-char) ?\;)
4255 (progn
4256 (verilog-backward-token)
4257 (looking-at verilog-ends-re)))
4258 (progn
4259 (goto-char pt)
4260 (throw 'done t)))))
4261 (verilog-forward-syntactic-ws)))
4262 ;
4263 ; (while (and
4264 ; (not (looking-at verilog-complete-reg))
4265 ; (not (bolp))
4266 ; (not (= (preceding-char) ?\;)))
4267 ; (verilog-backward-token)
4268 ; (verilog-backward-syntactic-ws)
4269 ; (setq pt (point)))
4270 ; (goto-char pt)
4271 ; ;(verilog-forward-syntactic-ws)
4272
4273 (defun verilog-end-of-statement ()
4274 "Move forward to end of current statement."
4275 (interactive)
4276 (let ((nest 0) pos)
4277 (cond
4278 ((verilog-in-directive-p)
4279 (forward-line 1)
4280 (backward-char 1))
4281
4282 ((looking-at verilog-beg-block-re)
4283 (verilog-forward-sexp))
4284
4285 ((equal (char-after) ?\})
4286 (forward-char))
4287
4288 ;; Skip to end of statement
4289 ((condition-case nil
4290 (setq pos
4291 (catch 'found
4292 (while t
4293 (forward-sexp 1)
4294 (verilog-skip-forward-comment-or-string)
4295 (if (eolp)
4296 (forward-line 1))
4297 (cond ((looking-at "[ \t]*;")
4298 (skip-chars-forward "^;")
4299 (forward-char 1)
4300 (throw 'found (point)))
4301 ((save-excursion
4302 (forward-sexp -1)
4303 (looking-at verilog-beg-block-re))
4304 (goto-char (match-beginning 0))
4305 (throw 'found nil))
4306 ((looking-at "[ \t]*)")
4307 (throw 'found (point)))
4308 ((eobp)
4309 (throw 'found (point)))
4310 )))
4311
4312 )
4313 (error nil))
4314 (if (not pos)
4315 ;; Skip a whole block
4316 (catch 'found
4317 (while t
4318 (verilog-re-search-forward verilog-end-statement-re nil 'move)
4319 (setq nest (if (match-end 1)
4320 (1+ nest)
4321 (1- nest)))
4322 (cond ((eobp)
4323 (throw 'found (point)))
4324 ((= 0 nest)
4325 (throw 'found (verilog-end-of-statement))))))
4326 pos)))))
4327
4328 (defun verilog-in-case-region-p ()
4329 "Return true if in a case region.
4330 More specifically, point @ in the line foo : @ begin"
4331 (interactive)
4332 (save-excursion
4333 (if (and
4334 (progn (verilog-forward-syntactic-ws)
4335 (looking-at "\\<begin\\>"))
4336 (progn (verilog-backward-syntactic-ws)
4337 (= (preceding-char) ?\:)))
4338 (catch 'found
4339 (let ((nest 1))
4340 (while t
4341 (verilog-re-search-backward
4342 (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
4343 "\\(\\<endcase\\>\\)\\>")
4344 nil 'move)
4345 (cond
4346 ((match-end 3)
4347 (setq nest (1+ nest)))
4348 ((match-end 2)
4349 (if (= nest 1)
4350 (throw 'found 1))
4351 (setq nest (1- nest)))
4352 (t
4353 (throw 'found (= nest 0)))))))
4354 nil)))
4355
4356 (defun verilog-backward-up-list (arg)
4357 "Call `backward-up-list' ARG, ignoring comments."
4358 (let ((parse-sexp-ignore-comments t))
4359 (backward-up-list arg)))
4360
4361 (defun verilog-forward-sexp-cmt (arg)
4362 "Call `forward-sexp' ARG, inside comments."
4363 (let ((parse-sexp-ignore-comments nil))
4364 (forward-sexp arg)))
4365
4366 (defun verilog-forward-sexp-ign-cmt (arg)
4367 "Call `forward-sexp' ARG, ignoring comments."
4368 (let ((parse-sexp-ignore-comments t))
4369 (forward-sexp arg)))
4370
4371 (defun verilog-in-generate-region-p ()
4372 "Return true if in a generate region.
4373 More specifically, after a generate and before an endgenerate."
4374 (interactive)
4375 (let ((nest 1))
4376 (save-excursion
4377 (catch 'done
4378 (while (and
4379 (/= nest 0)
4380 (verilog-re-search-backward
4381 "\\<\\(module\\)\\|\\(generate\\)\\|\\(endgenerate\\)\\>" nil 'move)
4382 (cond
4383 ((match-end 1) ; module - we have crawled out
4384 (throw 'done 1))
4385 ((match-end 2) ; generate
4386 (setq nest (1- nest)))
4387 ((match-end 3) ; endgenerate
4388 (setq nest (1+ nest))))))))
4389 (= nest 0) )) ; return nest
4390
4391 (defun verilog-in-fork-region-p ()
4392 "Return true if between a fork and join."
4393 (interactive)
4394 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
4395 (nest 1))
4396 (save-excursion
4397 (while (and
4398 (/= nest 0)
4399 (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
4400 (cond
4401 ((match-end 1) ; fork
4402 (setq nest (1- nest)))
4403 ((match-end 2) ; join
4404 (setq nest (1+ nest)))))))
4405 (= nest 0) )) ; return nest
4406
4407 (defun verilog-backward-case-item (lim)
4408 "Skip backward to nearest enclosing case item.
4409 Limit search to point LIM."
4410 (interactive)
4411 (let ((str 'nil)
4412 (lim1
4413 (progn
4414 (save-excursion
4415 (verilog-re-search-backward verilog-endcomment-reason-re
4416 lim 'move)
4417 (point)))))
4418 ;; Try to find the real :
4419 (if (save-excursion (search-backward ":" lim1 t))
4420 (let ((colon 0)
4421 b e )
4422 (while
4423 (and
4424 (< colon 1)
4425 (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
4426 lim1 'move))
4427 (cond
4428 ((match-end 1) ;; [
4429 (setq colon (1+ colon))
4430 (if (>= colon 0)
4431 (error "%s: unbalanced [" (verilog-point-text))))
4432 ((match-end 2) ;; ]
4433 (setq colon (1- colon)))
4434
4435 ((match-end 3) ;; :
4436 (setq colon (1+ colon)))))
4437 ;; Skip back to beginning of case item
4438 (skip-chars-backward "\t ")
4439 (verilog-skip-backward-comment-or-string)
4440 (setq e (point))
4441 (setq b
4442 (progn
4443 (if
4444 (verilog-re-search-backward
4445 "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
4446 (progn
4447 (cond
4448 ((match-end 1)
4449 (goto-char (match-end 1))
4450 (verilog-forward-ws&directives)
4451 (if (looking-at "(")
4452 (progn
4453 (forward-sexp)
4454 (verilog-forward-ws&directives)))
4455 (point))
4456 (t
4457 (goto-char (match-end 0))
4458 (verilog-forward-ws&directives)
4459 (point))))
4460 (error "Malformed case item"))))
4461 (setq str (buffer-substring b e))
4462 (if
4463 (setq e
4464 (string-match
4465 "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
4466 (setq str (concat (substring str 0 e) "...")))
4467 str)
4468 'nil)))
4469 \f
4470
4471 ;;
4472 ;; Other functions
4473 ;;
4474
4475 (defun verilog-kill-existing-comment ()
4476 "Kill auto comment on this line."
4477 (save-excursion
4478 (let* (
4479 (e (progn
4480 (end-of-line)
4481 (point)))
4482 (b (progn
4483 (beginning-of-line)
4484 (search-forward "//" e t))))
4485 (if b
4486 (delete-region (- b 2) e)))))
4487
4488 (defconst verilog-directive-nest-re
4489 (concat "\\(`else\\>\\)\\|"
4490 "\\(`endif\\>\\)\\|"
4491 "\\(`if\\>\\)\\|"
4492 "\\(`ifdef\\>\\)\\|"
4493 "\\(`ifndef\\>\\)\\|"
4494 "\\(`elsif\\>\\)"))
4495
4496 (defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
4497 "Add ending comment with given INDENT-STR.
4498 With KILL-EXISTING-COMMENT, remove what was there before.
4499 Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
4500 Insert `// case expr ' if this line ends a case block.
4501 Insert `// ifdef FOO ' if this line ends code conditional on FOO.
4502 Insert `// NAME ' if this line ends a function, task, module,
4503 primitive or interface named NAME."
4504 (save-excursion
4505 (cond
4506 (; Comment close preprocessor directives
4507 (and
4508 (looking-at "\\(`endif\\)\\|\\(`else\\)")
4509 (or kill-existing-comment
4510 (not (save-excursion
4511 (end-of-line)
4512 (search-backward "//" (point-at-bol) t)))))
4513 (let ((nest 1) b e
4514 m
4515 (else (if (match-end 2) "!" " ")))
4516 (end-of-line)
4517 (if kill-existing-comment
4518 (verilog-kill-existing-comment))
4519 (delete-horizontal-space)
4520 (save-excursion
4521 (backward-sexp 1)
4522 (while (and (/= nest 0)
4523 (verilog-re-search-backward verilog-directive-nest-re nil 'move))
4524 (cond
4525 ((match-end 1) ; `else
4526 (if (= nest 1)
4527 (setq else "!")))
4528 ((match-end 2) ; `endif
4529 (setq nest (1+ nest)))
4530 ((match-end 3) ; `if
4531 (setq nest (1- nest)))
4532 ((match-end 4) ; `ifdef
4533 (setq nest (1- nest)))
4534 ((match-end 5) ; `ifndef
4535 (setq nest (1- nest)))
4536 ((match-end 6) ; `elsif
4537 (if (= nest 1)
4538 (progn
4539 (setq else "!")
4540 (setq nest 0))))))
4541 (if (match-end 0)
4542 (setq
4543 m (buffer-substring
4544 (match-beginning 0)
4545 (match-end 0))
4546 b (progn
4547 (skip-chars-forward "^ \t")
4548 (verilog-forward-syntactic-ws)
4549 (point))
4550 e (progn
4551 (skip-chars-forward "a-zA-Z0-9_")
4552 (point)))))
4553 (if b
4554 (if (> (count-lines (point) b) verilog-minimum-comment-distance)
4555 (insert (concat " // " else m " " (buffer-substring b e))))
4556 (progn
4557 (insert " // unmatched `else, `elsif or `endif")
4558 (ding 't)))))
4559
4560 (; Comment close case/class/function/task/module and named block
4561 (and (looking-at "\\<end")
4562 (or kill-existing-comment
4563 (not (save-excursion
4564 (end-of-line)
4565 (search-backward "//" (point-at-bol) t)))))
4566 (let ((type (car indent-str)))
4567 (unless (eq type 'declaration)
4568 (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
4569 (if (looking-at verilog-end-block-ordered-re)
4570 (cond
4571 (;- This is a case block; search back for the start of this case
4572 (match-end 1) ;; of verilog-end-block-ordered-re
4573
4574 (let ((err 't)
4575 (str "UNMATCHED!!"))
4576 (save-excursion
4577 (verilog-leap-to-head)
4578 (cond
4579 ((looking-at "\\<randcase\\>")
4580 (setq str "randcase")
4581 (setq err nil))
4582 ((looking-at "\\(\\(unique0?\\s-+\\|priority\\s-+\\)?case[xz]?\\)")
4583 (goto-char (match-end 0))
4584 (setq str (concat (match-string 0) " " (verilog-get-expr)))
4585 (setq err nil))
4586 ))
4587 (end-of-line)
4588 (if kill-existing-comment
4589 (verilog-kill-existing-comment))
4590 (delete-horizontal-space)
4591 (insert (concat " // " str ))
4592 (if err (ding 't))))
4593
4594 (;- This is a begin..end block
4595 (match-end 2) ;; of verilog-end-block-ordered-re
4596 (let ((str " // UNMATCHED !!")
4597 (err 't)
4598 (here (point))
4599 there
4600 cntx)
4601 (save-excursion
4602 (verilog-leap-to-head)
4603 (setq there (point))
4604 (if (not (match-end 0))
4605 (progn
4606 (goto-char here)
4607 (end-of-line)
4608 (if kill-existing-comment
4609 (verilog-kill-existing-comment))
4610 (delete-horizontal-space)
4611 (insert str)
4612 (ding 't))
4613 (let ((lim
4614 (save-excursion (verilog-beg-of-defun) (point)))
4615 (here (point)))
4616 (cond
4617 (;-- handle named block differently
4618 (looking-at verilog-named-block-re)
4619 (search-forward ":")
4620 (setq there (point))
4621 (setq str (verilog-get-expr))
4622 (setq err nil)
4623 (setq str (concat " // block: " str )))
4624
4625 ((verilog-in-case-region-p) ;-- handle case item differently
4626 (goto-char here)
4627 (setq str (verilog-backward-case-item lim))
4628 (setq there (point))
4629 (setq err nil)
4630 (setq str (concat " // case: " str )))
4631
4632 (;- try to find "reason" for this begin
4633 (cond
4634 (;
4635 (eq here (progn
4636 ;; (verilog-backward-token)
4637 (verilog-beg-of-statement)
4638 (point)))
4639 (setq err nil)
4640 (setq str ""))
4641 ((looking-at verilog-endcomment-reason-re)
4642 (setq there (match-end 0))
4643 (setq cntx (concat (match-string 0) " "))
4644 (cond
4645 (;- begin
4646 (match-end 1)
4647 (setq err nil)
4648 (save-excursion
4649 (if (and (verilog-continued-line)
4650 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
4651 (progn
4652 (goto-char (match-end 0))
4653 (setq there (point))
4654 (setq str
4655 (concat " // " (match-string 0) " " (verilog-get-expr))))
4656 (setq str ""))))
4657
4658 (;- else
4659 (match-end 2)
4660 (let ((nest 0)
4661 ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
4662 (catch 'skip
4663 (while (verilog-re-search-backward reg nil 'move)
4664 (cond
4665 ((match-end 1) ; begin
4666 (setq nest (1- nest)))
4667 ((match-end 2) ; end
4668 (setq nest (1+ nest)))
4669 ((match-end 3)
4670 (if (= 0 nest)
4671 (progn
4672 (goto-char (match-end 0))
4673 (setq there (point))
4674 (setq err nil)
4675 (setq str (verilog-get-expr))
4676 (setq str (concat " // else: !if" str ))
4677 (throw 'skip 1))))
4678 ((match-end 4)
4679 (if (= 0 nest)
4680 (progn
4681 (goto-char (match-end 0))
4682 (setq there (point))
4683 (setq err nil)
4684 (setq str (verilog-get-expr))
4685 (setq str (concat " // else: !assert " str ))
4686 (throw 'skip 1)))))))))
4687 (;- end else
4688 (match-end 3)
4689 (goto-char there)
4690 (let ((nest 0)
4691 (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
4692 (catch 'skip
4693 (while (verilog-re-search-backward reg nil 'move)
4694 (cond
4695 ((match-end 1) ; begin
4696 (setq nest (1- nest)))
4697 ((match-end 2) ; end
4698 (setq nest (1+ nest)))
4699 ((match-end 3)
4700 (if (= 0 nest)
4701 (progn
4702 (goto-char (match-end 0))
4703 (setq there (point))
4704 (setq err nil)
4705 (setq str (verilog-get-expr))
4706 (setq str (concat " // else: !if" str ))
4707 (throw 'skip 1))))
4708 ((match-end 4)
4709 (if (= 0 nest)
4710 (progn
4711 (goto-char (match-end 0))
4712 (setq there (point))
4713 (setq err nil)
4714 (setq str (verilog-get-expr))
4715 (setq str (concat " // else: !assert " str ))
4716 (throw 'skip 1)))))))))
4717
4718 (; always_comb, always_ff, always_latch
4719 (or (match-end 4) (match-end 5) (match-end 6))
4720 (goto-char (match-end 0))
4721 (setq there (point))
4722 (setq err nil)
4723 (setq str (concat " // " cntx )))
4724
4725 (;- task/function/initial et cetera
4726 t
4727 (match-end 0)
4728 (goto-char (match-end 0))
4729 (setq there (point))
4730 (setq err nil)
4731 (setq str (concat " // " cntx (verilog-get-expr))))
4732
4733 (;-- otherwise...
4734 (setq str " // auto-endcomment confused "))))
4735
4736 ((and
4737 (verilog-in-case-region-p) ;-- handle case item differently
4738 (progn
4739 (setq there (point))
4740 (goto-char here)
4741 (setq str (verilog-backward-case-item lim))))
4742 (setq err nil)
4743 (setq str (concat " // case: " str )))
4744
4745 ((verilog-in-fork-region-p)
4746 (setq err nil)
4747 (setq str " // fork branch" ))
4748
4749 ((looking-at "\\<end\\>")
4750 ;; HERE
4751 (forward-word 1)
4752 (verilog-forward-syntactic-ws)
4753 (setq err nil)
4754 (setq str (verilog-get-expr))
4755 (setq str (concat " // " cntx str )))
4756
4757 ))))
4758 (goto-char here)
4759 (end-of-line)
4760 (if kill-existing-comment
4761 (verilog-kill-existing-comment))
4762 (delete-horizontal-space)
4763 (if (or err
4764 (> (count-lines here there) verilog-minimum-comment-distance))
4765 (insert str))
4766 (if err (ding 't))
4767 ))))
4768 (;- this is endclass, which can be nested
4769 (match-end 11) ;; of verilog-end-block-ordered-re
4770 ;;(goto-char there)
4771 (let ((nest 0)
4772 (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
4773 string)
4774 (save-excursion
4775 (catch 'skip
4776 (while (verilog-re-search-backward reg nil 'move)
4777 (cond
4778 ((match-end 3) ; endclass
4779 (ding 't)
4780 (setq string "unmatched endclass")
4781 (throw 'skip 1))
4782
4783 ((match-end 2) ; endclass
4784 (setq nest (1+ nest)))
4785
4786 ((match-end 1) ; class
4787 (setq nest (1- nest))
4788 (if (< nest 0)
4789 (progn
4790 (goto-char (match-end 0))
4791 (let (b e)
4792 (setq b (progn
4793 (skip-chars-forward "^ \t")
4794 (verilog-forward-ws&directives)
4795 (point))
4796 e (progn
4797 (skip-chars-forward "a-zA-Z0-9_")
4798 (point)))
4799 (setq string (buffer-substring b e)))
4800 (throw 'skip 1))))
4801 ))))
4802 (end-of-line)
4803 (insert (concat " // " string ))))
4804
4805 (;- this is end{function,generate,task,module,primitive,table,generate}
4806 ;- which can not be nested.
4807 t
4808 (let (string reg (name-re nil))
4809 (end-of-line)
4810 (if kill-existing-comment
4811 (save-match-data
4812 (verilog-kill-existing-comment)))
4813 (delete-horizontal-space)
4814 (backward-sexp)
4815 (cond
4816 ((match-end 5) ;; of verilog-end-block-ordered-re
4817 (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
4818 (setq name-re "\\w+\\(?:\n\\|\\s-\\)*[(;]"))
4819 ((match-end 6) ;; of verilog-end-block-ordered-re
4820 (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
4821 (setq name-re "\\w+\\(?:\n\\|\\s-\\)*[(;]"))
4822 ((match-end 7) ;; of verilog-end-block-ordered-re
4823 (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
4824 ((match-end 8) ;; of verilog-end-block-ordered-re
4825 (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4826 ((match-end 9) ;; of verilog-end-block-ordered-re
4827 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
4828 ((match-end 10) ;; of verilog-end-block-ordered-re
4829 (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4830 ((match-end 11) ;; of verilog-end-block-ordered-re
4831 (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4832 ((match-end 12) ;; of verilog-end-block-ordered-re
4833 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4834 ((match-end 13) ;; of verilog-end-block-ordered-re
4835 (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4836 ((match-end 14) ;; of verilog-end-block-ordered-re
4837 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4838 ((match-end 15) ;; of verilog-end-block-ordered-re
4839 (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
4840 ((match-end 16) ;; of verilog-end-block-ordered-re
4841 (setq reg "\\(\\<property\\>\\)\\|\\<endproperty\\>"))
4842
4843 (t (error "Problem in verilog-set-auto-endcomments")))
4844 (let (b e)
4845 (save-excursion
4846 (verilog-re-search-backward reg nil 'move)
4847 (cond
4848 ((match-end 1)
4849 (setq b (progn
4850 (skip-chars-forward "^ \t")
4851 (verilog-forward-ws&directives)
4852 (if (looking-at "static\\|automatic")
4853 (progn
4854 (goto-char (match-end 0))
4855 (verilog-forward-ws&directives)))
4856 (if (and name-re (verilog-re-search-forward name-re nil 'move))
4857 (progn
4858 (goto-char (match-beginning 0))
4859 (verilog-forward-ws&directives)))
4860 (point))
4861 e (progn
4862 (skip-chars-forward "a-zA-Z0-9_")
4863 (point)))
4864 (setq string (buffer-substring b e)))
4865 (t
4866 (ding 't)
4867 (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
4868 (end-of-line)
4869 (insert (concat " // " string )))
4870 ))))))))))
4871
4872 (defun verilog-get-expr()
4873 "Grab expression at point, e.g., case ( a | b & (c ^d))."
4874 (let* ((b (progn
4875 (verilog-forward-syntactic-ws)
4876 (skip-chars-forward " \t")
4877 (point)))
4878 (e (let ((par 1))
4879 (cond
4880 ((looking-at "@")
4881 (forward-char 1)
4882 (verilog-forward-syntactic-ws)
4883 (if (looking-at "(")
4884 (progn
4885 (forward-char 1)
4886 (while (and (/= par 0)
4887 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4888 (cond
4889 ((match-end 1)
4890 (setq par (1+ par)))
4891 ((match-end 2)
4892 (setq par (1- par)))))))
4893 (point))
4894 ((looking-at "(")
4895 (forward-char 1)
4896 (while (and (/= par 0)
4897 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4898 (cond
4899 ((match-end 1)
4900 (setq par (1+ par)))
4901 ((match-end 2)
4902 (setq par (1- par)))))
4903 (point))
4904 ((looking-at "\\[")
4905 (forward-char 1)
4906 (while (and (/= par 0)
4907 (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
4908 (cond
4909 ((match-end 1)
4910 (setq par (1+ par)))
4911 ((match-end 2)
4912 (setq par (1- par)))))
4913 (verilog-forward-syntactic-ws)
4914 (skip-chars-forward "^ \t\n\f")
4915 (point))
4916 ((looking-at "/[/\\*]")
4917 b)
4918 ('t
4919 (skip-chars-forward "^: \t\n\f")
4920 (point)))))
4921 (str (buffer-substring b e)))
4922 (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
4923 (setq str (concat (substring str 0 e) "...")))
4924 str))
4925
4926 (defun verilog-expand-vector ()
4927 "Take a signal vector on the current line and expand it to multiple lines.
4928 Useful for creating tri's and other expanded fields."
4929 (interactive)
4930 (verilog-expand-vector-internal "[" "]"))
4931
4932 (defun verilog-expand-vector-internal (bra ket)
4933 "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
4934 (save-excursion
4935 (forward-line 0)
4936 (let ((signal-string (buffer-substring (point)
4937 (progn
4938 (end-of-line) (point)))))
4939 (if (string-match
4940 (concat "\\(.*\\)"
4941 (regexp-quote bra)
4942 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
4943 (regexp-quote ket)
4944 "\\(.*\\)$") signal-string)
4945 (let* ((sig-head (match-string 1 signal-string))
4946 (vec-start (string-to-number (match-string 2 signal-string)))
4947 (vec-end (if (= (match-beginning 3) (match-end 3))
4948 vec-start
4949 (string-to-number
4950 (substring signal-string (1+ (match-beginning 3))
4951 (match-end 3)))))
4952 (vec-range
4953 (if (= (match-beginning 4) (match-end 4))
4954 1
4955 (string-to-number
4956 (substring signal-string (+ 2 (match-beginning 4))
4957 (match-end 4)))))
4958 (sig-tail (match-string 5 signal-string))
4959 vec)
4960 ;; Decode vectors
4961 (setq vec nil)
4962 (if (< vec-range 0)
4963 (let ((tmp vec-start))
4964 (setq vec-start vec-end
4965 vec-end tmp
4966 vec-range (- vec-range))))
4967 (if (< vec-end vec-start)
4968 (while (<= vec-end vec-start)
4969 (setq vec (append vec (list vec-start)))
4970 (setq vec-start (- vec-start vec-range)))
4971 (while (<= vec-start vec-end)
4972 (setq vec (append vec (list vec-start)))
4973 (setq vec-start (+ vec-start vec-range))))
4974 ;;
4975 ;; Delete current line
4976 (delete-region (point) (progn (forward-line 0) (point)))
4977 ;;
4978 ;; Expand vector
4979 (while vec
4980 (insert (concat sig-head bra
4981 (int-to-string (car vec)) ket sig-tail "\n"))
4982 (setq vec (cdr vec)))
4983 (delete-char -1)
4984 ;;
4985 )))))
4986
4987 (defun verilog-strip-comments ()
4988 "Strip all comments from the Verilog code."
4989 (interactive)
4990 (goto-char (point-min))
4991 (while (re-search-forward "//" nil t)
4992 (if (verilog-within-string)
4993 (re-search-forward "\"" nil t)
4994 (if (verilog-in-star-comment-p)
4995 (re-search-forward "\*/" nil t)
4996 (let ((bpt (- (point) 2)))
4997 (end-of-line)
4998 (delete-region bpt (point))))))
4999 ;;
5000 (goto-char (point-min))
5001 (while (re-search-forward "/\\*" nil t)
5002 (if (verilog-within-string)
5003 (re-search-forward "\"" nil t)
5004 (let ((bpt (- (point) 2)))
5005 (re-search-forward "\\*/")
5006 (delete-region bpt (point))))))
5007
5008 (defun verilog-one-line ()
5009 "Convert structural Verilog instances to occupy one line."
5010 (interactive)
5011 (goto-char (point-min))
5012 (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
5013 (replace-match "\\1 " nil nil)))
5014
5015 (defun verilog-linter-name ()
5016 "Return name of linter, either surelint or verilint."
5017 (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
5018 compile-command))
5019 (lint-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
5020 verilog-linter)))
5021 (cond ((equal compile-word1 "surelint") `surelint)
5022 ((equal compile-word1 "verilint") `verilint)
5023 ((equal lint-word1 "surelint") `surelint)
5024 ((equal lint-word1 "verilint") `verilint)
5025 (t `surelint)))) ;; back compatibility
5026
5027 (defun verilog-lint-off ()
5028 "Convert a Verilog linter warning line into a disable statement.
5029 For example:
5030 pci_bfm_null.v, line 46: Unused input: pci_rst_
5031 becomes a comment for the appropriate tool.
5032
5033 The first word of the `compile-command' or `verilog-linter'
5034 variables is used to determine which product is being used.
5035
5036 See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
5037 (interactive)
5038 (let ((linter (verilog-linter-name)))
5039 (cond ((equal linter `surelint)
5040 (verilog-surelint-off))
5041 ((equal linter `verilint)
5042 (verilog-verilint-off))
5043 (t (error "Linter name not set")))))
5044
5045 (defvar compilation-last-buffer)
5046 (defvar next-error-last-buffer)
5047
5048 (defun verilog-surelint-off ()
5049 "Convert a SureLint warning line into a disable statement.
5050 Run from Verilog source window; assumes there is a *compile* buffer
5051 with point set appropriately.
5052
5053 For example:
5054 WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
5055 becomes:
5056 // surefire lint_line_off UDDONX"
5057 (interactive)
5058 (let ((buff (if (boundp 'next-error-last-buffer)
5059 next-error-last-buffer
5060 compilation-last-buffer)))
5061 (when (buffer-live-p buff)
5062 (save-excursion
5063 (switch-to-buffer buff)
5064 (beginning-of-line)
5065 (when
5066 (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
5067 (let* ((code (match-string 2))
5068 (file (match-string 3))
5069 (line (match-string 4))
5070 (buffer (get-file-buffer file))
5071 dir filename)
5072 (unless buffer
5073 (progn
5074 (setq buffer
5075 (and (file-exists-p file)
5076 (find-file-noselect file)))
5077 (or buffer
5078 (let* ((pop-up-windows t))
5079 (let ((name (expand-file-name
5080 (read-file-name
5081 (format "Find this error in: (default %s) "
5082 file)
5083 dir file t))))
5084 (if (file-directory-p name)
5085 (setq name (expand-file-name filename name)))
5086 (setq buffer
5087 (and (file-exists-p name)
5088 (find-file-noselect name))))))))
5089 (switch-to-buffer buffer)
5090 (goto-char (point-min))
5091 (forward-line (- (string-to-number line)))
5092 (end-of-line)
5093 (catch 'already
5094 (cond
5095 ((verilog-in-slash-comment-p)
5096 (re-search-backward "//")
5097 (cond
5098 ((looking-at "// surefire lint_off_line ")
5099 (goto-char (match-end 0))
5100 (let ((lim (point-at-eol)))
5101 (if (re-search-forward code lim 'move)
5102 (throw 'already t)
5103 (insert (concat " " code)))))
5104 (t
5105 )))
5106 ((verilog-in-star-comment-p)
5107 (re-search-backward "/\*")
5108 (insert (format " // surefire lint_off_line %6s" code )))
5109 (t
5110 (insert (format " // surefire lint_off_line %6s" code ))
5111 )))))))))
5112
5113 (defun verilog-verilint-off ()
5114 "Convert a Verilint warning line into a disable statement.
5115
5116 For example:
5117 (W240) pci_bfm_null.v, line 46: Unused input: pci_rst_
5118 becomes:
5119 //Verilint 240 off // WARNING: Unused input"
5120 (interactive)
5121 (save-excursion
5122 (beginning-of-line)
5123 (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
5124 (replace-match (format
5125 ;; %3s makes numbers 1-999 line up nicely
5126 "\\1//Verilint %3s off // WARNING: \\3"
5127 (match-string 2)))
5128 (beginning-of-line)
5129 (verilog-indent-line))))
5130
5131 (defun verilog-auto-save-compile ()
5132 "Update automatics with \\[verilog-auto], save the buffer, and compile."
5133 (interactive)
5134 (verilog-auto) ; Always do it for safety
5135 (save-buffer)
5136 (compile compile-command))
5137
5138 (defun verilog-preprocess (&optional command filename)
5139 "Preprocess the buffer, similar to `compile', but put output in Verilog-Mode.
5140 Takes optional COMMAND or defaults to `verilog-preprocessor', and
5141 FILENAME to find directory to run in, or defaults to `buffer-file-name`."
5142 (interactive
5143 (list
5144 (let ((default (verilog-expand-command verilog-preprocessor)))
5145 (set (make-local-variable `verilog-preprocessor)
5146 (read-from-minibuffer "Run Preprocessor (like this): "
5147 default nil nil
5148 'verilog-preprocess-history default)))))
5149 (unless command (setq command (verilog-expand-command verilog-preprocessor)))
5150 (let* ((fontlocked (and (boundp 'font-lock-mode) font-lock-mode))
5151 (dir (file-name-directory (or filename buffer-file-name)))
5152 (cmd (concat "cd " dir "; " command)))
5153 (with-output-to-temp-buffer "*Verilog-Preprocessed*"
5154 (with-current-buffer (get-buffer "*Verilog-Preprocessed*")
5155 (insert (concat "// " cmd "\n"))
5156 (call-process shell-file-name nil t nil shell-command-switch cmd)
5157 (verilog-mode)
5158 ;; Without this force, it takes a few idle seconds
5159 ;; to get the color, which is very jarring
5160 (unless (fboundp 'font-lock-ensure)
5161 ;; We should use font-lock-ensure in preference to
5162 ;; font-lock-fontify-buffer, but IIUC the problem this is supposed to
5163 ;; solve only appears in Emacsen older than font-lock-ensure anyway.
5164 (when fontlocked (font-lock-fontify-buffer)))))))
5165 \f
5166
5167 ;;
5168 ;; Batch
5169 ;;
5170
5171 (defun verilog-warn (string &rest args)
5172 "Print a warning with `format' using STRING and optional ARGS."
5173 (apply 'message (concat "%%Warning: " string) args))
5174
5175 (defun verilog-warn-error (string &rest args)
5176 "Call `error' using STRING and optional ARGS.
5177 If `verilog-warn-fatal' is non-nil, call `verilog-warn' instead."
5178 (if verilog-warn-fatal
5179 (apply 'error string args)
5180 (apply 'verilog-warn string args)))
5181
5182 (defmacro verilog-batch-error-wrapper (&rest body)
5183 "Execute BODY and add error prefix to any errors found.
5184 This lets programs calling batch mode to easily extract error messages."
5185 `(let ((verilog-warn-fatal nil))
5186 (condition-case err
5187 (progn ,@body)
5188 (error
5189 (error "%%Error: %s%s" (error-message-string err)
5190 (if (featurep 'xemacs) "\n" "")))))) ;; XEmacs forgets to add a newline
5191
5192 (defun verilog-batch-execute-func (funref &optional no-save)
5193 "Internal processing of a batch command.
5194 Runs FUNREF on all command arguments.
5195 Save the result unless optional NO-SAVE is t."
5196 (verilog-batch-error-wrapper
5197 ;; Setting global variables like that is *VERY NASTY* !!! --Stef
5198 ;; However, this function is called only when Emacs is being used as
5199 ;; a standalone language instead of as an editor, so we'll live.
5200 ;;
5201 ;; General globals needed
5202 (setq make-backup-files nil)
5203 (setq-default make-backup-files nil)
5204 (setq enable-local-variables t)
5205 (setq enable-local-eval t)
5206 (setq create-lockfiles nil)
5207 ;; Make sure any sub-files we read get proper mode
5208 (setq-default major-mode 'verilog-mode)
5209 ;; Ditto files already read in
5210 ;; Remember buffer list, so don't later pickup any verilog-getopt files
5211 (let ((orig-buffer-list (buffer-list)))
5212 (mapc (lambda (buf)
5213 (when (buffer-file-name buf)
5214 (with-current-buffer buf
5215 (verilog-mode)
5216 (verilog-auto-reeval-locals)
5217 (verilog-getopt-flags))))
5218 orig-buffer-list)
5219 ;; Process the files
5220 (mapcar (lambda (buf)
5221 (when (buffer-file-name buf)
5222 (save-excursion
5223 (if (not (file-exists-p (buffer-file-name buf)))
5224 (error
5225 (concat "File not found: " (buffer-file-name buf))))
5226 (message (concat "Processing " (buffer-file-name buf)))
5227 (set-buffer buf)
5228 (funcall funref)
5229 (when (and (not no-save)
5230 (buffer-modified-p)) ;; Avoid "no changes to be saved"
5231 (save-buffer)))))
5232 orig-buffer-list))))
5233
5234 (defun verilog-batch-auto ()
5235 "For use with --batch, perform automatic expansions as a stand-alone tool.
5236 This sets up the appropriate Verilog mode environment, updates automatics
5237 with \\[verilog-auto] on all command-line files, and saves the buffers.
5238 For proper results, multiple filenames need to be passed on the command
5239 line in bottom-up order."
5240 (unless noninteractive
5241 (error "Use verilog-batch-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
5242 (verilog-batch-execute-func `verilog-auto))
5243
5244 (defun verilog-batch-delete-auto ()
5245 "For use with --batch, perform automatic deletion as a stand-alone tool.
5246 This sets up the appropriate Verilog mode environment, deletes automatics
5247 with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
5248 (unless noninteractive
5249 (error "Use verilog-batch-delete-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
5250 (verilog-batch-execute-func `verilog-delete-auto))
5251
5252 (defun verilog-batch-delete-trailing-whitespace ()
5253 "For use with --batch, perform whitespace deletion as a stand-alone tool.
5254 This sets up the appropriate Verilog mode environment, removes
5255 whitespace with \\[verilog-delete-trailing-whitespace] on all
5256 command-line files, and saves the buffers."
5257 (unless noninteractive
5258 (error "Use verilog-batch-delete-trailing-whitespace only with --batch")) ;; Otherwise we'd mess up buffer modes
5259 (verilog-batch-execute-func `verilog-delete-trailing-whitespace))
5260
5261 (defun verilog-batch-diff-auto ()
5262 "For use with --batch, perform automatic differences as a stand-alone tool.
5263 This sets up the appropriate Verilog mode environment, expand automatics
5264 with \\[verilog-diff-auto] on all command-line files, and reports an error
5265 if any differences are observed. This is appropriate for adding to regressions
5266 to insure automatics are always properly maintained."
5267 (unless noninteractive
5268 (error "Use verilog-batch-diff-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
5269 (verilog-batch-execute-func `verilog-diff-auto t))
5270
5271 (defun verilog-batch-inject-auto ()
5272 "For use with --batch, perform automatic injection as a stand-alone tool.
5273 This sets up the appropriate Verilog mode environment, injects new automatics
5274 with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
5275 For proper results, multiple filenames need to be passed on the command
5276 line in bottom-up order."
5277 (unless noninteractive
5278 (error "Use verilog-batch-inject-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
5279 (verilog-batch-execute-func `verilog-inject-auto))
5280
5281 (defun verilog-batch-indent ()
5282 "For use with --batch, reindent an entire file as a stand-alone tool.
5283 This sets up the appropriate Verilog mode environment, calls
5284 \\[verilog-indent-buffer] on all command-line files, and saves the buffers."
5285 (unless noninteractive
5286 (error "Use verilog-batch-indent only with --batch")) ;; Otherwise we'd mess up buffer modes
5287 (verilog-batch-execute-func `verilog-indent-buffer))
5288 \f
5289
5290 ;;
5291 ;; Indentation
5292 ;;
5293 (defconst verilog-indent-alist
5294 '((block . (+ ind verilog-indent-level))
5295 (case . (+ ind verilog-case-indent))
5296 (cparenexp . (+ ind verilog-indent-level))
5297 (cexp . (+ ind verilog-cexp-indent))
5298 (defun . verilog-indent-level-module)
5299 (declaration . verilog-indent-level-declaration)
5300 (directive . (verilog-calculate-indent-directive))
5301 (tf . verilog-indent-level)
5302 (behavioral . (+ verilog-indent-level-behavioral verilog-indent-level-module))
5303 (statement . ind)
5304 (cpp . 0)
5305 (comment . (verilog-comment-indent))
5306 (unknown . 3)
5307 (string . 0)))
5308
5309 (defun verilog-continued-line-1 (lim)
5310 "Return true if this is a continued line.
5311 Set point to where line starts. Limit search to point LIM."
5312 (let ((continued 't))
5313 (if (eq 0 (forward-line -1))
5314 (progn
5315 (end-of-line)
5316 (verilog-backward-ws&directives lim)
5317 (if (bobp)
5318 (setq continued nil)
5319 (setq continued (verilog-backward-token))))
5320 (setq continued nil))
5321 continued))
5322
5323 (defun verilog-calculate-indent ()
5324 "Calculate the indent of the current Verilog line.
5325 Examine previous lines. Once a line is found that is definitive as to the
5326 type of the current line, return that lines' indent level and its type.
5327 Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
5328 (save-excursion
5329 (let* ((starting_position (point))
5330 (par 0)
5331 (begin (looking-at "[ \t]*begin\\>"))
5332 (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
5333 (structres nil)
5334 (type (catch 'nesting
5335 ;; Keep working backwards until we can figure out
5336 ;; what type of statement this is.
5337 ;; Basically we need to figure out
5338 ;; 1) if this is a continuation of the previous line;
5339 ;; 2) are we in a block scope (begin..end)
5340
5341 ;; if we are in a comment, done.
5342 (if (verilog-in-star-comment-p)
5343 (throw 'nesting 'comment))
5344
5345 ;; if we have a directive, done.
5346 (if (save-excursion (beginning-of-line)
5347 (and (looking-at verilog-directive-re-1)
5348 (not (or (looking-at "[ \t]*`[ou]vm_")
5349 (looking-at "[ \t]*`vmm_")))))
5350 (throw 'nesting 'directive))
5351 ;; indent structs as if there were module level
5352 (setq structres (verilog-in-struct-nested-p))
5353 (cond ((not structres) nil)
5354 ;;((and structres (equal (char-after) ?\})) (throw 'nesting 'struct-close))
5355 ((> structres 0) (throw 'nesting 'nested-struct))
5356 ((= structres 0) (throw 'nesting 'block))
5357 (t nil))
5358
5359 ;; if we are in a parenthesized list, and the user likes to indent these, return.
5360 ;; unless we are in the newfangled coverpoint or constraint blocks
5361 (if (and
5362 verilog-indent-lists
5363 (verilog-in-paren)
5364 (not (verilog-in-coverage-p))
5365 )
5366 (progn (setq par 1)
5367 (throw 'nesting 'block)))
5368
5369 ;; See if we are continuing a previous line
5370 (while t
5371 ;; trap out if we crawl off the top of the buffer
5372 (if (bobp) (throw 'nesting 'cpp))
5373
5374 (if (and (verilog-continued-line-1 lim)
5375 (or (not (verilog-in-coverage-p))
5376 (looking-at verilog-in-constraint-re) )) ;; may still get hosed if concat in constraint
5377 (let ((sp (point)))
5378 (if (and
5379 (not (looking-at verilog-complete-reg))
5380 (verilog-continued-line-1 lim))
5381 (progn (goto-char sp)
5382 (throw 'nesting 'cexp))
5383
5384 (goto-char sp))
5385 (if (and (verilog-in-coverage-p)
5386 (looking-at verilog-in-constraint-re))
5387 (progn
5388 (beginning-of-line)
5389 (skip-chars-forward " \t")
5390 (throw 'nesting 'constraint)))
5391 (if (and begin
5392 (not verilog-indent-begin-after-if)
5393 (looking-at verilog-no-indent-begin-re))
5394 (progn
5395 (beginning-of-line)
5396 (skip-chars-forward " \t")
5397 (throw 'nesting 'statement))
5398 (progn
5399 (throw 'nesting 'cexp))))
5400 ;; not a continued line
5401 (goto-char starting_position))
5402
5403 (if (looking-at "\\<else\\>")
5404 ;; search back for governing if, striding across begin..end pairs
5405 ;; appropriately
5406 (let ((elsec 1))
5407 (while (verilog-re-search-backward verilog-ends-re nil 'move)
5408 (cond
5409 ((match-end 1) ; else, we're in deep
5410 (setq elsec (1+ elsec)))
5411 ((match-end 2) ; if
5412 (setq elsec (1- elsec))
5413 (if (= 0 elsec)
5414 (if verilog-align-ifelse
5415 (throw 'nesting 'statement)
5416 (progn ;; back up to first word on this line
5417 (beginning-of-line)
5418 (verilog-forward-syntactic-ws)
5419 (throw 'nesting 'statement)))))
5420 ((match-end 3) ; assert block
5421 (setq elsec (1- elsec))
5422 (verilog-beg-of-statement) ;; doesn't get to beginning
5423 (if (looking-at verilog-property-re)
5424 (throw 'nesting 'statement) ; We don't need an endproperty for these
5425 (throw 'nesting 'block) ;We still need an endproperty
5426 ))
5427 (t ; endblock
5428 ; try to leap back to matching outward block by striding across
5429 ; indent level changing tokens then immediately
5430 ; previous line governs indentation.
5431 (let (( reg) (nest 1))
5432 ;; verilog-ends => else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
5433 (cond
5434 ((match-end 4) ; end
5435 ;; Search back for matching begin
5436 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
5437 ((match-end 5) ; endcase
5438 ;; Search back for matching case
5439 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
5440 ((match-end 6) ; endfunction
5441 ;; Search back for matching function
5442 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
5443 ((match-end 7) ; endtask
5444 ;; Search back for matching task
5445 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
5446 ((match-end 8) ; endspecify
5447 ;; Search back for matching specify
5448 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
5449 ((match-end 9) ; endtable
5450 ;; Search back for matching table
5451 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
5452 ((match-end 10) ; endgenerate
5453 ;; Search back for matching generate
5454 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
5455 ((match-end 11) ; joins
5456 ;; Search back for matching fork
5457 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
5458 ((match-end 12) ; class
5459 ;; Search back for matching class
5460 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
5461 ((match-end 13) ; covergroup
5462 ;; Search back for matching covergroup
5463 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
5464 (catch 'skip
5465 (while (verilog-re-search-backward reg nil 'move)
5466 (cond
5467 ((match-end 1) ; begin
5468 (setq nest (1- nest))
5469 (if (= 0 nest)
5470 (throw 'skip 1)))
5471 ((match-end 2) ; end
5472 (setq nest (1+ nest)))))
5473 )))))))
5474 (throw 'nesting (verilog-calc-1)))
5475 );; catch nesting
5476 );; type
5477 )
5478 ;; Return type of block and indent level.
5479 (if (not type)
5480 (setq type 'cpp))
5481 (if (> par 0) ; Unclosed Parenthesis
5482 (list 'cparenexp par)
5483 (cond
5484 ((eq type 'case)
5485 (list type (verilog-case-indent-level)))
5486 ((eq type 'statement)
5487 (list type (current-column)))
5488 ((eq type 'defun)
5489 (list type 0))
5490 ((eq type 'constraint)
5491 (list 'block (current-column)))
5492 ((eq type 'nested-struct)
5493 (list 'block structres))
5494 (t
5495 (list type (verilog-current-indent-level))))))))
5496
5497 (defun verilog-wai ()
5498 "Show matching nesting block for debugging."
5499 (interactive)
5500 (save-excursion
5501 (let* ((type (verilog-calc-1))
5502 depth)
5503 ;; Return type of block and indent level.
5504 (if (not type)
5505 (setq type 'cpp))
5506 (if (and
5507 verilog-indent-lists
5508 (not(or (verilog-in-coverage-p)
5509 (verilog-in-struct-p)))
5510 (verilog-in-paren))
5511 (setq depth 1)
5512 (cond
5513 ((eq type 'case)
5514 (setq depth (verilog-case-indent-level)))
5515 ((eq type 'statement)
5516 (setq depth (current-column)))
5517 ((eq type 'defun)
5518 (setq depth 0))
5519 (t
5520 (setq depth (verilog-current-indent-level)))))
5521 (message "You are at nesting %s depth %d" type depth))))
5522
5523 (defun verilog-calc-1 ()
5524 (catch 'nesting
5525 (let ((re (concat "\\({\\|}\\|" verilog-indent-re "\\)"))
5526 (inconstraint (verilog-in-coverage-p)))
5527 (while (verilog-re-search-backward re nil 'move)
5528 (catch 'continue
5529 (cond
5530 ((equal (char-after) ?\{)
5531 ;; block type returned based on outer constraint { or inner
5532 (if (verilog-at-constraint-p)
5533 (cond (inconstraint (throw 'nesting 'constraint))
5534 (t (throw 'nesting 'statement)))))
5535 ((equal (char-after) ?\})
5536 (let (par-pos
5537 (there (verilog-at-close-constraint-p)))
5538 (if there ;; we are at the } that closes a constraint. Find the { that opens it
5539 (progn
5540 (if (> (verilog-in-paren-count) 0)
5541 (forward-char 1))
5542 (setq par-pos (verilog-parenthesis-depth))
5543 (cond (par-pos
5544 (goto-char par-pos)
5545 (forward-char 1))
5546 (t
5547 (backward-char 1)))))))
5548
5549 ((looking-at verilog-beg-block-re-ordered)
5550 (cond
5551 ((match-end 2) ; *sigh* could be "unique case" or "priority casex"
5552 (let ((here (point)))
5553 (verilog-beg-of-statement)
5554 (if (looking-at verilog-extended-case-re)
5555 (throw 'nesting 'case)
5556 (goto-char here)))
5557 (throw 'nesting 'case))
5558
5559 ((match-end 4) ; *sigh* could be "disable fork"
5560 (let ((here (point)))
5561 (verilog-beg-of-statement)
5562 (if (looking-at verilog-disable-fork-re)
5563 t ; this is a normal statement
5564 (progn ; or is fork, starts a new block
5565 (goto-char here)
5566 (throw 'nesting 'block)))))
5567
5568 ((match-end 27) ; *sigh* might be a clocking declaration
5569 (let ((here (point)))
5570 (if (verilog-in-paren)
5571 t ; this is a normal statement
5572 (progn ; or is fork, starts a new block
5573 (goto-char here)
5574 (throw 'nesting 'block)))))
5575
5576 ;; need to consider typedef struct here...
5577 ((looking-at "\\<class\\|struct\\|function\\|task\\>")
5578 ; *sigh* These words have an optional prefix:
5579 ; extern {virtual|protected}? function a();
5580 ; typedef class foo;
5581 ; and we don't want to confuse this with
5582 ; function a();
5583 ; property
5584 ; ...
5585 ; endfunction
5586 (verilog-beg-of-statement)
5587 (if (looking-at verilog-beg-block-re-ordered)
5588 (throw 'nesting 'block)
5589 (throw 'nesting 'defun)))
5590
5591 ;;
5592 ((looking-at "\\<property\\>")
5593 ; *sigh*
5594 ; {assert|assume|cover} property (); are complete
5595 ; and could also be labeled: - foo: assert property
5596 ; but
5597 ; property ID () ... needs end_property
5598 (verilog-beg-of-statement)
5599 (if (looking-at verilog-property-re)
5600 (throw 'continue 'statement) ; We don't need an endproperty for these
5601 (throw 'nesting 'block) ;We still need an endproperty
5602 ))
5603
5604 (t (throw 'nesting 'block))))
5605
5606 ((looking-at verilog-end-block-re)
5607 (verilog-leap-to-head)
5608 (if (verilog-in-case-region-p)
5609 (progn
5610 (verilog-leap-to-case-head)
5611 (if (looking-at verilog-extended-case-re)
5612 (throw 'nesting 'case)))))
5613
5614 ((looking-at verilog-defun-level-re)
5615 (if (looking-at verilog-defun-level-generate-only-re)
5616 (if (verilog-in-generate-region-p)
5617 (throw 'continue 'foo) ; always block in a generate - keep looking
5618 (throw 'nesting 'defun))
5619 (throw 'nesting 'defun)))
5620
5621 ((looking-at verilog-cpp-level-re)
5622 (throw 'nesting 'cpp))
5623
5624 ((bobp)
5625 (throw 'nesting 'cpp)))))
5626
5627 (throw 'nesting 'cpp))))
5628
5629 (defun verilog-calculate-indent-directive ()
5630 "Return indentation level for directive.
5631 For speed, the searcher looks at the last directive, not the indent
5632 of the appropriate enclosing block."
5633 (let ((base -1) ;; Indent of the line that determines our indentation
5634 (ind 0)) ;; Relative offset caused by other directives (like `endif on same line as `else)
5635 ;; Start at current location, scan back for another directive
5636
5637 (save-excursion
5638 (beginning-of-line)
5639 (while (and (< base 0)
5640 (verilog-re-search-backward verilog-directive-re nil t))
5641 (cond ((save-excursion (skip-chars-backward " \t") (bolp))
5642 (setq base (current-indentation))))
5643 (cond ((and (looking-at verilog-directive-end) (< base 0)) ;; Only matters when not at BOL
5644 (setq ind (- ind verilog-indent-level-directive)))
5645 ((and (looking-at verilog-directive-middle) (>= base 0)) ;; Only matters when at BOL
5646 (setq ind (+ ind verilog-indent-level-directive)))
5647 ((looking-at verilog-directive-begin)
5648 (setq ind (+ ind verilog-indent-level-directive)))))
5649 ;; Adjust indent to starting indent of critical line
5650 (setq ind (max 0 (+ ind base))))
5651
5652 (save-excursion
5653 (beginning-of-line)
5654 (skip-chars-forward " \t")
5655 (cond ((or (looking-at verilog-directive-middle)
5656 (looking-at verilog-directive-end))
5657 (setq ind (max 0 (- ind verilog-indent-level-directive))))))
5658 ind))
5659
5660 (defun verilog-leap-to-case-head ()
5661 (let ((nest 1))
5662 (while (/= 0 nest)
5663 (verilog-re-search-backward
5664 (concat
5665 "\\(\\<randcase\\>\\|\\(\\<unique0?\\s-+\\|priority\\s-+\\)?\\<case[xz]?\\>\\)"
5666 "\\|\\(\\<endcase\\>\\)" )
5667 nil 'move)
5668 (cond
5669 ((match-end 1)
5670 (let ((here (point)))
5671 (verilog-beg-of-statement)
5672 (unless (looking-at verilog-extended-case-re)
5673 (goto-char here)))
5674 (setq nest (1- nest)))
5675 ((match-end 3)
5676 (setq nest (1+ nest)))
5677 ((bobp)
5678 (ding 't)
5679 (setq nest 0))))))
5680
5681 (defun verilog-leap-to-head ()
5682 "Move point to the head of this block.
5683 Jump from end to matching begin, from endcase to matching case, and so on."
5684 (let ((reg nil)
5685 snest
5686 (nesting 'yes)
5687 (nest 1))
5688 (cond
5689 ((looking-at "\\<end\\>")
5690 ;; 1: Search back for matching begin
5691 (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
5692 "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
5693 ((looking-at "\\<endtask\\>")
5694 ;; 2: Search back for matching task
5695 (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
5696 (setq nesting 'no))
5697 ((looking-at "\\<endcase\\>")
5698 (catch 'nesting
5699 (verilog-leap-to-case-head) )
5700 (setq reg nil) ; to force skip
5701 )
5702
5703 ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
5704 ;; 4: Search back for matching fork
5705 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5706 ((looking-at "\\<endclass\\>")
5707 ;; 5: Search back for matching class
5708 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
5709 ((looking-at "\\<endtable\\>")
5710 ;; 6: Search back for matching table
5711 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
5712 ((looking-at "\\<endspecify\\>")
5713 ;; 7: Search back for matching specify
5714 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
5715 ((looking-at "\\<endfunction\\>")
5716 ;; 8: Search back for matching function
5717 (setq reg "\\(\\<function\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<function\\>\\)")
5718 (setq nesting 'no))
5719 ;;(setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
5720 ((looking-at "\\<endgenerate\\>")
5721 ;; 8: Search back for matching generate
5722 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
5723 ((looking-at "\\<endgroup\\>")
5724 ;; 10: Search back for matching covergroup
5725 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
5726 ((looking-at "\\<endproperty\\>")
5727 ;; 11: Search back for matching property
5728 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
5729 ((looking-at verilog-uvm-end-re)
5730 ;; 12: Search back for matching sequence
5731 (setq reg (concat "\\(" verilog-uvm-begin-re "\\|" verilog-uvm-end-re "\\)")))
5732 ((looking-at verilog-ovm-end-re)
5733 ;; 12: Search back for matching sequence
5734 (setq reg (concat "\\(" verilog-ovm-begin-re "\\|" verilog-ovm-end-re "\\)")))
5735 ((looking-at verilog-vmm-end-re)
5736 ;; 12: Search back for matching sequence
5737 (setq reg (concat "\\(" verilog-vmm-begin-re "\\|" verilog-vmm-end-re "\\)")))
5738 ((looking-at "\\<endinterface\\>")
5739 ;; 12: Search back for matching interface
5740 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
5741 ((looking-at "\\<endsequence\\>")
5742 ;; 12: Search back for matching sequence
5743 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
5744 ((looking-at "\\<endclocking\\>")
5745 ;; 12: Search back for matching clocking
5746 (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
5747 (if reg
5748 (catch 'skip
5749 (if (eq nesting 'yes)
5750 (let (sreg)
5751 (while (verilog-re-search-backward reg nil 'move)
5752 (cond
5753 ((match-end 1) ; begin
5754 (if (looking-at "fork")
5755 (let ((here (point)))
5756 (verilog-beg-of-statement)
5757 (unless (looking-at verilog-disable-fork-re)
5758 (goto-char here)
5759 (setq nest (1- nest))))
5760 (setq nest (1- nest)))
5761 (if (= 0 nest)
5762 ;; Now previous line describes syntax
5763 (throw 'skip 1))
5764 (if (and snest
5765 (= snest nest))
5766 (setq reg sreg)))
5767 ((match-end 2) ; end
5768 (setq nest (1+ nest)))
5769 ((match-end 3)
5770 ;; endcase, jump to case
5771 (setq snest nest)
5772 (setq nest (1+ nest))
5773 (setq sreg reg)
5774 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
5775 ((match-end 4)
5776 ;; join, jump to fork
5777 (setq snest nest)
5778 (setq nest (1+ nest))
5779 (setq sreg reg)
5780 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5781 )))
5782 ;; no nesting
5783 (if (and
5784 (verilog-re-search-backward reg nil 'move)
5785 (match-end 1)) ; task -> could be virtual and/or protected
5786 (progn
5787 (verilog-beg-of-statement)
5788 (throw 'skip 1))
5789 (throw 'skip 1)))))))
5790
5791 (defun verilog-continued-line ()
5792 "Return true if this is a continued line.
5793 Set point to where line starts."
5794 (let ((continued 't))
5795 (if (eq 0 (forward-line -1))
5796 (progn
5797 (end-of-line)
5798 (verilog-backward-ws&directives)
5799 (if (bobp)
5800 (setq continued nil)
5801 (while (and continued
5802 (save-excursion
5803 (skip-chars-backward " \t")
5804 (not (bolp))))
5805 (setq continued (verilog-backward-token)))))
5806 (setq continued nil))
5807 continued))
5808
5809 (defun verilog-backward-token ()
5810 "Step backward token, returning true if this is a continued line."
5811 (interactive)
5812 (verilog-backward-syntactic-ws)
5813 (cond
5814 ((bolp)
5815 nil)
5816 (;-- Anything ending in a ; is complete
5817 (= (preceding-char) ?\;)
5818 nil)
5819 (; If a "}" is prefixed by a ";", then this is a complete statement
5820 ; i.e.: constraint foo { a = b; }
5821 (= (preceding-char) ?\})
5822 (progn
5823 (backward-char)
5824 (not(verilog-at-close-constraint-p))))
5825 (;-- constraint foo { a = b }
5826 ; is a complete statement. *sigh*
5827 (= (preceding-char) ?\{)
5828 (progn
5829 (backward-char)
5830 (not (verilog-at-constraint-p))))
5831 (;" string "
5832 (= (preceding-char) ?\")
5833 (backward-char)
5834 (verilog-skip-backward-comment-or-string)
5835 nil)
5836
5837 (; [3:4]
5838 (= (preceding-char) ?\])
5839 (backward-char)
5840 (verilog-backward-open-bracket)
5841 t)
5842
5843 (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
5844 ; also could be simply '@(foo)'
5845 ; or foo u1 #(a=8)
5846 ; (b, ... which ISN'T complete
5847 ;;;; Do we need this???
5848 (= (preceding-char) ?\))
5849 (progn
5850 (backward-char)
5851 (verilog-backward-up-list 1)
5852 (verilog-backward-syntactic-ws)
5853 (let ((back (point)))
5854 (forward-word -1)
5855 (cond
5856 ;;XX
5857 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
5858 (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
5859 ((looking-at verilog-uvm-statement-re)
5860 nil)
5861 ((looking-at verilog-uvm-begin-re)
5862 t)
5863 ((looking-at verilog-uvm-end-re)
5864 t)
5865 ((looking-at verilog-ovm-statement-re)
5866 nil)
5867 ((looking-at verilog-ovm-begin-re)
5868 t)
5869 ((looking-at verilog-ovm-end-re)
5870 t)
5871 ;; JBA find VMM macros
5872 ((looking-at verilog-vmm-statement-re)
5873 nil )
5874 ((looking-at verilog-vmm-begin-re)
5875 t)
5876 ((looking-at verilog-vmm-end-re)
5877 nil)
5878 ;; JBA trying to catch macro lines with no ; at end
5879 ((looking-at "\\<`")
5880 nil)
5881 (t
5882 (goto-char back)
5883 (cond
5884 ((= (preceding-char) ?\@)
5885 (backward-char)
5886 (save-excursion
5887 (verilog-backward-token)
5888 (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
5889 ((= (preceding-char) ?\#)
5890 (backward-char))
5891 (t t)))))))
5892
5893 (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
5894 t
5895 (forward-word -1)
5896 (while (or (= (preceding-char) ?\_)
5897 (= (preceding-char) ?\@)
5898 (= (preceding-char) ?\.))
5899 (forward-word -1))
5900 (cond
5901 ((looking-at "\\<else\\>")
5902 t)
5903 ((looking-at verilog-behavioral-block-beg-re)
5904 t)
5905 ((looking-at verilog-indent-re)
5906 nil)
5907 (t
5908 (let
5909 ((back (point)))
5910 (verilog-backward-syntactic-ws)
5911 (cond
5912 ((= (preceding-char) ?\:)
5913 (backward-char)
5914 (verilog-backward-syntactic-ws)
5915 (backward-sexp)
5916 (if (looking-at verilog-nameable-item-re )
5917 nil
5918 t))
5919 ((= (preceding-char) ?\#)
5920 (backward-char)
5921 t)
5922 ((= (preceding-char) ?\`)
5923 (backward-char)
5924 t)
5925
5926 (t
5927 (goto-char back)
5928 t))))))))
5929
5930 (defun verilog-backward-syntactic-ws ()
5931 "Move backwards putting point after first non-whitespace non-comment."
5932 (verilog-skip-backward-comments)
5933 (forward-comment (- (buffer-size))))
5934
5935 (defun verilog-backward-syntactic-ws-quick ()
5936 "As with `verilog-backward-syntactic-ws' but use `verilog-scan' cache."
5937 (while (cond ((bobp)
5938 nil) ; Done
5939 ((> (skip-syntax-backward " ") 0)
5940 t)
5941 ((eq (preceding-char) ?\n) ;; \n's terminate // so aren't space syntax
5942 (forward-char -1)
5943 t)
5944 ((or (verilog-inside-comment-or-string-p (1- (point)))
5945 (verilog-inside-comment-or-string-p (point)))
5946 (re-search-backward "[/\"]" nil t) ;; Only way a comment or quote can begin
5947 t))))
5948
5949 (defun verilog-forward-syntactic-ws ()
5950 (verilog-skip-forward-comment-p)
5951 (forward-comment (buffer-size)))
5952
5953 (defun verilog-backward-ws&directives (&optional bound)
5954 "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
5955 Optional BOUND limits search."
5956 (save-restriction
5957 (let* ((bound (or bound (point-min)))
5958 (here bound)
5959 (p nil) )
5960 (if (< bound (point))
5961 (progn
5962 (let ((state (save-excursion (verilog-syntax-ppss))))
5963 (cond
5964 ((nth 7 state) ;; in // comment
5965 (verilog-re-search-backward "//" nil 'move)
5966 (skip-chars-backward "/"))
5967 ((nth 4 state) ;; in /* */ comment
5968 (verilog-re-search-backward "/\*" nil 'move))))
5969 (narrow-to-region bound (point))
5970 (while (/= here (point))
5971 (setq here (point))
5972 (verilog-skip-backward-comments)
5973 (setq p
5974 (save-excursion
5975 (beginning-of-line)
5976 (cond
5977 ((and verilog-highlight-translate-off
5978 (verilog-within-translate-off))
5979 (verilog-back-to-start-translate-off (point-min)))
5980 ((looking-at verilog-directive-re-1)
5981 (point))
5982 (t
5983 nil))))
5984 (if p (goto-char p))))))))
5985
5986 (defun verilog-forward-ws&directives (&optional bound)
5987 "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
5988 Optional BOUND limits search."
5989 (save-restriction
5990 (let* ((bound (or bound (point-max)))
5991 (here bound)
5992 jump)
5993 (if (> bound (point))
5994 (progn
5995 (let ((state (save-excursion (verilog-syntax-ppss))))
5996 (cond
5997 ((nth 7 state) ;; in // comment
5998 (end-of-line)
5999 (forward-char 1)
6000 (skip-chars-forward " \t\n\f")
6001 )
6002 ((nth 4 state) ;; in /* */ comment
6003 (verilog-re-search-forward "\*\/\\s-*" nil 'move))))
6004 (narrow-to-region (point) bound)
6005 (while (/= here (point))
6006 (setq here (point)
6007 jump nil)
6008 (forward-comment (buffer-size))
6009 (and (looking-at "\\s-*(\\*.*\\*)\\s-*") ;; Attribute
6010 (goto-char (match-end 0)))
6011 (save-excursion
6012 (beginning-of-line)
6013 (if (looking-at verilog-directive-re-1)
6014 (setq jump t)))
6015 (if jump
6016 (beginning-of-line 2))))))))
6017
6018 (defun verilog-in-comment-p ()
6019 "Return true if in a star or // comment."
6020 (let ((state (save-excursion (verilog-syntax-ppss))))
6021 (or (nth 4 state) (nth 7 state))))
6022
6023 (defun verilog-in-star-comment-p ()
6024 "Return true if in a star comment."
6025 (let ((state (save-excursion (verilog-syntax-ppss))))
6026 (and
6027 (nth 4 state) ; t if in a comment of style a // or b /**/
6028 (not
6029 (nth 7 state) ; t if in a comment of style b /**/
6030 ))))
6031
6032 (defun verilog-in-slash-comment-p ()
6033 "Return true if in a slash comment."
6034 (let ((state (save-excursion (verilog-syntax-ppss))))
6035 (nth 7 state)))
6036
6037 (defun verilog-in-comment-or-string-p ()
6038 "Return true if in a string or comment."
6039 (let ((state (save-excursion (verilog-syntax-ppss))))
6040 (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
6041
6042 (defun verilog-in-attribute-p ()
6043 "Return true if point is in an attribute (* [] attribute *)."
6044 (save-match-data
6045 (save-excursion
6046 (verilog-re-search-backward "\\((\\*\\)\\|\\(\\*)\\)" nil 'move)
6047 (numberp (match-beginning 1)))))
6048
6049 (defun verilog-in-parameter-p ()
6050 "Return true if point is in a parameter assignment #( p1=1, p2=5)."
6051 (save-match-data
6052 (save-excursion
6053 (verilog-re-search-backward "\\(#(\\)\\|\\()\\)" nil 'move)
6054 (numberp (match-beginning 1)))))
6055
6056 (defun verilog-in-escaped-name-p ()
6057 "Return true if in an escaped name."
6058 (save-excursion
6059 (backward-char)
6060 (skip-chars-backward "^ \t\n\f")
6061 (if (equal (char-after (point) ) ?\\ )
6062 t
6063 nil)))
6064 (defun verilog-in-directive-p ()
6065 "Return true if in a directive."
6066 (save-excursion
6067 (beginning-of-line)
6068 (looking-at verilog-directive-re-1)))
6069
6070 (defun verilog-in-parenthesis-p ()
6071 "Return true if in a ( ) expression (but not { } or [ ])."
6072 (save-match-data
6073 (save-excursion
6074 (verilog-re-search-backward "\\((\\)\\|\\()\\)" nil 'move)
6075 (numberp (match-beginning 1)))))
6076
6077 (defun verilog-in-paren ()
6078 "Return true if in a parenthetical expression.
6079 May cache result using `verilog-syntax-ppss'."
6080 (let ((state (save-excursion (verilog-syntax-ppss))))
6081 (> (nth 0 state) 0 )))
6082
6083 (defun verilog-in-paren-count ()
6084 "Return paren depth, floor to 0.
6085 May cache result using `verilog-syntax-ppss'."
6086 (let ((state (save-excursion (verilog-syntax-ppss))))
6087 (if (> (nth 0 state) 0)
6088 (nth 0 state)
6089 0 )))
6090
6091 (defun verilog-in-paren-quick ()
6092 "Return true if in a parenthetical expression.
6093 Always starts from `point-min', to allow inserts with hooks disabled."
6094 ;; The -quick refers to its use alongside the other -quick functions,
6095 ;; not that it's likely to be faster than verilog-in-paren.
6096 (let ((state (save-excursion (parse-partial-sexp (point-min) (point)))))
6097 (> (nth 0 state) 0 )))
6098
6099 (defun verilog-in-struct-p ()
6100 "Return true if in a struct declaration."
6101 (interactive)
6102 (save-excursion
6103 (if (verilog-in-paren)
6104 (progn
6105 (verilog-backward-up-list 1)
6106 (verilog-at-struct-p)
6107 )
6108 nil)))
6109
6110 (defun verilog-in-struct-nested-p ()
6111 "Return nil for not in struct.
6112 Return 0 for in non-nested struct.
6113 Return >0 for nested struct."
6114 (interactive)
6115 (let (col)
6116 (save-excursion
6117 (if (verilog-in-paren)
6118 (progn
6119 (verilog-backward-up-list 1)
6120 (setq col (verilog-at-struct-mv-p))
6121 (if col
6122 (if (verilog-in-struct-p) (current-column) 0)))
6123 nil))))
6124
6125 (defun verilog-in-coverage-p ()
6126 "Return true if in a constraint or coverpoint expression."
6127 (interactive)
6128 (save-excursion
6129 (if (verilog-in-paren)
6130 (progn
6131 (verilog-backward-up-list 1)
6132 (verilog-at-constraint-p)
6133 )
6134 nil)))
6135 (defun verilog-at-close-constraint-p ()
6136 "If at the } that closes a constraint or covergroup, return true."
6137 (if (and
6138 (equal (char-after) ?\})
6139 (verilog-in-coverage-p))
6140
6141 (save-excursion
6142 (verilog-backward-ws&directives)
6143 (if (or (equal (char-before) ?\;)
6144 (equal (char-before) ?\}) ;; can end with inner constraint { } block or ;
6145 (equal (char-before) ?\{)) ;; empty constraint block
6146 (point)
6147 nil))))
6148
6149 (defun verilog-at-constraint-p ()
6150 "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
6151 (if (save-excursion
6152 (let ((p (point)))
6153 (and
6154 (equal (char-after) ?\{)
6155 (forward-list)
6156 (progn (backward-char 1)
6157 (verilog-backward-ws&directives)
6158 (and
6159 (or (equal (char-before) ?\{) ;; empty case
6160 (equal (char-before) ?\;)
6161 (equal (char-before) ?\}))
6162 ;; skip what looks like bus repetition operator {#{
6163 (not (string-match "^{\\s-*[0-9]+\\s-*{" (buffer-substring p (point)))))))))
6164 (progn
6165 (let ( (pt (point)) (pass 0))
6166 (verilog-backward-ws&directives)
6167 (verilog-backward-token)
6168 (if (looking-at (concat "\\<constraint\\|coverpoint\\|cross\\|with\\>\\|" verilog-in-constraint-re))
6169 (progn (setq pass 1)
6170 (if (looking-at "\\<with\\>")
6171 (progn (verilog-backward-ws&directives)
6172 (beginning-of-line) ;; 1
6173 (verilog-forward-ws&directives)
6174 1 )
6175 (verilog-beg-of-statement)
6176 ))
6177 ;; if first word token not keyword, it maybe the instance name
6178 ;; check next word token
6179 (if (looking-at "\\<\\w+\\>\\|\\s-*(\\s-*\\w+")
6180 (progn (verilog-beg-of-statement)
6181 (if (looking-at (concat "\\<\\(constraint\\|"
6182 "\\(?:\\w+\\s-*:\\s-*\\)?\\(coverpoint\\|cross\\)"
6183 "\\|with\\)\\>\\|" verilog-in-constraint-re))
6184 (setq pass 1)))))
6185 (if (eq pass 0)
6186 (progn (goto-char pt) nil) 1)))
6187 ;; not
6188 nil))
6189
6190 (defun verilog-at-struct-p ()
6191 "If at the { of a struct, return true, not moving point."
6192 (save-excursion
6193 (if (and (equal (char-after) ?\{)
6194 (verilog-backward-token))
6195 (looking-at "\\<struct\\|union\\|packed\\|\\(un\\)?signed\\>")
6196 nil)))
6197
6198 (defun verilog-at-struct-mv-p ()
6199 "If at the { of a struct, return true, moving point to struct."
6200 (let ((pt (point)))
6201 (if (and (equal (char-after) ?\{)
6202 (verilog-backward-token))
6203 (if (looking-at "\\<struct\\|union\\|packed\\|\\(un\\)?signed\\>")
6204 (progn (verilog-beg-of-statement) (point))
6205 (progn (goto-char pt) nil))
6206 (progn (goto-char pt) nil))))
6207
6208 (defun verilog-at-close-struct-p ()
6209 "If at the } that closes a struct, return true."
6210 (if (and
6211 (equal (char-after) ?\})
6212 (verilog-in-struct-p))
6213 ;; true
6214 (save-excursion
6215 (if (looking-at "}\\(?:\\s-*\\w+\\s-*\\)?;") 1))
6216 ;; false
6217 nil))
6218
6219 (defun verilog-parenthesis-depth ()
6220 "Return non zero if in parenthetical-expression."
6221 (save-excursion (nth 1 (verilog-syntax-ppss))))
6222
6223
6224 (defun verilog-skip-forward-comment-or-string ()
6225 "Return true if in a string or comment."
6226 (let ((state (save-excursion (verilog-syntax-ppss))))
6227 (cond
6228 ((nth 3 state) ;Inside string
6229 (search-forward "\"")
6230 t)
6231 ((nth 7 state) ;Inside // comment
6232 (forward-line 1)
6233 t)
6234 ((nth 4 state) ;Inside any comment (hence /**/)
6235 (search-forward "*/"))
6236 (t
6237 nil))))
6238
6239 (defun verilog-skip-backward-comment-or-string ()
6240 "Return true if in a string or comment."
6241 (let ((state (save-excursion (verilog-syntax-ppss))))
6242 (cond
6243 ((nth 3 state) ;Inside string
6244 (search-backward "\"")
6245 t)
6246 ((nth 7 state) ;Inside // comment
6247 (search-backward "//")
6248 (skip-chars-backward "/")
6249 t)
6250 ((nth 4 state) ;Inside /* */ comment
6251 (search-backward "/*")
6252 t)
6253 (t
6254 nil))))
6255
6256 (defun verilog-skip-backward-comments ()
6257 "Return true if a comment was skipped."
6258 (let ((more t))
6259 (while more
6260 (setq more
6261 (let ((state (save-excursion (verilog-syntax-ppss))))
6262 (cond
6263 ((nth 7 state) ;Inside // comment
6264 (search-backward "//")
6265 (skip-chars-backward "/")
6266 (skip-chars-backward " \t\n\f")
6267 t)
6268 ((nth 4 state) ;Inside /* */ comment
6269 (search-backward "/*")
6270 (skip-chars-backward " \t\n\f")
6271 t)
6272 ((and (not (bobp))
6273 (= (char-before) ?\/)
6274 (= (char-before (1- (point))) ?\*))
6275 (goto-char (- (point) 2))
6276 t) ;; Let nth 4 state handle the rest
6277 ((and (not (bobp))
6278 (= (char-before) ?\))
6279 (= (char-before (1- (point))) ?\*))
6280 (goto-char (- (point) 2))
6281 (if (search-backward "(*" nil t)
6282 (progn
6283 (skip-chars-backward " \t\n\f")
6284 t)
6285 (progn
6286 (goto-char (+ (point) 2))
6287 nil)))
6288 (t
6289 (/= (skip-chars-backward " \t\n\f") 0))))))))
6290
6291 (defun verilog-skip-forward-comment-p ()
6292 "If in comment, move to end and return true."
6293 (let* (h
6294 (state (save-excursion (verilog-syntax-ppss)))
6295 (skip (cond
6296 ((nth 3 state) ;Inside string
6297 t)
6298 ((nth 7 state) ;Inside // comment
6299 (end-of-line)
6300 (forward-char 1)
6301 t)
6302 ((nth 4 state) ;Inside /* comment
6303 (search-forward "*/")
6304 t)
6305 ((verilog-in-attribute-p) ;Inside (* attribute
6306 (search-forward "*)" nil t)
6307 t)
6308 (t nil))))
6309 (skip-chars-forward " \t\n\f")
6310 (while
6311 (cond
6312 ((looking-at "\\/\\*")
6313 (progn
6314 (setq h (point))
6315 (goto-char (match-end 0))
6316 (if (search-forward "*/" nil t)
6317 (progn
6318 (skip-chars-forward " \t\n\f")
6319 (setq skip 't))
6320 (progn
6321 (goto-char h)
6322 nil))))
6323 ((looking-at "(\\*")
6324 (progn
6325 (setq h (point))
6326 (goto-char (match-end 0))
6327 (if (search-forward "*)" nil t)
6328 (progn
6329 (skip-chars-forward " \t\n\f")
6330 (setq skip 't))
6331 (progn
6332 (goto-char h)
6333 nil))))
6334 (t nil)))
6335 skip))
6336
6337 (defun verilog-indent-line-relative ()
6338 "Cheap version of indent line.
6339 Only look at a few lines to determine indent level."
6340 (interactive)
6341 (let ((indent-str)
6342 (sp (point)))
6343 (if (looking-at "^[ \t]*$")
6344 (cond ;- A blank line; No need to be too smart.
6345 ((bobp)
6346 (setq indent-str (list 'cpp 0)))
6347 ((verilog-continued-line)
6348 (let ((sp1 (point)))
6349 (if (verilog-continued-line)
6350 (progn
6351 (goto-char sp)
6352 (setq indent-str
6353 (list 'statement (verilog-current-indent-level))))
6354 (goto-char sp1)
6355 (setq indent-str (list 'block (verilog-current-indent-level)))))
6356 (goto-char sp))
6357 ((goto-char sp)
6358 (setq indent-str (verilog-calculate-indent))))
6359 (progn (skip-chars-forward " \t")
6360 (setq indent-str (verilog-calculate-indent))))
6361 (verilog-do-indent indent-str)))
6362
6363 (defun verilog-indent-line ()
6364 "Indent for special part of code."
6365 (verilog-do-indent (verilog-calculate-indent)))
6366
6367 (defun verilog-do-indent (indent-str)
6368 (let ((type (car indent-str))
6369 (ind (car (cdr indent-str))))
6370 (cond
6371 (; handle continued exp
6372 (eq type 'cexp)
6373 (let ((here (point)))
6374 (verilog-backward-syntactic-ws)
6375 (cond
6376 ((or
6377 (= (preceding-char) ?\,)
6378 (= (preceding-char) ?\])
6379 (save-excursion
6380 (verilog-beg-of-statement-1)
6381 (looking-at verilog-declaration-re)))
6382 (let* ( fst
6383 (val
6384 (save-excursion
6385 (backward-char 1)
6386 (verilog-beg-of-statement-1)
6387 (setq fst (point))
6388 (if (looking-at verilog-declaration-re)
6389 (progn ;; we have multiple words
6390 (goto-char (match-end 0))
6391 (skip-chars-forward " \t")
6392 (cond
6393 ((and verilog-indent-declaration-macros
6394 (= (following-char) ?\`))
6395 (progn
6396 (forward-char 1)
6397 (forward-word 1)
6398 (skip-chars-forward " \t")))
6399 ((= (following-char) ?\[)
6400 (progn
6401 (forward-char 1)
6402 (verilog-backward-up-list -1)
6403 (skip-chars-forward " \t"))))
6404 (current-column))
6405 (progn
6406 (goto-char fst)
6407 (+ (current-column) verilog-cexp-indent))))))
6408 (goto-char here)
6409 (indent-line-to val)
6410 (if (and (not verilog-indent-lists)
6411 (verilog-in-paren))
6412 (verilog-pretty-declarations-auto))
6413 ))
6414 ((= (preceding-char) ?\) )
6415 (goto-char here)
6416 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
6417 (indent-line-to val)))
6418 (t
6419 (goto-char here)
6420 (let ((val))
6421 (verilog-beg-of-statement-1)
6422 (if (and (< (point) here)
6423 (verilog-re-search-forward "=[ \\t]*" here 'move))
6424 (setq val (current-column))
6425 (setq val (eval (cdr (assoc type verilog-indent-alist)))))
6426 (goto-char here)
6427 (indent-line-to val))))))
6428
6429 (; handle inside parenthetical expressions
6430 (eq type 'cparenexp)
6431 (let* ( here
6432 (val (save-excursion
6433 (verilog-backward-up-list 1)
6434 (forward-char 1)
6435 (if verilog-indent-lists
6436 (skip-chars-forward " \t")
6437 (verilog-forward-syntactic-ws))
6438 (setq here (point))
6439 (current-column)))
6440
6441 (decl (save-excursion
6442 (goto-char here)
6443 (verilog-forward-syntactic-ws)
6444 (setq here (point))
6445 (looking-at verilog-declaration-re))))
6446 (indent-line-to val)
6447 (if decl
6448 (verilog-pretty-declarations-auto))))
6449
6450 (;-- Handle the ends
6451 (or
6452 (looking-at verilog-end-block-re)
6453 (verilog-at-close-constraint-p)
6454 (verilog-at-close-struct-p))
6455 (let ((val (if (eq type 'statement)
6456 (- ind verilog-indent-level)
6457 ind)))
6458 (indent-line-to val)))
6459
6460 (;-- Case -- maybe line 'em up
6461 (and (eq type 'case) (not (looking-at "^[ \t]*$")))
6462 (progn
6463 (cond
6464 ((looking-at "\\<endcase\\>")
6465 (indent-line-to ind))
6466 (t
6467 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
6468 (indent-line-to val))))))
6469
6470 (;-- defun
6471 (and (eq type 'defun)
6472 (looking-at verilog-zero-indent-re))
6473 (indent-line-to 0))
6474
6475 (;-- declaration
6476 (and (or
6477 (eq type 'defun)
6478 (eq type 'block))
6479 (looking-at verilog-declaration-re))
6480 (verilog-indent-declaration ind))
6481
6482 (;-- form feeds - ignored as bug in indent-line-to in < 24.5
6483 (looking-at "\f"))
6484
6485 (;-- Everything else
6486 t
6487 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
6488 (indent-line-to val))))
6489
6490 (if (looking-at "[ \t]+$")
6491 (skip-chars-forward " \t"))
6492 indent-str ; Return indent data
6493 ))
6494
6495 (defun verilog-current-indent-level ()
6496 "Return the indent-level of the current statement."
6497 (save-excursion
6498 (let (par-pos)
6499 (beginning-of-line)
6500 (setq par-pos (verilog-parenthesis-depth))
6501 (while par-pos
6502 (goto-char par-pos)
6503 (beginning-of-line)
6504 (setq par-pos (verilog-parenthesis-depth)))
6505 (skip-chars-forward " \t")
6506 (current-column))))
6507
6508 (defun verilog-case-indent-level ()
6509 "Return the indent-level of the current statement.
6510 Do not count named blocks or case-statements."
6511 (save-excursion
6512 (skip-chars-forward " \t")
6513 (cond
6514 ((looking-at verilog-named-block-re)
6515 (current-column))
6516 ((and (not (looking-at verilog-extended-case-re))
6517 (looking-at "^[^:;]+[ \t]*:"))
6518 (verilog-re-search-forward ":" nil t)
6519 (skip-chars-forward " \t")
6520 (current-column))
6521 (t
6522 (current-column)))))
6523
6524 (defun verilog-indent-comment ()
6525 "Indent current line as comment."
6526 (let* ((stcol
6527 (cond
6528 ((verilog-in-star-comment-p)
6529 (save-excursion
6530 (re-search-backward "/\\*" nil t)
6531 (1+(current-column))))
6532 (comment-column
6533 comment-column )
6534 (t
6535 (save-excursion
6536 (re-search-backward "//" nil t)
6537 (current-column))))))
6538 (indent-line-to stcol)
6539 stcol))
6540
6541 (defun verilog-more-comment ()
6542 "Make more comment lines like the previous."
6543 (let* ((star 0)
6544 (stcol
6545 (cond
6546 ((verilog-in-star-comment-p)
6547 (save-excursion
6548 (setq star 1)
6549 (re-search-backward "/\\*" nil t)
6550 (1+(current-column))))
6551 (comment-column
6552 comment-column )
6553 (t
6554 (save-excursion
6555 (re-search-backward "//" nil t)
6556 (current-column))))))
6557 (progn
6558 (indent-to stcol)
6559 (if (and star
6560 (save-excursion
6561 (forward-line -1)
6562 (skip-chars-forward " \t")
6563 (looking-at "\*")))
6564 (insert "* ")))))
6565
6566 (defun verilog-comment-indent (&optional _arg)
6567 "Return the column number the line should be indented to.
6568 _ARG is ignored, for `comment-indent-function' compatibility."
6569 (cond
6570 ((verilog-in-star-comment-p)
6571 (save-excursion
6572 (re-search-backward "/\\*" nil t)
6573 (1+(current-column))))
6574 ( comment-column
6575 comment-column )
6576 (t
6577 (save-excursion
6578 (re-search-backward "//" nil t)
6579 (current-column)))))
6580
6581 ;;
6582
6583 (defun verilog-pretty-declarations-auto (&optional quiet)
6584 "Call `verilog-pretty-declarations' QUIET based on `verilog-auto-lineup'."
6585 (when (or (eq 'all verilog-auto-lineup)
6586 (eq 'declarations verilog-auto-lineup))
6587 (verilog-pretty-declarations quiet)))
6588
6589 (defun verilog-pretty-declarations (&optional quiet)
6590 "Line up declarations around point.
6591 Be verbose about progress unless optional QUIET set."
6592 (interactive)
6593 (let* ((m1 (make-marker))
6594 (e (point))
6595 el
6596 r
6597 (here (point))
6598 ind
6599 start
6600 startpos
6601 end
6602 endpos
6603 base-ind
6604 )
6605 (save-excursion
6606 (if (progn
6607 ; (verilog-beg-of-statement-1)
6608 (beginning-of-line)
6609 (verilog-forward-syntactic-ws)
6610 (and (not (verilog-in-directive-p)) ;; could have `define input foo
6611 (looking-at verilog-declaration-re)))
6612 (progn
6613 (if (verilog-parenthesis-depth)
6614 ;; in an argument list or parameter block
6615 (setq el (verilog-backward-up-list -1)
6616 start (progn
6617 (goto-char e)
6618 (verilog-backward-up-list 1)
6619 (forward-line) ;; ignore ( input foo,
6620 (verilog-re-search-forward verilog-declaration-re el 'move)
6621 (goto-char (match-beginning 0))
6622 (skip-chars-backward " \t")
6623 (point))
6624 startpos (set-marker (make-marker) start)
6625 end (progn
6626 (goto-char start)
6627 (verilog-backward-up-list -1)
6628 (forward-char -1)
6629 (verilog-backward-syntactic-ws)
6630 (point))
6631 endpos (set-marker (make-marker) end)
6632 base-ind (progn
6633 (goto-char start)
6634 (forward-char 1)
6635 (skip-chars-forward " \t")
6636 (current-column)))
6637 ;; in a declaration block (not in argument list)
6638 (setq
6639 start (progn
6640 (verilog-beg-of-statement-1)
6641 (while (and (looking-at verilog-declaration-re)
6642 (not (bobp)))
6643 (skip-chars-backward " \t")
6644 (setq e (point))
6645 (beginning-of-line)
6646 (verilog-backward-syntactic-ws)
6647 (backward-char)
6648 (verilog-beg-of-statement-1))
6649 e)
6650 startpos (set-marker (make-marker) start)
6651 end (progn
6652 (goto-char here)
6653 (verilog-end-of-statement)
6654 (setq e (point)) ;Might be on last line
6655 (verilog-forward-syntactic-ws)
6656 (while (looking-at verilog-declaration-re)
6657 (verilog-end-of-statement)
6658 (setq e (point))
6659 (verilog-forward-syntactic-ws))
6660 e)
6661 endpos (set-marker (make-marker) end)
6662 base-ind (progn
6663 (goto-char start)
6664 (verilog-do-indent (verilog-calculate-indent))
6665 (verilog-forward-ws&directives)
6666 (current-column))))
6667 ;; OK, start and end are set
6668 (goto-char (marker-position startpos))
6669 (if (and (not quiet)
6670 (> (- end start) 100))
6671 (message "Lining up declarations..(please stand by)"))
6672 ;; Get the beginning of line indent first
6673 (while (progn (setq e (marker-position endpos))
6674 (< (point) e))
6675 (cond
6676 ((save-excursion (skip-chars-backward " \t")
6677 (bolp))
6678 (verilog-forward-ws&directives)
6679 (indent-line-to base-ind)
6680 (verilog-forward-ws&directives)
6681 (if (< (point) e)
6682 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
6683 (t
6684 (just-one-space)
6685 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
6686 ;;(forward-line)
6687 )
6688 ;; Now find biggest prefix
6689 (setq ind (verilog-get-lineup-indent (marker-position startpos) endpos))
6690 ;; Now indent each line.
6691 (goto-char (marker-position startpos))
6692 (while (progn (setq e (marker-position endpos))
6693 (setq r (- e (point)))
6694 (> r 0))
6695 (setq e (point))
6696 (unless quiet (message "%d" r))
6697 ;;(verilog-do-indent (verilog-calculate-indent)))
6698 (verilog-forward-ws&directives)
6699 (cond
6700 ((or (and verilog-indent-declaration-macros
6701 (looking-at verilog-declaration-re-2-macro))
6702 (looking-at verilog-declaration-re-2-no-macro))
6703 (let ((p (match-end 0)))
6704 (set-marker m1 p)
6705 (if (verilog-re-search-forward "[[#`]" p 'move)
6706 (progn
6707 (forward-char -1)
6708 (just-one-space)
6709 (goto-char (marker-position m1))
6710 (just-one-space)
6711 (indent-to ind))
6712 (progn
6713 (just-one-space)
6714 (indent-to ind)))))
6715 ((verilog-continued-line-1 (marker-position startpos))
6716 (goto-char e)
6717 (indent-line-to ind))
6718 ((verilog-in-struct-p)
6719 ;; could have a declaration of a user defined item
6720 (goto-char e)
6721 (verilog-end-of-statement))
6722 (t ; Must be comment or white space
6723 (goto-char e)
6724 (verilog-forward-ws&directives)
6725 (forward-line -1)))
6726 (forward-line 1))
6727 (unless quiet (message "")))))))
6728
6729 (defun verilog-pretty-expr (&optional quiet _myre)
6730 "Line up expressions around point, optionally QUIET with regexp _MYRE ignored."
6731 (interactive)
6732 (if (not (verilog-in-comment-or-string-p))
6733 (save-excursion
6734 (let ( (rexp (concat "^\\s-*" verilog-complete-reg))
6735 (rexp1 (concat "^\\s-*" verilog-basic-complete-re)))
6736 (beginning-of-line)
6737 (if (and (not (looking-at rexp ))
6738 (looking-at verilog-assignment-operation-re)
6739 (save-excursion
6740 (goto-char (match-end 2))
6741 (and (not (verilog-in-attribute-p))
6742 (not (verilog-in-parameter-p))
6743 (not (verilog-in-comment-or-string-p)))))
6744 (let* ((here (point))
6745 (e) (r)
6746 (start
6747 (progn
6748 (beginning-of-line)
6749 (setq e (point))
6750 (verilog-backward-syntactic-ws)
6751 (beginning-of-line)
6752 (while (and (not (looking-at rexp1))
6753 (looking-at verilog-assignment-operation-re)
6754 (not (bobp))
6755 )
6756 (setq e (point))
6757 (verilog-backward-syntactic-ws)
6758 (beginning-of-line)
6759 ) ;Ack, need to grok `define
6760 e))
6761 (end
6762 (progn
6763 (goto-char here)
6764 (end-of-line)
6765 (setq e (point)) ;Might be on last line
6766 (verilog-forward-syntactic-ws)
6767 (beginning-of-line)
6768 (while (and
6769 (not (looking-at rexp1 ))
6770 (looking-at verilog-assignment-operation-re)
6771 (progn
6772 (end-of-line)
6773 (not (eq e (point)))))
6774 (setq e (point))
6775 (verilog-forward-syntactic-ws)
6776 (beginning-of-line)
6777 )
6778 e))
6779 (endpos (set-marker (make-marker) end))
6780 (ind)
6781 )
6782 (goto-char start)
6783 (verilog-do-indent (verilog-calculate-indent))
6784 (if (and (not quiet)
6785 (> (- end start) 100))
6786 (message "Lining up expressions..(please stand by)"))
6787
6788 ;; Set indent to minimum throughout region
6789 (while (< (point) (marker-position endpos))
6790 (beginning-of-line)
6791 (verilog-just-one-space verilog-assignment-operation-re)
6792 (beginning-of-line)
6793 (verilog-do-indent (verilog-calculate-indent))
6794 (end-of-line)
6795 (verilog-forward-syntactic-ws)
6796 )
6797
6798 ;; Now find biggest prefix
6799 (setq ind (verilog-get-lineup-indent-2 verilog-assignment-operation-re start endpos))
6800
6801 ;; Now indent each line.
6802 (goto-char start)
6803 (while (progn (setq e (marker-position endpos))
6804 (setq r (- e (point)))
6805 (> r 0))
6806 (setq e (point))
6807 (if (not quiet) (message "%d" r))
6808 (cond
6809 ((looking-at verilog-assignment-operation-re)
6810 (goto-char (match-beginning 2))
6811 (if (not (or (verilog-in-parenthesis-p) ;; leave attributes and comparisons alone
6812 (verilog-in-coverage-p)))
6813 (if (eq (char-after) ?=)
6814 (indent-to (1+ ind)) ; line up the = of the <= with surrounding =
6815 (indent-to ind)
6816 ))
6817 )
6818 ((verilog-continued-line-1 start)
6819 (goto-char e)
6820 (indent-line-to ind))
6821 (t ; Must be comment or white space
6822 (goto-char e)
6823 (verilog-forward-ws&directives)
6824 (forward-line -1))
6825 )
6826 (forward-line 1))
6827 (unless quiet (message ""))
6828 ))))))
6829
6830 (defun verilog-just-one-space (myre)
6831 "Remove extra spaces around regular expression MYRE."
6832 (interactive)
6833 (if (and (not(looking-at verilog-complete-reg))
6834 (looking-at myre))
6835 (let ((p1 (match-end 1))
6836 (p2 (match-end 2)))
6837 (progn
6838 (goto-char p2)
6839 (just-one-space)
6840 (goto-char p1)
6841 (just-one-space)))))
6842
6843 (defun verilog-indent-declaration (baseind)
6844 "Indent current lines as declaration.
6845 Line up the variable names based on previous declaration's indentation.
6846 BASEIND is the base indent to offset everything."
6847 (interactive)
6848 (let ((pos (point-marker))
6849 (lim (save-excursion
6850 ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
6851 (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
6852 (point)))
6853 (ind)
6854 (val)
6855 (m1 (make-marker)))
6856 (setq val
6857 (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6858 (indent-line-to val)
6859
6860 ;; Use previous declaration (in this module) as template.
6861 (if (or (eq 'all verilog-auto-lineup)
6862 (eq 'declarations verilog-auto-lineup))
6863 (if (verilog-re-search-backward
6864 (or (and verilog-indent-declaration-macros
6865 verilog-declaration-re-1-macro)
6866 verilog-declaration-re-1-no-macro) lim t)
6867 (progn
6868 (goto-char (match-end 0))
6869 (skip-chars-forward " \t")
6870 (setq ind (current-column))
6871 (goto-char pos)
6872 (setq val
6873 (+ baseind
6874 (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6875 (indent-line-to val)
6876 (if (and verilog-indent-declaration-macros
6877 (looking-at verilog-declaration-re-2-macro))
6878 (let ((p (match-end 0)))
6879 (set-marker m1 p)
6880 (if (verilog-re-search-forward "[[#`]" p 'move)
6881 (progn
6882 (forward-char -1)
6883 (just-one-space)
6884 (goto-char (marker-position m1))
6885 (just-one-space)
6886 (indent-to ind))
6887 (if (/= (current-column) ind)
6888 (progn
6889 (just-one-space)
6890 (indent-to ind)))))
6891 (if (looking-at verilog-declaration-re-2-no-macro)
6892 (let ((p (match-end 0)))
6893 (set-marker m1 p)
6894 (if (verilog-re-search-forward "[[`#]" p 'move)
6895 (progn
6896 (forward-char -1)
6897 (just-one-space)
6898 (goto-char (marker-position m1))
6899 (just-one-space)
6900 (indent-to ind))
6901 (if (/= (current-column) ind)
6902 (progn
6903 (just-one-space)
6904 (indent-to ind))))))))))
6905 (goto-char pos)))
6906
6907 (defun verilog-get-lineup-indent (b edpos)
6908 "Return the indent level that will line up several lines within the region.
6909 Region is defined by B and EDPOS."
6910 (save-excursion
6911 (let ((ind 0) e)
6912 (goto-char b)
6913 ;; Get rightmost position
6914 (while (progn (setq e (marker-position edpos))
6915 (< (point) e))
6916 (if (verilog-re-search-forward
6917 (or (and verilog-indent-declaration-macros
6918 verilog-declaration-re-1-macro)
6919 verilog-declaration-re-1-no-macro) e 'move)
6920 (progn
6921 (goto-char (match-end 0))
6922 (verilog-backward-syntactic-ws)
6923 (if (> (current-column) ind)
6924 (setq ind (current-column)))
6925 (goto-char (match-end 0)))))
6926 (if (> ind 0)
6927 (1+ ind)
6928 ;; No lineup-string found
6929 (goto-char b)
6930 (end-of-line)
6931 (verilog-backward-syntactic-ws)
6932 ;;(skip-chars-backward " \t")
6933 (1+ (current-column))))))
6934
6935 (defun verilog-get-lineup-indent-2 (myre b edpos)
6936 "Return the indent level that will line up several lines within the region."
6937 (save-excursion
6938 (let ((ind 0) e)
6939 (goto-char b)
6940 ;; Get rightmost position
6941 (while (progn (setq e (marker-position edpos))
6942 (< (point) e))
6943 (if (and (verilog-re-search-forward myre e 'move)
6944 (not (verilog-in-attribute-p))) ;; skip attribute exprs
6945 (progn
6946 (goto-char (match-beginning 2))
6947 (verilog-backward-syntactic-ws)
6948 (if (> (current-column) ind)
6949 (setq ind (current-column)))
6950 (goto-char (match-end 0)))
6951 ))
6952 (if (> ind 0)
6953 (1+ ind)
6954 ;; No lineup-string found
6955 (goto-char b)
6956 (end-of-line)
6957 (skip-chars-backward " \t")
6958 (1+ (current-column))))))
6959
6960 (defun verilog-comment-depth (type val)
6961 "A useful mode debugging aide. TYPE and VAL are comments for insertion."
6962 (save-excursion
6963 (let
6964 ((b (prog2
6965 (beginning-of-line)
6966 (point-marker)
6967 (end-of-line))))
6968 (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
6969 (progn
6970 (replace-match " /* -# ## */")
6971 (end-of-line))
6972 (progn
6973 (end-of-line)
6974 (insert " /* ## ## */"))))
6975 (backward-char 6)
6976 (insert
6977 (format "%s %d" type val))))
6978
6979 ;; \f
6980 ;;
6981 ;; Completion
6982 ;;
6983 (defvar verilog-str nil)
6984 (defvar verilog-all nil)
6985 (defvar verilog-pred nil)
6986 (defvar verilog-buffer-to-use nil)
6987 (defvar verilog-flag nil)
6988 (defvar verilog-toggle-completions nil
6989 "True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
6990 Repeated use of \\[verilog-complete-word] will show you all of them.
6991 Normally, when there is more than one possible completion,
6992 it displays a list of all possible completions.")
6993
6994
6995 (defvar verilog-type-keywords
6996 '(
6997 "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
6998 "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
6999 "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
7000 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
7001 "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
7002 "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
7003 )
7004 "Keywords for types used when completing a word in a declaration or parmlist.
7005 \(integer, real, reg...)")
7006
7007 (defvar verilog-cpp-keywords
7008 '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
7009 "endif")
7010 "Keywords to complete when at first word of a line in declarative scope.
7011 \(initial, always, begin, assign...)
7012 The procedures and variables defined within the Verilog program
7013 will be completed at runtime and should not be added to this list.")
7014
7015 (defvar verilog-defun-keywords
7016 (append
7017 '(
7018 "always" "always_comb" "always_ff" "always_latch" "assign"
7019 "begin" "end" "generate" "endgenerate" "module" "endmodule"
7020 "specify" "endspecify" "function" "endfunction" "initial" "final"
7021 "task" "endtask" "primitive" "endprimitive"
7022 )
7023 verilog-type-keywords)
7024 "Keywords to complete when at first word of a line in declarative scope.
7025 \(initial, always, begin, assign...)
7026 The procedures and variables defined within the Verilog program
7027 will be completed at runtime and should not be added to this list.")
7028
7029 (defvar verilog-block-keywords
7030 '(
7031 "begin" "break" "case" "continue" "else" "end" "endfunction"
7032 "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
7033 "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
7034 "while")
7035 "Keywords to complete when at first word of a line in behavioral scope.
7036 \(begin, if, then, else, for, fork...)
7037 The procedures and variables defined within the Verilog program
7038 will be completed at runtime and should not be added to this list.")
7039
7040 (defvar verilog-tf-keywords
7041 '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
7042 "Keywords to complete when at first word of a line in a task or function.
7043 \(begin, if, then, else, for, fork.)
7044 The procedures and variables defined within the Verilog program
7045 will be completed at runtime and should not be added to this list.")
7046
7047 (defvar verilog-case-keywords
7048 '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
7049 "Keywords to complete when at first word of a line in case scope.
7050 \(begin, if, then, else, for, fork...)
7051 The procedures and variables defined within the Verilog program
7052 will be completed at runtime and should not be added to this list.")
7053
7054 (defvar verilog-separator-keywords
7055 '("else" "then" "begin")
7056 "Keywords to complete when NOT standing at the first word of a statement.
7057 \(else, then, begin...)
7058 Variables and function names defined within the Verilog program
7059 will be completed at runtime and should not be added to this list.")
7060
7061 (defvar verilog-gate-ios
7062 ;; All these have an implied {"input"...} at the end
7063 '(("and" "output")
7064 ("buf" "output")
7065 ("bufif0" "output")
7066 ("bufif1" "output")
7067 ("cmos" "output")
7068 ("nand" "output")
7069 ("nmos" "output")
7070 ("nor" "output")
7071 ("not" "output")
7072 ("notif0" "output")
7073 ("notif1" "output")
7074 ("or" "output")
7075 ("pmos" "output")
7076 ("pulldown" "output")
7077 ("pullup" "output")
7078 ("rcmos" "output")
7079 ("rnmos" "output")
7080 ("rpmos" "output")
7081 ("rtran" "inout" "inout")
7082 ("rtranif0" "inout" "inout")
7083 ("rtranif1" "inout" "inout")
7084 ("tran" "inout" "inout")
7085 ("tranif0" "inout" "inout")
7086 ("tranif1" "inout" "inout")
7087 ("xnor" "output")
7088 ("xor" "output"))
7089 "Map of direction for each positional argument to each gate primitive.")
7090
7091 (defvar verilog-gate-keywords (mapcar `car verilog-gate-ios)
7092 "Keywords for gate primitives.")
7093
7094 (defun verilog-string-diff (str1 str2)
7095 "Return index of first letter where STR1 and STR2 differs."
7096 (catch 'done
7097 (let ((diff 0))
7098 (while t
7099 (if (or (> (1+ diff) (length str1))
7100 (> (1+ diff) (length str2)))
7101 (throw 'done diff))
7102 (or (equal (aref str1 diff) (aref str2 diff))
7103 (throw 'done diff))
7104 (setq diff (1+ diff))))))
7105
7106 ;; Calculate all possible completions for functions if argument is `function',
7107 ;; completions for procedures if argument is `procedure' or both functions and
7108 ;; procedures otherwise.
7109
7110 (defun verilog-func-completion (type)
7111 "Build regular expression for module/task/function names.
7112 TYPE is 'module, 'tf for task or function, or t if unknown."
7113 (if (string= verilog-str "")
7114 (setq verilog-str "[a-zA-Z_]"))
7115 (let ((verilog-str (concat (cond
7116 ((eq type 'module) "\\<\\(module\\)\\s +")
7117 ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
7118 (t "\\<\\(task\\|function\\|module\\)\\s +"))
7119 "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
7120 match)
7121
7122 (if (not (looking-at verilog-defun-re))
7123 (verilog-re-search-backward verilog-defun-re nil t))
7124 (forward-char 1)
7125
7126 ;; Search through all reachable functions
7127 (goto-char (point-min))
7128 (while (verilog-re-search-forward verilog-str (point-max) t)
7129 (progn (setq match (buffer-substring (match-beginning 2)
7130 (match-end 2)))
7131 (if (or (null verilog-pred)
7132 (funcall verilog-pred match))
7133 (setq verilog-all (cons match verilog-all)))))
7134 (if (match-beginning 0)
7135 (goto-char (match-beginning 0)))))
7136
7137 (defun verilog-get-completion-decl (end)
7138 "Macro for searching through current declaration (var, type or const)
7139 for matches of `str' and adding the occurrence tp `all' through point END."
7140 (let ((re (or (and verilog-indent-declaration-macros
7141 verilog-declaration-re-2-macro)
7142 verilog-declaration-re-2-no-macro))
7143 decl-end match)
7144 ;; Traverse lines
7145 (while (and (< (point) end)
7146 (verilog-re-search-forward re end t))
7147 ;; Traverse current line
7148 (setq decl-end (save-excursion (verilog-declaration-end)))
7149 (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
7150 (not (match-end 1)))
7151 (setq match (buffer-substring (match-beginning 0) (match-end 0)))
7152 (if (string-match (concat "\\<" verilog-str) match)
7153 (if (or (null verilog-pred)
7154 (funcall verilog-pred match))
7155 (setq verilog-all (cons match verilog-all)))))
7156 (forward-line 1)))
7157 verilog-all)
7158
7159 (defun verilog-var-completion ()
7160 "Calculate all possible completions for variables (or constants)."
7161 (let ((start (point)))
7162 ;; Search for all reachable var declarations
7163 (verilog-beg-of-defun)
7164 (save-excursion
7165 ;; Check var declarations
7166 (verilog-get-completion-decl start))))
7167
7168 (defun verilog-keyword-completion (keyword-list)
7169 "Give list of all possible completions of keywords in KEYWORD-LIST."
7170 (mapcar (lambda (s)
7171 (if (string-match (concat "\\<" verilog-str) s)
7172 (if (or (null verilog-pred)
7173 (funcall verilog-pred s))
7174 (setq verilog-all (cons s verilog-all)))))
7175 keyword-list))
7176
7177
7178 (defun verilog-completion (verilog-str verilog-pred verilog-flag)
7179 "Function passed to `completing-read', `try-completion' or `all-completions'.
7180 Called to get completion on VERILOG-STR. If VERILOG-PRED is non-nil, it
7181 must be a function to be called for every match to check if this should
7182 really be a match. If VERILOG-FLAG is t, the function returns a list of
7183 all possible completions. If VERILOG-FLAG is nil it returns a string,
7184 the longest possible completion, or t if VERILOG-STR is an exact match.
7185 If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
7186 exact match, nil otherwise."
7187 (save-excursion
7188 (let ((verilog-all nil))
7189 ;; Set buffer to use for searching labels. This should be set
7190 ;; within functions which use verilog-completions
7191 (set-buffer verilog-buffer-to-use)
7192
7193 ;; Determine what should be completed
7194 (let ((state (car (verilog-calculate-indent))))
7195 (cond ((eq state 'defun)
7196 (save-excursion (verilog-var-completion))
7197 (verilog-func-completion 'module)
7198 (verilog-keyword-completion verilog-defun-keywords))
7199
7200 ((eq state 'behavioral)
7201 (save-excursion (verilog-var-completion))
7202 (verilog-func-completion 'module)
7203 (verilog-keyword-completion verilog-defun-keywords))
7204
7205 ((eq state 'block)
7206 (save-excursion (verilog-var-completion))
7207 (verilog-func-completion 'tf)
7208 (verilog-keyword-completion verilog-block-keywords))
7209
7210 ((eq state 'case)
7211 (save-excursion (verilog-var-completion))
7212 (verilog-func-completion 'tf)
7213 (verilog-keyword-completion verilog-case-keywords))
7214
7215 ((eq state 'tf)
7216 (save-excursion (verilog-var-completion))
7217 (verilog-func-completion 'tf)
7218 (verilog-keyword-completion verilog-tf-keywords))
7219
7220 ((eq state 'cpp)
7221 (save-excursion (verilog-var-completion))
7222 (verilog-keyword-completion verilog-cpp-keywords))
7223
7224 ((eq state 'cparenexp)
7225 (save-excursion (verilog-var-completion)))
7226
7227 (t;--Anywhere else
7228 (save-excursion (verilog-var-completion))
7229 (verilog-func-completion 'both)
7230 (verilog-keyword-completion verilog-separator-keywords))))
7231
7232 ;; Now we have built a list of all matches. Give response to caller
7233 (verilog-completion-response))))
7234
7235 (defun verilog-completion-response ()
7236 (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
7237 ;; This was not called by all-completions
7238 (if (null verilog-all)
7239 ;; Return nil if there was no matching label
7240 nil
7241 ;; Get longest string common in the labels
7242 ;; FIXME: Why not use `try-completion'?
7243 (let* ((elm (cdr verilog-all))
7244 (match (car verilog-all))
7245 (min (length match))
7246 tmp)
7247 (if (string= match verilog-str)
7248 ;; Return t if first match was an exact match
7249 (setq match t)
7250 (while (not (null elm))
7251 ;; Find longest common string
7252 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
7253 (progn
7254 (setq min tmp)
7255 (setq match (substring match 0 min))))
7256 ;; Terminate with match=t if this is an exact match
7257 (if (string= (car elm) verilog-str)
7258 (progn
7259 (setq match t)
7260 (setq elm nil))
7261 (setq elm (cdr elm)))))
7262 ;; If this is a test just for exact match, return nil ot t
7263 (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
7264 nil
7265 match))))
7266 ;; If flag is t, this was called by all-completions. Return
7267 ;; list of all possible completions
7268 (verilog-flag
7269 verilog-all)))
7270
7271 (defvar verilog-last-word-numb 0)
7272 (defvar verilog-last-word-shown nil)
7273 (defvar verilog-last-completions nil)
7274
7275 (defun verilog-complete-word ()
7276 "Complete word at current point.
7277 \(See also `verilog-toggle-completions', `verilog-type-keywords',
7278 and `verilog-separator-keywords'.)"
7279 ;; FIXME: Provide completion-at-point-function.
7280 (interactive)
7281 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
7282 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
7283 (verilog-str (buffer-substring b e))
7284 ;; The following variable is used in verilog-completion
7285 (verilog-buffer-to-use (current-buffer))
7286 (allcomp (if (and verilog-toggle-completions
7287 (string= verilog-last-word-shown verilog-str))
7288 verilog-last-completions
7289 (all-completions verilog-str 'verilog-completion)))
7290 (match (if verilog-toggle-completions
7291 "" (try-completion
7292 verilog-str (mapcar (lambda (elm)
7293 (cons elm 0)) allcomp)))))
7294 ;; Delete old string
7295 (delete-region b e)
7296
7297 ;; Toggle-completions inserts whole labels
7298 (if verilog-toggle-completions
7299 (progn
7300 ;; Update entry number in list
7301 (setq verilog-last-completions allcomp
7302 verilog-last-word-numb
7303 (if (>= verilog-last-word-numb (1- (length allcomp)))
7304 0
7305 (1+ verilog-last-word-numb)))
7306 (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
7307 ;; Display next match or same string if no match was found
7308 (if (not (null allcomp))
7309 (insert "" verilog-last-word-shown)
7310 (insert "" verilog-str)
7311 (message "(No match)")))
7312 ;; The other form of completion does not necessarily do that.
7313
7314 ;; Insert match if found, or the original string if no match
7315 (if (or (null match) (equal match 't))
7316 (progn (insert "" verilog-str)
7317 (message "(No match)"))
7318 (insert "" match))
7319 ;; Give message about current status of completion
7320 (cond ((equal match 't)
7321 (if (not (null (cdr allcomp)))
7322 (message "(Complete but not unique)")
7323 (message "(Sole completion)")))
7324 ;; Display buffer if the current completion didn't help
7325 ;; on completing the label.
7326 ((and (not (null (cdr allcomp))) (= (length verilog-str)
7327 (length match)))
7328 (with-output-to-temp-buffer "*Completions*"
7329 (display-completion-list allcomp))
7330 ;; Wait for a key press. Then delete *Completion* window
7331 (momentary-string-display "" (point))
7332 (delete-window (get-buffer-window (get-buffer "*Completions*")))
7333 )))))
7334
7335 (defun verilog-show-completions ()
7336 "Show all possible completions at current point."
7337 (interactive)
7338 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
7339 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
7340 (verilog-str (buffer-substring b e))
7341 ;; The following variable is used in verilog-completion
7342 (verilog-buffer-to-use (current-buffer))
7343 (allcomp (if (and verilog-toggle-completions
7344 (string= verilog-last-word-shown verilog-str))
7345 verilog-last-completions
7346 (all-completions verilog-str 'verilog-completion))))
7347 ;; Show possible completions in a temporary buffer.
7348 (with-output-to-temp-buffer "*Completions*"
7349 (display-completion-list allcomp))
7350 ;; Wait for a key press. Then delete *Completion* window
7351 (momentary-string-display "" (point))
7352 (delete-window (get-buffer-window (get-buffer "*Completions*")))))
7353
7354
7355 (defun verilog-get-default-symbol ()
7356 "Return symbol around current point as a string."
7357 (save-excursion
7358 (buffer-substring (progn
7359 (skip-chars-backward " \t")
7360 (skip-chars-backward "a-zA-Z0-9_")
7361 (point))
7362 (progn
7363 (skip-chars-forward "a-zA-Z0-9_")
7364 (point)))))
7365
7366 (defun verilog-build-defun-re (str &optional arg)
7367 "Return function/task/module starting with STR as regular expression.
7368 With optional second ARG non-nil, STR is the complete name of the instruction."
7369 (if arg
7370 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
7371 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
7372
7373 (defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
7374 "Function passed to `completing-read', `try-completion' or `all-completions'.
7375 Returns a completion on any function name based on VERILOG-STR prefix. If
7376 VERILOG-PRED is non-nil, it must be a function to be called for every match
7377 to check if this should really be a match. If VERILOG-FLAG is t, the
7378 function returns a list of all possible completions. If it is nil it
7379 returns a string, the longest possible completion, or t if VERILOG-STR is
7380 an exact match. If VERILOG-FLAG is 'lambda, the function returns t if
7381 VERILOG-STR is an exact match, nil otherwise."
7382 (save-excursion
7383 (let ((verilog-all nil)
7384 match)
7385
7386 ;; Set buffer to use for searching labels. This should be set
7387 ;; within functions which use verilog-completions
7388 (set-buffer verilog-buffer-to-use)
7389
7390 (let ((verilog-str verilog-str))
7391 ;; Build regular expression for functions
7392 (if (string= verilog-str "")
7393 (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
7394 (setq verilog-str (verilog-build-defun-re verilog-str)))
7395 (goto-char (point-min))
7396
7397 ;; Build a list of all possible completions
7398 (while (verilog-re-search-forward verilog-str nil t)
7399 (setq match (buffer-substring (match-beginning 2) (match-end 2)))
7400 (if (or (null verilog-pred)
7401 (funcall verilog-pred match))
7402 (setq verilog-all (cons match verilog-all)))))
7403
7404 ;; Now we have built a list of all matches. Give response to caller
7405 (verilog-completion-response))))
7406
7407 (defun verilog-goto-defun ()
7408 "Move to specified Verilog module/interface/task/function.
7409 The default is a name found in the buffer around point.
7410 If search fails, other files are checked based on
7411 `verilog-library-flags'."
7412 (interactive)
7413 (let* ((default (verilog-get-default-symbol))
7414 ;; The following variable is used in verilog-comp-function
7415 (verilog-buffer-to-use (current-buffer))
7416 (label (if (not (string= default ""))
7417 ;; Do completion with default
7418 (completing-read (concat "Goto-Label: (default "
7419 default ") ")
7420 'verilog-comp-defun nil nil "")
7421 ;; There is no default value. Complete without it
7422 (completing-read "Goto-Label: "
7423 'verilog-comp-defun nil nil "")))
7424 pt)
7425 ;; Make sure library paths are correct, in case need to resolve module
7426 (verilog-auto-reeval-locals)
7427 (verilog-getopt-flags)
7428 ;; If there was no response on prompt, use default value
7429 (if (string= label "")
7430 (setq label default))
7431 ;; Goto right place in buffer if label is not an empty string
7432 (or (string= label "")
7433 (progn
7434 (save-excursion
7435 (goto-char (point-min))
7436 (setq pt
7437 (re-search-forward (verilog-build-defun-re label t) nil t)))
7438 (when pt
7439 (goto-char pt)
7440 (beginning-of-line))
7441 pt)
7442 (verilog-goto-defun-file label))))
7443
7444 ;; Eliminate compile warning
7445 (defvar occur-pos-list)
7446
7447 (defun verilog-showscopes ()
7448 "List all scopes in this module."
7449 (interactive)
7450 (let ((buffer (current-buffer))
7451 (linenum 1)
7452 (nlines 0)
7453 (first 1)
7454 (prevpos (point-min))
7455 (final-context-start (make-marker))
7456 (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
7457 (with-output-to-temp-buffer "*Occur*"
7458 (save-excursion
7459 (message (format "Searching for %s ..." regexp))
7460 ;; Find next match, but give up if prev match was at end of buffer.
7461 (while (and (not (= prevpos (point-max)))
7462 (verilog-re-search-forward regexp nil t))
7463 (goto-char (match-beginning 0))
7464 (beginning-of-line)
7465 (save-match-data
7466 (setq linenum (+ linenum (count-lines prevpos (point)))))
7467 (setq prevpos (point))
7468 (goto-char (match-end 0))
7469 (let* ((start (save-excursion
7470 (goto-char (match-beginning 0))
7471 (forward-line (if (< nlines 0) nlines (- nlines)))
7472 (point)))
7473 (end (save-excursion
7474 (goto-char (match-end 0))
7475 (if (> nlines 0)
7476 (forward-line (1+ nlines))
7477 (forward-line 1))
7478 (point)))
7479 (tag (format "%3d" linenum))
7480 (empty (make-string (length tag) ?\ ))
7481 tem)
7482 (save-excursion
7483 (setq tem (make-marker))
7484 (set-marker tem (point))
7485 (set-buffer standard-output)
7486 (setq occur-pos-list (cons tem occur-pos-list))
7487 (or first (zerop nlines)
7488 (insert "--------\n"))
7489 (setq first nil)
7490 (insert-buffer-substring buffer start end)
7491 (backward-char (- end start))
7492 (setq tem (if (< nlines 0) (- nlines) nlines))
7493 (while (> tem 0)
7494 (insert empty ?:)
7495 (forward-line 1)
7496 (setq tem (1- tem)))
7497 (let ((this-linenum linenum))
7498 (set-marker final-context-start
7499 (+ (point) (- (match-end 0) (match-beginning 0))))
7500 (while (< (point) final-context-start)
7501 (if (null tag)
7502 (setq tag (format "%3d" this-linenum)))
7503 (insert tag ?:)))))))
7504 (set-buffer-modified-p nil))))
7505
7506
7507 ;; Highlight helper functions
7508 (defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
7509 (defun verilog-within-translate-off ()
7510 "Return point if within translate-off region, else nil."
7511 (and (save-excursion
7512 (re-search-backward
7513 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
7514 nil t))
7515 (equal "off" (match-string 2))
7516 (point)))
7517
7518 (defun verilog-start-translate-off (limit)
7519 "Return point before translate-off directive if before LIMIT, else nil."
7520 (when (re-search-forward
7521 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
7522 limit t)
7523 (match-beginning 0)))
7524
7525 (defun verilog-back-to-start-translate-off (limit)
7526 "Return point before translate-off directive if before LIMIT, else nil."
7527 (when (re-search-backward
7528 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
7529 limit t)
7530 (match-beginning 0)))
7531
7532 (defun verilog-end-translate-off (limit)
7533 "Return point after translate-on directive if before LIMIT, else nil."
7534
7535 (re-search-forward (concat
7536 "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
7537
7538 (defun verilog-match-translate-off (limit)
7539 "Match a translate-off block, setting `match-data' and returning t, else nil.
7540 Bound search by LIMIT."
7541 (when (< (point) limit)
7542 (let ((start (or (verilog-within-translate-off)
7543 (verilog-start-translate-off limit)))
7544 (case-fold-search t))
7545 (when start
7546 (let ((end (or (verilog-end-translate-off limit) limit)))
7547 (set-match-data (list start end))
7548 (goto-char end))))))
7549
7550 (defun verilog-font-lock-match-item (limit)
7551 "Match, and move over, any declaration item after point.
7552 Bound search by LIMIT. Adapted from
7553 `font-lock-match-c-style-declaration-item-and-skip-to-next'."
7554 (condition-case nil
7555 (save-restriction
7556 (narrow-to-region (point-min) limit)
7557 ;; match item
7558 (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
7559 (save-match-data
7560 (goto-char (match-end 1))
7561 ;; move to next item
7562 (if (looking-at "\\(\\s-*,\\)")
7563 (goto-char (match-end 1))
7564 (end-of-line) t))))
7565 (error nil)))
7566
7567
7568 ;; Added by Subbu Meiyappan for Header
7569
7570 (defun verilog-header ()
7571 "Insert a standard Verilog file header.
7572 See also `verilog-sk-header' for an alternative format."
7573 (interactive)
7574 (let ((start (point)))
7575 (insert "\
7576 //-----------------------------------------------------------------------------
7577 // Title : <title>
7578 // Project : <project>
7579 //-----------------------------------------------------------------------------
7580 // File : <filename>
7581 // Author : <author>
7582 // Created : <credate>
7583 // Last modified : <moddate>
7584 //-----------------------------------------------------------------------------
7585 // Description :
7586 // <description>
7587 //-----------------------------------------------------------------------------
7588 // Copyright (c) <copydate> by <company> This model is the confidential and
7589 // proprietary property of <company> and the possession or use of this
7590 // file requires a written license from <company>.
7591 //------------------------------------------------------------------------------
7592 // Modification history :
7593 // <modhist>
7594 //-----------------------------------------------------------------------------
7595
7596 ")
7597 (goto-char start)
7598 (search-forward "<filename>")
7599 (replace-match (buffer-name) t t)
7600 (search-forward "<author>") (replace-match "" t t)
7601 (insert (user-full-name))
7602 (insert " <" (user-login-name) "@" (system-name) ">")
7603 (search-forward "<credate>") (replace-match "" t t)
7604 (verilog-insert-date)
7605 (search-forward "<moddate>") (replace-match "" t t)
7606 (verilog-insert-date)
7607 (search-forward "<copydate>") (replace-match "" t t)
7608 (verilog-insert-year)
7609 (search-forward "<modhist>") (replace-match "" t t)
7610 (verilog-insert-date)
7611 (insert " : created")
7612 (goto-char start)
7613 (let (string)
7614 (setq string (read-string "title: "))
7615 (search-forward "<title>")
7616 (replace-match string t t)
7617 (setq string (read-string "project: " verilog-project))
7618 (setq verilog-project string)
7619 (search-forward "<project>")
7620 (replace-match string t t)
7621 (setq string (read-string "Company: " verilog-company))
7622 (setq verilog-company string)
7623 (search-forward "<company>")
7624 (replace-match string t t)
7625 (search-forward "<company>")
7626 (replace-match string t t)
7627 (search-forward "<company>")
7628 (replace-match string t t)
7629 (search-backward "<description>")
7630 (replace-match "" t t))))
7631
7632 ;; verilog-header Uses the verilog-insert-date function
7633
7634 (defun verilog-insert-date ()
7635 "Insert date from the system."
7636 (interactive)
7637 (if verilog-date-scientific-format
7638 (insert (format-time-string "%Y/%m/%d"))
7639 (insert (format-time-string "%d.%m.%Y"))))
7640
7641 (defun verilog-insert-year ()
7642 "Insert year from the system."
7643 (interactive)
7644 (insert (format-time-string "%Y")))
7645
7646 \f
7647 ;;
7648 ;; Signal list parsing
7649 ;;
7650
7651 ;; Elements of a signal list
7652 ;; Unfortunately we use 'assoc' on this, so can't be a vector
7653 (defsubst verilog-sig-new (name bits comment mem enum signed type multidim modport)
7654 (list name bits comment mem enum signed type multidim modport))
7655 (defsubst verilog-sig-name (sig)
7656 (car sig))
7657 (defsubst verilog-sig-bits (sig) ;; First element of packed array (pre signal-name)
7658 (nth 1 sig))
7659 (defsubst verilog-sig-comment (sig)
7660 (nth 2 sig))
7661 (defsubst verilog-sig-memory (sig) ;; Unpacked array (post signal-name)
7662 (nth 3 sig))
7663 (defsubst verilog-sig-enum (sig)
7664 (nth 4 sig))
7665 (defsubst verilog-sig-signed (sig)
7666 (nth 5 sig))
7667 (defsubst verilog-sig-type (sig)
7668 (nth 6 sig))
7669 (defsubst verilog-sig-type-set (sig type)
7670 (setcar (nthcdr 6 sig) type))
7671 (defsubst verilog-sig-multidim (sig) ;; Second and additional elements of packed array
7672 (nth 7 sig))
7673 (defsubst verilog-sig-multidim-string (sig)
7674 (if (verilog-sig-multidim sig)
7675 (let ((str "") (args (verilog-sig-multidim sig)))
7676 (while args
7677 (setq str (concat str (car args)))
7678 (setq args (cdr args)))
7679 str)))
7680 (defsubst verilog-sig-modport (sig)
7681 (nth 8 sig))
7682 (defsubst verilog-sig-width (sig)
7683 (verilog-make-width-expression (verilog-sig-bits sig)))
7684
7685 (defsubst verilog-alw-new (outputs-del outputs-imm temps inputs)
7686 (vector outputs-del outputs-imm temps inputs))
7687 (defsubst verilog-alw-get-outputs-delayed (sigs)
7688 (aref sigs 0))
7689 (defsubst verilog-alw-get-outputs-immediate (sigs)
7690 (aref sigs 1))
7691 (defsubst verilog-alw-get-temps (sigs)
7692 (aref sigs 2))
7693 (defsubst verilog-alw-get-inputs (sigs)
7694 (aref sigs 3))
7695 (defsubst verilog-alw-get-uses-delayed (sigs)
7696 (aref sigs 0))
7697
7698 (defsubst verilog-modport-new (name clockings decls)
7699 (list name clockings decls))
7700 (defsubst verilog-modport-name (sig)
7701 (car sig))
7702 (defsubst verilog-modport-clockings (sig)
7703 (nth 1 sig)) ;; Returns list of names
7704 (defsubst verilog-modport-clockings-add (sig val)
7705 (setcar (nthcdr 1 sig) (cons val (nth 1 sig))))
7706 (defsubst verilog-modport-decls (sig)
7707 (nth 2 sig)) ;; Returns verilog-decls-* structure
7708 (defsubst verilog-modport-decls-set (sig val)
7709 (setcar (nthcdr 2 sig) val))
7710
7711 (defsubst verilog-modi-new (name fob pt type)
7712 (vector name fob pt type))
7713 (defsubst verilog-modi-name (modi)
7714 (aref modi 0))
7715 (defsubst verilog-modi-file-or-buffer (modi)
7716 (aref modi 1))
7717 (defsubst verilog-modi-get-point (modi)
7718 (aref modi 2))
7719 (defsubst verilog-modi-get-type (modi) ;; "module" or "interface"
7720 (aref modi 3))
7721 (defsubst verilog-modi-get-decls (modi)
7722 (verilog-modi-cache-results modi 'verilog-read-decls))
7723 (defsubst verilog-modi-get-sub-decls (modi)
7724 (verilog-modi-cache-results modi 'verilog-read-sub-decls))
7725
7726 ;; Signal reading for given module
7727 ;; Note these all take modi's - as returned from verilog-modi-current
7728 (defsubst verilog-decls-new (out inout in vars modports assigns consts gparams interfaces)
7729 (vector out inout in vars modports assigns consts gparams interfaces))
7730 (defsubst verilog-decls-append (a b)
7731 (cond ((not a) b) ((not b) a)
7732 (t (vector (append (aref a 0) (aref b 0)) (append (aref a 1) (aref b 1))
7733 (append (aref a 2) (aref b 2)) (append (aref a 3) (aref b 3))
7734 (append (aref a 4) (aref b 4)) (append (aref a 5) (aref b 5))
7735 (append (aref a 6) (aref b 6)) (append (aref a 7) (aref b 7))
7736 (append (aref a 8) (aref b 8))))))
7737 (defsubst verilog-decls-get-outputs (decls)
7738 (aref decls 0))
7739 (defsubst verilog-decls-get-inouts (decls)
7740 (aref decls 1))
7741 (defsubst verilog-decls-get-inputs (decls)
7742 (aref decls 2))
7743 (defsubst verilog-decls-get-vars (decls)
7744 (aref decls 3))
7745 (defsubst verilog-decls-get-modports (decls) ;; Also for clocking blocks; contains another verilog-decls struct
7746 (aref decls 4)) ;; Returns verilog-modport* structure
7747 (defsubst verilog-decls-get-assigns (decls)
7748 (aref decls 5))
7749 (defsubst verilog-decls-get-consts (decls)
7750 (aref decls 6))
7751 (defsubst verilog-decls-get-gparams (decls)
7752 (aref decls 7))
7753 (defsubst verilog-decls-get-interfaces (decls)
7754 (aref decls 8))
7755
7756
7757 (defsubst verilog-subdecls-new (out inout in intf intfd)
7758 (vector out inout in intf intfd))
7759 (defsubst verilog-subdecls-get-outputs (subdecls)
7760 (aref subdecls 0))
7761 (defsubst verilog-subdecls-get-inouts (subdecls)
7762 (aref subdecls 1))
7763 (defsubst verilog-subdecls-get-inputs (subdecls)
7764 (aref subdecls 2))
7765 (defsubst verilog-subdecls-get-interfaces (subdecls)
7766 (aref subdecls 3))
7767 (defsubst verilog-subdecls-get-interfaced (subdecls)
7768 (aref subdecls 4))
7769
7770 (defun verilog-signals-from-signame (signame-list)
7771 "Return signals in standard form from SIGNAME-LIST, a simple list of names."
7772 (mapcar (lambda (name) (verilog-sig-new name nil nil nil nil nil nil nil nil))
7773 signame-list))
7774
7775 (defun verilog-signals-in (in-list not-list)
7776 "Return list of signals in IN-LIST that are also in NOT-LIST.
7777 Also remove any duplicates in IN-LIST.
7778 Signals must be in standard (base vector) form."
7779 ;; This function is hot, so implemented as O(1)
7780 (cond ((eval-when-compile (fboundp 'make-hash-table))
7781 (let ((ht (make-hash-table :test 'equal :rehash-size 4.0))
7782 (ht-not (make-hash-table :test 'equal :rehash-size 4.0))
7783 out-list)
7784 (while not-list
7785 (puthash (car (car not-list)) t ht-not)
7786 (setq not-list (cdr not-list)))
7787 (while in-list
7788 (when (and (gethash (verilog-sig-name (car in-list)) ht-not)
7789 (not (gethash (verilog-sig-name (car in-list)) ht)))
7790 (setq out-list (cons (car in-list) out-list))
7791 (puthash (verilog-sig-name (car in-list)) t ht))
7792 (setq in-list (cdr in-list)))
7793 (nreverse out-list)))
7794 ;; Slower Fallback if no hash tables (pre Emacs 21.1/XEmacs 21.4)
7795 (t
7796 (let (out-list)
7797 (while in-list
7798 (if (and (assoc (verilog-sig-name (car in-list)) not-list)
7799 (not (assoc (verilog-sig-name (car in-list)) out-list)))
7800 (setq out-list (cons (car in-list) out-list)))
7801 (setq in-list (cdr in-list)))
7802 (nreverse out-list)))))
7803 ;;(verilog-signals-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("C" "")))
7804
7805 (defun verilog-signals-not-in (in-list not-list)
7806 "Return list of signals in IN-LIST that aren't also in NOT-LIST.
7807 Also remove any duplicates in IN-LIST.
7808 Signals must be in standard (base vector) form."
7809 ;; This function is hot, so implemented as O(1)
7810 (cond ((eval-when-compile (fboundp 'make-hash-table))
7811 (let ((ht (make-hash-table :test 'equal :rehash-size 4.0))
7812 out-list)
7813 (while not-list
7814 (puthash (car (car not-list)) t ht)
7815 (setq not-list (cdr not-list)))
7816 (while in-list
7817 (when (not (gethash (verilog-sig-name (car in-list)) ht))
7818 (setq out-list (cons (car in-list) out-list))
7819 (puthash (verilog-sig-name (car in-list)) t ht))
7820 (setq in-list (cdr in-list)))
7821 (nreverse out-list)))
7822 ;; Slower Fallback if no hash tables (pre Emacs 21.1/XEmacs 21.4)
7823 (t
7824 (let (out-list)
7825 (while in-list
7826 (if (and (not (assoc (verilog-sig-name (car in-list)) not-list))
7827 (not (assoc (verilog-sig-name (car in-list)) out-list)))
7828 (setq out-list (cons (car in-list) out-list)))
7829 (setq in-list (cdr in-list)))
7830 (nreverse out-list)))))
7831 ;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
7832
7833 (defun verilog-signals-memory (in-list)
7834 "Return list of signals in IN-LIST that are memorized (multidimensional)."
7835 (let (out-list)
7836 (while in-list
7837 (if (nth 3 (car in-list))
7838 (setq out-list (cons (car in-list) out-list)))
7839 (setq in-list (cdr in-list)))
7840 out-list))
7841 ;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
7842
7843 (defun verilog-signals-sort-compare (a b)
7844 "Compare signal A and B for sorting."
7845 (string< (verilog-sig-name a) (verilog-sig-name b)))
7846
7847 (defun verilog-signals-not-params (in-list)
7848 "Return list of signals in IN-LIST that aren't parameters or numeric constants."
7849 (let (out-list)
7850 (while in-list
7851 ;; Namespace intentionally short for AUTOs and compatibility
7852 (unless (boundp (intern (concat "vh-" (verilog-sig-name (car in-list)))))
7853 (setq out-list (cons (car in-list) out-list)))
7854 (setq in-list (cdr in-list)))
7855 (nreverse out-list)))
7856
7857 (defun verilog-signals-with (func in-list)
7858 "Return list of signals where FUNC is true executed on each signal in IN-LIST."
7859 (let (out-list)
7860 (while in-list
7861 (when (funcall func (car in-list))
7862 (setq out-list (cons (car in-list) out-list)))
7863 (setq in-list (cdr in-list)))
7864 (nreverse out-list)))
7865
7866 (defun verilog-signals-combine-bus (in-list)
7867 "Return a list of signals in IN-LIST, with buses combined.
7868 Duplicate signals are also removed. For example A[2] and A[1] become A[2:1]."
7869 (let (combo buswarn
7870 out-list
7871 sig highbit lowbit ; Temp information about current signal
7872 sv-name sv-highbit sv-lowbit ; Details about signal we are forming
7873 sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
7874 sv-modport
7875 bus)
7876 ;; Shove signals so duplicated signals will be adjacent
7877 (setq in-list (sort in-list `verilog-signals-sort-compare))
7878 (while in-list
7879 (setq sig (car in-list))
7880 ;; No current signal; form from existing details
7881 (unless sv-name
7882 (setq sv-name (verilog-sig-name sig)
7883 sv-highbit nil
7884 sv-busstring nil
7885 sv-comment (verilog-sig-comment sig)
7886 sv-memory (verilog-sig-memory sig)
7887 sv-enum (verilog-sig-enum sig)
7888 sv-signed (verilog-sig-signed sig)
7889 sv-type (verilog-sig-type sig)
7890 sv-multidim (verilog-sig-multidim sig)
7891 sv-modport (verilog-sig-modport sig)
7892 combo ""
7893 buswarn ""))
7894 ;; Extract bus details
7895 (setq bus (verilog-sig-bits sig))
7896 (setq bus (and bus (verilog-simplify-range-expression bus)))
7897 (cond ((and bus
7898 (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
7899 (setq highbit (string-to-number (match-string 1 bus))
7900 lowbit (string-to-number
7901 (match-string 2 bus))))
7902 (and (string-match "\\[\\([0-9]+\\)\\]" bus)
7903 (setq highbit (string-to-number (match-string 1 bus))
7904 lowbit highbit))))
7905 ;; Combine bits in bus
7906 (if sv-highbit
7907 (setq sv-highbit (max highbit sv-highbit)
7908 sv-lowbit (min lowbit sv-lowbit))
7909 (setq sv-highbit highbit
7910 sv-lowbit lowbit)))
7911 (bus
7912 ;; String, probably something like `preproc:0
7913 (setq sv-busstring bus)))
7914 ;; Peek ahead to next signal
7915 (setq in-list (cdr in-list))
7916 (setq sig (car in-list))
7917 (cond ((and sig (equal sv-name (verilog-sig-name sig)))
7918 ;; Combine with this signal
7919 (when (and sv-busstring
7920 (not (equal sv-busstring (verilog-sig-bits sig))))
7921 (when nil ;; Debugging
7922 (message (concat "Warning, can't merge into single bus "
7923 sv-name bus
7924 ", the AUTOs may be wrong")))
7925 (setq buswarn ", Couldn't Merge"))
7926 (if (verilog-sig-comment sig) (setq combo ", ..."))
7927 (setq sv-memory (or sv-memory (verilog-sig-memory sig))
7928 sv-enum (or sv-enum (verilog-sig-enum sig))
7929 sv-signed (or sv-signed (verilog-sig-signed sig))
7930 sv-type (or sv-type (verilog-sig-type sig))
7931 sv-multidim (or sv-multidim (verilog-sig-multidim sig))
7932 sv-modport (or sv-modport (verilog-sig-modport sig))))
7933 ;; Doesn't match next signal, add to queue, zero in prep for next
7934 ;; Note sig may also be nil for the last signal in the list
7935 (t
7936 (setq out-list
7937 (cons (verilog-sig-new
7938 sv-name
7939 (or sv-busstring
7940 (if sv-highbit
7941 (concat "[" (int-to-string sv-highbit) ":"
7942 (int-to-string sv-lowbit) "]")))
7943 (concat sv-comment combo buswarn)
7944 sv-memory sv-enum sv-signed sv-type sv-multidim sv-modport)
7945 out-list)
7946 sv-name nil))))
7947 ;;
7948 out-list))
7949
7950 (defun verilog-sig-tieoff (sig)
7951 "Return tieoff expression for given SIG, with appropriate width.
7952 Tieoff value uses `verilog-active-low-regexp' and
7953 `verilog-auto-reset-widths'."
7954 (concat
7955 (if (and verilog-active-low-regexp
7956 (verilog-string-match-fold verilog-active-low-regexp (verilog-sig-name sig)))
7957 "~" "")
7958 (cond ((not verilog-auto-reset-widths)
7959 "0")
7960 ((equal verilog-auto-reset-widths 'unbased)
7961 "'0")
7962 ;; Else presume verilog-auto-reset-widths is true
7963 (t
7964 (let* ((width (verilog-sig-width sig)))
7965 (cond ((not width)
7966 "`0/*NOWIDTH*/")
7967 ((string-match "^[0-9]+$" width)
7968 (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
7969 (t
7970 (concat "{" width "{1'b0}}"))))))))
7971
7972 ;;
7973 ;; Dumping
7974 ;;
7975
7976 (defun verilog-decls-princ (decls &optional header prefix)
7977 "For debug, dump the `verilog-read-decls' structure DECLS."
7978 (when decls
7979 (if header (princ header))
7980 (setq prefix (or prefix ""))
7981 (verilog-signals-princ (verilog-decls-get-outputs decls)
7982 (concat prefix "Outputs:\n") (concat prefix " "))
7983 (verilog-signals-princ (verilog-decls-get-inouts decls)
7984 (concat prefix "Inout:\n") (concat prefix " "))
7985 (verilog-signals-princ (verilog-decls-get-inputs decls)
7986 (concat prefix "Inputs:\n") (concat prefix " "))
7987 (verilog-signals-princ (verilog-decls-get-vars decls)
7988 (concat prefix "Vars:\n") (concat prefix " "))
7989 (verilog-signals-princ (verilog-decls-get-assigns decls)
7990 (concat prefix "Assigns:\n") (concat prefix " "))
7991 (verilog-signals-princ (verilog-decls-get-consts decls)
7992 (concat prefix "Consts:\n") (concat prefix " "))
7993 (verilog-signals-princ (verilog-decls-get-gparams decls)
7994 (concat prefix "Gparams:\n") (concat prefix " "))
7995 (verilog-signals-princ (verilog-decls-get-interfaces decls)
7996 (concat prefix "Interfaces:\n") (concat prefix " "))
7997 (verilog-modport-princ (verilog-decls-get-modports decls)
7998 (concat prefix "Modports:\n") (concat prefix " "))
7999 (princ "\n")))
8000
8001 (defun verilog-signals-princ (signals &optional header prefix)
8002 "For debug, dump internal SIGNALS structures, with HEADER and PREFIX."
8003 (when signals
8004 (if header (princ header))
8005 (while signals
8006 (let ((sig (car signals)))
8007 (setq signals (cdr signals))
8008 (princ prefix)
8009 (princ "\"") (princ (verilog-sig-name sig)) (princ "\"")
8010 (princ " bits=") (princ (verilog-sig-bits sig))
8011 (princ " cmt=") (princ (verilog-sig-comment sig))
8012 (princ " mem=") (princ (verilog-sig-memory sig))
8013 (princ " enum=") (princ (verilog-sig-enum sig))
8014 (princ " sign=") (princ (verilog-sig-signed sig))
8015 (princ " type=") (princ (verilog-sig-type sig))
8016 (princ " dim=") (princ (verilog-sig-multidim sig))
8017 (princ " modp=") (princ (verilog-sig-modport sig))
8018 (princ "\n")))))
8019
8020 (defun verilog-modport-princ (modports &optional header prefix)
8021 "For debug, dump internal MODPORT structures, with HEADER and PREFIX."
8022 (when modports
8023 (if header (princ header))
8024 (while modports
8025 (let ((sig (car modports)))
8026 (setq modports (cdr modports))
8027 (princ prefix)
8028 (princ "\"") (princ (verilog-modport-name sig)) (princ "\"")
8029 (princ " clockings=") (princ (verilog-modport-clockings sig))
8030 (princ "\n")
8031 (verilog-decls-princ (verilog-modport-decls sig)
8032 (concat prefix " syms:\n")
8033 (concat prefix " "))))))
8034
8035 ;;
8036 ;; Port/Wire/Etc Reading
8037 ;;
8038
8039 (defun verilog-read-inst-backward-name ()
8040 "Internal. Move point back to beginning of inst-name."
8041 (verilog-backward-open-paren)
8042 (let (done)
8043 (while (not done)
8044 (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil) ; ] isn't word boundary
8045 (cond ((looking-at ")")
8046 (verilog-backward-open-paren))
8047 (t (setq done t)))))
8048 (while (looking-at "\\]")
8049 (verilog-backward-open-bracket)
8050 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
8051 (skip-chars-backward "a-zA-Z0-9`_$"))
8052
8053 (defun verilog-read-inst-module-matcher ()
8054 "Set match data 0 with module_name when point is inside instantiation."
8055 (verilog-read-inst-backward-name)
8056 ;; Skip over instantiation name
8057 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
8058 ;; Check for parameterized instantiations
8059 (when (looking-at ")")
8060 (verilog-backward-open-paren)
8061 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
8062 (skip-chars-backward "a-zA-Z0-9'_$")
8063 ;; #1 is legal syntax for gate primitives
8064 (when (save-excursion
8065 (verilog-backward-syntactic-ws-quick)
8066 (eq ?# (char-before)))
8067 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
8068 (skip-chars-backward "a-zA-Z0-9'_$"))
8069 (looking-at "[a-zA-Z0-9`_\$]+")
8070 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
8071 (buffer-substring-no-properties (match-beginning 0) (match-end 0))
8072 ;; Caller assumes match-beginning/match-end is still set
8073 )
8074
8075 (defun verilog-read-inst-module ()
8076 "Return module_name when point is inside instantiation."
8077 (save-excursion
8078 (verilog-read-inst-module-matcher)))
8079
8080 (defun verilog-read-inst-name ()
8081 "Return instance_name when point is inside instantiation."
8082 (save-excursion
8083 (verilog-read-inst-backward-name)
8084 (looking-at "[a-zA-Z0-9`_\$]+")
8085 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
8086 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
8087
8088 (defun verilog-read-module-name ()
8089 "Return module name when after its ( or ;."
8090 (save-excursion
8091 (re-search-backward "[(;]")
8092 ;; Due to "module x import y (" we must search for declaration begin
8093 (verilog-re-search-backward-quick verilog-defun-re nil nil)
8094 (goto-char (match-end 0))
8095 (verilog-re-search-forward-quick "\\b[a-zA-Z0-9`_\$]+" nil nil)
8096 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
8097 (verilog-symbol-detick
8098 (buffer-substring-no-properties (match-beginning 0) (match-end 0)) t)))
8099
8100 (defun verilog-read-inst-param-value ()
8101 "Return list of parameters and values when point is inside instantiation."
8102 (save-excursion
8103 (verilog-read-inst-backward-name)
8104 ;; Skip over instantiation name
8105 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
8106 ;; If there are parameterized instantiations
8107 (when (looking-at ")")
8108 (let ((end-pt (point))
8109 params
8110 param-name paren-beg-pt param-value)
8111 (verilog-backward-open-paren)
8112 (while (verilog-re-search-forward-quick "\\." end-pt t)
8113 (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
8114 (skip-chars-backward "a-zA-Z0-9'_$")
8115 (looking-at "[a-zA-Z0-9`_\$]+")
8116 (setq param-name (buffer-substring-no-properties
8117 (match-beginning 0) (match-end 0)))
8118 (verilog-re-search-forward-quick "(" nil nil)
8119 (setq paren-beg-pt (point))
8120 (verilog-forward-close-paren)
8121 (setq param-value (verilog-string-remove-spaces
8122 (buffer-substring-no-properties
8123 paren-beg-pt (1- (point)))))
8124 (setq params (cons (list param-name param-value) params)))
8125 params))))
8126
8127 (defun verilog-read-auto-params (num-param &optional max-param)
8128 "Return parameter list inside auto.
8129 Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
8130 (let ((olist))
8131 (save-excursion
8132 ;; /*AUTOPUNT("parameter", "parameter")*/
8133 (backward-sexp 1)
8134 (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
8135 (setq olist (cons (match-string 1) olist))
8136 (goto-char (match-end 0))))
8137 (or (eq nil num-param)
8138 (<= num-param (length olist))
8139 (error "%s: Expected %d parameters" (verilog-point-text) num-param))
8140 (if (eq max-param nil) (setq max-param num-param))
8141 (or (eq nil max-param)
8142 (>= max-param (length olist))
8143 (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
8144 (nreverse olist)))
8145
8146 (defun verilog-read-decls ()
8147 "Compute signal declaration information for the current module at point.
8148 Return an array of [outputs inouts inputs wire reg assign const]."
8149 (let ((end-mod-point (or (verilog-get-end-of-defun) (point-max)))
8150 (functask 0) (paren 0) (sig-paren 0) (v2kargs-ok t)
8151 in-modport in-clocking in-ign-to-semi ptype ign-prop
8152 sigs-in sigs-out sigs-inout sigs-var sigs-assign sigs-const
8153 sigs-gparam sigs-intf sigs-modports
8154 vec expect-signal keywd newsig rvalue enum io signed typedefed multidim
8155 modport
8156 varstack tmp)
8157 ;;(if dbg (setq dbg (concat dbg (format "\n\nverilog-read-decls START PT %s END %s\n" (point) end-mod-point))))
8158 (save-excursion
8159 (verilog-beg-of-defun-quick)
8160 (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
8161 (while (< (point) end-mod-point)
8162 ;;(if dbg (setq dbg (concat dbg (format "Pt %s Vec %s C%c Kwd'%s'\n" (point) vec (following-char) keywd))))
8163 (cond
8164 ((looking-at "//")
8165 (if (looking-at "[^\n]*\\(auto\\|synopsys\\)\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
8166 (setq enum (match-string 2)))
8167 (search-forward "\n"))
8168 ((looking-at "/\\*")
8169 (forward-char 2)
8170 (if (looking-at "[^\n]*\\(auto\\|synopsys\\)\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
8171 (setq enum (match-string 2)))
8172 (or (search-forward "*/")
8173 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8174 ((looking-at "(\\*")
8175 ;; To advance past either "(*)" or "(* ... *)" don't forward past first *
8176 (forward-char 1)
8177 (or (search-forward "*)")
8178 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
8179 ((eq ?\" (following-char))
8180 (or (re-search-forward "[^\\]\"" nil t) ;; don't forward-char first, since we look for a non backslash first
8181 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
8182 ((eq ?\; (following-char))
8183 (cond (in-ign-to-semi ;; Such as inside a "import ...;" in a module header
8184 (setq in-ign-to-semi nil))
8185 ((and in-modport (not (eq in-modport t))) ;; end of a modport declaration
8186 (verilog-modport-decls-set
8187 in-modport
8188 (verilog-decls-new sigs-out sigs-inout sigs-in
8189 nil nil nil nil nil nil))
8190 ;; Pop from varstack to restore state to pre-clocking
8191 (setq tmp (car varstack)
8192 varstack (cdr varstack)
8193 sigs-out (aref tmp 0)
8194 sigs-inout (aref tmp 1)
8195 sigs-in (aref tmp 2))
8196 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil
8197 v2kargs-ok nil in-modport nil ign-prop nil))
8198 (t
8199 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil
8200 v2kargs-ok nil in-modport nil ign-prop nil)))
8201 (forward-char 1))
8202 ((eq ?= (following-char))
8203 (setq rvalue t newsig nil)
8204 (forward-char 1))
8205 ((and (eq ?, (following-char))
8206 (eq paren sig-paren))
8207 (setq rvalue nil)
8208 (forward-char 1))
8209 ;; ,'s can occur inside {} & funcs
8210 ((looking-at "[{(]")
8211 (setq paren (1+ paren))
8212 (forward-char 1))
8213 ((looking-at "[})]")
8214 (setq paren (1- paren))
8215 (forward-char 1)
8216 (when (< paren sig-paren)
8217 (setq expect-signal nil rvalue nil))) ; ) that ends variables inside v2k arg list
8218 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
8219 (goto-char (match-end 0))
8220 (cond (newsig ; Memory, not just width. Patch last signal added's memory (nth 3)
8221 (setcar (cdr (cdr (cdr newsig)))
8222 (if (verilog-sig-memory newsig)
8223 (concat (verilog-sig-memory newsig) (match-string 1))
8224 (match-string 1))))
8225 (vec ;; Multidimensional
8226 (setq multidim (cons vec multidim))
8227 (setq vec (verilog-string-replace-matches
8228 "\\s-+" "" nil nil (match-string 1))))
8229 (t ;; Bit width
8230 (setq vec (verilog-string-replace-matches
8231 "\\s-+" "" nil nil (match-string 1))))))
8232 ;; Normal or escaped identifier -- note we remember the \ if escaped
8233 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
8234 (goto-char (match-end 0))
8235 (setq keywd (match-string 1))
8236 (when (string-match "^\\\\" (match-string 1))
8237 (setq keywd (concat keywd " "))) ;; Escaped ID needs space at end
8238 ;; Add any :: package names to same identifier
8239 (while (looking-at "\\s-*::\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
8240 (goto-char (match-end 0))
8241 (setq keywd (concat keywd "::" (match-string 1)))
8242 (when (string-match "^\\\\" (match-string 1))
8243 (setq keywd (concat keywd " ")))) ;; Escaped ID needs space at end
8244 (cond ((equal keywd "input")
8245 (setq vec nil enum nil rvalue nil newsig nil signed nil
8246 typedefed nil multidim nil ptype nil modport nil
8247 expect-signal 'sigs-in io t sig-paren paren))
8248 ((equal keywd "output")
8249 (setq vec nil enum nil rvalue nil newsig nil signed nil
8250 typedefed nil multidim nil ptype nil modport nil
8251 expect-signal 'sigs-out io t sig-paren paren))
8252 ((equal keywd "inout")
8253 (setq vec nil enum nil rvalue nil newsig nil signed nil
8254 typedefed nil multidim nil ptype nil modport nil
8255 expect-signal 'sigs-inout io t sig-paren paren))
8256 ((equal keywd "parameter")
8257 (setq vec nil enum nil rvalue nil signed nil
8258 typedefed nil multidim nil ptype nil modport nil
8259 expect-signal 'sigs-gparam io t sig-paren paren))
8260 ((member keywd '("wire" "reg" ; Fast
8261 ;; net_type
8262 "tri" "tri0" "tri1" "triand" "trior" "trireg"
8263 "uwire" "wand" "wor"
8264 ;; integer_atom_type
8265 "byte" "shortint" "int" "longint" "integer" "time"
8266 "supply0" "supply1"
8267 ;; integer_vector_type - "reg" above
8268 "bit" "logic"
8269 ;; non_integer_type
8270 "shortreal" "real" "realtime"
8271 ;; data_type
8272 "string" "event" "chandle"))
8273 (cond (io
8274 (setq typedefed
8275 (if typedefed (concat typedefed " " keywd) keywd)))
8276 (t (setq vec nil enum nil rvalue nil signed nil
8277 typedefed nil multidim nil sig-paren paren
8278 expect-signal 'sigs-var modport nil))))
8279 ((equal keywd "assign")
8280 (setq vec nil enum nil rvalue nil signed nil
8281 typedefed nil multidim nil ptype nil modport nil
8282 expect-signal 'sigs-assign sig-paren paren))
8283 ((member keywd '("localparam" "genvar"))
8284 (unless io
8285 (setq vec nil enum nil rvalue nil signed nil
8286 typedefed nil multidim nil ptype nil modport nil
8287 expect-signal 'sigs-const sig-paren paren)))
8288 ((member keywd '("signed" "unsigned"))
8289 (setq signed keywd))
8290 ((member keywd '("assert" "assume" "cover" "expect" "restrict"))
8291 (setq ign-prop t))
8292 ((member keywd '("class" "covergroup" "function"
8293 "property" "randsequence" "sequence" "task"))
8294 (unless ign-prop
8295 (setq functask (1+ functask))))
8296 ((member keywd '("endclass" "endgroup" "endfunction"
8297 "endproperty" "endsequence" "endtask"))
8298 (setq functask (1- functask)))
8299 ((equal keywd "modport")
8300 (setq in-modport t))
8301 ((equal keywd "clocking")
8302 (setq in-clocking t))
8303 ((equal keywd "import")
8304 (if v2kargs-ok ;; import in module header, not a modport import
8305 (setq in-ign-to-semi t rvalue t)))
8306 ((equal keywd "type")
8307 (setq ptype t))
8308 ((equal keywd "var"))
8309 ;; Ifdef? Ignore name of define
8310 ((member keywd '("`ifdef" "`ifndef" "`elsif"))
8311 (setq rvalue t))
8312 ;; Type?
8313 ((unless ptype
8314 (verilog-typedef-name-p keywd))
8315 (cond (io
8316 (setq typedefed
8317 (if typedefed (concat typedefed " " keywd) keywd)))
8318 (t (setq vec nil enum nil rvalue nil signed nil
8319 typedefed keywd ; Have a type
8320 multidim nil sig-paren paren
8321 expect-signal 'sigs-var modport nil))))
8322 ;; Interface with optional modport in v2k arglist?
8323 ;; Skip over parsing modport, and take the interface name as the type
8324 ((and v2kargs-ok
8325 (eq paren 1)
8326 (not rvalue)
8327 (looking-at "\\s-*\\(\\.\\(\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*\\)\\|\\)\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*"))
8328 (when (match-end 2) (goto-char (match-end 2)))
8329 (setq vec nil enum nil rvalue nil signed nil
8330 typedefed keywd multidim nil ptype nil modport (match-string 2)
8331 newsig nil sig-paren paren
8332 expect-signal 'sigs-intf io t ))
8333 ;; Ignore dotted LHS assignments: "assign foo.bar = z;"
8334 ((looking-at "\\s-*\\.")
8335 (goto-char (match-end 0))
8336 (when (not rvalue)
8337 (setq expect-signal nil)))
8338 ;; "modport <keywd>"
8339 ((and (eq in-modport t)
8340 (not (member keywd verilog-keywords)))
8341 (setq in-modport (verilog-modport-new keywd nil nil))
8342 (setq sigs-modports (cons in-modport sigs-modports))
8343 ;; Push old sig values to stack and point to new signal list
8344 (setq varstack (cons (vector sigs-out sigs-inout sigs-in)
8345 varstack))
8346 (setq sigs-in nil sigs-inout nil sigs-out nil))
8347 ;; "modport x (clocking <keywd>)"
8348 ((and in-modport in-clocking)
8349 (verilog-modport-clockings-add in-modport keywd)
8350 (setq in-clocking nil))
8351 ;; endclocking
8352 ((and in-clocking
8353 (equal keywd "endclocking"))
8354 (unless (eq in-clocking t)
8355 (verilog-modport-decls-set
8356 in-clocking
8357 (verilog-decls-new sigs-out sigs-inout sigs-in
8358 nil nil nil nil nil nil))
8359 ;; Pop from varstack to restore state to pre-clocking
8360 (setq tmp (car varstack)
8361 varstack (cdr varstack)
8362 sigs-out (aref tmp 0)
8363 sigs-inout (aref tmp 1)
8364 sigs-in (aref tmp 2)))
8365 (setq in-clocking nil))
8366 ;; "clocking <keywd>"
8367 ((and (eq in-clocking t)
8368 (not (member keywd verilog-keywords)))
8369 (setq in-clocking (verilog-modport-new keywd nil nil))
8370 (setq sigs-modports (cons in-clocking sigs-modports))
8371 ;; Push old sig values to stack and point to new signal list
8372 (setq varstack (cons (vector sigs-out sigs-inout sigs-in)
8373 varstack))
8374 (setq sigs-in nil sigs-inout nil sigs-out nil))
8375 ;; New signal, maybe?
8376 ((and expect-signal
8377 (not rvalue)
8378 (eq functask 0)
8379 (not (member keywd verilog-keywords)))
8380 ;; Add new signal to expect-signal's variable
8381 ;;(if dbg (setq dbg (concat dbg (format "Pt %s New sig %s'\n" (point) keywd))))
8382 (setq newsig (verilog-sig-new keywd vec nil nil enum signed typedefed multidim modport))
8383 (set expect-signal (cons newsig
8384 (symbol-value expect-signal))))))
8385 (t
8386 (forward-char 1)))
8387 (skip-syntax-forward " "))
8388 ;; Return arguments
8389 (setq tmp (verilog-decls-new (nreverse sigs-out)
8390 (nreverse sigs-inout)
8391 (nreverse sigs-in)
8392 (nreverse sigs-var)
8393 (nreverse sigs-modports)
8394 (nreverse sigs-assign)
8395 (nreverse sigs-const)
8396 (nreverse sigs-gparam)
8397 (nreverse sigs-intf)))
8398 ;;(if dbg (verilog-decls-princ tmp))
8399 tmp)))
8400
8401 (defvar verilog-read-sub-decls-in-interfaced nil
8402 "For `verilog-read-sub-decls', process next signal as under interfaced block.")
8403
8404 (defvar verilog-read-sub-decls-gate-ios nil
8405 "For `verilog-read-sub-decls', gate IO pins remaining, nil if non-primitive.")
8406
8407 (eval-when-compile
8408 ;; Prevent compile warnings; these are let's, not globals
8409 ;; Do not remove the eval-when-compile
8410 ;; - we want an error when we are debugging this code if they are refed.
8411 (defvar sigs-in)
8412 (defvar sigs-inout)
8413 (defvar sigs-intf)
8414 (defvar sigs-intfd)
8415 (defvar sigs-out)
8416 (defvar sigs-out-d)
8417 (defvar sigs-out-i)
8418 (defvar sigs-out-unk)
8419 (defvar sigs-temp)
8420 ;; These are known to be from other packages and may not be defined
8421 (defvar diff-command nil)
8422 (defvar vector-skip-list)
8423 ;; There are known to be from newer versions of Emacs
8424 (defvar create-lockfiles))
8425
8426 (defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
8427 "For `verilog-read-sub-decls-line', add a signal."
8428 ;; sig eq t to indicate .name syntax
8429 ;;(message "vrsds: %s(%S)" port sig)
8430 (let ((dotname (eq sig t))
8431 portdata)
8432 (when sig
8433 (setq port (verilog-symbol-detick-denumber port))
8434 (setq sig (if dotname port (verilog-symbol-detick-denumber sig)))
8435 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
8436 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
8437 (unless (or (not sig)
8438 (equal sig "")) ;; Ignore .foo(1'b1) assignments
8439 (cond ((or (setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
8440 (equal "inout" verilog-read-sub-decls-gate-ios))
8441 (setq sigs-inout
8442 (cons (verilog-sig-new
8443 sig
8444 (if dotname (verilog-sig-bits portdata) vec)
8445 (concat "To/From " comment)
8446 (verilog-sig-memory portdata)
8447 nil
8448 (verilog-sig-signed portdata)
8449 (unless (member (verilog-sig-type portdata) '("wire" "reg"))
8450 (verilog-sig-type portdata))
8451 multidim nil)
8452 sigs-inout)))
8453 ((or (setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
8454 (equal "output" verilog-read-sub-decls-gate-ios))
8455 (setq sigs-out
8456 (cons (verilog-sig-new
8457 sig
8458 (if dotname (verilog-sig-bits portdata) vec)
8459 (concat "From " comment)
8460 (verilog-sig-memory portdata)
8461 nil
8462 (verilog-sig-signed portdata)
8463 ;; Though ok in SV, in V2K code, propagating the
8464 ;; "reg" in "output reg" upwards isn't legal.
8465 ;; Also for backwards compatibility we don't propagate
8466 ;; "input wire" upwards.
8467 ;; See also `verilog-signals-edit-wire-reg'.
8468 (unless (member (verilog-sig-type portdata) '("wire" "reg"))
8469 (verilog-sig-type portdata))
8470 multidim nil)
8471 sigs-out)))
8472 ((or (setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
8473 (equal "input" verilog-read-sub-decls-gate-ios))
8474 (setq sigs-in
8475 (cons (verilog-sig-new
8476 sig
8477 (if dotname (verilog-sig-bits portdata) vec)
8478 (concat "To " comment)
8479 (verilog-sig-memory portdata)
8480 nil
8481 (verilog-sig-signed portdata)
8482 (unless (member (verilog-sig-type portdata) '("wire" "reg"))
8483 (verilog-sig-type portdata))
8484 multidim nil)
8485 sigs-in)))
8486 ((setq portdata (assoc port (verilog-decls-get-interfaces submoddecls)))
8487 (setq sigs-intf
8488 (cons (verilog-sig-new
8489 sig
8490 (if dotname (verilog-sig-bits portdata) vec)
8491 (concat "To/From " comment)
8492 (verilog-sig-memory portdata)
8493 nil
8494 (verilog-sig-signed portdata)
8495 (verilog-sig-type portdata)
8496 multidim nil)
8497 sigs-intf)))
8498 ((setq portdata (and verilog-read-sub-decls-in-interfaced
8499 (assoc port (verilog-decls-get-vars submoddecls))))
8500 (setq sigs-intfd
8501 (cons (verilog-sig-new
8502 sig
8503 (if dotname (verilog-sig-bits portdata) vec)
8504 (concat "To/From " comment)
8505 (verilog-sig-memory portdata)
8506 nil
8507 (verilog-sig-signed portdata)
8508 (verilog-sig-type portdata)
8509 multidim nil)
8510 sigs-intf)))
8511 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
8512 )))))
8513
8514 (defun verilog-read-sub-decls-expr (submoddecls comment port expr)
8515 "For `verilog-read-sub-decls-line', parse a subexpression and add signals."
8516 ;;(message "vrsde: '%s'" expr)
8517 ;; Replace special /*[....]*/ comments inserted by verilog-auto-inst-port
8518 (setq expr (verilog-string-replace-matches "/\\*\\(\\[[^*]+\\]\\)\\*/" "\\1" nil nil expr))
8519 ;; Remove front operators
8520 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
8521 ;;
8522 (cond
8523 ;; {..., a, b} requires us to recurse on a,b
8524 ;; To support {#{},{#{a,b}} we'll just split everything on [{},]
8525 ((string-match "^\\s-*{\\(.*\\)}\\s-*$" expr)
8526 (unless verilog-auto-ignore-concat
8527 (let ((mlst (split-string (match-string 1 expr) "[{},]"))
8528 mstr)
8529 (while (setq mstr (pop mlst))
8530 (verilog-read-sub-decls-expr submoddecls comment port mstr)))))
8531 (t
8532 (let (sig vec multidim)
8533 ;; Remove leading reduction operators, etc
8534 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
8535 ;;(message "vrsde-ptop: '%s'" expr)
8536 (cond ;; Find \signal. Final space is part of escaped signal name
8537 ((string-match "^\\s-*\\(\\\\[^ \t\n\f]+\\s-\\)" expr)
8538 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
8539 (setq sig (match-string 1 expr)
8540 expr (substring expr (match-end 0))))
8541 ;; Find signal
8542 ((string-match "^\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" expr)
8543 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
8544 (setq sig (verilog-string-remove-spaces (match-string 1 expr))
8545 expr (substring expr (match-end 0)))))
8546 ;; Find [vector] or [multi][multi][multi][vector]
8547 (while (string-match "^\\s-*\\(\\[[^]]+\\]\\)" expr)
8548 ;;(message "vrsde-v: '%s'" (match-string 1 expr))
8549 (when vec (setq multidim (cons vec multidim)))
8550 (setq vec (match-string 1 expr)
8551 expr (substring expr (match-end 0))))
8552 ;; If found signal, and nothing unrecognized, add the signal
8553 ;;(message "vrsde-rem: '%s'" expr)
8554 (when (and sig (string-match "^\\s-*$" expr))
8555 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))))
8556
8557 (defun verilog-read-sub-decls-line (submoddecls comment)
8558 "For `verilog-read-sub-decls', read lines of port defs until none match.
8559 Inserts the list of signals found, using submodi to look up each port."
8560 (let (done port)
8561 (save-excursion
8562 (forward-line 1)
8563 (while (not done)
8564 ;; Get port name
8565 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
8566 (setq port (match-string 1))
8567 (goto-char (match-end 0)))
8568 ;; .\escaped (
8569 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
8570 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
8571 (goto-char (match-end 0)))
8572 ;; .name
8573 ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*[,)/]")
8574 (verilog-read-sub-decls-sig
8575 submoddecls comment (match-string 1) t ; sig==t for .name
8576 nil nil) ; vec multidim
8577 (setq port nil))
8578 ;; .\escaped_name
8579 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*[,)/]")
8580 (verilog-read-sub-decls-sig
8581 submoddecls comment (concat (match-string 1) " ") t ; sig==t for .name
8582 nil nil) ; vec multidim
8583 (setq port nil))
8584 ;; random
8585 ((looking-at "\\s-*\\.[^(]*(")
8586 (setq port nil) ;; skip this line
8587 (goto-char (match-end 0)))
8588 (t
8589 (setq port nil done t))) ;; Unknown, ignore rest of line
8590 ;; Get signal name. Point is at the first-non-space after (
8591 ;; We intentionally ignore (non-escaped) signals with .s in them
8592 ;; this prevents AUTOWIRE etc from noticing hierarchical sigs.
8593 (when port
8594 (cond ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*)")
8595 (verilog-read-sub-decls-sig
8596 submoddecls comment port
8597 (verilog-string-remove-spaces (match-string 1)) ; sig
8598 nil nil)) ; vec multidim
8599 ;;
8600 ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
8601 (verilog-read-sub-decls-sig
8602 submoddecls comment port
8603 (verilog-string-remove-spaces (match-string 1)) ; sig
8604 (match-string 2) nil)) ; vec multidim
8605 ;; Fastpath was above looking-at's.
8606 ;; For something more complicated invoke a parser
8607 ((looking-at "[^)]+")
8608 (verilog-read-sub-decls-expr
8609 submoddecls comment port
8610 (buffer-substring
8611 (point) (1- (progn (search-backward "(") ; start at (
8612 (verilog-forward-sexp-ign-cmt 1)
8613 (point)))))))) ; expr
8614 ;;
8615 (forward-line 1)))))
8616
8617 (defun verilog-read-sub-decls-gate (submoddecls comment submod end-inst-point)
8618 "For `verilog-read-sub-decls', read lines of UDP gate decl until none match.
8619 Inserts the list of signals found."
8620 (save-excursion
8621 (let ((iolist (cdr (assoc submod verilog-gate-ios))))
8622 (while (< (point) end-inst-point)
8623 ;; Get primitive's signal name, as will never have port, and no trailing )
8624 (cond ((looking-at "//")
8625 (search-forward "\n"))
8626 ((looking-at "/\\*")
8627 (or (search-forward "*/")
8628 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8629 ((looking-at "(\\*")
8630 ;; To advance past either "(*)" or "(* ... *)" don't forward past first *
8631 (forward-char 1)
8632 (or (search-forward "*)")
8633 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
8634 ;; On pins, parse and advance to next pin
8635 ;; Looking at pin, but *not* an // Output comment, or ) to end the inst
8636 ((looking-at "\\s-*[a-zA-Z0-9`_$({}\\\\][^,]*")
8637 (goto-char (match-end 0))
8638 (setq verilog-read-sub-decls-gate-ios (or (car iolist) "input")
8639 iolist (cdr iolist))
8640 (verilog-read-sub-decls-expr
8641 submoddecls comment "primitive_port"
8642 (match-string 0)))
8643 (t
8644 (forward-char 1)
8645 (skip-syntax-forward " ")))))))
8646
8647 (defun verilog-read-sub-decls ()
8648 "Internally parse signals going to modules under this module.
8649 Return an array of [ outputs inouts inputs ] signals for modules that are
8650 instantiated in this module. For example if declare A A (.B(SIG)) and SIG
8651 is an output, then SIG will be included in the list.
8652
8653 This only works on instantiations created with /*AUTOINST*/ converted by
8654 \\[verilog-auto-inst]. Otherwise, it would have to read in the whole
8655 component library to determine connectivity of the design.
8656
8657 One work around for this problem is to manually create // Inputs and //
8658 Outputs comments above subcell signals, for example:
8659
8660 module ModuleName (
8661 // Outputs
8662 .out (out),
8663 // Inputs
8664 .in (in));"
8665 (save-excursion
8666 (let ((end-mod-point (verilog-get-end-of-defun))
8667 st-point end-inst-point
8668 ;; below 3 modified by verilog-read-sub-decls-line
8669 sigs-out sigs-inout sigs-in sigs-intf sigs-intfd)
8670 (verilog-beg-of-defun-quick)
8671 (while (verilog-re-search-forward-quick "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
8672 (save-excursion
8673 (goto-char (match-beginning 0))
8674 (unless (verilog-inside-comment-or-string-p)
8675 ;; Attempt to snarf a comment
8676 (let* ((submod (verilog-read-inst-module))
8677 (inst (verilog-read-inst-name))
8678 (subprim (member submod verilog-gate-keywords))
8679 (comment (concat inst " of " submod ".v"))
8680 submodi submoddecls)
8681 (cond
8682 (subprim
8683 (setq submodi `primitive
8684 submoddecls (verilog-decls-new nil nil nil nil nil nil nil nil nil)
8685 comment (concat inst " of " submod))
8686 (verilog-backward-open-paren)
8687 (setq end-inst-point (save-excursion (verilog-forward-sexp-ign-cmt 1)
8688 (point))
8689 st-point (point))
8690 (forward-char 1)
8691 (verilog-read-sub-decls-gate submoddecls comment submod end-inst-point))
8692 ;; Non-primitive
8693 (t
8694 (when (setq submodi (verilog-modi-lookup submod t))
8695 (setq submoddecls (verilog-modi-get-decls submodi)
8696 verilog-read-sub-decls-gate-ios nil)
8697 (verilog-backward-open-paren)
8698 (setq end-inst-point (save-excursion (verilog-forward-sexp-ign-cmt 1)
8699 (point))
8700 st-point (point))
8701 ;; This could have used a list created by verilog-auto-inst
8702 ;; However I want it to be runnable even on user's manually added signals
8703 (let ((verilog-read-sub-decls-in-interfaced t))
8704 (while (re-search-forward "\\s *(?\\s *// Interfaced" end-inst-point t)
8705 (verilog-read-sub-decls-line submoddecls comment))) ;; Modifies sigs-ifd
8706 (goto-char st-point)
8707 (while (re-search-forward "\\s *(?\\s *// Interfaces" end-inst-point t)
8708 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
8709 (goto-char st-point)
8710 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
8711 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
8712 (goto-char st-point)
8713 (while (re-search-forward "\\s *(?\\s *// Inouts" end-inst-point t)
8714 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
8715 (goto-char st-point)
8716 (while (re-search-forward "\\s *(?\\s *// Inputs" end-inst-point t)
8717 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
8718 )))))))
8719 ;; Combine duplicate bits
8720 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
8721 (verilog-subdecls-new
8722 (verilog-signals-combine-bus (nreverse sigs-out))
8723 (verilog-signals-combine-bus (nreverse sigs-inout))
8724 (verilog-signals-combine-bus (nreverse sigs-in))
8725 (verilog-signals-combine-bus (nreverse sigs-intf))
8726 (verilog-signals-combine-bus (nreverse sigs-intfd))))))
8727
8728 (defun verilog-read-inst-pins ()
8729 "Return an array of [ pins ] for the current instantiation at point.
8730 For example if declare A A (.B(SIG)) then B will be included in the list."
8731 (save-excursion
8732 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
8733 pins pin)
8734 (verilog-backward-open-paren)
8735 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
8736 (setq pin (match-string 1))
8737 (unless (verilog-inside-comment-or-string-p)
8738 (setq pins (cons (list pin) pins))
8739 (when (looking-at "(")
8740 (verilog-forward-sexp-ign-cmt 1))))
8741 (vector pins))))
8742
8743 (defun verilog-read-arg-pins ()
8744 "Return an array of [ pins ] for the current argument declaration at point."
8745 (save-excursion
8746 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
8747 pins pin)
8748 (verilog-backward-open-paren)
8749 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
8750 (setq pin (match-string 1))
8751 (unless (verilog-inside-comment-or-string-p)
8752 (setq pins (cons (list pin) pins))))
8753 (vector pins))))
8754
8755 (defun verilog-read-auto-constants (beg end-mod-point)
8756 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
8757 ;; Insert new
8758 (save-excursion
8759 (let (sig-list tpl-end-pt)
8760 (goto-char beg)
8761 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
8762 (if (not (looking-at "\\s *("))
8763 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
8764 (search-forward "(" end-mod-point)
8765 (setq tpl-end-pt (save-excursion
8766 (backward-char 1)
8767 (verilog-forward-sexp-cmt 1) ;; Moves to paren that closes argdecl's
8768 (backward-char 1)
8769 (point)))
8770 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
8771 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
8772 sig-list)))
8773
8774 (defvar verilog-cache-has-lisp nil "True if any AUTO_LISP in buffer.")
8775 (make-variable-buffer-local 'verilog-cache-has-lisp)
8776
8777 (defun verilog-read-auto-lisp-present ()
8778 "Set `verilog-cache-has-lisp' if any AUTO_LISP in this buffer."
8779 (save-excursion
8780 (goto-char (point-min))
8781 (setq verilog-cache-has-lisp (re-search-forward "\\<AUTO_LISP(" nil t))))
8782
8783 (defun verilog-read-auto-lisp (start end)
8784 "Look for and evaluate an AUTO_LISP between START and END.
8785 Must call `verilog-read-auto-lisp-present' before this function."
8786 ;; This function is expensive for large buffers, so we cache if any AUTO_LISP exists
8787 (when verilog-cache-has-lisp
8788 (save-excursion
8789 (goto-char start)
8790 (while (re-search-forward "\\<AUTO_LISP(" end t)
8791 (backward-char)
8792 (let* ((beg-pt (prog1 (point)
8793 (verilog-forward-sexp-cmt 1))) ;; Closing paren
8794 (end-pt (point))
8795 (verilog-in-hooks t))
8796 (eval-region beg-pt end-pt nil))))))
8797
8798 (defun verilog-read-always-signals-recurse
8799 (exit-keywd rvalue temp-next)
8800 "Recursive routine for parentheses/bracket matching.
8801 EXIT-KEYWD is expression to stop at, nil if top level.
8802 RVALUE is true if at right hand side of equal.
8803 IGNORE-NEXT is true to ignore next token, fake from inside case statement."
8804 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
8805 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-list end-else-check
8806 ignore-next)
8807 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue temp-next))))
8808 (while (not (or (eobp) gotend))
8809 (cond
8810 ((looking-at "//")
8811 (search-forward "\n"))
8812 ((looking-at "/\\*")
8813 (or (search-forward "*/")
8814 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8815 ((looking-at "(\\*")
8816 ;; To advance past either "(*)" or "(* ... *)" don't forward past first *
8817 (forward-char 1)
8818 (or (search-forward "*)")
8819 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
8820 (t (setq keywd (buffer-substring-no-properties
8821 (point)
8822 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
8823 (forward-char 1))
8824 (point)))
8825 sig-last-tolk sig-tolk
8826 sig-tolk nil)
8827 ;;(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))))
8828 (cond
8829 ((equal keywd "\"")
8830 (or (re-search-forward "[^\\]\"" nil t)
8831 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
8832 ;; else at top level loop, keep parsing
8833 ((and end-else-check (equal keywd "else"))
8834 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
8835 ;; no forward movement, want to see else in lower loop
8836 (setq end-else-check nil))
8837 ;; End at top level loop
8838 ((and end-else-check (looking-at "[^ \t\n\f]"))
8839 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
8840 (setq gotend t))
8841 ;; Final statement?
8842 ((and exit-keywd (equal keywd exit-keywd))
8843 (setq gotend t)
8844 (forward-char (length keywd)))
8845 ;; Standard tokens...
8846 ((equal keywd ";")
8847 (setq ignore-next nil rvalue semi-rvalue)
8848 ;; Final statement at top level loop?
8849 (when (not exit-keywd)
8850 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
8851 (setq end-else-check t))
8852 (forward-char 1))
8853 ((equal keywd "'")
8854 (if (looking-at "'[sS]?[hdxboHDXBO]?[ \t]*[0-9a-fA-F_xzXZ?]+")
8855 (goto-char (match-end 0))
8856 (forward-char 1)))
8857 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
8858 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
8859 (setq ignore-next nil rvalue nil))
8860 ((equal "?" exit-keywd) ;; x?y:z rvalue
8861 ) ;; NOP
8862 ((equal "]" exit-keywd) ;; [x:y] rvalue
8863 ) ;; NOP
8864 (got-sig ;; label: statement
8865 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
8866 ((not rvalue) ;; begin label
8867 (setq ignore-next t rvalue nil)))
8868 (forward-char 1))
8869 ((equal keywd "=")
8870 (when got-sig
8871 ;;(if dbg (setq dbg (concat dbg (format "\t\tequal got-sig=%S got-list=%s\n" got-sig got-list))))
8872 (set got-list (cons got-sig (symbol-value got-list)))
8873 (setq got-sig nil))
8874 (when (not rvalue)
8875 (if (eq (char-before) ?< )
8876 (setq sigs-out-d (append sigs-out-d sigs-out-unk)
8877 sigs-out-unk nil)
8878 (setq sigs-out-i (append sigs-out-i sigs-out-unk)
8879 sigs-out-unk nil)))
8880 (setq ignore-next nil rvalue t)
8881 (forward-char 1))
8882 ((equal keywd "?")
8883 (forward-char 1)
8884 (verilog-read-always-signals-recurse ":" rvalue nil))
8885 ((equal keywd "[")
8886 (forward-char 1)
8887 (verilog-read-always-signals-recurse "]" t nil))
8888 ((equal keywd "(")
8889 (forward-char 1)
8890 (cond (sig-last-tolk ;; Function call; zap last signal
8891 (setq got-sig nil)))
8892 (cond ((equal last-keywd "for")
8893 ;; temp-next: Variables on LHS are lvalues, but generally we want
8894 ;; to ignore them, assuming they are loop increments
8895 (verilog-read-always-signals-recurse ";" nil t)
8896 (verilog-read-always-signals-recurse ";" t nil)
8897 (verilog-read-always-signals-recurse ")" nil nil))
8898 (t (verilog-read-always-signals-recurse ")" t nil))))
8899 ((equal keywd "begin")
8900 (skip-syntax-forward "w_")
8901 (verilog-read-always-signals-recurse "end" nil nil)
8902 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
8903 (setq ignore-next nil rvalue semi-rvalue)
8904 (if (not exit-keywd) (setq end-else-check t)))
8905 ((member keywd '("case" "casex" "casez"))
8906 (skip-syntax-forward "w_")
8907 (verilog-read-always-signals-recurse "endcase" t nil)
8908 (setq ignore-next nil rvalue semi-rvalue)
8909 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
8910 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
8911 (cond ((member keywd '("`ifdef" "`ifndef" "`elsif"))
8912 (setq ignore-next t))
8913 ((or ignore-next
8914 (member keywd verilog-keywords)
8915 (string-match "^\\$" keywd)) ;; PLI task
8916 (setq ignore-next nil))
8917 (t
8918 (setq keywd (verilog-symbol-detick-denumber keywd))
8919 (when got-sig
8920 (set got-list (cons got-sig (symbol-value got-list)))
8921 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S got-list=%S\n" got-sig got-list))))
8922 )
8923 (setq got-list (cond (temp-next 'sigs-temp)
8924 (rvalue 'sigs-in)
8925 (t 'sigs-out-unk))
8926 got-sig (if (or (not keywd)
8927 (assoc keywd (symbol-value got-list)))
8928 nil (list keywd nil nil))
8929 temp-next nil
8930 sig-tolk t)))
8931 (skip-chars-forward "a-zA-Z0-9$_.%`"))
8932 (t
8933 (forward-char 1)))
8934 ;; End of non-comment token
8935 (setq last-keywd keywd)))
8936 (skip-syntax-forward " "))
8937 ;; Append the final pending signal
8938 (when got-sig
8939 ;;(if dbg (setq dbg (concat dbg (format "\t\tfinal got-sig=%S got-list=%s\n" got-sig got-list))))
8940 (set got-list (cons got-sig (symbol-value got-list)))
8941 (setq got-sig nil))
8942 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
8943 ))
8944
8945 (defun verilog-read-always-signals ()
8946 "Parse always block at point and return list of (outputs inout inputs)."
8947 (save-excursion
8948 (let* (;;(dbg "")
8949 sigs-out-d sigs-out-i sigs-out-unk sigs-temp sigs-in)
8950 (verilog-read-always-signals-recurse nil nil nil)
8951 (setq sigs-out-i (append sigs-out-i sigs-out-unk)
8952 sigs-out-unk nil)
8953 ;;(if dbg (with-current-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg ""))
8954 ;; Return what was found
8955 (verilog-alw-new sigs-out-d sigs-out-i sigs-temp sigs-in))))
8956
8957 (defun verilog-read-instants ()
8958 "Parse module at point and return list of ( ( file instance ) ... )."
8959 (verilog-beg-of-defun-quick)
8960 (let* ((end-mod-point (verilog-get-end-of-defun))
8961 (state nil)
8962 (instants-list nil))
8963 (save-excursion
8964 (while (< (point) end-mod-point)
8965 ;; Stay at level 0, no comments
8966 (while (progn
8967 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
8968 (or (> (car state) 0) ; in parens
8969 (nth 5 state) ; comment
8970 ))
8971 (forward-line 1))
8972 (beginning-of-line)
8973 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
8974 ;;(if (looking-at "^\\(.+\\)$")
8975 (let ((module (match-string 1))
8976 (instant (match-string 2)))
8977 (if (not (member module verilog-keywords))
8978 (setq instants-list (cons (list module instant) instants-list)))))
8979 (forward-line 1)))
8980 instants-list))
8981
8982
8983 (defun verilog-read-auto-template-middle ()
8984 "With point in middle of an AUTO_TEMPLATE, parse it.
8985 Returns REGEXP and list of ( (signal_name connection_name)... )."
8986 (save-excursion
8987 ;; Find beginning
8988 (let ((tpl-regexp "\\([0-9]+\\)")
8989 (lineno -1) ; -1 to offset for the AUTO_TEMPLATE's newline
8990 (templateno 0)
8991 tpl-sig-list tpl-wild-list tpl-end-pt rep)
8992 ;; Parse "REGEXP"
8993 ;; We reserve @"..." for future lisp expressions that evaluate
8994 ;; once-per-AUTOINST
8995 (when (looking-at "\\s-*\"\\([^\"]*\\)\"")
8996 (setq tpl-regexp (match-string 1))
8997 (goto-char (match-end 0)))
8998 (search-forward "(")
8999 ;; Parse lines in the template
9000 (when (or verilog-auto-inst-template-numbers
9001 verilog-auto-template-warn-unused)
9002 (save-excursion
9003 (let ((pre-pt (point)))
9004 (goto-char (point-min))
9005 (while (search-forward "AUTO_TEMPLATE" pre-pt t)
9006 (setq templateno (1+ templateno)))
9007 (while (< (point) pre-pt)
9008 (forward-line 1)
9009 (setq lineno (1+ lineno))))))
9010 (setq tpl-end-pt (save-excursion
9011 (backward-char 1)
9012 (verilog-forward-sexp-cmt 1) ;; Moves to paren that closes argdecl's
9013 (backward-char 1)
9014 (point)))
9015 ;;
9016 (while (< (point) tpl-end-pt)
9017 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
9018 (setq tpl-sig-list
9019 (cons (list
9020 (match-string-no-properties 1)
9021 (match-string-no-properties 2)
9022 templateno lineno)
9023 tpl-sig-list))
9024 (goto-char (match-end 0)))
9025 ;; Regexp form??
9026 ((looking-at
9027 ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
9028 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
9029 (setq rep (match-string-no-properties 3))
9030 (goto-char (match-end 0))
9031 (setq tpl-wild-list
9032 (cons (list
9033 (concat "^"
9034 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
9035 (match-string 1))
9036 "$")
9037 rep
9038 templateno lineno)
9039 tpl-wild-list)))
9040 ((looking-at "[ \t\f]+")
9041 (goto-char (match-end 0)))
9042 ((looking-at "\n")
9043 (setq lineno (1+ lineno))
9044 (goto-char (match-end 0)))
9045 ((looking-at "//")
9046 (search-forward "\n")
9047 (setq lineno (1+ lineno)))
9048 ((looking-at "/\\*")
9049 (forward-char 2)
9050 (or (search-forward "*/")
9051 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
9052 (t
9053 (error "%s: AUTO_TEMPLATE parsing error: %s"
9054 (verilog-point-text)
9055 (progn (looking-at ".*$") (match-string 0))))))
9056 ;; Return
9057 (vector tpl-regexp
9058 (list tpl-sig-list tpl-wild-list)))))
9059
9060 (defun verilog-read-auto-template (module)
9061 "Look for an auto_template for the instantiation of the given MODULE.
9062 If found returns `verilog-read-auto-template-inside' structure."
9063 (save-excursion
9064 ;; Find beginning
9065 (let ((pt (point)))
9066 ;; Note this search is expensive, as we hunt from mod-begin to point
9067 ;; for every instantiation. Likewise in verilog-read-auto-lisp.
9068 ;; So, we look first for an exact string rather than a slow regexp.
9069 ;; Someday we may keep a cache of every template, but this would also
9070 ;; need to record the relative position of each AUTOINST, as multiple
9071 ;; templates exist for each module, and we're inserting lines.
9072 (cond ((or
9073 ;; See also regexp in `verilog-auto-template-lint'
9074 (verilog-re-search-backward-substr
9075 "AUTO_TEMPLATE"
9076 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
9077 ;; Also try forward of this AUTOINST
9078 ;; This is for historical support; this isn't speced as working
9079 (progn
9080 (goto-char pt)
9081 (verilog-re-search-forward-substr
9082 "AUTO_TEMPLATE"
9083 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
9084 (goto-char (match-end 0))
9085 (verilog-read-auto-template-middle))
9086 ;; If no template found
9087 (t (vector "" nil))))))
9088 ;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
9089
9090 (defvar verilog-auto-template-hits nil "Successful lookups with `verilog-read-auto-template-hit'.")
9091 (make-variable-buffer-local 'verilog-auto-template-hits)
9092
9093 (defun verilog-read-auto-template-hit (tpl-ass)
9094 "Record that TPL-ASS template from `verilog-read-auto-template' was used."
9095 (when (eval-when-compile (fboundp 'make-hash-table)) ;; else feature not allowed
9096 (when verilog-auto-template-warn-unused
9097 (unless verilog-auto-template-hits
9098 (setq verilog-auto-template-hits
9099 (make-hash-table :test 'equal :rehash-size 4.0)))
9100 (puthash (vector (nth 2 tpl-ass) (nth 3 tpl-ass)) t
9101 verilog-auto-template-hits))))
9102
9103 (defun verilog-set-define (defname defvalue &optional buffer enumname)
9104 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
9105 Optionally associate it with the specified enumeration ENUMNAME."
9106 (with-current-buffer (or buffer (current-buffer))
9107 ;; Namespace intentionally short for AUTOs and compatibility
9108 (let ((mac (intern (concat "vh-" defname))))
9109 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
9110 ;; Need to define to a constant if no value given
9111 (set (make-local-variable mac)
9112 (if (equal defvalue "") "1" defvalue)))
9113 (if enumname
9114 ;; Namespace intentionally short for AUTOs and compatibility
9115 (let ((enumvar (intern (concat "venum-" enumname))))
9116 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
9117 (unless (boundp enumvar) (set enumvar nil))
9118 (add-to-list (make-local-variable enumvar) defname)))))
9119
9120 (defun verilog-read-defines (&optional filename recurse subcall)
9121 "Read `defines and parameters for the current file, or optional FILENAME.
9122 If the filename is provided, `verilog-library-flags' will be used to
9123 resolve it. If optional RECURSE is non-nil, recurse through `includes.
9124
9125 Parameters must be simple assignments to constants, or have their own
9126 \"parameter\" label rather than a list of parameters. Thus:
9127
9128 parameter X = 5, Y = 10; // Ok
9129 parameter X = {1'b1, 2'h2}; // Ok
9130 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
9131
9132 Defines must be simple text substitutions, one on a line, starting
9133 at the beginning of the line. Any ifdefs or multiline comments around the
9134 define are ignored.
9135
9136 Defines are stored inside Emacs variables using the name vh-{definename}.
9137
9138 This function is useful for setting vh-* variables. The file variables
9139 feature can be used to set defines that `verilog-mode' can see; put at the
9140 *END* of your file something like:
9141
9142 // Local Variables:
9143 // vh-macro:\"macro_definition\"
9144 // End:
9145
9146 If macros are defined earlier in the same file and you want their values,
9147 you can read them automatically (provided `enable-local-eval' is on):
9148
9149 // Local Variables:
9150 // eval:(verilog-read-defines)
9151 // eval:(verilog-read-defines \"group_standard_includes.v\")
9152 // End:
9153
9154 Note these are only read when the file is first visited, you must use
9155 \\[find-alternate-file] RET to have these take effect after editing them!
9156
9157 If you want to disable the \"Process `eval' or hook local variables\"
9158 warning message, you need to add to your init file:
9159
9160 (setq enable-local-eval t)"
9161 (let ((origbuf (current-buffer)))
9162 (save-excursion
9163 (unless subcall (verilog-getopt-flags))
9164 (when filename
9165 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
9166 (if fns
9167 (set-buffer (find-file-noselect (car fns)))
9168 (error (concat (verilog-point-text)
9169 ": Can't find verilog-read-defines file: " filename)))))
9170 (when recurse
9171 (goto-char (point-min))
9172 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
9173 (let ((inc (verilog-string-replace-matches
9174 "\"" "" nil nil (match-string-no-properties 1))))
9175 (unless (verilog-inside-comment-or-string-p)
9176 (verilog-read-defines inc recurse t)))))
9177 ;; Read `defines
9178 ;; note we don't use verilog-re... it's faster this way, and that
9179 ;; function has problems when comments are at the end of the define
9180 (goto-char (point-min))
9181 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
9182 (let ((defname (match-string-no-properties 1))
9183 (defvalue (match-string-no-properties 2)))
9184 (unless (verilog-inside-comment-or-string-p (match-beginning 0))
9185 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
9186 (verilog-set-define defname defvalue origbuf))))
9187 ;; Hack: Read parameters
9188 (goto-char (point-min))
9189 (while (re-search-forward
9190 "^\\s-*\\(parameter\\|localparam\\)\\(\\s-*\\[[^]]*\\]\\)?\\s-*" nil t)
9191 (let (enumname)
9192 ;; The primary way of getting defines is verilog-read-decls
9193 ;; However, that isn't called yet for included files, so we'll add another scheme
9194 (if (looking-at "[^\n]*\\(auto\\|synopsys\\)\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
9195 (setq enumname (match-string-no-properties 2)))
9196 (forward-comment 99999)
9197 (while (looking-at (concat "\\s-*,?\\s-*\\(?:/[/*].*?$\\)?\\s-*\\([a-zA-Z0-9_$]+\\)"
9198 "\\s-*=\\s-*\\([^;,]*\\),?\\s-*\\(/[/*].*?$\\)?\\s-*"))
9199 (unless (verilog-inside-comment-or-string-p (match-beginning 0))
9200 (verilog-set-define (match-string-no-properties 1)
9201 (match-string-no-properties 2) origbuf enumname))
9202 (goto-char (match-end 0))
9203 (forward-comment 99999)))))))
9204
9205 (defun verilog-read-includes ()
9206 "Read `includes for the current file.
9207 This will find all of the `includes which are at the beginning of lines,
9208 ignoring any ifdefs or multiline comments around them.
9209 `verilog-read-defines' is then performed on the current and each included
9210 file.
9211
9212 It is often useful put at the *END* of your file something like:
9213
9214 // Local Variables:
9215 // eval:(verilog-read-defines)
9216 // eval:(verilog-read-includes)
9217 // End:
9218
9219 Note includes are only read when the file is first visited, you must use
9220 \\[find-alternate-file] RET to have these take effect after editing them!
9221
9222 It is good to get in the habit of including all needed files in each .v
9223 file that needs it, rather than waiting for compile time. This will aid
9224 this process, Verilint, and readability. To prevent defining the same
9225 variable over and over when many modules are compiled together, put a test
9226 around the inside each include file:
9227
9228 foo.v (an include file):
9229 `ifdef _FOO_V // include if not already included
9230 `else
9231 `define _FOO_V
9232 ... contents of file
9233 `endif // _FOO_V"
9234 ;;slow: (verilog-read-defines nil t)
9235 (save-excursion
9236 (verilog-getopt-flags)
9237 (goto-char (point-min))
9238 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
9239 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
9240 (verilog-read-defines inc nil t)))))
9241
9242 (defun verilog-read-signals (&optional start end)
9243 "Return a simple list of all possible signals in the file.
9244 Bounded by optional region from START to END. Overly aggressive but fast.
9245 Some macros and such are also found and included. For dinotrace.el."
9246 (let (sigs-all keywd)
9247 (progn;save-excursion
9248 (goto-char (or start (point-min)))
9249 (setq end (or end (point-max)))
9250 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
9251 (forward-char -1)
9252 (cond
9253 ((looking-at "//")
9254 (search-forward "\n"))
9255 ((looking-at "/\\*")
9256 (search-forward "*/"))
9257 ((looking-at "(\\*")
9258 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
9259 (search-forward "*)")))
9260 ((eq ?\" (following-char))
9261 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
9262 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
9263 (goto-char (match-end 0))
9264 (setq keywd (match-string-no-properties 1))
9265 (or (member keywd verilog-keywords)
9266 (member keywd sigs-all)
9267 (setq sigs-all (cons keywd sigs-all))))
9268 (t (forward-char 1))))
9269 ;; Return list
9270 sigs-all)))
9271
9272 ;;
9273 ;; Argument file parsing
9274 ;;
9275
9276 (defun verilog-getopt (arglist)
9277 "Parse -f, -v etc arguments in ARGLIST list or string."
9278 (unless (listp arglist) (setq arglist (list arglist)))
9279 (let ((space-args '())
9280 arg next-param)
9281 ;; Split on spaces, so users can pass whole command lines
9282 (while arglist
9283 (setq arg (car arglist)
9284 arglist (cdr arglist))
9285 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
9286 (setq space-args (append space-args
9287 (list (match-string-no-properties 1 arg))))
9288 (setq arg (match-string 2 arg))))
9289 ;; Parse arguments
9290 (while space-args
9291 (setq arg (car space-args)
9292 space-args (cdr space-args))
9293 (cond
9294 ;; Need another arg
9295 ((equal arg "-f")
9296 (setq next-param arg))
9297 ((equal arg "-v")
9298 (setq next-param arg))
9299 ((equal arg "-y")
9300 (setq next-param arg))
9301 ;; +libext+(ext1)+(ext2)...
9302 ((string-match "^\\+libext\\+\\(.*\\)" arg)
9303 (setq arg (match-string 1 arg))
9304 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
9305 (verilog-add-list-unique `verilog-library-extensions
9306 (match-string 1 arg))
9307 (setq arg (match-string 2 arg))))
9308 ;;
9309 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
9310 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
9311 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
9312 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
9313 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
9314 ;;
9315 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
9316 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
9317 (verilog-add-list-unique `verilog-library-directories
9318 (match-string 1 (substitute-in-file-name arg))))
9319 ;; Ignore
9320 ((equal "+librescan" arg))
9321 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
9322 ;; Second parameters
9323 ((equal next-param "-f")
9324 (setq next-param nil)
9325 (verilog-getopt-file (substitute-in-file-name arg)))
9326 ((equal next-param "-v")
9327 (setq next-param nil)
9328 (verilog-add-list-unique `verilog-library-files
9329 (substitute-in-file-name arg)))
9330 ((equal next-param "-y")
9331 (setq next-param nil)
9332 (verilog-add-list-unique `verilog-library-directories
9333 (substitute-in-file-name arg)))
9334 ;; Filename
9335 ((string-match "^[^-+]" arg)
9336 (verilog-add-list-unique `verilog-library-files
9337 (substitute-in-file-name arg)))
9338 ;; Default - ignore; no warning
9339 ))))
9340 ;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
9341
9342 (defun verilog-getopt-file (filename)
9343 "Read Verilog options from the specified FILENAME."
9344 (save-excursion
9345 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
9346 (orig-buffer (current-buffer))
9347 line)
9348 (if fns
9349 (set-buffer (find-file-noselect (car fns)))
9350 (error (concat (verilog-point-text)
9351 ": Can't find verilog-getopt-file -f file: " filename)))
9352 (goto-char (point-min))
9353 (while (not (eobp))
9354 (setq line (buffer-substring (point) (point-at-eol)))
9355 (forward-line 1)
9356 (when (string-match "//" line)
9357 (setq line (substring line 0 (match-beginning 0))))
9358 (with-current-buffer orig-buffer ; Variables are buffer-local, so need right context.
9359 (verilog-getopt line))))))
9360
9361 (defun verilog-getopt-flags ()
9362 "Convert `verilog-library-flags' into standard library variables."
9363 ;; If the flags are local, then all the outputs should be local also
9364 (when (local-variable-p `verilog-library-flags (current-buffer))
9365 (mapc 'make-local-variable '(verilog-library-extensions
9366 verilog-library-directories
9367 verilog-library-files
9368 verilog-library-flags)))
9369 ;; Allow user to customize
9370 (verilog-run-hooks 'verilog-before-getopt-flags-hook)
9371 ;; Process arguments
9372 (verilog-getopt verilog-library-flags)
9373 ;; Allow user to customize
9374 (verilog-run-hooks 'verilog-getopt-flags-hook))
9375
9376 (defun verilog-add-list-unique (varref object)
9377 "Append to VARREF list the given OBJECT,
9378 unless it is already a member of the variable's list."
9379 (unless (member object (symbol-value varref))
9380 (set varref (append (symbol-value varref) (list object))))
9381 varref)
9382 ;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
9383
9384 (defun verilog-current-flags ()
9385 "Convert `verilog-library-flags' and similar variables to command line.
9386 Used for __FLAGS__ in `verilog-expand-command'."
9387 (let ((cmd (mapconcat `concat verilog-library-flags " ")))
9388 (when (equal cmd "")
9389 (setq cmd (concat
9390 "+libext+" (mapconcat `concat verilog-library-extensions "+")
9391 (mapconcat (lambda (i) (concat " -y " i " +incdir+" i))
9392 verilog-library-directories "")
9393 (mapconcat (lambda (i) (concat " -v " i))
9394 verilog-library-files ""))))
9395 cmd))
9396 ;;(verilog-current-flags)
9397
9398 \f
9399 ;;
9400 ;; Cached directory support
9401 ;;
9402
9403 (defvar verilog-dir-cache-preserving nil
9404 "If true, the directory cache is enabled, and file system changes are ignored.
9405 See `verilog-dir-exists-p' and `verilog-dir-files'.")
9406
9407 ;; If adding new cached variable, add also to verilog-preserve-dir-cache
9408 (defvar verilog-dir-cache-list nil
9409 "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
9410 (defvar verilog-dir-cache-lib-filenames nil
9411 "Cached data for `verilog-library-filenames'.")
9412
9413 (defmacro verilog-preserve-dir-cache (&rest body)
9414 "Execute the BODY forms, allowing directory cache preservation within BODY.
9415 This means that changes inside BODY made to the file system will not be
9416 seen by the `verilog-dir-files' and related functions."
9417 `(let ((verilog-dir-cache-preserving (current-buffer))
9418 verilog-dir-cache-list
9419 verilog-dir-cache-lib-filenames)
9420 (progn ,@body)))
9421
9422 (defun verilog-dir-files (dirname)
9423 "Return all filenames in the DIRNAME directory.
9424 Relative paths depend on the `default-directory'.
9425 Results are cached if inside `verilog-preserve-dir-cache'."
9426 (unless verilog-dir-cache-preserving
9427 (setq verilog-dir-cache-list nil)) ;; Cache disabled
9428 ;; We don't use expand-file-name on the dirname to make key, as it's slow
9429 (let* ((cache-key (list dirname default-directory))
9430 (fass (assoc cache-key verilog-dir-cache-list))
9431 exp-dirname data)
9432 (cond (fass ;; Return data from cache hit
9433 (nth 1 fass))
9434 (t
9435 (setq exp-dirname (expand-file-name dirname)
9436 data (and (file-directory-p exp-dirname)
9437 (directory-files exp-dirname nil nil nil)))
9438 ;; Note we also encache nil for non-existing dirs.
9439 (setq verilog-dir-cache-list (cons (list cache-key data)
9440 verilog-dir-cache-list))
9441 data))))
9442 ;; Miss-and-hit test:
9443 ;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
9444 ;; (prin1 (verilog-dir-files ".")) nil)
9445
9446 (defun verilog-dir-file-exists-p (filename)
9447 "Return true if FILENAME exists.
9448 Like `file-exists-p' but results are cached if inside
9449 `verilog-preserve-dir-cache'."
9450 (let* ((dirname (file-name-directory filename))
9451 ;; Correct for file-name-nondirectory returning same if no slash.
9452 (dirnamed (if (or (not dirname) (equal dirname filename))
9453 default-directory dirname))
9454 (flist (verilog-dir-files dirnamed)))
9455 (and flist
9456 (member (file-name-nondirectory filename) flist)
9457 t)))
9458 ;;(verilog-dir-file-exists-p "verilog-mode.el")
9459 ;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
9460
9461 \f
9462 ;;
9463 ;; Module name lookup
9464 ;;
9465
9466 (defun verilog-module-inside-filename-p (module filename)
9467 "Return modi if MODULE is specified inside FILENAME, else nil.
9468 Allows version control to check out the file if need be."
9469 (and (or (file-exists-p filename)
9470 (and (fboundp 'vc-backend)
9471 (vc-backend filename)))
9472 (let (modi type)
9473 (with-current-buffer (find-file-noselect filename)
9474 (save-excursion
9475 (goto-char (point-min))
9476 (while (and
9477 ;; It may be tempting to look for verilog-defun-re,
9478 ;; don't, it slows things down a lot!
9479 (verilog-re-search-forward-quick "\\<\\(module\\|interface\\|program\\)\\>" nil t)
9480 (setq type (match-string-no-properties 0))
9481 (verilog-re-search-forward-quick "[(;]" nil t))
9482 (if (equal module (verilog-read-module-name))
9483 (setq modi (verilog-modi-new module filename (point) type))))
9484 modi)))))
9485
9486 (defun verilog-is-number (symbol)
9487 "Return true if SYMBOL is number-like."
9488 (or (string-match "^[0-9 \t:]+$" symbol)
9489 (string-match "^[---]*[0-9]+$" symbol)
9490 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
9491
9492 (defun verilog-symbol-detick (symbol wing-it)
9493 "Return an expanded SYMBOL name without any defines.
9494 If the variable vh-{symbol} is defined, return that value.
9495 If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
9496 (while (and symbol (string-match "^`" symbol))
9497 (setq symbol (substring symbol 1))
9498 (setq symbol
9499 ;; Namespace intentionally short for AUTOs and compatibility
9500 (if (boundp (intern (concat "vh-" symbol)))
9501 ;; Emacs has a bug where boundp on a buffer-local
9502 ;; variable in only one buffer returns t in another.
9503 ;; This can confuse, so check for nil.
9504 ;; Namespace intentionally short for AUTOs and compatibility
9505 (let ((val (eval (intern (concat "vh-" symbol)))))
9506 (if (eq val nil)
9507 (if wing-it symbol nil)
9508 val))
9509 (if wing-it symbol nil))))
9510 symbol)
9511 ;;(verilog-symbol-detick "`mod" nil)
9512
9513 (defun verilog-symbol-detick-denumber (symbol)
9514 "Return SYMBOL with defines converted and any numbers dropped to nil."
9515 (when (string-match "^`" symbol)
9516 ;; This only will work if the define is a simple signal, not
9517 ;; something like a[b]. Sorry, it should be substituted into the parser
9518 (setq symbol
9519 (verilog-string-replace-matches
9520 "\[[^0-9: \t]+\]" "" nil nil
9521 (or (verilog-symbol-detick symbol nil)
9522 (if verilog-auto-sense-defines-constant
9523 "0"
9524 symbol)))))
9525 (if (verilog-is-number symbol)
9526 nil
9527 symbol))
9528
9529 (defun verilog-symbol-detick-text (text)
9530 "Return TEXT without any known defines.
9531 If the variable vh-{symbol} is defined, substitute that value."
9532 (let ((ok t) symbol val)
9533 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
9534 (setq symbol (match-string 1 text))
9535 ;;(message symbol)
9536 (cond ((and
9537 ;; Namespace intentionally short for AUTOs and compatibility
9538 (boundp (intern (concat "vh-" symbol)))
9539 ;; Emacs has a bug where boundp on a buffer-local
9540 ;; variable in only one buffer returns t in another.
9541 ;; This can confuse, so check for nil.
9542 ;; Namespace intentionally short for AUTOs and compatibility
9543 (setq val (eval (intern (concat "vh-" symbol)))))
9544 (setq text (replace-match val nil nil text)))
9545 (t (setq ok nil)))))
9546 text)
9547 ;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
9548
9549 (defun verilog-expand-dirnames (&optional dirnames)
9550 "Return a list of existing directories given a list of wildcarded DIRNAMES.
9551 Or, just the existing dirnames themselves if there are no wildcards."
9552 ;; Note this function is performance critical.
9553 ;; Do not call anything that requires disk access that cannot be cached.
9554 (interactive)
9555 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
9556 (setq dirnames (reverse dirnames)) ; not nreverse
9557 (let ((dirlist nil)
9558 pattern dirfile dirfiles dirname root filename rest basefile)
9559 (while dirnames
9560 (setq dirname (substitute-in-file-name (car dirnames))
9561 dirnames (cdr dirnames))
9562 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
9563 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
9564 "\\(.*\\)") ;; rest
9565 dirname)
9566 (setq root (match-string 1 dirname)
9567 filename (match-string 2 dirname)
9568 rest (match-string 3 dirname)
9569 pattern filename)
9570 ;; now replace those * and ? with .+ and .
9571 ;; use ^ and /> to get only whole file names
9572 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
9573 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
9574 pattern (concat "^" pattern "$")
9575 dirfiles (verilog-dir-files root))
9576 (while dirfiles
9577 (setq basefile (car dirfiles)
9578 dirfile (expand-file-name (concat root basefile rest))
9579 dirfiles (cdr dirfiles))
9580 (if (and (string-match pattern basefile)
9581 ;; Don't allow abc/*/rtl to match abc/rtl via ..
9582 (not (equal basefile "."))
9583 (not (equal basefile ".."))
9584 (file-directory-p dirfile))
9585 (setq dirlist (cons dirfile dirlist)))))
9586 ;; Defaults
9587 (t
9588 (if (file-directory-p dirname)
9589 (setq dirlist (cons dirname dirlist))))))
9590 dirlist))
9591 ;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
9592
9593 (defun verilog-library-filenames (filename &optional current check-ext)
9594 "Return a search path to find the given FILENAME or module name.
9595 Uses the optional CURRENT filename or variable `buffer-file-name', plus
9596 `verilog-library-directories' and `verilog-library-extensions'
9597 variables to build the path. With optional CHECK-EXT also check
9598 `verilog-library-extensions'."
9599 (unless current (setq current (buffer-file-name)))
9600 (unless verilog-dir-cache-preserving
9601 (setq verilog-dir-cache-lib-filenames nil))
9602 (let* ((cache-key (list filename current check-ext))
9603 (fass (assoc cache-key verilog-dir-cache-lib-filenames))
9604 chkdirs chkdir chkexts fn outlist)
9605 (cond (fass ;; Return data from cache hit
9606 (nth 1 fass))
9607 (t
9608 ;; Note this expand can't be easily cached, as we need to
9609 ;; pick up buffer-local variables for newly read sub-module files
9610 (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
9611 (while chkdirs
9612 (setq chkdir (expand-file-name (car chkdirs)
9613 (file-name-directory current))
9614 chkexts (if check-ext verilog-library-extensions `("")))
9615 (while chkexts
9616 (setq fn (expand-file-name (concat filename (car chkexts))
9617 chkdir))
9618 ;;(message "Check for %s" fn)
9619 (if (verilog-dir-file-exists-p fn)
9620 (setq outlist (cons (expand-file-name
9621 fn (file-name-directory current))
9622 outlist)))
9623 (setq chkexts (cdr chkexts)))
9624 (setq chkdirs (cdr chkdirs)))
9625 (setq outlist (nreverse outlist))
9626 (setq verilog-dir-cache-lib-filenames
9627 (cons (list cache-key outlist)
9628 verilog-dir-cache-lib-filenames))
9629 outlist))))
9630
9631 (defun verilog-module-filenames (module current)
9632 "Return a search path to find the given MODULE name.
9633 Uses the CURRENT filename, `verilog-library-extensions',
9634 `verilog-library-directories' and `verilog-library-files'
9635 variables to build the path."
9636 ;; Return search locations for it
9637 (append (list current) ; first, current buffer
9638 (verilog-library-filenames module current t)
9639 verilog-library-files)) ; finally, any libraries
9640
9641 ;;
9642 ;; Module Information
9643 ;;
9644 ;; Many of these functions work on "modi" a module information structure
9645 ;; A modi is: [module-name-string file-name begin-point]
9646
9647 (defvar verilog-cache-enabled t
9648 "Non-nil enables caching of signals, etc. Set to nil for debugging to make things SLOW!")
9649
9650 (defvar verilog-modi-cache-list nil
9651 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
9652 For speeding up verilog-modi-get-* commands.
9653 Buffer-local.")
9654 (make-variable-buffer-local 'verilog-modi-cache-list)
9655
9656 (defvar verilog-modi-cache-preserve-tick nil
9657 "Modification tick after which the cache is still considered valid.
9658 Use `verilog-preserve-modi-cache' to set it.")
9659 (defvar verilog-modi-cache-preserve-buffer nil
9660 "Modification tick after which the cache is still considered valid.
9661 Use `verilog-preserve-modi-cache' to set it.")
9662 (defvar verilog-modi-cache-current-enable nil
9663 "Non-nil means allow caching `verilog-modi-current', set by let().")
9664 (defvar verilog-modi-cache-current nil
9665 "Currently active `verilog-modi-current', if any, set by let().")
9666 (defvar verilog-modi-cache-current-max nil
9667 "Current endmodule point for `verilog-modi-cache-current', if any.")
9668
9669 (defun verilog-modi-current ()
9670 "Return the modi structure for the module currently at point, possibly cached."
9671 (cond ((and verilog-modi-cache-current
9672 (>= (point) (verilog-modi-get-point verilog-modi-cache-current))
9673 (<= (point) verilog-modi-cache-current-max))
9674 ;; Slow assertion, for debugging the cache:
9675 ;;(or (equal verilog-modi-cache-current (verilog-modi-current-get)) (debug))
9676 verilog-modi-cache-current)
9677 (verilog-modi-cache-current-enable
9678 (setq verilog-modi-cache-current (verilog-modi-current-get)
9679 verilog-modi-cache-current-max
9680 ;; The cache expires when we pass "endmodule" as then the
9681 ;; current modi may change to the next module
9682 ;; This relies on the AUTOs generally inserting, not deleting text
9683 (save-excursion
9684 (verilog-re-search-forward-quick verilog-end-defun-re nil nil)))
9685 verilog-modi-cache-current)
9686 (t
9687 (verilog-modi-current-get))))
9688
9689 (defun verilog-modi-current-get ()
9690 "Return the modi structure for the module currently at point."
9691 (let* (name type pt)
9692 ;; read current module's name
9693 (save-excursion
9694 (verilog-re-search-backward-quick verilog-defun-re nil nil)
9695 (setq type (match-string-no-properties 0))
9696 (verilog-re-search-forward-quick "(" nil nil)
9697 (setq name (verilog-read-module-name))
9698 (setq pt (point)))
9699 ;; return modi - note this vector built two places
9700 (verilog-modi-new name (or (buffer-file-name) (current-buffer)) pt type)))
9701
9702 (defvar verilog-modi-lookup-cache nil "Hash of (modulename modi).")
9703 (make-variable-buffer-local 'verilog-modi-lookup-cache)
9704 (defvar verilog-modi-lookup-last-current nil "Cache of `current-buffer' at last lookup.")
9705 (defvar verilog-modi-lookup-last-tick nil "Cache of `buffer-chars-modified-tick' at last lookup.")
9706
9707 (defun verilog-modi-lookup (module allow-cache &optional ignore-error)
9708 "Find the file and point at which MODULE is defined.
9709 If ALLOW-CACHE is set, check and remember cache of previous lookups.
9710 Return modi if successful, else print message unless IGNORE-ERROR is true."
9711 (let* ((current (or (buffer-file-name) (current-buffer)))
9712 modi)
9713 ;; Check cache
9714 ;;(message "verilog-modi-lookup: %s" module)
9715 (cond ((and verilog-modi-lookup-cache
9716 verilog-cache-enabled
9717 allow-cache
9718 (setq modi (gethash module verilog-modi-lookup-cache))
9719 (equal verilog-modi-lookup-last-current current)
9720 ;; If hit is in current buffer, then tick must match
9721 (or (equal verilog-modi-lookup-last-tick (buffer-chars-modified-tick))
9722 (not (equal current (verilog-modi-file-or-buffer modi)))))
9723 ;;(message "verilog-modi-lookup: HIT %S" modi)
9724 modi)
9725 ;; Miss
9726 (t (let* ((realname (verilog-symbol-detick module t))
9727 (orig-filenames (verilog-module-filenames realname current))
9728 (filenames orig-filenames)
9729 mif)
9730 (while (and filenames (not mif))
9731 (if (not (setq mif (verilog-module-inside-filename-p realname (car filenames))))
9732 (setq filenames (cdr filenames))))
9733 ;; mif has correct form to become later elements of modi
9734 (cond (mif (setq modi mif))
9735 (t (setq modi nil)
9736 (or ignore-error
9737 (error (concat (verilog-point-text)
9738 ": Can't locate " module " module definition"
9739 (if (not (equal module realname))
9740 (concat " (Expanded macro to " realname ")")
9741 "")
9742 "\n Check the verilog-library-directories variable."
9743 "\n I looked in (if not listed, doesn't exist):\n\t"
9744 (mapconcat 'concat orig-filenames "\n\t"))))))
9745 (when (eval-when-compile (fboundp 'make-hash-table))
9746 (unless verilog-modi-lookup-cache
9747 (setq verilog-modi-lookup-cache
9748 (make-hash-table :test 'equal :rehash-size 4.0)))
9749 (puthash module modi verilog-modi-lookup-cache))
9750 (setq verilog-modi-lookup-last-current current
9751 verilog-modi-lookup-last-tick (buffer-chars-modified-tick)))))
9752 modi))
9753
9754 (defun verilog-modi-filename (modi)
9755 "Filename of MODI, or name of buffer if it's never been saved."
9756 (if (bufferp (verilog-modi-file-or-buffer modi))
9757 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
9758 (buffer-name (verilog-modi-file-or-buffer modi)))
9759 (verilog-modi-file-or-buffer modi)))
9760
9761 (defun verilog-modi-goto (modi)
9762 "Move point/buffer to specified MODI."
9763 (or modi (error "Passed unfound modi to goto, check earlier"))
9764 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
9765 (verilog-modi-file-or-buffer modi)
9766 (find-file-noselect (verilog-modi-file-or-buffer modi))))
9767 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
9768 (verilog-mode))
9769 (goto-char (verilog-modi-get-point modi)))
9770
9771 (defun verilog-goto-defun-file (module)
9772 "Move point to the file at which a given MODULE is defined."
9773 (interactive "sGoto File for Module: ")
9774 (let* ((modi (verilog-modi-lookup module nil)))
9775 (when modi
9776 (verilog-modi-goto modi)
9777 (switch-to-buffer (current-buffer)))))
9778
9779 (defun verilog-modi-cache-results (modi function)
9780 "Run on MODI the given FUNCTION. Locate the module in a file.
9781 Cache the output of function so next call may have faster access."
9782 (let (fass)
9783 (save-excursion ;; Cache is buffer-local so can't avoid this.
9784 (verilog-modi-goto modi)
9785 (if (and (setq fass (assoc (list modi function)
9786 verilog-modi-cache-list))
9787 ;; Destroy caching when incorrect; Modified or file changed
9788 (not (and verilog-cache-enabled
9789 (or (equal (buffer-chars-modified-tick) (nth 1 fass))
9790 (and verilog-modi-cache-preserve-tick
9791 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
9792 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
9793 (equal (visited-file-modtime) (nth 2 fass)))))
9794 (setq verilog-modi-cache-list nil
9795 fass nil))
9796 (cond (fass
9797 ;; Return data from cache hit
9798 (nth 3 fass))
9799 (t
9800 ;; Read from file
9801 ;; Clear then restore any highlighting to make emacs19 happy
9802 (let (func-returns)
9803 (verilog-save-font-mods
9804 (setq func-returns (funcall function)))
9805 ;; Cache for next time
9806 (setq verilog-modi-cache-list
9807 (cons (list (list modi function)
9808 (buffer-chars-modified-tick)
9809 (visited-file-modtime)
9810 func-returns)
9811 verilog-modi-cache-list))
9812 func-returns))))))
9813
9814 (defun verilog-modi-cache-add (modi function element sig-list)
9815 "Add function return results to the module cache.
9816 Update MODI's cache for given FUNCTION so that the return ELEMENT of that
9817 function now contains the additional SIG-LIST parameters."
9818 (let (fass)
9819 (save-excursion
9820 (verilog-modi-goto modi)
9821 (if (setq fass (assoc (list modi function)
9822 verilog-modi-cache-list))
9823 (let ((func-returns (nth 3 fass)))
9824 (aset func-returns element
9825 (append sig-list (aref func-returns element))))))))
9826
9827 (defmacro verilog-preserve-modi-cache (&rest body)
9828 "Execute the BODY forms, allowing cache preservation within BODY.
9829 This means that changes to the buffer will not result in the cache being
9830 flushed. If the changes affect the modsig state, they must call the
9831 modsig-cache-add-* function, else the results of later calls may be
9832 incorrect. Without this, changes are assumed to be adding/removing signals
9833 and invalidating the cache."
9834 `(let ((verilog-modi-cache-preserve-tick (buffer-chars-modified-tick))
9835 (verilog-modi-cache-preserve-buffer (current-buffer)))
9836 (progn ,@body)))
9837
9838
9839 (defun verilog-modi-modport-lookup-one (modi name &optional ignore-error)
9840 "Given a MODI, return the declarations related to the given modport NAME."
9841 ;; Recursive routine - see below
9842 (let* ((realname (verilog-symbol-detick name t))
9843 (modport (assoc name (verilog-decls-get-modports (verilog-modi-get-decls modi)))))
9844 (or modport ignore-error
9845 (error (concat (verilog-point-text)
9846 ": Can't locate " name " modport definition"
9847 (if (not (equal name realname))
9848 (concat " (Expanded macro to " realname ")")
9849 ""))))
9850 (let* ((decls (verilog-modport-decls modport))
9851 (clks (verilog-modport-clockings modport)))
9852 ;; Now expand any clocking's
9853 (while clks
9854 (setq decls (verilog-decls-append
9855 decls
9856 (verilog-modi-modport-lookup-one modi (car clks) ignore-error)))
9857 (setq clks (cdr clks)))
9858 decls)))
9859
9860 (defun verilog-modi-modport-lookup (modi name-re &optional ignore-error)
9861 "Given a MODI, return the declarations related to the given modport NAME-RE.
9862 If the modport points to any clocking blocks, expand the signals to include
9863 those clocking block's signals."
9864 ;; Recursive routine - see below
9865 (let* ((mod-decls (verilog-modi-get-decls modi))
9866 (clks (verilog-decls-get-modports mod-decls))
9867 (name-re (concat "^" name-re "$"))
9868 (decls (verilog-decls-new nil nil nil nil nil nil nil nil nil)))
9869 ;; Pull in all modports
9870 (while clks
9871 (when (string-match name-re (verilog-modport-name (car clks)))
9872 (setq decls (verilog-decls-append
9873 decls
9874 (verilog-modi-modport-lookup-one modi (verilog-modport-name (car clks)) ignore-error))))
9875 (setq clks (cdr clks)))
9876 decls))
9877
9878 (defun verilog-signals-matching-enum (in-list enum)
9879 "Return all signals in IN-LIST matching the given ENUM."
9880 (let (out-list)
9881 (while in-list
9882 (if (equal (verilog-sig-enum (car in-list)) enum)
9883 (setq out-list (cons (car in-list) out-list)))
9884 (setq in-list (cdr in-list)))
9885 ;; New scheme
9886 ;; Namespace intentionally short for AUTOs and compatibility
9887 (let* ((enumvar (intern (concat "venum-" enum)))
9888 (enumlist (and (boundp enumvar) (eval enumvar))))
9889 (while enumlist
9890 (add-to-list 'out-list (list (car enumlist)))
9891 (setq enumlist (cdr enumlist))))
9892 (nreverse out-list)))
9893
9894 (defun verilog-signals-matching-regexp (in-list regexp)
9895 "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
9896 (if (or (not regexp) (equal regexp ""))
9897 in-list
9898 (let ((case-fold-search verilog-case-fold)
9899 out-list)
9900 (while in-list
9901 (if (string-match regexp (verilog-sig-name (car in-list)))
9902 (setq out-list (cons (car in-list) out-list)))
9903 (setq in-list (cdr in-list)))
9904 (nreverse out-list))))
9905
9906 (defun verilog-signals-not-matching-regexp (in-list regexp)
9907 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
9908 (if (or (not regexp) (equal regexp ""))
9909 in-list
9910 (let ((case-fold-search verilog-case-fold)
9911 out-list)
9912 (while in-list
9913 (if (not (string-match regexp (verilog-sig-name (car in-list))))
9914 (setq out-list (cons (car in-list) out-list)))
9915 (setq in-list (cdr in-list)))
9916 (nreverse out-list))))
9917
9918 (defun verilog-signals-matching-dir-re (in-list decl-type regexp)
9919 "Return all signals in IN-LIST matching the given DECL-TYPE and REGEXP,
9920 if non-nil."
9921 (if (or (not regexp) (equal regexp ""))
9922 in-list
9923 (let (out-list to-match)
9924 (while in-list
9925 ;; Note verilog-insert-one-definition matches on this order
9926 (setq to-match (concat
9927 decl-type
9928 " " (verilog-sig-signed (car in-list))
9929 " " (verilog-sig-multidim (car in-list))
9930 (verilog-sig-bits (car in-list))))
9931 (if (string-match regexp to-match)
9932 (setq out-list (cons (car in-list) out-list)))
9933 (setq in-list (cdr in-list)))
9934 (nreverse out-list))))
9935
9936 (defun verilog-signals-edit-wire-reg (in-list)
9937 "Return all signals in IN-LIST with wire/reg data types made blank."
9938 (mapcar (lambda (sig)
9939 (when (member (verilog-sig-type sig) '("wire" "reg"))
9940 (verilog-sig-type-set sig nil))
9941 sig) in-list))
9942
9943 ;; Combined
9944 (defun verilog-decls-get-signals (decls)
9945 "Return all declared signals in DECLS, excluding 'assign' statements."
9946 (append
9947 (verilog-decls-get-outputs decls)
9948 (verilog-decls-get-inouts decls)
9949 (verilog-decls-get-inputs decls)
9950 (verilog-decls-get-vars decls)
9951 (verilog-decls-get-consts decls)
9952 (verilog-decls-get-gparams decls)))
9953
9954 (defun verilog-decls-get-ports (decls)
9955 (append
9956 (verilog-decls-get-outputs decls)
9957 (verilog-decls-get-inouts decls)
9958 (verilog-decls-get-inputs decls)))
9959
9960 (defun verilog-decls-get-iovars (decls)
9961 (append
9962 (verilog-decls-get-vars decls)
9963 (verilog-decls-get-outputs decls)
9964 (verilog-decls-get-inouts decls)
9965 (verilog-decls-get-inputs decls)))
9966
9967 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
9968 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
9969 (defsubst verilog-modi-cache-add-inouts (modi sig-list)
9970 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
9971 (defsubst verilog-modi-cache-add-inputs (modi sig-list)
9972 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
9973 (defsubst verilog-modi-cache-add-vars (modi sig-list)
9974 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
9975 (defsubst verilog-modi-cache-add-gparams (modi sig-list)
9976 (verilog-modi-cache-add modi 'verilog-read-decls 7 sig-list))
9977
9978 \f
9979 ;;
9980 ;; Auto creation utilities
9981 ;;
9982
9983 (defun verilog-auto-re-search-do (search-for func)
9984 "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
9985 (goto-char (point-min))
9986 (while (verilog-re-search-forward-quick search-for nil t)
9987 (funcall func)))
9988
9989 (defun verilog-insert-one-definition (sig type indent-pt)
9990 "Print out a definition for SIG of the given TYPE,
9991 with appropriate INDENT-PT indentation."
9992 (indent-to indent-pt)
9993 ;; Note verilog-signals-matching-dir-re matches on this order
9994 (insert type)
9995 (when (verilog-sig-modport sig)
9996 (insert "." (verilog-sig-modport sig)))
9997 (when (verilog-sig-signed sig)
9998 (insert " " (verilog-sig-signed sig)))
9999 (when (verilog-sig-multidim sig)
10000 (insert " " (verilog-sig-multidim-string sig)))
10001 (when (verilog-sig-bits sig)
10002 (insert " " (verilog-sig-bits sig)))
10003 (indent-to (max 24 (+ indent-pt 16)))
10004 (unless (= (char-syntax (preceding-char)) ?\ )
10005 (insert " ")) ; Need space between "]name" if indent-to did nothing
10006 (insert (verilog-sig-name sig))
10007 (when (verilog-sig-memory sig)
10008 (insert " " (verilog-sig-memory sig))))
10009
10010 (defun verilog-insert-definition (modi sigs direction indent-pt v2k &optional dont-sort)
10011 "Print out a definition for MODI's list of SIGS of the given DIRECTION,
10012 with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
10013 format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output.
10014 When MODI is non-null, also add to modi-cache, for tracking."
10015 (when modi
10016 (cond ((equal direction "wire")
10017 (verilog-modi-cache-add-vars modi sigs))
10018 ((equal direction "reg")
10019 (verilog-modi-cache-add-vars modi sigs))
10020 ((equal direction "output")
10021 (verilog-modi-cache-add-outputs modi sigs)
10022 (when verilog-auto-declare-nettype
10023 (verilog-modi-cache-add-vars modi sigs)))
10024 ((equal direction "input")
10025 (verilog-modi-cache-add-inputs modi sigs)
10026 (when verilog-auto-declare-nettype
10027 (verilog-modi-cache-add-vars modi sigs)))
10028 ((equal direction "inout")
10029 (verilog-modi-cache-add-inouts modi sigs)
10030 (when verilog-auto-declare-nettype
10031 (verilog-modi-cache-add-vars modi sigs)))
10032 ((equal direction "interface"))
10033 ((equal direction "parameter")
10034 (verilog-modi-cache-add-gparams modi sigs))
10035 (t
10036 (error "Unsupported verilog-insert-definition direction: %s" direction))))
10037 (or dont-sort
10038 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
10039 (while sigs
10040 (let ((sig (car sigs)))
10041 (verilog-insert-one-definition
10042 sig
10043 ;; Want "type x" or "output type x", not "wire type x"
10044 (cond ((or (verilog-sig-type sig)
10045 verilog-auto-wire-type)
10046 (concat
10047 (when (member direction '("input" "output" "inout"))
10048 (concat direction " "))
10049 (or (verilog-sig-type sig)
10050 verilog-auto-wire-type)))
10051 ((and verilog-auto-declare-nettype
10052 (member direction '("input" "output" "inout")))
10053 (concat direction " " verilog-auto-declare-nettype))
10054 (t
10055 direction))
10056 indent-pt)
10057 (insert (if v2k "," ";"))
10058 (if (or (not (verilog-sig-comment sig))
10059 (equal "" (verilog-sig-comment sig)))
10060 (insert "\n")
10061 (indent-to (max 48 (+ indent-pt 40)))
10062 (verilog-insert "// " (verilog-sig-comment sig) "\n"))
10063 (setq sigs (cdr sigs)))))
10064
10065 (eval-when-compile
10066 (if (not (boundp 'indent-pt))
10067 (defvar indent-pt nil "Local used by insert-indent")))
10068
10069 (defun verilog-insert-indent (&rest stuff)
10070 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
10071 Presumes that any newlines end a list element."
10072 (let ((need-indent t))
10073 (while stuff
10074 (if need-indent (indent-to indent-pt))
10075 (setq need-indent nil)
10076 (verilog-insert (car stuff))
10077 (setq need-indent (string-match "\n$" (car stuff))
10078 stuff (cdr stuff)))))
10079 ;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
10080
10081 (defun verilog-forward-or-insert-line ()
10082 "Move forward a line, unless at EOB, then insert a newline."
10083 (if (eobp) (insert "\n")
10084 (forward-line)))
10085
10086 (defun verilog-repair-open-comma ()
10087 "Insert comma if previous argument is other than an open parenthesis or endif."
10088 ;; We can't just search backward for ) as it might be inside another expression.
10089 ;; Also want "`ifdef X input foo `endif" to just leave things to the human to deal with
10090 (save-excursion
10091 (verilog-backward-syntactic-ws-quick)
10092 (when (and (not (save-excursion ;; Not beginning (, or existing ,
10093 (backward-char 1)
10094 (looking-at "[(,]")))
10095 (not (save-excursion ;; Not `endif, or user define
10096 (backward-char 1)
10097 (skip-chars-backward "[a-zA-Z0-9_`]")
10098 (looking-at "`"))))
10099 (insert ","))))
10100
10101 (defun verilog-repair-close-comma ()
10102 "If point is at a comma followed by a close parenthesis, fix it.
10103 This repairs those mis-inserted by an AUTOARG."
10104 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
10105 (save-excursion
10106 (verilog-forward-close-paren)
10107 (backward-char 1)
10108 (verilog-backward-syntactic-ws-quick)
10109 (backward-char 1)
10110 (when (looking-at ",")
10111 (delete-char 1))))
10112
10113 (defun verilog-make-width-expression (range-exp)
10114 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
10115 ;; strip off the []
10116 (cond ((not range-exp)
10117 "1")
10118 (t
10119 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
10120 (setq range-exp (match-string 1 range-exp)))
10121 (cond ((not range-exp)
10122 "1")
10123 ;; [#:#] We can compute a numeric result
10124 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
10125 range-exp)
10126 (int-to-string
10127 (1+ (abs (- (string-to-number (match-string 1 range-exp))
10128 (string-to-number (match-string 2 range-exp)))))))
10129 ;; [PARAM-1:0] can just return PARAM
10130 ((string-match "^\\s *\\([a-zA-Z_][a-zA-Z0-9_]*\\)\\s *-\\s *1\\s *:\\s *0\\s *$" range-exp)
10131 (match-string 1 range-exp))
10132 ;; [arbitrary] need math
10133 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
10134 (concat "(1+(" (match-string 1 range-exp) ")"
10135 (if (equal "0" (match-string 2 range-exp))
10136 "" ;; Don't bother with -(0)
10137 (concat "-(" (match-string 2 range-exp) ")"))
10138 ")"))
10139 (t nil)))))
10140 ;;(verilog-make-width-expression "`A:`B")
10141
10142 (defun verilog-simplify-range-expression (expr)
10143 "Return a simplified range expression with constants eliminated from EXPR."
10144 ;; Note this is always called with brackets; ie [z] or [z:z]
10145 (if (not (string-match "[---+*()]" expr))
10146 expr ;; short-circuit
10147 (let ((out expr)
10148 (last-pass ""))
10149 (while (not (equal last-pass out))
10150 (setq last-pass out)
10151 ;; Prefix regexp needs beginning of match, or some symbol of
10152 ;; lesser or equal precedence. We assume the [:]'s exist in expr.
10153 ;; Ditto the end.
10154 (while (string-match
10155 (concat "\\([[({:*+-]\\)" ; - must be last
10156 "(\\<\\([0-9A-Za-z_]+\\))"
10157 "\\([])}:*+-]\\)")
10158 out)
10159 (setq out (replace-match "\\1\\2\\3" nil nil out)))
10160 (while (string-match
10161 (concat "\\([[({:*+-]\\)" ; - must be last
10162 "\\$clog2\\s *(\\<\\([0-9]+\\))"
10163 "\\([])}:*+-]\\)")
10164 out)
10165 (setq out (replace-match
10166 (concat
10167 (match-string 1 out)
10168 (int-to-string (verilog-clog2 (string-to-number (match-string 2 out))))
10169 (match-string 3 out))
10170 nil nil out)))
10171 ;; For precedence do * before +/-
10172 (while (string-match
10173 (concat "\\([[({:*+-]\\)"
10174 "\\([0-9]+\\)\\s *\\([*]\\)\\s *\\([0-9]+\\)"
10175 "\\([])}:*+-]\\)")
10176 out)
10177 (setq out (replace-match
10178 (concat (match-string 1 out)
10179 (int-to-string (* (string-to-number (match-string 2 out))
10180 (string-to-number (match-string 4 out))))
10181 (match-string 5 out))
10182 nil nil out)))
10183 (while (string-match
10184 (concat "\\([[({:+-]\\)" ; No * here as higher prec
10185 "\\([0-9]+\\)\\s *\\([---+]\\)\\s *\\([0-9]+\\)"
10186 "\\([])}:+-]\\)")
10187 out)
10188 (let ((pre (match-string 1 out))
10189 (lhs (string-to-number (match-string 2 out)))
10190 (rhs (string-to-number (match-string 4 out)))
10191 (post (match-string 5 out))
10192 val)
10193 (when (equal pre "-")
10194 (setq lhs (- lhs)))
10195 (setq val (if (equal (match-string 3 out) "-")
10196 (- lhs rhs)
10197 (+ lhs rhs))
10198 out (replace-match
10199 (concat (if (and (equal pre "-")
10200 (< val 0))
10201 "" ;; Not "--20" but just "-20"
10202 pre)
10203 (int-to-string val)
10204 post)
10205 nil nil out)) )))
10206 out)))
10207
10208 ;;(verilog-simplify-range-expression "[1:3]") ;; 1
10209 ;;(verilog-simplify-range-expression "[(1):3]") ;; 1
10210 ;;(verilog-simplify-range-expression "[(((16)+1)+1+(1+1))]") ;;20
10211 ;;(verilog-simplify-range-expression "[(2*3+6*7)]") ;; 48
10212 ;;(verilog-simplify-range-expression "[(FOO*4-1*2)]") ;; FOO*4-2
10213 ;;(verilog-simplify-range-expression "[(FOO*4+1-1)]") ;; FOO*4+0
10214 ;;(verilog-simplify-range-expression "[(func(BAR))]") ;; func(BAR)
10215 ;;(verilog-simplify-range-expression "[FOO-1+1-1+1]") ;; FOO-0
10216 ;;(verilog-simplify-range-expression "[$clog2(2)]") ;; 1
10217 ;;(verilog-simplify-range-expression "[$clog2(7)]") ;; 3
10218
10219 (defun verilog-clog2 (value)
10220 "Compute $clog2 - ceiling log2 of VALUE."
10221 (if (< value 1)
10222 0
10223 (ceiling (/ (log value) (log 2)))))
10224
10225 (defun verilog-typedef-name-p (variable-name)
10226 "Return true if the VARIABLE-NAME is a type definition."
10227 (when verilog-typedef-regexp
10228 (verilog-string-match-fold verilog-typedef-regexp variable-name)))
10229 \f
10230 ;;
10231 ;; Auto deletion
10232 ;;
10233
10234 (defun verilog-delete-autos-lined ()
10235 "Delete autos that occupy multiple lines, between begin and end comments."
10236 ;; The newline must not have a comment property, so we must
10237 ;; delete the end auto's newline, not the first newline
10238 (forward-line 1)
10239 (let ((pt (point)))
10240 (when (and
10241 (looking-at "\\s-*// Beginning")
10242 (search-forward "// End of automatic" nil t))
10243 ;; End exists
10244 (end-of-line)
10245 (forward-line 1)
10246 (delete-region pt (point)))))
10247
10248 (defun verilog-delete-empty-auto-pair ()
10249 "Delete begin/end auto pair at point, if empty."
10250 (forward-line 0)
10251 (when (looking-at (concat "\\s-*// Beginning of automatic.*\n"
10252 "\\s-*// End of automatics\n"))
10253 (delete-region (point) (save-excursion (forward-line 2) (point)))))
10254
10255 (defun verilog-forward-close-paren ()
10256 "Find the close parenthesis that match the current point.
10257 Ignore other close parenthesis with matching open parens."
10258 (let ((parens 1))
10259 (while (> parens 0)
10260 (unless (verilog-re-search-forward-quick "[()]" nil t)
10261 (error "%s: Mismatching ()" (verilog-point-text)))
10262 (cond ((= (preceding-char) ?\( )
10263 (setq parens (1+ parens)))
10264 ((= (preceding-char) ?\) )
10265 (setq parens (1- parens)))))))
10266
10267 (defun verilog-backward-open-paren ()
10268 "Find the open parenthesis that match the current point.
10269 Ignore other open parenthesis with matching close parens."
10270 (let ((parens 1))
10271 (while (> parens 0)
10272 (unless (verilog-re-search-backward-quick "[()]" nil t)
10273 (error "%s: Mismatching ()" (verilog-point-text)))
10274 (cond ((= (following-char) ?\) )
10275 (setq parens (1+ parens)))
10276 ((= (following-char) ?\( )
10277 (setq parens (1- parens)))))))
10278
10279 (defun verilog-backward-open-bracket ()
10280 "Find the open bracket that match the current point.
10281 Ignore other open bracket with matching close bracket."
10282 (let ((parens 1))
10283 (while (> parens 0)
10284 (unless (verilog-re-search-backward-quick "[][]" nil t)
10285 (error "%s: Mismatching []" (verilog-point-text)))
10286 (cond ((= (following-char) ?\] )
10287 (setq parens (1+ parens)))
10288 ((= (following-char) ?\[ )
10289 (setq parens (1- parens)))))))
10290
10291 (defun verilog-delete-to-paren ()
10292 "Delete the automatic inst/sense/arg created by autos.
10293 Deletion stops at the matching end parenthesis, outside comments."
10294 (delete-region (point)
10295 (save-excursion
10296 (verilog-backward-open-paren)
10297 (verilog-forward-sexp-ign-cmt 1) ;; Moves to paren that closes argdecl's
10298 (backward-char 1)
10299 (point))))
10300
10301 (defun verilog-auto-star-safe ()
10302 "Return if a .* AUTOINST is safe to delete or expand.
10303 It was created by the AUTOS themselves, or by the user."
10304 (and verilog-auto-star-expand
10305 (looking-at
10306 (concat "[ \t\n\f,]*\\([)]\\|// " verilog-inst-comment-re "\\)"))))
10307
10308 (defun verilog-delete-auto-star-all ()
10309 "Delete a .* AUTOINST, if it is safe."
10310 (when (verilog-auto-star-safe)
10311 (verilog-delete-to-paren)))
10312
10313 (defun verilog-delete-auto-star-implicit ()
10314 "Delete all .* implicit connections created by `verilog-auto-star'.
10315 This function will be called automatically at save unless
10316 `verilog-auto-star-save' is set, any non-templated expanded pins will be
10317 removed."
10318 (interactive)
10319 (let (paren-pt indent have-close-paren)
10320 (save-excursion
10321 (goto-char (point-min))
10322 ;; We need to match these even outside of comments.
10323 ;; For reasonable performance, we don't check if inside comments, sorry.
10324 (while (re-search-forward "// Implicit \\.\\*" nil t)
10325 (setq paren-pt (point))
10326 (beginning-of-line)
10327 (setq have-close-paren
10328 (save-excursion
10329 (when (search-forward ");" paren-pt t)
10330 (setq indent (current-indentation))
10331 t)))
10332 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
10333 (when have-close-paren
10334 ;; Delete extra commentary
10335 (save-excursion
10336 (while (progn
10337 (forward-line -1)
10338 (looking-at (concat "\\s *//\\s *" verilog-inst-comment-re "\n")))
10339 (delete-region (match-beginning 0) (match-end 0))))
10340 ;; If it is simple, we can put the ); on the same line as the last text
10341 (let ((rtn-pt (point)))
10342 (save-excursion
10343 (while (progn (backward-char 1)
10344 (looking-at "[ \t\n\f]")))
10345 (when (looking-at ",")
10346 (delete-region (+ 1 (point)) rtn-pt))))
10347 (when (bolp)
10348 (indent-to indent))
10349 (insert ");\n")
10350 ;; Still need to kill final comma - always is one as we put one after the .*
10351 (re-search-backward ",")
10352 (delete-char 1))))))
10353
10354 (defun verilog-delete-auto ()
10355 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
10356 Use \\[verilog-auto] to re-insert the updated AUTOs.
10357
10358 The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
10359 called before and after this function, respectively."
10360 (interactive)
10361 (save-excursion
10362 (if (buffer-file-name)
10363 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
10364 (verilog-save-no-change-functions
10365 (verilog-save-scan-cache
10366 ;; Allow user to customize
10367 (verilog-run-hooks 'verilog-before-delete-auto-hook)
10368
10369 ;; Remove those that have multi-line insertions, possibly with parameters
10370 ;; We allow anything beginning with AUTO, so that users can add their own
10371 ;; patterns
10372 (verilog-auto-re-search-do
10373 (concat "/\\*AUTO[A-Za-z0-9_]+"
10374 ;; Optional parens or quoted parameter or .* for (((...)))
10375 "\\(\\|([^)]*)\\|(\"[^\"]*\")\\).*?"
10376 "\\*/")
10377 'verilog-delete-autos-lined)
10378 ;; Remove those that are in parenthesis
10379 (verilog-auto-re-search-do
10380 (concat "/\\*"
10381 (eval-when-compile
10382 (verilog-regexp-words
10383 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
10384 "AUTOSENSE")))
10385 "\\*/")
10386 'verilog-delete-to-paren)
10387 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
10388 (verilog-auto-re-search-do "\\.\\*"
10389 'verilog-delete-auto-star-all)
10390 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
10391 (goto-char (point-min))
10392 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)\\([ \tLT0-9]*\\| LHS: .*\\)?$" nil t)
10393 (replace-match ""))
10394
10395 ;; Final customize
10396 (verilog-run-hooks 'verilog-delete-auto-hook)))))
10397 \f
10398 ;;
10399 ;; Auto inject
10400 ;;
10401
10402 (defun verilog-inject-auto ()
10403 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
10404
10405 Any always @ blocks with sensitivity lists that match computed lists will
10406 be replaced with /*AS*/ comments.
10407
10408 Any cells will get /*AUTOINST*/ added to the end of the pin list.
10409 Pins with have identical names will be deleted.
10410
10411 Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
10412 support adding new ports. You may wish to delete older ports yourself.
10413
10414 For example:
10415
10416 module ExampInject (i, o);
10417 input i;
10418 input j;
10419 output o;
10420 always @ (i or j)
10421 o = i | j;
10422 InstModule instName
10423 (.foobar(baz),
10424 j(j));
10425 endmodule
10426
10427 Typing \\[verilog-inject-auto] will make this into:
10428
10429 module ExampInject (i, o/*AUTOARG*/
10430 // Inputs
10431 j);
10432 input i;
10433 output o;
10434 always @ (/*AS*/i or j)
10435 o = i | j;
10436 InstModule instName
10437 (.foobar(baz),
10438 /*AUTOINST*/
10439 // Outputs
10440 j(j));
10441 endmodule"
10442 (interactive)
10443 (verilog-auto t))
10444
10445 (defun verilog-inject-arg ()
10446 "Inject AUTOARG into new code. See `verilog-inject-auto'."
10447 ;; Presume one module per file.
10448 (save-excursion
10449 (goto-char (point-min))
10450 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
10451 (let ((endmodp (save-excursion
10452 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
10453 (point))))
10454 ;; See if there's already a comment .. inside a comment so not verilog-re-search
10455 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
10456 (verilog-re-search-forward-quick ";" nil t)
10457 (backward-char 1)
10458 (verilog-backward-syntactic-ws-quick)
10459 (backward-char 1) ; Moves to paren that closes argdecl's
10460 (when (looking-at ")")
10461 (verilog-insert "/*AUTOARG*/")))))))
10462
10463 (defun verilog-inject-sense ()
10464 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
10465 (save-excursion
10466 (goto-char (point-min))
10467 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
10468 (let* ((start-pt (point))
10469 (modi (verilog-modi-current))
10470 (moddecls (verilog-modi-get-decls modi))
10471 pre-sigs
10472 got-sigs)
10473 (backward-char 1)
10474 (verilog-forward-sexp-ign-cmt 1)
10475 (backward-char 1) ;; End )
10476 (when (not (verilog-re-search-backward-quick "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
10477 (setq pre-sigs (verilog-signals-from-signame
10478 (verilog-read-signals start-pt (point)))
10479 got-sigs (verilog-auto-sense-sigs moddecls nil))
10480 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
10481 (verilog-signals-not-in got-sigs pre-sigs)))
10482 (delete-region start-pt (point))
10483 (verilog-insert "/*AS*/")))))))
10484
10485 (defun verilog-inject-inst ()
10486 "Inject AUTOINST into new code. See `verilog-inject-auto'."
10487 (save-excursion
10488 (goto-char (point-min))
10489 ;; It's hard to distinguish modules; we'll instead search for pins.
10490 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
10491 (verilog-backward-open-paren) ;; Inst start
10492 (cond
10493 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
10494 (forward-char 1)
10495 (verilog-forward-close-paren)) ;; Parameters done
10496 (t
10497 (forward-char 1)
10498 (let ((indent-pt (+ (current-column)))
10499 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
10500 (cond ((verilog-re-search-forward-quick "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
10501 (goto-char end-pt)) ;; Already there, continue search with next instance
10502 (t
10503 ;; Delete identical interconnect
10504 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
10505 (while (verilog-re-search-forward-quick "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
10506 (delete-region (match-beginning 0) (match-end 0))
10507 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
10508 (while (or (looking-at "[ \t\n\f,]+")
10509 (looking-at "//[^\n]*"))
10510 (delete-region (match-beginning 0) (match-end 0))
10511 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
10512 (verilog-forward-close-paren)
10513 (backward-char 1)
10514 ;; Not verilog-re-search, as we don't want to strip comments
10515 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
10516 (delete-region (match-beginning 0) (match-end 0)))
10517 (verilog-insert "\n")
10518 (verilog-insert-indent "/*AUTOINST*/")))))))))
10519 \f
10520 ;;
10521 ;; Auto diff
10522 ;;
10523
10524 (defun verilog-diff-buffers-p (b1 b2 &optional whitespace)
10525 "Return nil if buffers B1 and B2 have same contents.
10526 Else, return point in B1 that first mismatches.
10527 If optional WHITESPACE true, ignore whitespace."
10528 (save-excursion
10529 (let* ((case-fold-search nil) ;; compare-buffer-substrings cares
10530 (p1 (with-current-buffer b1 (goto-char (point-min))))
10531 (p2 (with-current-buffer b2 (goto-char (point-min))))
10532 (maxp1 (with-current-buffer b1 (point-max)))
10533 (maxp2 (with-current-buffer b2 (point-max)))
10534 (op1 -1) (op2 -1)
10535 progress size)
10536 (while (not (and (eq p1 op1) (eq p2 op2)))
10537 ;; If both windows have whitespace optionally skip over it.
10538 (when whitespace
10539 ;; skip-syntax-* doesn't count \n
10540 (with-current-buffer b1
10541 (goto-char p1)
10542 (skip-chars-forward " \t\n\r\f\v")
10543 (setq p1 (point)))
10544 (with-current-buffer b2
10545 (goto-char p2)
10546 (skip-chars-forward " \t\n\r\f\v")
10547 (setq p2 (point))))
10548 (setq size (min (- maxp1 p1) (- maxp2 p2)))
10549 (setq progress (compare-buffer-substrings b2 p2 (+ size p2)
10550 b1 p1 (+ size p1)))
10551 (setq progress (if (zerop progress) size (1- (abs progress))))
10552 (setq op1 p1 op2 p2
10553 p1 (+ p1 progress)
10554 p2 (+ p2 progress)))
10555 ;; Return value
10556 (if (and (eq p1 maxp1) (eq p2 maxp2))
10557 nil p1))))
10558
10559 (defun verilog-diff-file-with-buffer (f1 b2 &optional whitespace show)
10560 "View the differences between file F1 and buffer B2.
10561 This requires the external program `diff-command' to be in your `exec-path',
10562 and uses `diff-switches' in which you may want to have \"-u\" flag.
10563 Ignores WHITESPACE if t, and writes output to stdout if SHOW."
10564 ;; Similar to `diff-buffer-with-file' but works on XEmacs, and doesn't
10565 ;; call `diff' as `diff' has different calling semantics on different
10566 ;; versions of Emacs.
10567 (if (not (file-exists-p f1))
10568 (message "Buffer %s has no associated file on disc" (buffer-name b2))
10569 (with-temp-buffer "*Verilog-Diff*"
10570 (let ((outbuf (current-buffer))
10571 (f2 (make-temp-file "vm-diff-auto-")))
10572 (unwind-protect
10573 (progn
10574 (with-current-buffer b2
10575 (save-restriction
10576 (widen)
10577 (write-region (point-min) (point-max) f2 nil 'nomessage)))
10578 (call-process diff-command nil outbuf t
10579 diff-switches ;; User may want -u in diff-switches
10580 (if whitespace "-b" "")
10581 f1 f2)
10582 ;; Print out results. Alternatively we could have call-processed
10583 ;; ourself, but this way we can reuse diff switches
10584 (when show
10585 (with-current-buffer outbuf (message "%s" (buffer-string))))))
10586 (sit-for 0)
10587 (when (file-exists-p f2)
10588 (delete-file f2))))))
10589
10590 (defun verilog-diff-report (b1 b2 diffpt)
10591 "Report differences detected with `verilog-diff-auto'.
10592 Differences are between buffers B1 and B2, starting at point
10593 DIFFPT. This function is called via `verilog-diff-function'."
10594 (let ((name1 (with-current-buffer b1 (buffer-file-name))))
10595 (verilog-warn "%s:%d: Difference in AUTO expansion found"
10596 name1 (with-current-buffer b1
10597 (count-lines (point-min) diffpt)))
10598 (cond (noninteractive
10599 (verilog-diff-file-with-buffer name1 b2 t t))
10600 (t
10601 (ediff-buffers b1 b2)))))
10602
10603 (defun verilog-diff-auto ()
10604 "Expand AUTOs in a temporary buffer and indicate any change.
10605 Whitespace is ignored when detecting differences, but once a
10606 difference is detected, whitespace differences may be shown.
10607
10608 To call this from the command line, see \\[verilog-batch-diff-auto].
10609
10610 The action on differences is selected with
10611 `verilog-diff-function'. The default is `verilog-diff-report'
10612 which will report an error and run `ediff' in interactive mode,
10613 or `diff' in batch mode."
10614 (interactive)
10615 (let ((b1 (current-buffer)) b2 diffpt
10616 (name1 (buffer-file-name))
10617 (newname "*Verilog-Diff*"))
10618 (save-excursion
10619 (when (get-buffer newname)
10620 (kill-buffer newname))
10621 (setq b2 (let (buffer-file-name) ;; Else clone is upset
10622 (clone-buffer newname)))
10623 (with-current-buffer b2
10624 ;; auto requires the filename, but can't have same filename in two
10625 ;; buffers; so override both b1 and b2's names
10626 (let ((buffer-file-name name1))
10627 (unwind-protect
10628 (progn
10629 (with-current-buffer b1 (setq buffer-file-name nil))
10630 (verilog-auto)
10631 (when (not verilog-auto-star-save)
10632 (verilog-delete-auto-star-implicit)))
10633 ;; Restore name if unwind
10634 (with-current-buffer b1 (setq buffer-file-name name1)))))
10635 ;;
10636 (setq diffpt (verilog-diff-buffers-p b1 b2 t))
10637 (cond ((not diffpt)
10638 (unless noninteractive (message "AUTO expansion identical"))
10639 (kill-buffer newname)) ;; Nice to cleanup after oneself
10640 (t
10641 (funcall verilog-diff-function b1 b2 diffpt)))
10642 ;; Return result of compare
10643 diffpt)))
10644
10645 \f
10646 ;;
10647 ;; Auto save
10648 ;;
10649
10650 (defun verilog-auto-save-check ()
10651 "On saving see if we need auto update."
10652 (cond ((not verilog-auto-save-policy)) ; disabled
10653 ((not (save-excursion
10654 (save-match-data
10655 (let ((case-fold-search nil))
10656 (goto-char (point-min))
10657 (re-search-forward "AUTO" nil t))))))
10658 ((eq verilog-auto-save-policy 'force)
10659 (verilog-auto))
10660 ((not (buffer-modified-p)))
10661 ((eq verilog-auto-update-tick (buffer-chars-modified-tick))) ; up-to-date
10662 ((eq verilog-auto-save-policy 'detect)
10663 (verilog-auto))
10664 (t
10665 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
10666 (verilog-auto))
10667 ;; Don't ask again if didn't update
10668 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))))
10669 (when (not verilog-auto-star-save)
10670 (verilog-delete-auto-star-implicit))
10671 nil) ;; Always return nil -- we don't write the file ourselves
10672
10673 (defun verilog-auto-read-locals ()
10674 "Return file local variable segment at bottom of file."
10675 (save-excursion
10676 (goto-char (point-max))
10677 (if (re-search-backward "Local Variables:" nil t)
10678 (buffer-substring-no-properties (point) (point-max))
10679 "")))
10680
10681 (defun verilog-auto-reeval-locals (&optional force)
10682 "Read file local variable segment at bottom of file if it has changed.
10683 If FORCE, always reread it."
10684 (let ((curlocal (verilog-auto-read-locals)))
10685 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
10686 (set (make-local-variable 'verilog-auto-last-file-locals) curlocal)
10687 ;; Note this may cause this function to be recursively invoked,
10688 ;; because hack-local-variables may call (verilog-mode)
10689 ;; The above when statement will prevent it from recursing forever.
10690 (hack-local-variables)
10691 t)))
10692 \f
10693 ;;
10694 ;; Auto creation
10695 ;;
10696
10697 (defun verilog-auto-arg-ports (sigs message indent-pt)
10698 "Print a list of ports for AUTOARG.
10699 Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
10700 (when sigs
10701 (when verilog-auto-arg-sort
10702 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
10703 (insert "\n")
10704 (indent-to indent-pt)
10705 (insert message)
10706 (insert "\n")
10707 (let ((space ""))
10708 (indent-to indent-pt)
10709 (while sigs
10710 (cond ((equal verilog-auto-arg-format 'single)
10711 (insert space)
10712 (indent-to indent-pt)
10713 (setq space "\n"))
10714 ;; verilog-auto-arg-format 'packed
10715 ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
10716 (insert "\n")
10717 (indent-to indent-pt)
10718 (setq space " "))
10719 (t
10720 (insert space)
10721 (setq space " ")))
10722 (insert (verilog-sig-name (car sigs)) ",")
10723 (setq sigs (cdr sigs))))))
10724
10725 (defun verilog-auto-arg ()
10726 "Expand AUTOARG statements.
10727 Replace the argument declarations at the beginning of the
10728 module with ones automatically derived from input and output
10729 statements. This can be dangerous if the module is instantiated
10730 using position-based connections, so use only name-based when
10731 instantiating the resulting module. Long lines are split based
10732 on the `fill-column', see \\[set-fill-column].
10733
10734 Limitations:
10735 Concatenation and outputting partial buses is not supported.
10736
10737 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10738
10739 For example:
10740
10741 module ExampArg (/*AUTOARG*/);
10742 input i;
10743 output o;
10744 endmodule
10745
10746 Typing \\[verilog-auto] will make this into:
10747
10748 module ExampArg (/*AUTOARG*/
10749 // Outputs
10750 o,
10751 // Inputs
10752 i
10753 );
10754 input i;
10755 output o;
10756 endmodule
10757
10758 The argument declarations may be printed in declaration order to
10759 best suit order based instantiations, or alphabetically, based on
10760 the `verilog-auto-arg-sort' variable.
10761
10762 Formatting is controlled with `verilog-auto-arg-format' variable.
10763
10764 Any ports declared between the ( and /*AUTOARG*/ are presumed to be
10765 predeclared and are not redeclared by AUTOARG. AUTOARG will make a
10766 conservative guess on adding a comma for the first signal, if you have
10767 any ifdefs or complicated expressions before the AUTOARG you will need
10768 to choose the comma yourself.
10769
10770 Avoid declaring ports manually, as it makes code harder to maintain."
10771 (save-excursion
10772 (let* ((modi (verilog-modi-current))
10773 (moddecls (verilog-modi-get-decls modi))
10774 (skip-pins (aref (verilog-read-arg-pins) 0)))
10775 (verilog-repair-open-comma)
10776 (verilog-auto-arg-ports (verilog-signals-not-in
10777 (verilog-decls-get-outputs moddecls)
10778 skip-pins)
10779 "// Outputs"
10780 verilog-indent-level-declaration)
10781 (verilog-auto-arg-ports (verilog-signals-not-in
10782 (verilog-decls-get-inouts moddecls)
10783 skip-pins)
10784 "// Inouts"
10785 verilog-indent-level-declaration)
10786 (verilog-auto-arg-ports (verilog-signals-not-in
10787 (verilog-decls-get-inputs moddecls)
10788 skip-pins)
10789 "// Inputs"
10790 verilog-indent-level-declaration)
10791 (verilog-repair-close-comma)
10792 (unless (eq (char-before) ?/ )
10793 (insert "\n"))
10794 (indent-to verilog-indent-level-declaration))))
10795
10796 (defun verilog-auto-assign-modport ()
10797 "Expand AUTOASSIGNMODPORT statements, as part of \\[verilog-auto].
10798 Take input/output/inout statements from the specified interface
10799 and modport and use to build assignments into the modport, for
10800 making verification modules that connect to UVM interfaces.
10801
10802 The first parameter is the name of an interface.
10803
10804 The second parameter is a regexp of modports to read from in
10805 that interface.
10806
10807 The third parameter is the instance name to use to dot reference into.
10808
10809 The optional fourth parameter is a regular expression, and only
10810 signals matching the regular expression will be included.
10811
10812 Limitations:
10813
10814 Interface names must be resolvable to filenames. See `verilog-auto-inst'.
10815
10816 Inouts are not supported, as assignments must be unidirectional.
10817
10818 If a signal is part of the interface header and in both a
10819 modport and the interface itself, it will not be listed. (As
10820 this would result in a syntax error when the connections are
10821 made.)
10822
10823 See the example in `verilog-auto-inout-modport'."
10824 (save-excursion
10825 (let* ((params (verilog-read-auto-params 3 4))
10826 (submod (nth 0 params))
10827 (modport-re (nth 1 params))
10828 (inst-name (nth 2 params))
10829 (regexp (nth 3 params))
10830 direction-re submodi) ;; direction argument not supported until requested
10831 ;; Lookup position, etc of co-module
10832 ;; Note this may raise an error
10833 (when (setq submodi (verilog-modi-lookup submod t))
10834 (let* ((indent-pt (current-indentation))
10835 (submoddecls (verilog-modi-get-decls submodi))
10836 (submodportdecls (verilog-modi-modport-lookup submodi modport-re))
10837 (sig-list-i (verilog-signals-in ;; Decls doesn't have data types, must resolve
10838 (verilog-decls-get-vars submoddecls)
10839 (verilog-signals-not-in
10840 (verilog-decls-get-inputs submodportdecls)
10841 (verilog-decls-get-ports submoddecls))))
10842 (sig-list-o (verilog-signals-in ;; Decls doesn't have data types, must resolve
10843 (verilog-decls-get-vars submoddecls)
10844 (verilog-signals-not-in
10845 (verilog-decls-get-outputs submodportdecls)
10846 (verilog-decls-get-ports submoddecls)))))
10847 (forward-line 1)
10848 (setq sig-list-i (verilog-signals-edit-wire-reg
10849 (verilog-signals-matching-dir-re
10850 (verilog-signals-matching-regexp sig-list-i regexp)
10851 "input" direction-re))
10852 sig-list-o (verilog-signals-edit-wire-reg
10853 (verilog-signals-matching-dir-re
10854 (verilog-signals-matching-regexp sig-list-o regexp)
10855 "output" direction-re)))
10856 (setq sig-list-i (sort (copy-alist sig-list-i) `verilog-signals-sort-compare))
10857 (setq sig-list-o (sort (copy-alist sig-list-o) `verilog-signals-sort-compare))
10858 (when (or sig-list-i sig-list-o)
10859 (verilog-insert-indent "// Beginning of automatic assignments from modport\n")
10860 ;; Don't sort them so an upper AUTOINST will match the main module
10861 (let ((sigs sig-list-o))
10862 (while sigs
10863 (verilog-insert-indent "assign " (verilog-sig-name (car sigs))
10864 " = " inst-name
10865 "." (verilog-sig-name (car sigs)) ";\n")
10866 (setq sigs (cdr sigs))))
10867 (let ((sigs sig-list-i))
10868 (while sigs
10869 (verilog-insert-indent "assign " inst-name
10870 "." (verilog-sig-name (car sigs))
10871 " = " (verilog-sig-name (car sigs)) ";\n")
10872 (setq sigs (cdr sigs))))
10873 (verilog-insert-indent "// End of automatics\n")))))))
10874
10875 (defun verilog-auto-inst-port-map (_port-st)
10876 nil)
10877
10878 (defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
10879 (defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
10880 (defvar vl-modport nil "See `verilog-auto-inst'.") ; Prevent compile warning
10881 (defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
10882 (defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
10883 (defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
10884 (defvar vl-bits nil "See `verilog-auto-inst'.") ; Prevent compile warning
10885 (defvar vl-mbits nil "See `verilog-auto-inst'.") ; Prevent compile warning
10886
10887 (defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
10888 "Print out an instantiation connection for this PORT-ST.
10889 Insert to INDENT-PT, use template TPL-LIST.
10890 @ are instantiation numbers, replaced with TPL-NUM.
10891 @\"(expression @)\" are evaluated, with @ as a variable.
10892 If FOR-STAR add comment it is a .* expansion.
10893 If PAR-VALUES replace final strings with these parameter values."
10894 (let* ((port (verilog-sig-name port-st))
10895 (tpl-ass (or (assoc port (car tpl-list))
10896 (verilog-auto-inst-port-map port-st)))
10897 ;; vl-* are documented for user use
10898 (vl-name (verilog-sig-name port-st))
10899 (vl-width (verilog-sig-width port-st))
10900 (vl-modport (verilog-sig-modport port-st))
10901 (vl-mbits (if (verilog-sig-multidim port-st)
10902 (verilog-sig-multidim-string port-st) ""))
10903 (vl-bits (if (or verilog-auto-inst-vector
10904 (not (assoc port vector-skip-list))
10905 (not (equal (verilog-sig-bits port-st)
10906 (verilog-sig-bits (assoc port vector-skip-list)))))
10907 (or (verilog-sig-bits port-st) "")
10908 ""))
10909 (case-fold-search nil)
10910 (check-values par-values)
10911 tpl-net dflt-bits)
10912 ;; Replace parameters in bit-width
10913 (when (and check-values
10914 (not (equal vl-bits "")))
10915 (while check-values
10916 (setq vl-bits (verilog-string-replace-matches
10917 (concat "\\<" (nth 0 (car check-values)) "\\>")
10918 (concat "(" (nth 1 (car check-values)) ")")
10919 t t vl-bits)
10920 vl-mbits (verilog-string-replace-matches
10921 (concat "\\<" (nth 0 (car check-values)) "\\>")
10922 (concat "(" (nth 1 (car check-values)) ")")
10923 t t vl-mbits)
10924 check-values (cdr check-values)))
10925 (setq vl-bits (verilog-simplify-range-expression vl-bits)
10926 vl-mbits (verilog-simplify-range-expression vl-mbits)
10927 vl-width (verilog-make-width-expression vl-bits))) ; Not in the loop for speed
10928 ;; Default net value if not found
10929 (setq dflt-bits (if (and (verilog-sig-bits port-st)
10930 (or (verilog-sig-multidim port-st)
10931 (verilog-sig-memory port-st)))
10932 (concat "/*" vl-mbits vl-bits "*/")
10933 (concat vl-bits))
10934 tpl-net (concat port
10935 (if vl-modport (concat "." vl-modport) "")
10936 dflt-bits))
10937 ;; Find template
10938 (cond (tpl-ass ; Template of exact port name
10939 (setq tpl-net (nth 1 tpl-ass)))
10940 ((nth 1 tpl-list) ; Wildcards in template, search them
10941 (let ((wildcards (nth 1 tpl-list)))
10942 (while wildcards
10943 (when (string-match (nth 0 (car wildcards)) port)
10944 (setq tpl-ass (car wildcards) ; so allow @ parsing
10945 tpl-net (replace-match (nth 1 (car wildcards))
10946 t nil port)))
10947 (setq wildcards (cdr wildcards))))))
10948 ;; Parse Templated variable
10949 (when tpl-ass
10950 ;; Evaluate @"(lispcode)"
10951 (when (string-match "@\".*[^\\]\"" tpl-net)
10952 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
10953 (setq tpl-net
10954 (concat
10955 (substring tpl-net 0 (match-beginning 0))
10956 (save-match-data
10957 (let* ((expr (match-string 1 tpl-net))
10958 (value
10959 (progn
10960 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
10961 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
10962 (prin1 (eval (car (read-from-string expr)))
10963 (lambda (_ch) ())))))
10964 (if (numberp value) (setq value (number-to-string value)))
10965 value))
10966 (substring tpl-net (match-end 0))))))
10967 ;; Replace @ and [] magic variables in final output
10968 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
10969 (setq tpl-net (verilog-string-replace-matches "\\[\\]\\[\\]" dflt-bits nil nil tpl-net))
10970 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
10971 ;; Insert it
10972 (indent-to indent-pt)
10973 (insert "." port)
10974 (unless (and verilog-auto-inst-dot-name
10975 (equal port tpl-net))
10976 (indent-to verilog-auto-inst-column)
10977 (insert "(" tpl-net ")"))
10978 (insert ",")
10979 (cond (tpl-ass
10980 (verilog-read-auto-template-hit tpl-ass)
10981 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
10982 verilog-auto-inst-column))
10983 ;; verilog-insert requires the complete comment in one call - including the newline
10984 (cond ((equal verilog-auto-inst-template-numbers `lhs)
10985 (verilog-insert " // Templated"
10986 " LHS: " (nth 0 tpl-ass)
10987 "\n"))
10988 (verilog-auto-inst-template-numbers
10989 (verilog-insert " // Templated"
10990 " T" (int-to-string (nth 2 tpl-ass))
10991 " L" (int-to-string (nth 3 tpl-ass))
10992 "\n"))
10993 (t
10994 (verilog-insert " // Templated\n"))))
10995 (for-star
10996 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
10997 verilog-auto-inst-column))
10998 (verilog-insert " // Implicit .\*\n")) ;For some reason the . or * must be escaped...
10999 (t
11000 (insert "\n")))))
11001 ;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
11002 ;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
11003 ;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
11004
11005 (defun verilog-auto-inst-port-list (sig-list indent-pt tpl-list tpl-num for-star par-values)
11006 "For `verilog-auto-inst' print a list of ports using `verilog-auto-inst-port'."
11007 (when verilog-auto-inst-sort
11008 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare)))
11009 (mapc (lambda (port)
11010 (verilog-auto-inst-port port indent-pt
11011 tpl-list tpl-num for-star par-values))
11012 sig-list))
11013
11014 (defun verilog-auto-inst-first ()
11015 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
11016 ;; Do we need a trailing comma?
11017 ;; There maybe an ifdef or something similar before us. What a mess. Thus
11018 ;; to avoid trouble we only insert on preceding ) or *.
11019 ;; Insert first port on new line
11020 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
11021 (save-excursion
11022 (verilog-re-search-backward-quick "[^ \t\n\f]" nil nil)
11023 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
11024 (forward-char 1)
11025 (insert ","))))
11026
11027 (defun verilog-auto-star ()
11028 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
11029
11030 If `verilog-auto-star-expand' is set, .* pins are treated if they were
11031 AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
11032 will also ignore any .* that are not last in your pin list (this prevents
11033 it from deleting pins following the .* when it expands the AUTOINST.)
11034
11035 On writing your file, unless `verilog-auto-star-save' is set, any
11036 non-templated expanded pins will be removed. You may do this at any time
11037 with \\[verilog-delete-auto-star-implicit].
11038
11039 If you are converting a module to use .* for the first time, you may wish
11040 to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
11041
11042 See `verilog-auto-inst' for examples, templates, and more information."
11043 (when (verilog-auto-star-safe)
11044 (verilog-auto-inst)))
11045
11046 (defun verilog-auto-inst ()
11047 "Expand AUTOINST statements, as part of \\[verilog-auto].
11048 Replace the pin connections to an instantiation or interface
11049 declaration with ones automatically derived from the module or
11050 interface header of the instantiated item.
11051
11052 If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
11053 and delete them before saving unless `verilog-auto-star-save' is set.
11054 See `verilog-auto-star' for more information.
11055
11056 The pins are printed in declaration order or alphabetically,
11057 based on the `verilog-auto-inst-sort' variable.
11058
11059 Limitations:
11060 Module names must be resolvable to filenames by adding a
11061 `verilog-library-extensions', and being found in the same directory, or
11062 by changing the variable `verilog-library-flags' or
11063 `verilog-library-directories'. Macros `modname are translated through the
11064 vh-{name} Emacs variable, if that is not found, it just ignores the `.
11065
11066 In templates you must have one signal per line, ending in a ), or ));,
11067 and have proper () nesting, including a final ); to end the template.
11068
11069 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
11070
11071 SystemVerilog multidimensional input/output has only experimental support.
11072
11073 SystemVerilog .name syntax is used if `verilog-auto-inst-dot-name' is set.
11074
11075 Parameters referenced by the instantiation will remain symbolic, unless
11076 `verilog-auto-inst-param-value' is set.
11077
11078 Gate primitives (and/or) may have AUTOINST for the purpose of
11079 AUTOWIRE declarations, etc. Gates are the only case when
11080 position based connections are passed.
11081
11082 The array part of arrayed instances are ignored; this may
11083 result in undesirable default AUTOINST connections; use a
11084 template instead.
11085
11086 For example, first take the submodule InstModule.v:
11087
11088 module InstModule (o,i);
11089 output [31:0] o;
11090 input i;
11091 wire [31:0] o = {32{i}};
11092 endmodule
11093
11094 This is then used in an upper level module:
11095
11096 module ExampInst (o,i);
11097 output o;
11098 input i;
11099 InstModule instName
11100 (/*AUTOINST*/);
11101 endmodule
11102
11103 Typing \\[verilog-auto] will make this into:
11104
11105 module ExampInst (o,i);
11106 output o;
11107 input i;
11108 InstModule instName
11109 (/*AUTOINST*/
11110 // Outputs
11111 .ov (ov[31:0]),
11112 // Inputs
11113 .i (i));
11114 endmodule
11115
11116 Where the list of inputs and outputs came from the inst module.
11117 \f
11118 Exceptions:
11119
11120 Unless you are instantiating a module multiple times, or the module is
11121 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
11122 It just makes for unmaintainable code. To sanitize signal names, try
11123 vrename from URL `http://www.veripool.org'.
11124
11125 When you need to violate this suggestion there are two ways to list
11126 exceptions, placing them before the AUTOINST, or using templates.
11127
11128 Any ports defined before the /*AUTOINST*/ are not included in the list of
11129 automatics. This is similar to making a template as described below, but
11130 is restricted to simple connections just like you normally make. Also note
11131 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
11132 you have the appropriate // Input or // Output comment, and exactly the
11133 same line formatting as AUTOINST itself uses.
11134
11135 InstModule instName
11136 (// Inputs
11137 .i (my_i_dont_mess_with_it),
11138 /*AUTOINST*/
11139 // Outputs
11140 .ov (ov[31:0]));
11141
11142 \f
11143 Templates:
11144
11145 For multiple instantiations based upon a single template, create a
11146 commented out template:
11147
11148 /* InstModule AUTO_TEMPLATE (
11149 .sig3 (sigz[]),
11150 );
11151 */
11152
11153 Templates go ABOVE the instantiation(s). When an instantiation is
11154 expanded `verilog-mode' simply searches up for the closest template.
11155 Thus you can have multiple templates for the same module, just alternate
11156 between the template for an instantiation and the instantiation itself.
11157 (For backward compatibility if no template is found above, it
11158 will also look below, but do not use this behavior in new designs.)
11159
11160 The module name must be the same as the name of the module in the
11161 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
11162 words and capitalized. Only signals that must be different for each
11163 instantiation need to be listed.
11164
11165 Inside a template, a [] in a connection name (with nothing else
11166 inside the brackets) will be replaced by the same bus subscript
11167 as it is being connected to, or the [] will be removed if it is
11168 a single bit signal.
11169
11170 Inside a template, a [][] in a connection name will behave
11171 similarly to a [] for scalar or single-dimensional connection;
11172 for a multidimensional connection it will print a comment
11173 similar to that printed when a template is not used. Generally
11174 it is a good idea to do this for all connections in a template,
11175 as then they will work for any width signal, and with AUTOWIRE.
11176 See PTL_BUS becoming PTL_BUSNEW below.
11177
11178 Inside a template, a [] in a connection name (with nothing else inside
11179 the brackets) will be replaced by the same bus subscript as it is being
11180 connected to, or the [] will be removed if it is a single bit signal.
11181 Generally it is a good idea to do this for all connections in a template,
11182 as then they will work for any width signal, and with AUTOWIRE. See
11183 PTL_BUS becoming PTL_BUSNEW below.
11184
11185 If you have a complicated template, set `verilog-auto-inst-template-numbers'
11186 to see which regexps are matching. Don't leave that mode set after
11187 debugging is completed though, it will result in lots of extra differences
11188 and merge conflicts.
11189
11190 Setting `verilog-auto-template-warn-unused' will report errors
11191 if any template lines are unused.
11192
11193 For example:
11194
11195 /* InstModule AUTO_TEMPLATE (
11196 .ptl_bus (ptl_busnew[]),
11197 );
11198 */
11199 InstModule ms2m (/*AUTOINST*/);
11200
11201 Typing \\[verilog-auto] will make this into:
11202
11203 InstModule ms2m (/*AUTOINST*/
11204 // Outputs
11205 .NotInTemplate (NotInTemplate),
11206 .ptl_bus (ptl_busnew[3:0]), // Templated
11207 ....
11208
11209 \f
11210 Multiple Module Templates:
11211
11212 The same template lines can be applied to multiple modules with
11213 the syntax as follows:
11214
11215 /* InstModuleA AUTO_TEMPLATE
11216 InstModuleB AUTO_TEMPLATE
11217 InstModuleC AUTO_TEMPLATE
11218 InstModuleD AUTO_TEMPLATE (
11219 .ptl_bus (ptl_busnew[]),
11220 );
11221 */
11222
11223 Note there is only one AUTO_TEMPLATE opening parenthesis.
11224 \f
11225 @ Templates:
11226
11227 It is common to instantiate a cell multiple times, so templates make it
11228 trivial to substitute part of the cell name into the connection name.
11229
11230 /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
11231 .sig1 (sigx[@]),
11232 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
11233 );
11234 */
11235
11236 If no regular expression is provided immediately after the AUTO_TEMPLATE
11237 keyword, then the @ character in any connection names will be replaced
11238 with the instantiation number; the first digits found in the cell's
11239 instantiation name.
11240
11241 If a regular expression is provided, the @ character will be replaced
11242 with the first \(\) grouping that matches against the cell name. Using a
11243 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
11244 regexp is provided. If you use multiple layers of parenthesis,
11245 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
11246 characters after test and before _, whereas
11247 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
11248 match.
11249
11250 For example:
11251
11252 /* InstModule AUTO_TEMPLATE (
11253 .ptl_mapvalidx (ptl_mapvalid[@]),
11254 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
11255 );
11256 */
11257 InstModule ms2m (/*AUTOINST*/);
11258
11259 Typing \\[verilog-auto] will make this into:
11260
11261 InstModule ms2m (/*AUTOINST*/
11262 // Outputs
11263 .ptl_mapvalidx (ptl_mapvalid[2]),
11264 .ptl_mapvalidp1x (ptl_mapvalid[3]));
11265
11266 Note the @ character was replaced with the 2 from \"ms2m\".
11267
11268 Alternatively, using a regular expression for @:
11269
11270 /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
11271 .ptl_mapvalidx (@_ptl_mapvalid),
11272 .ptl_mapvalidp1x (ptl_mapvalid_@),
11273 );
11274 */
11275 InstModule ms2_FOO (/*AUTOINST*/);
11276 InstModule ms2_BAR (/*AUTOINST*/);
11277
11278 Typing \\[verilog-auto] will make this into:
11279
11280 InstModule ms2_FOO (/*AUTOINST*/
11281 // Outputs
11282 .ptl_mapvalidx (FOO_ptl_mapvalid),
11283 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
11284 InstModule ms2_BAR (/*AUTOINST*/
11285 // Outputs
11286 .ptl_mapvalidx (BAR_ptl_mapvalid),
11287 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
11288
11289 \f
11290 Regexp Templates:
11291
11292 A template entry of the form
11293
11294 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
11295
11296 will apply an Emacs style regular expression search for any port beginning
11297 in pci_req followed by numbers and ending in _l and connecting that to
11298 the pci_req_jtag_[] net, with the bus subscript coming from what matches
11299 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
11300
11301 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
11302 does the same thing. (Note a @ in the connection/replacement text is
11303 completely different -- still use \\1 there!) Thus this is the same as
11304 the above template:
11305
11306 .pci_req@_l (pci_req_jtag_[\\1]),
11307
11308 Here's another example to remove the _l, useful when naming conventions
11309 specify _ alone to mean active low. Note the use of [] to keep the bus
11310 subscript:
11311
11312 .\\(.*\\)_l (\\1_[]),
11313 \f
11314 Lisp Templates:
11315
11316 First any regular expression template is expanded.
11317
11318 If the syntax @\"( ... )\" is found in a connection, the expression in
11319 quotes will be evaluated as a Lisp expression, with @ replaced by the
11320 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
11321 4 into the brackets. Quote all double-quotes inside the expression with
11322 a leading backslash (\\\"...\\\"); or if the Lisp template is also a
11323 regexp template backslash the backslash quote (\\\\\"...\\\\\").
11324
11325 There are special variables defined that are useful in these
11326 Lisp functions:
11327
11328 vl-name Name portion of the input/output port.
11329 vl-bits Bus bits portion of the input/output port ('[2:0]').
11330 vl-mbits Multidimensional array bits for port ('[2:0][3:0]').
11331 vl-width Width of the input/output port ('3' for [2:0]).
11332 May be a (...) expression if bits isn't a constant.
11333 vl-dir Direction of the pin input/output/inout/interface.
11334 vl-modport The modport, if an interface with a modport.
11335 vl-cell-type Module name/type of the cell ('InstModule').
11336 vl-cell-name Instance name of the cell ('instName').
11337
11338 Normal Lisp variables may be used in expressions. See
11339 `verilog-read-defines' which can set vh-{definename} variables for use
11340 here. Also, any comments of the form:
11341
11342 /*AUTO_LISP(setq foo 1)*/
11343
11344 will evaluate any Lisp expression inside the parenthesis between the
11345 beginning of the buffer and the point of the AUTOINST. This allows
11346 functions to be defined or variables to be changed between instantiations.
11347 (See also `verilog-auto-insert-lisp' if you want the output from your
11348 lisp function to be inserted.)
11349
11350 Note that when using lisp expressions errors may occur when @ is not a
11351 number; you may need to use the standard Emacs Lisp functions
11352 `number-to-string' and `string-to-number'.
11353
11354 After the evaluation is completed, @ substitution and [] substitution
11355 occur.
11356
11357 For more information see the \\[verilog-faq] and forums at URL
11358 `http://www.veripool.org'."
11359 (save-excursion
11360 ;; Find beginning
11361 (let* ((pt (point))
11362 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
11363 (indent-pt (save-excursion (verilog-backward-open-paren)
11364 (1+ (current-column))))
11365 (verilog-auto-inst-column (max verilog-auto-inst-column
11366 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
11367 (modi (verilog-modi-current))
11368 (moddecls (verilog-modi-get-decls modi))
11369 (vector-skip-list (unless verilog-auto-inst-vector
11370 (verilog-decls-get-signals moddecls)))
11371 submod submodi submoddecls
11372 inst skip-pins tpl-list tpl-num did-first par-values)
11373
11374 ;; Find module name that is instantiated
11375 (setq submod (verilog-read-inst-module)
11376 inst (verilog-read-inst-name)
11377 vl-cell-type submod
11378 vl-cell-name inst
11379 skip-pins (aref (verilog-read-inst-pins) 0))
11380
11381 ;; Parse any AUTO_LISP() before here
11382 (verilog-read-auto-lisp (point-min) pt)
11383
11384 ;; Read parameters (after AUTO_LISP)
11385 (setq par-values (and verilog-auto-inst-param-value
11386 (verilog-read-inst-param-value)))
11387
11388 ;; Lookup position, etc of submodule
11389 ;; Note this may raise an error
11390 (when (and (not (member submod verilog-gate-keywords))
11391 (setq submodi (verilog-modi-lookup submod t)))
11392 (setq submoddecls (verilog-modi-get-decls submodi))
11393 ;; If there's a number in the instantiation, it may be an argument to the
11394 ;; automatic variable instantiation program.
11395 (let* ((tpl-info (verilog-read-auto-template submod))
11396 (tpl-regexp (aref tpl-info 0)))
11397 (setq tpl-num (if (verilog-string-match-fold tpl-regexp inst)
11398 (match-string 1 inst)
11399 "")
11400 tpl-list (aref tpl-info 1)))
11401 ;; Find submodule's signals and dump
11402 (let ((sig-list (and (equal (verilog-modi-get-type submodi) "interface")
11403 (verilog-signals-not-in
11404 (verilog-decls-get-vars submoddecls)
11405 skip-pins)))
11406 (vl-dir "interfaced"))
11407 (when (and sig-list
11408 verilog-auto-inst-interfaced-ports)
11409 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11410 ;; Note these are searched for in verilog-read-sub-decls.
11411 (verilog-insert-indent "// Interfaced\n")
11412 (verilog-auto-inst-port-list sig-list indent-pt
11413 tpl-list tpl-num for-star par-values)))
11414 (let ((sig-list (verilog-signals-not-in
11415 (verilog-decls-get-interfaces submoddecls)
11416 skip-pins))
11417 (vl-dir "interface"))
11418 (when sig-list
11419 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11420 ;; Note these are searched for in verilog-read-sub-decls.
11421 (verilog-insert-indent "// Interfaces\n")
11422 (verilog-auto-inst-port-list sig-list indent-pt
11423 tpl-list tpl-num for-star par-values)))
11424 (let ((sig-list (verilog-signals-not-in
11425 (verilog-decls-get-outputs submoddecls)
11426 skip-pins))
11427 (vl-dir "output"))
11428 (when sig-list
11429 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11430 (verilog-insert-indent "// Outputs\n")
11431 (verilog-auto-inst-port-list sig-list indent-pt
11432 tpl-list tpl-num for-star par-values)))
11433 (let ((sig-list (verilog-signals-not-in
11434 (verilog-decls-get-inouts submoddecls)
11435 skip-pins))
11436 (vl-dir "inout"))
11437 (when sig-list
11438 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11439 (verilog-insert-indent "// Inouts\n")
11440 (verilog-auto-inst-port-list sig-list indent-pt
11441 tpl-list tpl-num for-star par-values)))
11442 (let ((sig-list (verilog-signals-not-in
11443 (verilog-decls-get-inputs submoddecls)
11444 skip-pins))
11445 (vl-dir "input"))
11446 (when sig-list
11447 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11448 (verilog-insert-indent "// Inputs\n")
11449 (verilog-auto-inst-port-list sig-list indent-pt
11450 tpl-list tpl-num for-star par-values)))
11451 ;; Kill extra semi
11452 (save-excursion
11453 (cond (did-first
11454 (re-search-backward "," pt t)
11455 (delete-char 1)
11456 (insert ");")
11457 (search-forward "\n") ;; Added by inst-port
11458 (delete-char -1)
11459 (if (search-forward ")" nil t) ;; From user, moved up a line
11460 (delete-char -1))
11461 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
11462 (delete-char -1)))))))))
11463
11464 (defun verilog-auto-inst-param ()
11465 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
11466 Replace the parameter connections to an instantiation with ones
11467 automatically derived from the module header of the instantiated netlist.
11468
11469 See \\[verilog-auto-inst] for limitations, and templates to customize the
11470 output.
11471
11472 For example, first take the submodule InstModule.v:
11473
11474 module InstModule (o,i);
11475 parameter PAR;
11476 endmodule
11477
11478 This is then used in an upper level module:
11479
11480 module ExampInst (o,i);
11481 parameter PAR;
11482 InstModule #(/*AUTOINSTPARAM*/)
11483 instName (/*AUTOINST*/);
11484 endmodule
11485
11486 Typing \\[verilog-auto] will make this into:
11487
11488 module ExampInst (o,i);
11489 output o;
11490 input i;
11491 InstModule #(/*AUTOINSTPARAM*/
11492 // Parameters
11493 .PAR (PAR));
11494 instName (/*AUTOINST*/);
11495 endmodule
11496
11497 Where the list of parameter connections come from the inst module.
11498 \f
11499 Templates:
11500
11501 You can customize the parameter connections using AUTO_TEMPLATEs,
11502 just as you would with \\[verilog-auto-inst]."
11503 (save-excursion
11504 ;; Find beginning
11505 (let* ((pt (point))
11506 (indent-pt (save-excursion (verilog-backward-open-paren)
11507 (1+ (current-column))))
11508 (verilog-auto-inst-column (max verilog-auto-inst-column
11509 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
11510 (modi (verilog-modi-current))
11511 (moddecls (verilog-modi-get-decls modi))
11512 (vector-skip-list (unless verilog-auto-inst-vector
11513 (verilog-decls-get-signals moddecls)))
11514 submod submodi submoddecls
11515 inst skip-pins tpl-list tpl-num did-first)
11516 ;; Find module name that is instantiated
11517 (setq submod (save-excursion
11518 ;; Get to the point where AUTOINST normally is to read the module
11519 (verilog-re-search-forward-quick "[(;]" nil nil)
11520 (verilog-read-inst-module))
11521 inst (save-excursion
11522 ;; Get to the point where AUTOINST normally is to read the module
11523 (verilog-re-search-forward-quick "[(;]" nil nil)
11524 (verilog-read-inst-name))
11525 vl-cell-type submod
11526 vl-cell-name inst
11527 skip-pins (aref (verilog-read-inst-pins) 0))
11528
11529 ;; Parse any AUTO_LISP() before here
11530 (verilog-read-auto-lisp (point-min) pt)
11531
11532 ;; Lookup position, etc of submodule
11533 ;; Note this may raise an error
11534 (when (setq submodi (verilog-modi-lookup submod t))
11535 (setq submoddecls (verilog-modi-get-decls submodi))
11536 ;; If there's a number in the instantiation, it may be an argument to the
11537 ;; automatic variable instantiation program.
11538 (let* ((tpl-info (verilog-read-auto-template submod))
11539 (tpl-regexp (aref tpl-info 0)))
11540 (setq tpl-num (if (verilog-string-match-fold tpl-regexp inst)
11541 (match-string 1 inst)
11542 "")
11543 tpl-list (aref tpl-info 1)))
11544 ;; Find submodule's signals and dump
11545 (let ((sig-list (verilog-signals-not-in
11546 (verilog-decls-get-gparams submoddecls)
11547 skip-pins))
11548 (vl-dir "parameter"))
11549 (when sig-list
11550 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11551 ;; Note these are searched for in verilog-read-sub-decls.
11552 (verilog-insert-indent "// Parameters\n")
11553 (verilog-auto-inst-port-list sig-list indent-pt
11554 tpl-list tpl-num nil nil)))
11555 ;; Kill extra semi
11556 (save-excursion
11557 (cond (did-first
11558 (re-search-backward "," pt t)
11559 (delete-char 1)
11560 (insert ")")
11561 (search-forward "\n") ;; Added by inst-port
11562 (delete-char -1)
11563 (if (search-forward ")" nil t) ;; From user, moved up a line
11564 (delete-char -1)))))))))
11565
11566 (defun verilog-auto-reg ()
11567 "Expand AUTOREG statements, as part of \\[verilog-auto].
11568 Make reg statements for any output that isn't already declared,
11569 and isn't a wire output from a block. `verilog-auto-wire-type'
11570 may be used to change the datatype of the declarations.
11571
11572 Limitations:
11573 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11574
11575 This does NOT work on memories, declare those yourself.
11576
11577 An example:
11578
11579 module ExampReg (o,i);
11580 output o;
11581 input i;
11582 /*AUTOREG*/
11583 always o = i;
11584 endmodule
11585
11586 Typing \\[verilog-auto] will make this into:
11587
11588 module ExampReg (o,i);
11589 output o;
11590 input i;
11591 /*AUTOREG*/
11592 // Beginning of automatic regs (for this module's undeclared outputs)
11593 reg o;
11594 // End of automatics
11595 always o = i;
11596 endmodule"
11597 (save-excursion
11598 ;; Point must be at insertion point.
11599 (let* ((indent-pt (current-indentation))
11600 (modi (verilog-modi-current))
11601 (moddecls (verilog-modi-get-decls modi))
11602 (modsubdecls (verilog-modi-get-sub-decls modi))
11603 (sig-list (verilog-signals-not-in
11604 (verilog-decls-get-outputs moddecls)
11605 (append (verilog-signals-with ;; ignore typed signals
11606 'verilog-sig-type
11607 (verilog-decls-get-outputs moddecls))
11608 (verilog-decls-get-vars moddecls)
11609 (verilog-decls-get-assigns moddecls)
11610 (verilog-decls-get-consts moddecls)
11611 (verilog-decls-get-gparams moddecls)
11612 (verilog-subdecls-get-interfaced modsubdecls)
11613 (verilog-subdecls-get-outputs modsubdecls)
11614 (verilog-subdecls-get-inouts modsubdecls)))))
11615 (when sig-list
11616 (verilog-forward-or-insert-line)
11617 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
11618 (verilog-insert-definition modi sig-list "reg" indent-pt nil)
11619 (verilog-insert-indent "// End of automatics\n")))))
11620
11621 (defun verilog-auto-reg-input ()
11622 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
11623 Make reg statements instantiation inputs that aren't already declared.
11624 This is useful for making a top level shell for testing the module that is
11625 to be instantiated.
11626
11627 Limitations:
11628 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
11629
11630 This does NOT work on memories, declare those yourself.
11631
11632 An example (see `verilog-auto-inst' for what else is going on here):
11633
11634 module ExampRegInput (o,i);
11635 output o;
11636 input i;
11637 /*AUTOREGINPUT*/
11638 InstModule instName
11639 (/*AUTOINST*/);
11640 endmodule
11641
11642 Typing \\[verilog-auto] will make this into:
11643
11644 module ExampRegInput (o,i);
11645 output o;
11646 input i;
11647 /*AUTOREGINPUT*/
11648 // Beginning of automatic reg inputs (for undeclared ...
11649 reg [31:0] iv; // From inst of inst.v
11650 // End of automatics
11651 InstModule instName
11652 (/*AUTOINST*/
11653 // Outputs
11654 .o (o[31:0]),
11655 // Inputs
11656 .iv (iv));
11657 endmodule"
11658 (save-excursion
11659 ;; Point must be at insertion point.
11660 (let* ((indent-pt (current-indentation))
11661 (modi (verilog-modi-current))
11662 (moddecls (verilog-modi-get-decls modi))
11663 (modsubdecls (verilog-modi-get-sub-decls modi))
11664 (sig-list (verilog-signals-combine-bus
11665 (verilog-signals-not-in
11666 (append (verilog-subdecls-get-inputs modsubdecls)
11667 (verilog-subdecls-get-inouts modsubdecls))
11668 (append (verilog-decls-get-signals moddecls)
11669 (verilog-decls-get-assigns moddecls))))))
11670 (when sig-list
11671 (verilog-forward-or-insert-line)
11672 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
11673 (verilog-insert-definition modi sig-list "reg" indent-pt nil)
11674 (verilog-insert-indent "// End of automatics\n")))))
11675
11676 (defun verilog-auto-logic-setup ()
11677 "Prepare variables due to AUTOLOGIC."
11678 (unless verilog-auto-wire-type
11679 (set (make-local-variable 'verilog-auto-wire-type)
11680 "logic")))
11681
11682 (defun verilog-auto-logic ()
11683 "Expand AUTOLOGIC statements, as part of \\[verilog-auto].
11684 Make wire statements using the SystemVerilog logic keyword.
11685 This is currently equivalent to:
11686
11687 /*AUTOWIRE*/
11688
11689 with the below at the bottom of the file
11690
11691 // Local Variables:
11692 // verilog-auto-logic-type:\"logic\"
11693 // End:
11694
11695 In the future AUTOLOGIC may declare additional identifiers,
11696 while AUTOWIRE will not."
11697 (save-excursion
11698 (verilog-auto-logic-setup)
11699 (verilog-auto-wire)))
11700
11701 (defun verilog-auto-wire ()
11702 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
11703 Make wire statements for instantiations outputs that aren't
11704 already declared. `verilog-auto-wire-type' may be used to change
11705 the datatype of the declarations.
11706
11707 Limitations:
11708 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
11709 and all buses must have widths, such as those from AUTOINST, or using []
11710 in AUTO_TEMPLATEs.
11711
11712 This does NOT work on memories or SystemVerilog .name connections,
11713 declare those yourself.
11714
11715 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
11716 determine how to bus together. This occurs when you have ports with
11717 non-numeric or non-sequential bus subscripts. If Verilog mode
11718 mis-guessed, you'll have to declare them yourself.
11719
11720 An example (see `verilog-auto-inst' for what else is going on here):
11721
11722 module ExampWire (o,i);
11723 output o;
11724 input i;
11725 /*AUTOWIRE*/
11726 InstModule instName
11727 (/*AUTOINST*/);
11728 endmodule
11729
11730 Typing \\[verilog-auto] will make this into:
11731
11732 module ExampWire (o,i);
11733 output o;
11734 input i;
11735 /*AUTOWIRE*/
11736 // Beginning of automatic wires
11737 wire [31:0] ov; // From inst of inst.v
11738 // End of automatics
11739 InstModule instName
11740 (/*AUTOINST*/
11741 // Outputs
11742 .ov (ov[31:0]),
11743 // Inputs
11744 .i (i));
11745 wire o = | ov;
11746 endmodule"
11747 (save-excursion
11748 ;; Point must be at insertion point.
11749 (let* ((indent-pt (current-indentation))
11750 (modi (verilog-modi-current))
11751 (moddecls (verilog-modi-get-decls modi))
11752 (modsubdecls (verilog-modi-get-sub-decls modi))
11753 (sig-list (verilog-signals-combine-bus
11754 (verilog-signals-not-in
11755 (append (verilog-subdecls-get-outputs modsubdecls)
11756 (verilog-subdecls-get-inouts modsubdecls))
11757 (verilog-decls-get-signals moddecls)))))
11758 (when sig-list
11759 (verilog-forward-or-insert-line)
11760 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
11761 (verilog-insert-definition modi sig-list "wire" indent-pt nil)
11762 (verilog-insert-indent "// End of automatics\n")
11763 ;; We used to optionally call verilog-pretty-declarations and
11764 ;; verilog-pretty-expr here, but it's too slow on huge modules,
11765 ;; plus makes everyone's module change. Finally those call
11766 ;; syntax-ppss which is broken when change hooks are disabled.
11767 ))))
11768
11769 (defun verilog-auto-output ()
11770 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
11771 Make output statements for any output signal from an /*AUTOINST*/ that
11772 isn't an input to another AUTOINST. This is useful for modules which
11773 only instantiate other modules.
11774
11775 Limitations:
11776 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11777
11778 If placed inside the parenthesis of a module declaration, it creates
11779 Verilog 2001 style, else uses Verilog 1995 style.
11780
11781 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
11782 instantiation, all bets are off. (For example due to an AUTO_TEMPLATE).
11783
11784 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
11785
11786 Types are added to declarations if an AUTOLOGIC or
11787 `verilog-auto-wire-type' is set to logic.
11788
11789 Signals matching `verilog-auto-output-ignore-regexp' are not included.
11790
11791 An example (see `verilog-auto-inst' for what else is going on here):
11792
11793 module ExampOutput (ov,i);
11794 input i;
11795 /*AUTOOUTPUT*/
11796 InstModule instName
11797 (/*AUTOINST*/);
11798 endmodule
11799
11800 Typing \\[verilog-auto] will make this into:
11801
11802 module ExampOutput (ov,i);
11803 input i;
11804 /*AUTOOUTPUT*/
11805 // Beginning of automatic outputs (from unused autoinst outputs)
11806 output [31:0] ov; // From inst of inst.v
11807 // End of automatics
11808 InstModule instName
11809 (/*AUTOINST*/
11810 // Outputs
11811 .ov (ov[31:0]),
11812 // Inputs
11813 .i (i));
11814 endmodule
11815
11816 You may also provide an optional regular expression, in which case only
11817 signals matching the regular expression will be included. For example the
11818 same expansion will result from only extracting outputs starting with ov:
11819
11820 /*AUTOOUTPUT(\"^ov\")*/"
11821 (save-excursion
11822 ;; Point must be at insertion point.
11823 (let* ((indent-pt (current-indentation))
11824 (params (verilog-read-auto-params 0 1))
11825 (regexp (nth 0 params))
11826 (v2k (verilog-in-paren-quick))
11827 (modi (verilog-modi-current))
11828 (moddecls (verilog-modi-get-decls modi))
11829 (modsubdecls (verilog-modi-get-sub-decls modi))
11830 (sig-list (verilog-signals-not-in
11831 (verilog-subdecls-get-outputs modsubdecls)
11832 (append (verilog-decls-get-outputs moddecls)
11833 (verilog-decls-get-inouts moddecls)
11834 (verilog-decls-get-inputs moddecls)
11835 (verilog-subdecls-get-inputs modsubdecls)
11836 (verilog-subdecls-get-inouts modsubdecls)))))
11837 (when regexp
11838 (setq sig-list (verilog-signals-matching-regexp
11839 sig-list regexp)))
11840 (setq sig-list (verilog-signals-not-matching-regexp
11841 sig-list verilog-auto-output-ignore-regexp))
11842 (verilog-forward-or-insert-line)
11843 (when v2k (verilog-repair-open-comma))
11844 (when sig-list
11845 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
11846 (verilog-insert-definition modi sig-list "output" indent-pt v2k)
11847 (verilog-insert-indent "// End of automatics\n"))
11848 (when v2k (verilog-repair-close-comma)))))
11849
11850 (defun verilog-auto-output-every ()
11851 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
11852 Make output statements for any signals that aren't primary inputs or
11853 outputs already. This makes every signal in the design an output. This is
11854 useful to get Synopsys to preserve every signal in the design, since it
11855 won't optimize away the outputs.
11856
11857 An example:
11858
11859 module ExampOutputEvery (o,i,tempa,tempb);
11860 output o;
11861 input i;
11862 /*AUTOOUTPUTEVERY*/
11863 wire tempa = i;
11864 wire tempb = tempa;
11865 wire o = tempb;
11866 endmodule
11867
11868 Typing \\[verilog-auto] will make this into:
11869
11870 module ExampOutputEvery (o,i,tempa,tempb);
11871 output o;
11872 input i;
11873 /*AUTOOUTPUTEVERY*/
11874 // Beginning of automatic outputs (every signal)
11875 output tempb;
11876 output tempa;
11877 // End of automatics
11878 wire tempa = i;
11879 wire tempb = tempa;
11880 wire o = tempb;
11881 endmodule
11882
11883 You may also provide an optional regular expression, in which case only
11884 signals matching the regular expression will be included. For example the
11885 same expansion will result from only extracting outputs starting with ov:
11886
11887 /*AUTOOUTPUTEVERY(\"^ov\")*/"
11888 (save-excursion
11889 ;;Point must be at insertion point
11890 (let* ((indent-pt (current-indentation))
11891 (params (verilog-read-auto-params 0 1))
11892 (regexp (nth 0 params))
11893 (v2k (verilog-in-paren-quick))
11894 (modi (verilog-modi-current))
11895 (moddecls (verilog-modi-get-decls modi))
11896 (sig-list (verilog-signals-combine-bus
11897 (verilog-signals-not-in
11898 (verilog-decls-get-signals moddecls)
11899 (verilog-decls-get-ports moddecls)))))
11900 (when regexp
11901 (setq sig-list (verilog-signals-matching-regexp
11902 sig-list regexp)))
11903 (setq sig-list (verilog-signals-not-matching-regexp
11904 sig-list verilog-auto-output-ignore-regexp))
11905 (verilog-forward-or-insert-line)
11906 (when v2k (verilog-repair-open-comma))
11907 (when sig-list
11908 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
11909 (verilog-insert-definition modi sig-list "output" indent-pt v2k)
11910 (verilog-insert-indent "// End of automatics\n"))
11911 (when v2k (verilog-repair-close-comma)))))
11912
11913 (defun verilog-auto-input ()
11914 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
11915 Make input statements for any input signal into an /*AUTOINST*/ that
11916 isn't declared elsewhere inside the module. This is useful for modules which
11917 only instantiate other modules.
11918
11919 Limitations:
11920 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11921
11922 If placed inside the parenthesis of a module declaration, it creates
11923 Verilog 2001 style, else uses Verilog 1995 style.
11924
11925 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
11926 instantiation, all bets are off. (For example due to an AUTO_TEMPLATE).
11927
11928 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
11929
11930 Types are added to declarations if an AUTOLOGIC or
11931 `verilog-auto-wire-type' is set to logic.
11932
11933 Signals matching `verilog-auto-input-ignore-regexp' are not included.
11934
11935 An example (see `verilog-auto-inst' for what else is going on here):
11936
11937 module ExampInput (ov,i);
11938 output [31:0] ov;
11939 /*AUTOINPUT*/
11940 InstModule instName
11941 (/*AUTOINST*/);
11942 endmodule
11943
11944 Typing \\[verilog-auto] will make this into:
11945
11946 module ExampInput (ov,i);
11947 output [31:0] ov;
11948 /*AUTOINPUT*/
11949 // Beginning of automatic inputs (from unused autoinst inputs)
11950 input i; // From inst of inst.v
11951 // End of automatics
11952 InstModule instName
11953 (/*AUTOINST*/
11954 // Outputs
11955 .ov (ov[31:0]),
11956 // Inputs
11957 .i (i));
11958 endmodule
11959
11960 You may also provide an optional regular expression, in which case only
11961 signals matching the regular expression will be included. For example the
11962 same expansion will result from only extracting inputs starting with i:
11963
11964 /*AUTOINPUT(\"^i\")*/"
11965 (save-excursion
11966 (let* ((indent-pt (current-indentation))
11967 (params (verilog-read-auto-params 0 1))
11968 (regexp (nth 0 params))
11969 (v2k (verilog-in-paren-quick))
11970 (modi (verilog-modi-current))
11971 (moddecls (verilog-modi-get-decls modi))
11972 (modsubdecls (verilog-modi-get-sub-decls modi))
11973 (sig-list (verilog-signals-not-in
11974 (verilog-subdecls-get-inputs modsubdecls)
11975 (append (verilog-decls-get-inputs moddecls)
11976 (verilog-decls-get-inouts moddecls)
11977 (verilog-decls-get-outputs moddecls)
11978 (verilog-decls-get-vars moddecls)
11979 (verilog-decls-get-consts moddecls)
11980 (verilog-decls-get-gparams moddecls)
11981 (verilog-subdecls-get-interfaced modsubdecls)
11982 (verilog-subdecls-get-outputs modsubdecls)
11983 (verilog-subdecls-get-inouts modsubdecls)))))
11984 (when regexp
11985 (setq sig-list (verilog-signals-matching-regexp
11986 sig-list regexp)))
11987 (setq sig-list (verilog-signals-not-matching-regexp
11988 sig-list verilog-auto-input-ignore-regexp))
11989 (verilog-forward-or-insert-line)
11990 (when v2k (verilog-repair-open-comma))
11991 (when sig-list
11992 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
11993 (verilog-insert-definition modi sig-list "input" indent-pt v2k)
11994 (verilog-insert-indent "// End of automatics\n"))
11995 (when v2k (verilog-repair-close-comma)))))
11996
11997 (defun verilog-auto-inout ()
11998 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
11999 Make inout statements for any inout signal in an /*AUTOINST*/ that
12000 isn't declared elsewhere inside the module.
12001
12002 Limitations:
12003 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
12004
12005 If placed inside the parenthesis of a module declaration, it creates
12006 Verilog 2001 style, else uses Verilog 1995 style.
12007
12008 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
12009 instantiation, all bets are off. (For example due to an AUTO_TEMPLATE).
12010
12011 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
12012
12013 Types are added to declarations if an AUTOLOGIC or
12014 `verilog-auto-wire-type' is set to logic.
12015
12016 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
12017
12018 An example (see `verilog-auto-inst' for what else is going on here):
12019
12020 module ExampInout (ov,i);
12021 input i;
12022 /*AUTOINOUT*/
12023 InstModule instName
12024 (/*AUTOINST*/);
12025 endmodule
12026
12027 Typing \\[verilog-auto] will make this into:
12028
12029 module ExampInout (ov,i);
12030 input i;
12031 /*AUTOINOUT*/
12032 // Beginning of automatic inouts (from unused autoinst inouts)
12033 inout [31:0] ov; // From inst of inst.v
12034 // End of automatics
12035 InstModule instName
12036 (/*AUTOINST*/
12037 // Inouts
12038 .ov (ov[31:0]),
12039 // Inputs
12040 .i (i));
12041 endmodule
12042
12043 You may also provide an optional regular expression, in which case only
12044 signals matching the regular expression will be included. For example the
12045 same expansion will result from only extracting inouts starting with i:
12046
12047 /*AUTOINOUT(\"^i\")*/"
12048 (save-excursion
12049 ;; Point must be at insertion point.
12050 (let* ((indent-pt (current-indentation))
12051 (params (verilog-read-auto-params 0 1))
12052 (regexp (nth 0 params))
12053 (v2k (verilog-in-paren-quick))
12054 (modi (verilog-modi-current))
12055 (moddecls (verilog-modi-get-decls modi))
12056 (modsubdecls (verilog-modi-get-sub-decls modi))
12057 (sig-list (verilog-signals-not-in
12058 (verilog-subdecls-get-inouts modsubdecls)
12059 (append (verilog-decls-get-outputs moddecls)
12060 (verilog-decls-get-inouts moddecls)
12061 (verilog-decls-get-inputs moddecls)
12062 (verilog-subdecls-get-inputs modsubdecls)
12063 (verilog-subdecls-get-outputs modsubdecls)))))
12064 (when regexp
12065 (setq sig-list (verilog-signals-matching-regexp
12066 sig-list regexp)))
12067 (setq sig-list (verilog-signals-not-matching-regexp
12068 sig-list verilog-auto-inout-ignore-regexp))
12069 (verilog-forward-or-insert-line)
12070 (when v2k (verilog-repair-open-comma))
12071 (when sig-list
12072 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
12073 (verilog-insert-definition modi sig-list "inout" indent-pt v2k)
12074 (verilog-insert-indent "// End of automatics\n"))
12075 (when v2k (verilog-repair-close-comma)))))
12076
12077 (defun verilog-auto-inout-module (&optional complement all-in)
12078 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
12079 Take input/output/inout statements from the specified module and insert
12080 into the current module. This is useful for making null templates and
12081 shell modules which need to have identical I/O with another module.
12082 Any I/O which are already defined in this module will not be redefined.
12083 For the complement of this function, see `verilog-auto-inout-comp',
12084 and to make monitors with all inputs, see `verilog-auto-inout-in'.
12085
12086 Limitations:
12087 If placed inside the parenthesis of a module declaration, it creates
12088 Verilog 2001 style, else uses Verilog 1995 style.
12089
12090 Concatenation and outputting partial buses is not supported.
12091
12092 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12093
12094 Signals are not inserted in the same order as in the original module,
12095 though they will appear to be in the same order to an AUTOINST
12096 instantiating either module.
12097
12098 Signals declared as \"output reg\" or \"output wire\" etc will
12099 lose the wire/reg declaration so that shell modules may
12100 generate those outputs differently. However, \"output logic\"
12101 is propagated.
12102
12103 An example:
12104
12105 module ExampShell (/*AUTOARG*/);
12106 /*AUTOINOUTMODULE(\"ExampMain\")*/
12107 endmodule
12108
12109 module ExampMain (i,o,io);
12110 input i;
12111 output o;
12112 inout io;
12113 endmodule
12114
12115 Typing \\[verilog-auto] will make this into:
12116
12117 module ExampShell (/*AUTOARG*/i,o,io);
12118 /*AUTOINOUTMODULE(\"ExampMain\")*/
12119 // Beginning of automatic in/out/inouts (from specific module)
12120 output o;
12121 inout io;
12122 input i;
12123 // End of automatics
12124 endmodule
12125
12126 You may also provide an optional regular expression, in which case only
12127 signals matching the regular expression will be included. For example the
12128 same expansion will result from only extracting signals starting with i:
12129
12130 /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/
12131
12132 You may also provide an optional third argument regular
12133 expression, in which case only signals which have that pin
12134 direction and data type matching that regular expression will be
12135 included. This matches against everything before the signal name
12136 in the declaration, for example against \"input\" (single bit),
12137 \"output logic\" (direction and type) or \"output
12138 [1:0]\" (direction and implicit type). You also probably want to
12139 skip spaces in your regexp.
12140
12141 For example, the below will result in matching the output \"o\"
12142 against the previous example's module:
12143
12144 /*AUTOINOUTMODULE(\"ExampMain\",\"\",\"^output.*\")*/"
12145 (save-excursion
12146 (let* ((params (verilog-read-auto-params 1 3))
12147 (submod (nth 0 params))
12148 (regexp (nth 1 params))
12149 (direction-re (nth 2 params))
12150 submodi)
12151 ;; Lookup position, etc of co-module
12152 ;; Note this may raise an error
12153 (when (setq submodi (verilog-modi-lookup submod t))
12154 (let* ((indent-pt (current-indentation))
12155 (v2k (verilog-in-paren-quick))
12156 (modi (verilog-modi-current))
12157 (moddecls (verilog-modi-get-decls modi))
12158 (submoddecls (verilog-modi-get-decls submodi))
12159 (sig-list-i (verilog-signals-not-in
12160 (cond (all-in
12161 (append
12162 (verilog-decls-get-inputs submoddecls)
12163 (verilog-decls-get-inouts submoddecls)
12164 (verilog-decls-get-outputs submoddecls)))
12165 (complement
12166 (verilog-decls-get-outputs submoddecls))
12167 (t (verilog-decls-get-inputs submoddecls)))
12168 (append (verilog-decls-get-inputs moddecls))))
12169 (sig-list-o (verilog-signals-not-in
12170 (cond (all-in nil)
12171 (complement
12172 (verilog-decls-get-inputs submoddecls))
12173 (t (verilog-decls-get-outputs submoddecls)))
12174 (append (verilog-decls-get-outputs moddecls))))
12175 (sig-list-io (verilog-signals-not-in
12176 (cond (all-in nil)
12177 (t (verilog-decls-get-inouts submoddecls)))
12178 (append (verilog-decls-get-inouts moddecls))))
12179 (sig-list-if (verilog-signals-not-in
12180 (verilog-decls-get-interfaces submoddecls)
12181 (append (verilog-decls-get-interfaces moddecls)))))
12182 (forward-line 1)
12183 (setq sig-list-i (verilog-signals-edit-wire-reg
12184 (verilog-signals-matching-dir-re
12185 (verilog-signals-matching-regexp sig-list-i regexp)
12186 "input" direction-re))
12187 sig-list-o (verilog-signals-edit-wire-reg
12188 (verilog-signals-matching-dir-re
12189 (verilog-signals-matching-regexp sig-list-o regexp)
12190 "output" direction-re))
12191 sig-list-io (verilog-signals-edit-wire-reg
12192 (verilog-signals-matching-dir-re
12193 (verilog-signals-matching-regexp sig-list-io regexp)
12194 "inout" direction-re))
12195 sig-list-if (verilog-signals-matching-dir-re
12196 (verilog-signals-matching-regexp sig-list-if regexp)
12197 "interface" direction-re))
12198 (when v2k (verilog-repair-open-comma))
12199 (when (or sig-list-i sig-list-o sig-list-io sig-list-if)
12200 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
12201 ;; Don't sort them so an upper AUTOINST will match the main module
12202 (verilog-insert-definition modi sig-list-o "output" indent-pt v2k t)
12203 (verilog-insert-definition modi sig-list-io "inout" indent-pt v2k t)
12204 (verilog-insert-definition modi sig-list-i "input" indent-pt v2k t)
12205 (verilog-insert-definition modi sig-list-if "interface" indent-pt v2k t)
12206 (verilog-insert-indent "// End of automatics\n"))
12207 (when v2k (verilog-repair-close-comma)))))))
12208
12209 (defun verilog-auto-inout-comp ()
12210 "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
12211 Take input/output/inout statements from the specified module and
12212 insert the inverse into the current module (inputs become outputs
12213 and vice-versa.) This is useful for making test and stimulus
12214 modules which need to have complementing I/O with another module.
12215 Any I/O which are already defined in this module will not be
12216 redefined. For the complement of this function, see
12217 `verilog-auto-inout-module'.
12218
12219 Limitations:
12220 If placed inside the parenthesis of a module declaration, it creates
12221 Verilog 2001 style, else uses Verilog 1995 style.
12222
12223 Concatenation and outputting partial buses is not supported.
12224
12225 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12226
12227 Signals are not inserted in the same order as in the original module,
12228 though they will appear to be in the same order to an AUTOINST
12229 instantiating either module.
12230
12231 An example:
12232
12233 module ExampShell (/*AUTOARG*/);
12234 /*AUTOINOUTCOMP(\"ExampMain\")*/
12235 endmodule
12236
12237 module ExampMain (i,o,io);
12238 input i;
12239 output o;
12240 inout io;
12241 endmodule
12242
12243 Typing \\[verilog-auto] will make this into:
12244
12245 module ExampShell (/*AUTOARG*/i,o,io);
12246 /*AUTOINOUTCOMP(\"ExampMain\")*/
12247 // Beginning of automatic in/out/inouts (from specific module)
12248 output i;
12249 inout io;
12250 input o;
12251 // End of automatics
12252 endmodule
12253
12254 You may also provide an optional regular expression, in which case only
12255 signals matching the regular expression will be included. For example the
12256 same expansion will result from only extracting signals starting with i:
12257
12258 /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/
12259
12260 You may also provide an optional third argument regular
12261 expression, in which case only signals which have that pin
12262 direction and data type matching that regular expression will be
12263 included. This matches against everything before the signal name
12264 in the declaration, for example against \"input\" (single bit),
12265 \"output logic\" (direction and type) or \"output
12266 [1:0]\" (direction and implicit type). You also probably want to
12267 skip spaces in your regexp.
12268
12269 For example, the below will result in matching the output \"o\"
12270 against the previous example's module:
12271
12272 /*AUTOINOUTCOMP(\"ExampMain\",\"\",\"^output.*\")*/"
12273 (verilog-auto-inout-module t nil))
12274
12275 (defun verilog-auto-inout-in ()
12276 "Expand AUTOINOUTIN statements, as part of \\[verilog-auto].
12277 Take input/output/inout statements from the specified module and
12278 insert them as all inputs into the current module. This is
12279 useful for making monitor modules which need to see all signals
12280 as inputs based on another module. Any I/O which are already
12281 defined in this module will not be redefined. See also
12282 `verilog-auto-inout-module'.
12283
12284 Limitations:
12285 If placed inside the parenthesis of a module declaration, it creates
12286 Verilog 2001 style, else uses Verilog 1995 style.
12287
12288 Concatenation and outputting partial buses is not supported.
12289
12290 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12291
12292 Signals are not inserted in the same order as in the original module,
12293 though they will appear to be in the same order to an AUTOINST
12294 instantiating either module.
12295
12296 An example:
12297
12298 module ExampShell (/*AUTOARG*/);
12299 /*AUTOINOUTIN(\"ExampMain\")*/
12300 endmodule
12301
12302 module ExampMain (i,o,io);
12303 input i;
12304 output o;
12305 inout io;
12306 endmodule
12307
12308 Typing \\[verilog-auto] will make this into:
12309
12310 module ExampShell (/*AUTOARG*/i,o,io);
12311 /*AUTOINOUTIN(\"ExampMain\")*/
12312 // Beginning of automatic in/out/inouts (from specific module)
12313 input i;
12314 input io;
12315 input o;
12316 // End of automatics
12317 endmodule
12318
12319 You may also provide an optional regular expression, in which case only
12320 signals matching the regular expression will be included. For example the
12321 same expansion will result from only extracting signals starting with i:
12322
12323 /*AUTOINOUTIN(\"ExampMain\",\"^i\")*/"
12324 (verilog-auto-inout-module nil t))
12325
12326 (defun verilog-auto-inout-param ()
12327 "Expand AUTOINOUTPARAM statements, as part of \\[verilog-auto].
12328 Take input/output/inout statements from the specified module and insert
12329 into the current module. This is useful for making null templates and
12330 shell modules which need to have identical I/O with another module.
12331 Any I/O which are already defined in this module will not be redefined.
12332 For the complement of this function, see `verilog-auto-inout-comp',
12333 and to make monitors with all inputs, see `verilog-auto-inout-in'.
12334
12335 Limitations:
12336 If placed inside the parenthesis of a module declaration, it creates
12337 Verilog 2001 style, else uses Verilog 1995 style.
12338
12339 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12340
12341 Parameters are inserted in the same order as in the original module.
12342
12343 Parameters do not have values, which is SystemVerilog 2009 syntax.
12344
12345 An example:
12346
12347 module ExampShell ();
12348 /*AUTOINOUTPARAM(\"ExampMain\")*/
12349 endmodule
12350
12351 module ExampMain ();
12352 parameter PARAM = 22;
12353 endmodule
12354
12355 Typing \\[verilog-auto] will make this into:
12356
12357 module ExampShell (/*AUTOARG*/i,o,io);
12358 /*AUTOINOUTPARAM(\"ExampMain\")*/
12359 // Beginning of automatic parameters (from specific module)
12360 parameter PARAM;
12361 // End of automatics
12362 endmodule
12363
12364 You may also provide an optional regular expression, in which case only
12365 parameters matching the regular expression will be included. For example the
12366 same expansion will result from only extracting parameters starting with i:
12367
12368 /*AUTOINOUTPARAM(\"ExampMain\",\"^i\")*/"
12369 (save-excursion
12370 (let* ((params (verilog-read-auto-params 1 2))
12371 (submod (nth 0 params))
12372 (regexp (nth 1 params))
12373 submodi)
12374 ;; Lookup position, etc of co-module
12375 ;; Note this may raise an error
12376 (when (setq submodi (verilog-modi-lookup submod t))
12377 (let* ((indent-pt (current-indentation))
12378 (v2k (verilog-in-paren-quick))
12379 (modi (verilog-modi-current))
12380 (moddecls (verilog-modi-get-decls modi))
12381 (submoddecls (verilog-modi-get-decls submodi))
12382 (sig-list-p (verilog-signals-not-in
12383 (verilog-decls-get-gparams submoddecls)
12384 (append (verilog-decls-get-gparams moddecls)))))
12385 (forward-line 1)
12386 (setq sig-list-p (verilog-signals-matching-regexp sig-list-p regexp))
12387 (when v2k (verilog-repair-open-comma))
12388 (when sig-list-p
12389 (verilog-insert-indent "// Beginning of automatic parameters (from specific module)\n")
12390 ;; Don't sort them so an upper AUTOINST will match the main module
12391 (verilog-insert-definition modi sig-list-p "parameter" indent-pt v2k t)
12392 (verilog-insert-indent "// End of automatics\n"))
12393 (when v2k (verilog-repair-close-comma)))))))
12394
12395 (defun verilog-auto-inout-modport ()
12396 "Expand AUTOINOUTMODPORT statements, as part of \\[verilog-auto].
12397 Take input/output/inout statements from the specified interface
12398 and modport and insert into the current module. This is useful
12399 for making verification modules that connect to UVM interfaces.
12400
12401 The first parameter is the name of an interface.
12402
12403 The second parameter is a regexp of modports to read from in
12404 that interface.
12405
12406 The optional third parameter is a regular expression, and only
12407 signals matching the regular expression will be included.
12408
12409 Limitations:
12410 If placed inside the parenthesis of a module declaration, it creates
12411 Verilog 2001 style, else uses Verilog 1995 style.
12412
12413 Interface names must be resolvable to filenames. See `verilog-auto-inst'.
12414
12415 As with other autos, any inputs/outputs declared in the module
12416 will suppress the AUTO from redeclaring an inputs/outputs by
12417 the same name.
12418
12419 An example:
12420
12421 interface ExampIf
12422 ( input logic clk );
12423 logic req_val;
12424 logic [7:0] req_dat;
12425 clocking mon_clkblk @(posedge clk);
12426 input req_val;
12427 input req_dat;
12428 endclocking
12429 modport mp(clocking mon_clkblk);
12430 endinterface
12431
12432 module ExampMain
12433 ( input clk,
12434 /*AUTOINOUTMODPORT(\"ExampIf\" \"mp\")*/
12435 // Beginning of automatic in/out/inouts (from modport)
12436 input [7:0] req_dat,
12437 input req_val
12438 // End of automatics
12439 );
12440 /*AUTOASSIGNMODPORT(\"ExampIf\" \"mp\")*/
12441 endmodule
12442
12443 Typing \\[verilog-auto] will make this into:
12444
12445 ...
12446 module ExampMain
12447 ( input clk,
12448 /*AUTOINOUTMODPORT(\"ExampIf\" \"mp\")*/
12449 // Beginning of automatic in/out/inouts (from modport)
12450 input req_dat,
12451 input req_val
12452 // End of automatics
12453 );
12454
12455 If the modport is part of a UVM monitor/driver class, this
12456 creates a wrapper module that may be used to instantiate the
12457 driver/monitor using AUTOINST in the testbench."
12458 (save-excursion
12459 (let* ((params (verilog-read-auto-params 2 3))
12460 (submod (nth 0 params))
12461 (modport-re (nth 1 params))
12462 (regexp (nth 2 params))
12463 direction-re submodi) ;; direction argument not supported until requested
12464 ;; Lookup position, etc of co-module
12465 ;; Note this may raise an error
12466 (when (setq submodi (verilog-modi-lookup submod t))
12467 (let* ((indent-pt (current-indentation))
12468 (v2k (verilog-in-paren-quick))
12469 (modi (verilog-modi-current))
12470 (moddecls (verilog-modi-get-decls modi))
12471 (submoddecls (verilog-modi-get-decls submodi))
12472 (submodportdecls (verilog-modi-modport-lookup submodi modport-re))
12473 (sig-list-i (verilog-signals-in ;; Decls doesn't have data types, must resolve
12474 (verilog-decls-get-vars submoddecls)
12475 (verilog-signals-not-in
12476 (verilog-decls-get-inputs submodportdecls)
12477 (append (verilog-decls-get-ports submoddecls)
12478 (verilog-decls-get-ports moddecls)))))
12479 (sig-list-o (verilog-signals-in ;; Decls doesn't have data types, must resolve
12480 (verilog-decls-get-vars submoddecls)
12481 (verilog-signals-not-in
12482 (verilog-decls-get-outputs submodportdecls)
12483 (append (verilog-decls-get-ports submoddecls)
12484 (verilog-decls-get-ports moddecls)))))
12485 (sig-list-io (verilog-signals-in ;; Decls doesn't have data types, must resolve
12486 (verilog-decls-get-vars submoddecls)
12487 (verilog-signals-not-in
12488 (verilog-decls-get-inouts submodportdecls)
12489 (append (verilog-decls-get-ports submoddecls)
12490 (verilog-decls-get-ports moddecls))))))
12491 (forward-line 1)
12492 (setq sig-list-i (verilog-signals-edit-wire-reg
12493 (verilog-signals-matching-dir-re
12494 (verilog-signals-matching-regexp sig-list-i regexp)
12495 "input" direction-re))
12496 sig-list-o (verilog-signals-edit-wire-reg
12497 (verilog-signals-matching-dir-re
12498 (verilog-signals-matching-regexp sig-list-o regexp)
12499 "output" direction-re))
12500 sig-list-io (verilog-signals-edit-wire-reg
12501 (verilog-signals-matching-dir-re
12502 (verilog-signals-matching-regexp sig-list-io regexp)
12503 "inout" direction-re)))
12504 (when v2k (verilog-repair-open-comma))
12505 (when (or sig-list-i sig-list-o sig-list-io)
12506 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from modport)\n")
12507 ;; Don't sort them so an upper AUTOINST will match the main module
12508 (verilog-insert-definition modi sig-list-o "output" indent-pt v2k t)
12509 (verilog-insert-definition modi sig-list-io "inout" indent-pt v2k t)
12510 (verilog-insert-definition modi sig-list-i "input" indent-pt v2k t)
12511 (verilog-insert-indent "// End of automatics\n"))
12512 (when v2k (verilog-repair-close-comma)))))))
12513
12514 (defun verilog-auto-insert-lisp ()
12515 "Expand AUTOINSERTLISP statements, as part of \\[verilog-auto].
12516 The Lisp code provided is called before other AUTOS are expanded,
12517 and the Lisp code generally will call `insert` to insert text
12518 into the current file beginning on the line after the
12519 AUTOINSERTLISP.
12520
12521 See also AUTOINSERTLAST and `verilog-auto-insert-last' which
12522 executes after (as opposed to before) other AUTOs.
12523
12524 See also AUTO_LISP, which takes a Lisp expression and evaluates
12525 it during `verilog-auto-inst' but does not insert any text.
12526
12527 An example:
12528
12529 module ExampInsertLisp;
12530 /*AUTOINSERTLISP(my-verilog-insert-hello \"world\")*/
12531 endmodule
12532
12533 // For this example we declare the function in the
12534 // module's file itself. Often you'd define it instead
12535 // in a site-start.el or init file.
12536 /*
12537 Local Variables:
12538 eval:
12539 (defun my-verilog-insert-hello (who)
12540 (insert (concat \"initial $write(\\\"hello \" who \"\\\");\\n\")))
12541 End:
12542 */
12543
12544 Typing \\[verilog-auto] will call my-verilog-insert-hello and
12545 expand the above into:
12546
12547 // Beginning of automatic insert lisp
12548 initial $write(\"hello world\");
12549 // End of automatics
12550
12551 You can also call an external program and insert the returned
12552 text:
12553
12554 /*AUTOINSERTLISP(insert (shell-command-to-string \"echo //hello\"))*/
12555 // Beginning of automatic insert lisp
12556 //hello
12557 // End of automatics"
12558 (save-excursion
12559 ;; Point is at end of /*AUTO...*/
12560 (let* ((indent-pt (current-indentation))
12561 (cmd-end-pt (save-excursion (search-backward ")")
12562 (forward-char)
12563 (point))) ;; Closing paren
12564 (cmd-beg-pt (save-excursion (goto-char cmd-end-pt)
12565 (backward-sexp 1) ;; Inside comment
12566 (point))) ;; Beginning paren
12567 (cmd (buffer-substring-no-properties cmd-beg-pt cmd-end-pt)))
12568 (verilog-forward-or-insert-line)
12569 ;; Some commands don't move point (like insert-file) so we always
12570 ;; add the begin/end comments, then delete it if not needed
12571 (verilog-insert-indent "// Beginning of automatic insert lisp\n")
12572 (verilog-insert-indent "// End of automatics\n")
12573 (forward-line -1)
12574 (eval (read cmd))
12575 (forward-line -1)
12576 (setq verilog-scan-cache-tick nil) ;; Clear cache; inserted unknown text
12577 (verilog-delete-empty-auto-pair))))
12578
12579 (defun verilog-auto-insert-last ()
12580 "Expand AUTOINSERTLAST statements, as part of \\[verilog-auto].
12581 The Lisp code provided is called after all other AUTOS have been
12582 expanded, and the Lisp code generally will call `insert` to
12583 insert text into the current file beginning on the line after the
12584 AUTOINSERTLAST.
12585
12586 Other than when called (after AUTOs are expanded), the functionality
12587 is otherwise identical to AUTOINSERTLISP and `verilog-auto-insert-lisp' which
12588 executes before (as opposed to after) other AUTOs.
12589
12590 See `verilog-auto-insert-lisp' for examples."
12591 (verilog-auto-insert-lisp))
12592
12593 (defun verilog-auto-sense-sigs (moddecls presense-sigs)
12594 "Return list of signals for current AUTOSENSE block."
12595 (let* ((sigss (save-excursion
12596 (search-forward ")")
12597 (verilog-read-always-signals)))
12598 (sig-list (verilog-signals-not-params
12599 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
12600 (append (and (not verilog-auto-sense-include-inputs)
12601 (verilog-alw-get-outputs-delayed sigss))
12602 (and (not verilog-auto-sense-include-inputs)
12603 (verilog-alw-get-outputs-immediate sigss))
12604 (verilog-alw-get-temps sigss)
12605 (verilog-decls-get-consts moddecls)
12606 (verilog-decls-get-gparams moddecls)
12607 presense-sigs)))))
12608 sig-list))
12609
12610 (defun verilog-auto-sense ()
12611 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
12612 Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
12613 with one automatically derived from all inputs declared in the always
12614 statement. Signals that are generated within the same always block are NOT
12615 placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
12616 Long lines are split based on the `fill-column', see \\[set-fill-column].
12617
12618 Limitations:
12619 Verilog does not allow memories (multidimensional arrays) in sensitivity
12620 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
12621
12622 Constant signals:
12623 AUTOSENSE cannot always determine if a `define is a constant or a signal
12624 (it could be in an include file for example). If a `define or other signal
12625 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
12626 declaration anywhere in the module (parenthesis are required):
12627
12628 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
12629
12630 Better yet, use a parameter, which will be understood to be constant
12631 automatically.
12632
12633 OOps!
12634 If AUTOSENSE makes a mistake, please report it. (First try putting
12635 a begin/end after your always!) As a workaround, if a signal that
12636 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
12637 If a signal should be in the sensitivity list wasn't, placing it before
12638 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
12639 autos are updated (or added if it occurs there already).
12640
12641 An example:
12642
12643 always @ (/*AS*/) begin
12644 /* AUTO_CONSTANT (`constant) */
12645 outin = ina | inb | `constant;
12646 out = outin;
12647 end
12648
12649 Typing \\[verilog-auto] will make this into:
12650
12651 always @ (/*AS*/ina or inb) begin
12652 /* AUTO_CONSTANT (`constant) */
12653 outin = ina | inb | `constant;
12654 out = outin;
12655 end
12656
12657 Note in Verilog 2001, you can often get the same result from the new @*
12658 operator. (This was added to the language in part due to AUTOSENSE!)
12659
12660 always @* begin
12661 outin = ina | inb | `constant;
12662 out = outin;
12663 end"
12664 (save-excursion
12665 ;; Find beginning
12666 (let* ((start-pt (save-excursion
12667 (verilog-re-search-backward-quick "(" nil t)
12668 (point)))
12669 (indent-pt (save-excursion
12670 (or (and (goto-char start-pt) (1+ (current-column)))
12671 (current-indentation))))
12672 (modi (verilog-modi-current))
12673 (moddecls (verilog-modi-get-decls modi))
12674 (sig-memories (verilog-signals-memory
12675 (verilog-decls-get-vars moddecls)))
12676 sig-list not-first presense-sigs)
12677 ;; Read signals in always, eliminate outputs from sense list
12678 (setq presense-sigs (verilog-signals-from-signame
12679 (save-excursion
12680 (verilog-read-signals start-pt (point)))))
12681 (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
12682 (when sig-memories
12683 (let ((tlen (length sig-list)))
12684 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
12685 (if (not (eq tlen (length sig-list))) (verilog-insert " /*memory or*/ "))))
12686 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
12687 (save-excursion (goto-char (point))
12688 (verilog-re-search-backward-quick "[a-zA-Z0-9$_.%`]+" start-pt t)
12689 (verilog-re-search-backward-quick "\\s-" start-pt t)
12690 (while (looking-at "\\s-`endif")
12691 (verilog-re-search-backward-quick "[a-zA-Z0-9$_.%`]+" start-pt t)
12692 (verilog-re-search-backward-quick "\\s-" start-pt t))
12693 (not (looking-at "\\s-or\\b"))))
12694 (setq not-first t))
12695 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
12696 (while sig-list
12697 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
12698 (insert "\n")
12699 (indent-to indent-pt)
12700 (if not-first (insert "or ")))
12701 (not-first (insert " or ")))
12702 (insert (verilog-sig-name (car sig-list)))
12703 (setq sig-list (cdr sig-list)
12704 not-first t)))))
12705
12706 (defun verilog-auto-reset ()
12707 "Expand AUTORESET statements, as part of \\[verilog-auto].
12708 Replace the /*AUTORESET*/ comment with code to initialize all
12709 registers set elsewhere in the always block.
12710
12711 Limitations:
12712 AUTORESET will not clear memories.
12713
12714 AUTORESET uses <= if the signal has a <= assignment in the block,
12715 else it uses =.
12716
12717 If <= is used, all = assigned variables are ignored if
12718 `verilog-auto-reset-blocking-in-non' is nil; they are presumed
12719 to be temporaries.
12720
12721 /*AUTORESET*/ presumes that any signals mentioned between the previous
12722 begin/case/if statement and the AUTORESET comment are being reset manually
12723 and should not be automatically reset. This includes omitting any signals
12724 used on the right hand side of assignments.
12725
12726 By default, AUTORESET will include the width of the signal in the
12727 autos, SystemVerilog designs may want to change this. To control
12728 this behavior, see `verilog-auto-reset-widths'. In some cases
12729 AUTORESET must use a '0 assignment and it will print NOWIDTH; use
12730 `verilog-auto-reset-widths' unbased to prevent this.
12731
12732 AUTORESET ties signals to deasserted, which is presumed to be zero.
12733 Signals that match `verilog-active-low-regexp' will be deasserted by tying
12734 them to a one.
12735
12736 AUTORESET may try to reset arrays or structures that cannot be
12737 reset by a simple assignment, resulting in compile errors. This
12738 is a feature to be taken as a hint that you need to reset these
12739 signals manually (or put them into a \"`ifdef NEVER signal<=`0;
12740 `endif\" so Verilog-Mode ignores them.)
12741
12742 An example:
12743
12744 always @(posedge clk or negedge reset_l) begin
12745 if (!reset_l) begin
12746 c <= 1;
12747 /*AUTORESET*/
12748 end
12749 else begin
12750 a <= in_a;
12751 b <= in_b;
12752 c <= in_c;
12753 end
12754 end
12755
12756 Typing \\[verilog-auto] will make this into:
12757
12758 always @(posedge core_clk or negedge reset_l) begin
12759 if (!reset_l) begin
12760 c <= 1;
12761 /*AUTORESET*/
12762 // Beginning of autoreset for uninitialized flops
12763 a <= 0;
12764 b = 0; // if `verilog-auto-reset-blocking-in-non' true
12765 // End of automatics
12766 end
12767 else begin
12768 a <= in_a;
12769 b = in_b;
12770 c <= in_c;
12771 end
12772 end"
12773
12774 (interactive)
12775 (save-excursion
12776 ;; Find beginning
12777 (let* ((indent-pt (current-indentation))
12778 (modi (verilog-modi-current))
12779 (moddecls (verilog-modi-get-decls modi))
12780 (all-list (verilog-decls-get-signals moddecls))
12781 sigss sig-list dly-list prereset-sigs)
12782 ;; Read signals in always, eliminate outputs from reset list
12783 (setq prereset-sigs (verilog-signals-from-signame
12784 (save-excursion
12785 (verilog-read-signals
12786 (save-excursion
12787 (verilog-re-search-backward-quick
12788 "\\(@\\|\\<\\(begin\\|if\\|case\\|always\\(_latch\\|_ff\\|_comb\\)?\\)\\>\\)" nil t)
12789 (point))
12790 (point)))))
12791 (save-excursion
12792 (verilog-re-search-backward-quick "\\(@\\|\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\)\\>\\)" nil t)
12793 (setq sigss (verilog-read-always-signals)))
12794 (setq dly-list (verilog-alw-get-outputs-delayed sigss))
12795 (setq sig-list (verilog-signals-not-in (append
12796 (verilog-alw-get-outputs-delayed sigss)
12797 (when (or (not (verilog-alw-get-uses-delayed sigss))
12798 verilog-auto-reset-blocking-in-non)
12799 (verilog-alw-get-outputs-immediate sigss)))
12800 (append
12801 (verilog-alw-get-temps sigss)
12802 prereset-sigs)))
12803 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
12804 (when sig-list
12805 (insert "\n");
12806 (verilog-insert-indent "// Beginning of autoreset for uninitialized flops\n");
12807 (while sig-list
12808 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
12809 (car sig-list))))
12810 (indent-to indent-pt)
12811 (insert (verilog-sig-name sig)
12812 (if (assoc (verilog-sig-name sig) dly-list)
12813 (concat " <= " verilog-assignment-delay)
12814 " = ")
12815 (verilog-sig-tieoff sig)
12816 ";\n")
12817 (setq sig-list (cdr sig-list))))
12818 (verilog-insert-indent "// End of automatics")))))
12819
12820 (defun verilog-auto-tieoff ()
12821 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
12822 Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
12823 signals to deasserted.
12824
12825 /*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
12826 input/output list as another module, but no internals. Specifically, it
12827 finds all outputs in the module, and if that input is not otherwise declared
12828 as a register or wire, creates a tieoff.
12829
12830 AUTORESET ties signals to deasserted, which is presumed to be zero.
12831 Signals that match `verilog-active-low-regexp' will be deasserted by tying
12832 them to a one.
12833
12834 You can add signals you do not want included in AUTOTIEOFF with
12835 `verilog-auto-tieoff-ignore-regexp'.
12836
12837 `verilog-auto-wire-type' may be used to change the datatype of
12838 the declarations.
12839
12840 `verilog-auto-reset-widths' may be used to change how the tieoff
12841 value's width is generated.
12842
12843 An example of making a stub for another module:
12844
12845 module ExampStub (/*AUTOINST*/);
12846 /*AUTOINOUTPARAM(\"Foo\")*/
12847 /*AUTOINOUTMODULE(\"Foo\")*/
12848 /*AUTOTIEOFF*/
12849 // verilator lint_off UNUSED
12850 wire _unused_ok = &{1'b0,
12851 /*AUTOUNUSED*/
12852 1'b0};
12853 // verilator lint_on UNUSED
12854 endmodule
12855
12856 Typing \\[verilog-auto] will make this into:
12857
12858 module ExampStub (/*AUTOINST*/...);
12859 /*AUTOINOUTPARAM(\"Foo\")*/
12860 /*AUTOINOUTMODULE(\"Foo\")*/
12861 // Beginning of autotieoff
12862 output [2:0] foo;
12863 // End of automatics
12864
12865 /*AUTOTIEOFF*/
12866 // Beginning of autotieoff
12867 wire [2:0] foo = 3'b0;
12868 // End of automatics
12869 ...
12870 endmodule"
12871 (interactive)
12872 (save-excursion
12873 ;; Find beginning
12874 (let* ((indent-pt (current-indentation))
12875 (modi (verilog-modi-current))
12876 (moddecls (verilog-modi-get-decls modi))
12877 (modsubdecls (verilog-modi-get-sub-decls modi))
12878 (sig-list (verilog-signals-not-in
12879 (verilog-decls-get-outputs moddecls)
12880 (append (verilog-decls-get-vars moddecls)
12881 (verilog-decls-get-assigns moddecls)
12882 (verilog-decls-get-consts moddecls)
12883 (verilog-decls-get-gparams moddecls)
12884 (verilog-subdecls-get-interfaced modsubdecls)
12885 (verilog-subdecls-get-outputs modsubdecls)
12886 (verilog-subdecls-get-inouts modsubdecls)))))
12887 (setq sig-list (verilog-signals-not-matching-regexp
12888 sig-list verilog-auto-tieoff-ignore-regexp))
12889 (when sig-list
12890 (verilog-forward-or-insert-line)
12891 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
12892 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
12893 (verilog-modi-cache-add-vars modi sig-list) ; Before we trash list
12894 (while sig-list
12895 (let ((sig (car sig-list)))
12896 (cond ((equal verilog-auto-tieoff-declaration "assign")
12897 (indent-to indent-pt)
12898 (insert "assign " (verilog-sig-name sig)))
12899 (t
12900 (verilog-insert-one-definition sig verilog-auto-tieoff-declaration indent-pt)))
12901 (indent-to (max 48 (+ indent-pt 40)))
12902 (insert "= " (verilog-sig-tieoff sig)
12903 ";\n")
12904 (setq sig-list (cdr sig-list))))
12905 (verilog-insert-indent "// End of automatics\n")))))
12906
12907 (defun verilog-auto-undef ()
12908 "Expand AUTOUNDEF statements, as part of \\[verilog-auto].
12909 Take any `defines since the last AUTOUNDEF in the current file
12910 and create `undefs for them. This is used to insure that
12911 file-local defines do not pollute the global `define name space.
12912
12913 Limitations:
12914 AUTOUNDEF presumes any identifier following `define is the
12915 name of a define. Any `ifdefs are ignored.
12916
12917 AUTOUNDEF suppresses creating an `undef for any define that was
12918 `undefed before the AUTOUNDEF. This may be used to work around
12919 the ignoring of `ifdefs as shown below.
12920
12921 An example:
12922
12923 `define XX_FOO
12924 `define M_BAR(x)
12925 `define M_BAZ
12926 ...
12927 `ifdef NEVER
12928 `undef M_BAZ // Emacs will see this and not `undef M_BAZ
12929 `endif
12930 ...
12931 /*AUTOUNDEF*/
12932
12933 Typing \\[verilog-auto] will make this into:
12934
12935 ...
12936 /*AUTOUNDEF*/
12937 // Beginning of automatic undefs
12938 `undef XX_FOO
12939 `undef M_BAR
12940 // End of automatics
12941
12942 You may also provide an optional regular expression, in which case only
12943 defines the regular expression will be undefed."
12944 (save-excursion
12945 (let* ((params (verilog-read-auto-params 0 1))
12946 (regexp (nth 0 params))
12947 (indent-pt (current-indentation))
12948 (end-pt (point))
12949 defs def)
12950 (save-excursion
12951 ;; Scan from start of file, or last AUTOUNDEF
12952 (or (verilog-re-search-backward-quick "/\\*AUTOUNDEF\\>" end-pt t)
12953 (goto-char (point-min)))
12954 (while (verilog-re-search-forward-quick
12955 "`\\(define\\|undef\\)\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" end-pt t)
12956 (cond ((equal (match-string-no-properties 1) "define")
12957 (setq def (match-string-no-properties 2))
12958 (when (and (or (not regexp)
12959 (string-match regexp def))
12960 (not (member def defs))) ;; delete-dups not in 21.1
12961 (setq defs (cons def defs))))
12962 (t
12963 (setq defs (delete (match-string-no-properties 2) defs))))))
12964 ;; Insert
12965 (setq defs (sort defs 'string<))
12966 (when defs
12967 (verilog-forward-or-insert-line)
12968 (verilog-insert-indent "// Beginning of automatic undefs\n")
12969 (while defs
12970 (verilog-insert-indent "`undef " (car defs) "\n")
12971 (setq defs (cdr defs)))
12972 (verilog-insert-indent "// End of automatics\n")))))
12973
12974 (defun verilog-auto-unused ()
12975 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
12976 Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
12977 input and inout signals.
12978
12979 /*AUTOUNUSED*/ is used to make stub modules; modules that have the same
12980 input/output list as another module, but no internals. Specifically, it
12981 finds all inputs and inouts in the module, and if that input is not otherwise
12982 used, adds it to a comma separated list.
12983
12984 The comma separated list is intended to be used to create a _unused_ok
12985 signal. Using the exact name \"_unused_ok\" for name of the temporary
12986 signal is recommended as it will insure maximum forward compatibility, it
12987 also makes lint warnings easy to understand; ignore any unused warnings
12988 with \"unused\" in the signal name.
12989
12990 To reduce simulation time, the _unused_ok signal should be forced to a
12991 constant to prevent wiggling. The easiest thing to do is use a
12992 reduction-and with 1'b0 as shown.
12993
12994 This way all unused signals are in one place, making it convenient to add
12995 your tool's specific pragmas around the assignment to disable any unused
12996 warnings.
12997
12998 You can add signals you do not want included in AUTOUNUSED with
12999 `verilog-auto-unused-ignore-regexp'.
13000
13001 An example of making a stub for another module:
13002
13003 module ExampStub (/*AUTOINST*/);
13004 /*AUTOINOUTPARAM(\"Examp\")*/
13005 /*AUTOINOUTMODULE(\"Examp\")*/
13006 /*AUTOTIEOFF*/
13007 // verilator lint_off UNUSED
13008 wire _unused_ok = &{1'b0,
13009 /*AUTOUNUSED*/
13010 1'b0};
13011 // verilator lint_on UNUSED
13012 endmodule
13013
13014 Typing \\[verilog-auto] will make this into:
13015
13016 ...
13017 // verilator lint_off UNUSED
13018 wire _unused_ok = &{1'b0,
13019 /*AUTOUNUSED*/
13020 // Beginning of automatics
13021 unused_input_a,
13022 unused_input_b,
13023 unused_input_c,
13024 // End of automatics
13025 1'b0};
13026 // verilator lint_on UNUSED
13027 endmodule"
13028 (interactive)
13029 (save-excursion
13030 ;; Find beginning
13031 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
13032 (modi (verilog-modi-current))
13033 (moddecls (verilog-modi-get-decls modi))
13034 (modsubdecls (verilog-modi-get-sub-decls modi))
13035 (sig-list (verilog-signals-not-in
13036 (append (verilog-decls-get-inputs moddecls)
13037 (verilog-decls-get-inouts moddecls))
13038 (append (verilog-subdecls-get-inputs modsubdecls)
13039 (verilog-subdecls-get-inouts modsubdecls)))))
13040 (setq sig-list (verilog-signals-not-matching-regexp
13041 sig-list verilog-auto-unused-ignore-regexp))
13042 (when sig-list
13043 (verilog-forward-or-insert-line)
13044 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
13045 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
13046 (while sig-list
13047 (let ((sig (car sig-list)))
13048 (indent-to indent-pt)
13049 (insert (verilog-sig-name sig) ",\n")
13050 (setq sig-list (cdr sig-list))))
13051 (verilog-insert-indent "// End of automatics\n")))))
13052
13053 (defun verilog-enum-ascii (signm elim-regexp)
13054 "Convert an enum name SIGNM to an ascii string for insertion.
13055 Remove user provided prefix ELIM-REGEXP."
13056 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
13057 (let ((case-fold-search t))
13058 ;; All upper becomes all lower for readability
13059 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
13060
13061 (defun verilog-auto-ascii-enum ()
13062 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
13063 Create a register to contain the ASCII decode of an enumerated signal type.
13064 This will allow trace viewers to show the ASCII name of states.
13065
13066 First, parameters are built into an enumeration using the synopsys enum
13067 comment. The comment must be between the keyword and the symbol.
13068 \(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
13069
13070 Next, registers which that enum applies to are also tagged with the same
13071 enum.
13072
13073 Finally, an AUTOASCIIENUM command is used.
13074
13075 The first parameter is the name of the signal to be decoded.
13076
13077 The second parameter is the name to store the ASCII code into. For the
13078 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
13079 a signal that is just for simulation, and the magic characters _ascii
13080 tell viewers like Dinotrace to display in ASCII format.
13081
13082 The third optional parameter is a string which will be removed
13083 from the state names. It defaults to \"\" which removes nothing.
13084
13085 The fourth optional parameter is \"onehot\" to force one-hot
13086 decoding. If unspecified, if and only if the first parameter
13087 width is 2^(number of states in enum) and does NOT match the
13088 width of the enum, the signal is assumed to be a one-hot
13089 decode. Otherwise, it's a normal encoded state vector.
13090
13091 `verilog-auto-wire-type' may be used to change the datatype of
13092 the declarations.
13093
13094 \"auto enum\" may be used in place of \"synopsys enum\".
13095
13096 An example:
13097
13098 //== State enumeration
13099 parameter [2:0] // synopsys enum state_info
13100 SM_IDLE = 3'b000,
13101 SM_SEND = 3'b001,
13102 SM_WAIT1 = 3'b010;
13103 //== State variables
13104 reg [2:0] /* synopsys enum state_info */
13105 state_r; /* synopsys state_vector state_r */
13106 reg [2:0] /* synopsys enum state_info */
13107 state_e1;
13108
13109 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
13110
13111 Typing \\[verilog-auto] will make this into:
13112
13113 ... same front matter ...
13114
13115 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
13116 // Beginning of automatic ASCII enum decoding
13117 reg [39:0] state_ascii_r; // Decode of state_r
13118 always @(state_r) begin
13119 case ({state_r})
13120 SM_IDLE: state_ascii_r = \"idle \";
13121 SM_SEND: state_ascii_r = \"send \";
13122 SM_WAIT1: state_ascii_r = \"wait1\";
13123 default: state_ascii_r = \"%Erro\";
13124 endcase
13125 end
13126 // End of automatics"
13127 (save-excursion
13128 (let* ((params (verilog-read-auto-params 2 4))
13129 (undecode-name (nth 0 params))
13130 (ascii-name (nth 1 params))
13131 (elim-regexp (and (nth 2 params)
13132 (not (equal (nth 2 params) ""))
13133 (nth 2 params)))
13134 (one-hot-flag (nth 3 params))
13135 ;;
13136 (indent-pt (current-indentation))
13137 (modi (verilog-modi-current))
13138 (moddecls (verilog-modi-get-decls modi))
13139 ;;
13140 (sig-list-consts (append (verilog-decls-get-consts moddecls)
13141 (verilog-decls-get-gparams moddecls)))
13142 (sig-list-all (verilog-decls-get-iovars moddecls))
13143 ;;
13144 (undecode-sig (or (assoc undecode-name sig-list-all)
13145 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
13146 (undecode-enum (or (verilog-sig-enum undecode-sig)
13147 (error "%s: Signal %s does not have an enum tag" (verilog-point-text) undecode-name)))
13148 ;;
13149 (enum-sigs (verilog-signals-not-in
13150 (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
13151 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum))
13152 nil))
13153 ;;
13154 (one-hot (or
13155 (string-match "onehot" (or one-hot-flag ""))
13156 (and ;; width(enum) != width(sig)
13157 (or (not (verilog-sig-bits (car enum-sigs)))
13158 (not (equal (verilog-sig-width (car enum-sigs))
13159 (verilog-sig-width undecode-sig))))
13160 ;; count(enums) == width(sig)
13161 (equal (number-to-string (length enum-sigs))
13162 (verilog-sig-width undecode-sig)))))
13163 (enum-chars 0)
13164 (ascii-chars 0))
13165 ;;
13166 ;; Find number of ascii chars needed
13167 (let ((tmp-sigs enum-sigs))
13168 (while tmp-sigs
13169 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
13170 ascii-chars (max ascii-chars (length (verilog-enum-ascii
13171 (verilog-sig-name (car tmp-sigs))
13172 elim-regexp)))
13173 tmp-sigs (cdr tmp-sigs))))
13174 ;;
13175 (verilog-forward-or-insert-line)
13176 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
13177 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
13178 (concat "Decode of " undecode-name) nil nil))))
13179 (verilog-insert-definition modi decode-sig-list "reg" indent-pt nil))
13180 ;;
13181 (verilog-insert-indent "always @(" undecode-name ") begin\n")
13182 (setq indent-pt (+ indent-pt verilog-indent-level))
13183 (verilog-insert-indent "case ({" undecode-name "})\n")
13184 (setq indent-pt (+ indent-pt verilog-case-indent))
13185 ;;
13186 (let ((tmp-sigs enum-sigs)
13187 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n"
13188 (+ (if one-hot 9 1) (max 8 enum-chars))
13189 ascii-name ascii-chars))
13190 (errname (substring "%Error" 0 (min 6 ascii-chars))))
13191 (while tmp-sigs
13192 (verilog-insert-indent
13193 (concat
13194 (format chrfmt
13195 (concat (if one-hot "(")
13196 ;; Use enum-sigs length as that's numeric
13197 ;; verilog-sig-width undecode-sig might not be.
13198 (if one-hot (number-to-string (length enum-sigs)))
13199 ;; We use a shift instead of var[index]
13200 ;; so that a non-one hot value will show as error.
13201 (if one-hot "'b1<<")
13202 (verilog-sig-name (car tmp-sigs))
13203 (if one-hot ")") ":")
13204 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
13205 elim-regexp))))
13206 (setq tmp-sigs (cdr tmp-sigs)))
13207 (verilog-insert-indent (format chrfmt "default:" errname)))
13208 ;;
13209 (setq indent-pt (- indent-pt verilog-case-indent))
13210 (verilog-insert-indent "endcase\n")
13211 (setq indent-pt (- indent-pt verilog-indent-level))
13212 (verilog-insert-indent "end\n"
13213 "// End of automatics\n"))))
13214
13215 (defun verilog-auto-templated-rel ()
13216 "Replace Templated relative line numbers with absolute line numbers.
13217 Internal use only. This hacks around the line numbers in AUTOINST Templates
13218 being different from the final output's line numbering."
13219 (let ((templateno 0) (template-line (list 0)) (buf-line 1))
13220 ;; Find line number each template is on
13221 ;; Count lines as we go, as otherwise it's O(n^2) to use count-lines
13222 (goto-char (point-min))
13223 (while (not (eobp))
13224 (when (looking-at ".*AUTO_TEMPLATE")
13225 (setq templateno (1+ templateno))
13226 (setq template-line (cons buf-line template-line)))
13227 (setq buf-line (1+ buf-line))
13228 (forward-line 1))
13229 (setq template-line (nreverse template-line))
13230 ;; Replace T# L# with absolute line number
13231 (goto-char (point-min))
13232 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
13233 (replace-match
13234 (concat " Templated "
13235 (int-to-string (+ (nth (string-to-number (match-string 1))
13236 template-line)
13237 (string-to-number (match-string 2)))))
13238 t t))))
13239
13240 (defun verilog-auto-template-lint ()
13241 "Check AUTO_TEMPLATEs for unused lines.
13242 Enable with `verilog-auto-template-warn-unused'."
13243 (let ((name1 (or (buffer-file-name) (buffer-name))))
13244 (save-excursion
13245 (goto-char (point-min))
13246 (while (re-search-forward
13247 "^\\s-*/?\\*?\\s-*[a-zA-Z0-9`_$]+\\s-+AUTO_TEMPLATE" nil t)
13248 (let* ((tpl-info (verilog-read-auto-template-middle))
13249 (tpl-list (aref tpl-info 1))
13250 (tlines (append (nth 0 tpl-list) (nth 1 tpl-list)))
13251 tpl-ass)
13252 (while tlines
13253 (setq tpl-ass (car tlines)
13254 tlines (cdr tlines))
13255 ;;;
13256 (unless (or (not (eval-when-compile (fboundp 'make-hash-table))) ;; Not supported, no warning
13257 (not verilog-auto-template-hits)
13258 (gethash (vector (nth 2 tpl-ass) (nth 3 tpl-ass))
13259 verilog-auto-template-hits))
13260 (verilog-warn-error "%s:%d: AUTO_TEMPLATE line unused: \".%s (%s)\""
13261 name1
13262 (+ (elt tpl-ass 3) ;; Template line number
13263 (count-lines (point-min) (point)))
13264 (elt tpl-ass 0) (elt tpl-ass 1))
13265 )))))))
13266
13267 \f
13268 ;;
13269 ;; Auto top level
13270 ;;
13271
13272 (defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing an arg
13273 "Expand AUTO statements.
13274 Look for any /*AUTO...*/ commands in the code, as used in
13275 instantiations or argument headers. Update the list of signals
13276 following the /*AUTO...*/ command.
13277
13278 Use \\[verilog-delete-auto] to remove the AUTOs.
13279
13280 Use \\[verilog-diff-auto] to see differences in AUTO expansion.
13281
13282 Use \\[verilog-inject-auto] to insert AUTOs for the first time.
13283
13284 Use \\[verilog-faq] for a pointer to frequently asked questions.
13285
13286 For new users, we recommend setting `verilog-case-fold' to nil
13287 and `verilog-auto-arg-sort' to t.
13288
13289 The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
13290 called before and after this function, respectively.
13291
13292 For example:
13293 module ModuleName (/*AUTOARG*/);
13294 /*AUTOINPUT*/
13295 /*AUTOOUTPUT*/
13296 /*AUTOWIRE*/
13297 /*AUTOREG*/
13298 InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
13299
13300 You can also update the AUTOs from the shell using:
13301 emacs --batch <filenames.v> -f verilog-batch-auto
13302 Or fix indentation with:
13303 emacs --batch <filenames.v> -f verilog-batch-indent
13304 Likewise, you can delete or inject AUTOs with:
13305 emacs --batch <filenames.v> -f verilog-batch-delete-auto
13306 emacs --batch <filenames.v> -f verilog-batch-inject-auto
13307 Or check if AUTOs have the same expansion
13308 emacs --batch <filenames.v> -f verilog-batch-diff-auto
13309
13310 Using \\[describe-function], see also:
13311 `verilog-auto-arg' for AUTOARG module instantiations
13312 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
13313 `verilog-auto-assign-modport' for AUTOASSIGNMODPORT assignment to/from modport
13314 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
13315 `verilog-auto-inout-comp' for AUTOINOUTCOMP copy complemented i/o
13316 `verilog-auto-inout-in' for AUTOINOUTIN inputs for all i/o
13317 `verilog-auto-inout-modport' for AUTOINOUTMODPORT i/o from an interface modport
13318 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
13319 `verilog-auto-inout-param' for AUTOINOUTPARAM copying params from elsewhere
13320 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
13321 `verilog-auto-insert-lisp' for AUTOINSERTLISP insert code from lisp function
13322 `verilog-auto-insert-last' for AUTOINSERTLAST insert code from lisp function
13323 `verilog-auto-inst' for AUTOINST instantiation pins
13324 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
13325 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
13326 `verilog-auto-logic' for AUTOLOGIC declaring logic signals
13327 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
13328 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
13329 `verilog-auto-reg' for AUTOREG registers
13330 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
13331 `verilog-auto-reset' for AUTORESET flop resets
13332 `verilog-auto-sense' for AUTOSENSE or AS always sensitivity lists
13333 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
13334 `verilog-auto-undef' for AUTOUNDEF `undef of local `defines
13335 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
13336 `verilog-auto-wire' for AUTOWIRE instantiation wires
13337
13338 `verilog-read-defines' for reading `define values
13339 `verilog-read-includes' for reading `includes
13340
13341 If you have bugs with these autos, please file an issue at
13342 URL `http://www.veripool.org/verilog-mode' or contact the AUTOAUTHOR
13343 Wilson Snyder (wsnyder@wsnyder.org)."
13344 (interactive)
13345 (unless noninteractive (message "Updating AUTOs..."))
13346 (if (fboundp 'dinotrace-unannotate-all)
13347 (dinotrace-unannotate-all))
13348 (verilog-save-font-mods
13349 (let ((oldbuf (if (not (buffer-modified-p))
13350 (buffer-string)))
13351 (case-fold-search verilog-case-fold)
13352 ;; Cache directories; we don't write new files, so can't change
13353 (verilog-dir-cache-preserving t)
13354 ;; Cache current module
13355 (verilog-modi-cache-current-enable t)
13356 (verilog-modi-cache-current-max (point-min)) ; IE it's invalid
13357 verilog-modi-cache-current)
13358 (unwind-protect
13359 ;; Disable change hooks for speed
13360 ;; This let can't be part of above let; must restore
13361 ;; after-change-functions before font-lock resumes
13362 (verilog-save-no-change-functions
13363 (verilog-save-scan-cache
13364 (save-excursion
13365 ;; Wipe cache; otherwise if we AUTOed a block above this one,
13366 ;; we'll misremember we have generated IOs, confusing AUTOOUTPUT
13367 (setq verilog-modi-cache-list nil)
13368 ;; Local state
13369 (setq verilog-auto-template-hits nil)
13370 ;; If we're not in verilog-mode, change syntax table so parsing works right
13371 (unless (eq major-mode `verilog-mode) (verilog-mode))
13372 ;; Allow user to customize
13373 (verilog-run-hooks 'verilog-before-auto-hook)
13374 ;; Try to save the user from needing to revert-file to reread file local-variables
13375 (verilog-auto-reeval-locals)
13376 (verilog-read-auto-lisp-present)
13377 (verilog-read-auto-lisp (point-min) (point-max))
13378 (verilog-getopt-flags)
13379 ;; From here on out, we can cache anything we read from disk
13380 (verilog-preserve-dir-cache
13381 ;; These two may seem obvious to do always, but on large includes it can be way too slow
13382 (when verilog-auto-read-includes
13383 (verilog-read-includes)
13384 (verilog-read-defines nil nil t))
13385 ;; Setup variables due to SystemVerilog expansion
13386 (verilog-auto-re-search-do "/\\*AUTOLOGIC\\*/" 'verilog-auto-logic-setup)
13387 ;; This particular ordering is important
13388 ;; INST: Lower modules correct, no internal dependencies, FIRST
13389 (verilog-preserve-modi-cache
13390 ;; Clear existing autos else we'll be screwed by existing ones
13391 (verilog-delete-auto)
13392 ;; Injection if appropriate
13393 (when inject
13394 (verilog-inject-inst)
13395 (verilog-inject-sense)
13396 (verilog-inject-arg))
13397 ;;
13398 ;; Do user inserts first, so their code can insert AUTOs
13399 (verilog-auto-re-search-do "/\\*AUTOINSERTLISP(.*?)\\*/"
13400 'verilog-auto-insert-lisp)
13401 ;; Expand instances before need the signals the instances input/output
13402 (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
13403 (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
13404 (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
13405 ;; Doesn't matter when done, but combine it with a common changer
13406 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
13407 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
13408 ;; Must be done before autoin/out as creates a reg
13409 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM(.*?)\\*/" 'verilog-auto-ascii-enum)
13410 ;;
13411 ;; first in/outs from other files
13412 (verilog-auto-re-search-do "/\\*AUTOINOUTMODPORT(.*?)\\*/" 'verilog-auto-inout-modport)
13413 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE(.*?)\\*/" 'verilog-auto-inout-module)
13414 (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP(.*?)\\*/" 'verilog-auto-inout-comp)
13415 (verilog-auto-re-search-do "/\\*AUTOINOUTIN(.*?)\\*/" 'verilog-auto-inout-in)
13416 (verilog-auto-re-search-do "/\\*AUTOINOUTPARAM(.*?)\\*/" 'verilog-auto-inout-param)
13417 ;; next in/outs which need previous sucked inputs first
13418 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((.*?)\\)?\\*/" 'verilog-auto-output)
13419 (verilog-auto-re-search-do "/\\*AUTOINPUT\\((.*?)\\)?\\*/" 'verilog-auto-input)
13420 (verilog-auto-re-search-do "/\\*AUTOINOUT\\((.*?)\\)?\\*/" 'verilog-auto-inout)
13421 ;; Then tie off those in/outs
13422 (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
13423 ;; These can be anywhere after AUTOINSERTLISP
13424 (verilog-auto-re-search-do "/\\*AUTOUNDEF\\((.*?)\\)?\\*/" 'verilog-auto-undef)
13425 ;; Wires/regs must be after inputs/outputs
13426 (verilog-auto-re-search-do "/\\*AUTOASSIGNMODPORT(.*?)\\*/" 'verilog-auto-assign-modport)
13427 (verilog-auto-re-search-do "/\\*AUTOLOGIC\\*/" 'verilog-auto-logic)
13428 (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
13429 (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
13430 (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
13431 ;; outputevery needs AUTOOUTPUTs done first
13432 (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\((.*?)\\)?\\*/" 'verilog-auto-output-every)
13433 ;; After we've created all new variables
13434 (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
13435 ;; Must be after all inputs outputs are generated
13436 (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
13437 ;; User inserts
13438 (verilog-auto-re-search-do "/\\*AUTOINSERTLAST(.*?)\\*/" 'verilog-auto-insert-last)
13439 ;; Fix line numbers (comments only)
13440 (when verilog-auto-inst-template-numbers
13441 (verilog-auto-templated-rel))
13442 (when verilog-auto-template-warn-unused
13443 (verilog-auto-template-lint))))
13444 ;;
13445 (verilog-run-hooks 'verilog-auto-hook)
13446 ;;
13447 (when verilog-auto-delete-trailing-whitespace
13448 (verilog-delete-trailing-whitespace))
13449 ;;
13450 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))
13451 ;;
13452 ;; If end result is same as when started, clear modified flag
13453 (cond ((and oldbuf (equal oldbuf (buffer-string)))
13454 (set-buffer-modified-p nil)
13455 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
13456 (t (unless noninteractive (message "Updating AUTOs...done"))))
13457 ;; End of after-change protection
13458 )))
13459 ;; Unwind forms
13460 ;; Currently handled in verilog-save-font-mods
13461 ))))
13462 \f
13463
13464 ;;
13465 ;; Skeleton based code insertion
13466 ;;
13467 (defvar verilog-template-map
13468 (let ((map (make-sparse-keymap)))
13469 (define-key map "a" 'verilog-sk-always)
13470 (define-key map "b" 'verilog-sk-begin)
13471 (define-key map "c" 'verilog-sk-case)
13472 (define-key map "f" 'verilog-sk-for)
13473 (define-key map "g" 'verilog-sk-generate)
13474 (define-key map "h" 'verilog-sk-header)
13475 (define-key map "i" 'verilog-sk-initial)
13476 (define-key map "j" 'verilog-sk-fork)
13477 (define-key map "m" 'verilog-sk-module)
13478 (define-key map "o" 'verilog-sk-ovm-class)
13479 (define-key map "p" 'verilog-sk-primitive)
13480 (define-key map "r" 'verilog-sk-repeat)
13481 (define-key map "s" 'verilog-sk-specify)
13482 (define-key map "t" 'verilog-sk-task)
13483 (define-key map "u" 'verilog-sk-uvm-object)
13484 (define-key map "w" 'verilog-sk-while)
13485 (define-key map "x" 'verilog-sk-casex)
13486 (define-key map "z" 'verilog-sk-casez)
13487 (define-key map "?" 'verilog-sk-if)
13488 (define-key map ":" 'verilog-sk-else-if)
13489 (define-key map "/" 'verilog-sk-comment)
13490 (define-key map "A" 'verilog-sk-assign)
13491 (define-key map "F" 'verilog-sk-function)
13492 (define-key map "I" 'verilog-sk-input)
13493 (define-key map "O" 'verilog-sk-output)
13494 (define-key map "S" 'verilog-sk-state-machine)
13495 (define-key map "=" 'verilog-sk-inout)
13496 (define-key map "U" 'verilog-sk-uvm-component)
13497 (define-key map "W" 'verilog-sk-wire)
13498 (define-key map "R" 'verilog-sk-reg)
13499 (define-key map "D" 'verilog-sk-define-signal)
13500 map)
13501 "Keymap used in Verilog mode for smart template operations.")
13502
13503
13504 ;;
13505 ;; Place the templates into Verilog Mode. They may be inserted under any key.
13506 ;; C-c C-t will be the default. If you use templates a lot, you
13507 ;; may want to consider moving the binding to another key in your init
13508 ;; file.
13509 ;;
13510 ;; Note \C-c and letter are reserved for users
13511 (define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
13512
13513 ;;; ---- statement skeletons ------------------------------------------
13514
13515 (define-skeleton verilog-sk-prompt-condition
13516 "Prompt for the loop condition."
13517 "[condition]: " str )
13518
13519 (define-skeleton verilog-sk-prompt-init
13520 "Prompt for the loop init statement."
13521 "[initial statement]: " str )
13522
13523 (define-skeleton verilog-sk-prompt-inc
13524 "Prompt for the loop increment statement."
13525 "[increment statement]: " str )
13526
13527 (define-skeleton verilog-sk-prompt-name
13528 "Prompt for the name of something."
13529 "[name]: " str)
13530
13531 (define-skeleton verilog-sk-prompt-clock
13532 "Prompt for the name of something."
13533 "name and edge of clock(s): " str)
13534
13535 (defvar verilog-sk-reset nil)
13536 (defun verilog-sk-prompt-reset ()
13537 "Prompt for the name of a state machine reset."
13538 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
13539
13540
13541 (define-skeleton verilog-sk-prompt-state-selector
13542 "Prompt for the name of a state machine selector."
13543 "name of selector (eg {a,b,c,d}): " str )
13544
13545 (define-skeleton verilog-sk-prompt-output
13546 "Prompt for the name of something."
13547 "output: " str)
13548
13549 (define-skeleton verilog-sk-prompt-msb
13550 "Prompt for most significant bit specification."
13551 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
13552
13553 (define-skeleton verilog-sk-prompt-lsb
13554 "Prompt for least significant bit specification."
13555 "lsb:" str )
13556
13557 (defvar verilog-sk-p nil)
13558 (define-skeleton verilog-sk-prompt-width
13559 "Prompt for a width specification."
13560 ()
13561 (progn
13562 (setq verilog-sk-p (point))
13563 (verilog-sk-prompt-msb)
13564 (if (> (point) verilog-sk-p) "] " " ")))
13565
13566 (defun verilog-sk-header ()
13567 "Insert a descriptive header at the top of the file.
13568 See also `verilog-header' for an alternative format."
13569 (interactive "*")
13570 (save-excursion
13571 (goto-char (point-min))
13572 (verilog-sk-header-tmpl)))
13573
13574 (define-skeleton verilog-sk-header-tmpl
13575 "Insert a comment block containing the module title, author, etc."
13576 "[Description]: "
13577 "// -*- Mode: Verilog -*-"
13578 "\n// Filename : " (buffer-name)
13579 "\n// Description : " str
13580 "\n// Author : " (user-full-name)
13581 "\n// Created On : " (current-time-string)
13582 "\n// Last Modified By: " (user-full-name)
13583 "\n// Last Modified On: " (current-time-string)
13584 "\n// Update Count : 0"
13585 "\n// Status : Unknown, Use with caution!"
13586 "\n")
13587
13588 (define-skeleton verilog-sk-module
13589 "Insert a module definition."
13590 ()
13591 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
13592 > _ \n
13593 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
13594
13595 ;;; ------------------------------------------------------------------------
13596 ;;; Define a default OVM class, with macros and new()
13597 ;;; ------------------------------------------------------------------------
13598
13599 (define-skeleton verilog-sk-ovm-class
13600 "Insert a class definition"
13601 ()
13602 > "class " (setq name (skeleton-read "Name: ")) " extends " (skeleton-read "Extends: ") ";" \n
13603 > _ \n
13604 > "`ovm_object_utils_begin(" name ")" \n
13605 > (- verilog-indent-level) " `ovm_object_utils_end" \n
13606 > _ \n
13607 > "function new(string name=\"" name "\");" \n
13608 > "super.new(name);" \n
13609 > (- verilog-indent-level) "endfunction" \n
13610 > _ \n
13611 > "endclass" (progn (electric-verilog-terminate-line) nil))
13612
13613 (define-skeleton verilog-sk-uvm-object
13614 "Insert a class definition"
13615 ()
13616 > "class " (setq name (skeleton-read "Name: ")) " extends " (skeleton-read "Extends: ") ";" \n
13617 > _ \n
13618 > "`uvm_object_utils_begin(" name ")" \n
13619 > (- verilog-indent-level) "`uvm_object_utils_end" \n
13620 > _ \n
13621 > "function new(string name=\"" name "\");" \n
13622 > "super.new(name);" \n
13623 > (- verilog-indent-level) "endfunction" \n
13624 > _ \n
13625 > "endclass" (progn (electric-verilog-terminate-line) nil))
13626
13627 (define-skeleton verilog-sk-uvm-component
13628 "Insert a class definition"
13629 ()
13630 > "class " (setq name (skeleton-read "Name: ")) " extends " (skeleton-read "Extends: ") ";" \n
13631 > _ \n
13632 > "`uvm_component_utils_begin(" name ")" \n
13633 > (- verilog-indent-level) "`uvm_component_utils_end" \n
13634 > _ \n
13635 > "function new(string name=\"\", uvm_component parent);" \n
13636 > "super.new(name, parent);" \n
13637 > (- verilog-indent-level) "endfunction" \n
13638 > _ \n
13639 > "endclass" (progn (electric-verilog-terminate-line) nil))
13640
13641 (define-skeleton verilog-sk-primitive
13642 "Insert a task definition."
13643 ()
13644 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
13645 > _ \n
13646 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
13647
13648 (define-skeleton verilog-sk-task
13649 "Insert a task definition."
13650 ()
13651 > "task " '(verilog-sk-prompt-name) & ?; \n
13652 > _ \n
13653 > "begin" \n
13654 > \n
13655 > (- verilog-indent-level-behavioral) "end" \n
13656 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
13657
13658 (define-skeleton verilog-sk-function
13659 "Insert a function definition."
13660 ()
13661 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
13662 > _ \n
13663 > "begin" \n
13664 > \n
13665 > (- verilog-indent-level-behavioral) "end" \n
13666 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
13667
13668 (define-skeleton verilog-sk-always
13669 "Insert always block. Uses the minibuffer to prompt
13670 for sensitivity list."
13671 ()
13672 > "always @ ( /*AUTOSENSE*/ ) begin\n"
13673 > _ \n
13674 > (- verilog-indent-level-behavioral) "end" \n >
13675 )
13676
13677 (define-skeleton verilog-sk-initial
13678 "Insert an initial block."
13679 ()
13680 > "initial begin\n"
13681 > _ \n
13682 > (- verilog-indent-level-behavioral) "end" \n > )
13683
13684 (define-skeleton verilog-sk-specify
13685 "Insert specify block. "
13686 ()
13687 > "specify\n"
13688 > _ \n
13689 > (- verilog-indent-level-behavioral) "endspecify" \n > )
13690
13691 (define-skeleton verilog-sk-generate
13692 "Insert generate block. "
13693 ()
13694 > "generate\n"
13695 > _ \n
13696 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
13697
13698 (define-skeleton verilog-sk-begin
13699 "Insert begin end block. Uses the minibuffer to prompt for name."
13700 ()
13701 > "begin" '(verilog-sk-prompt-name) \n
13702 > _ \n
13703 > (- verilog-indent-level-behavioral) "end" )
13704
13705 (define-skeleton verilog-sk-fork
13706 "Insert a fork join block."
13707 ()
13708 > "fork\n"
13709 > "begin" \n
13710 > _ \n
13711 > (- verilog-indent-level-behavioral) "end" \n
13712 > "begin" \n
13713 > \n
13714 > (- verilog-indent-level-behavioral) "end" \n
13715 > (- verilog-indent-level-behavioral) "join" \n
13716 > )
13717
13718
13719 (define-skeleton verilog-sk-case
13720 "Build skeleton case statement, prompting for the selector expression,
13721 and the case items."
13722 "[selector expression]: "
13723 > "case (" str ") " \n
13724 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
13725 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
13726
13727 (define-skeleton verilog-sk-casex
13728 "Build skeleton casex statement, prompting for the selector expression,
13729 and the case items."
13730 "[selector expression]: "
13731 > "casex (" str ") " \n
13732 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
13733 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
13734
13735 (define-skeleton verilog-sk-casez
13736 "Build skeleton casez statement, prompting for the selector expression,
13737 and the case items."
13738 "[selector expression]: "
13739 > "casez (" str ") " \n
13740 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
13741 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
13742
13743 (define-skeleton verilog-sk-if
13744 "Insert a skeleton if statement."
13745 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
13746 > _ \n
13747 > (- verilog-indent-level-behavioral) "end " \n )
13748
13749 (define-skeleton verilog-sk-else-if
13750 "Insert a skeleton else if statement."
13751 > (verilog-indent-line) "else if ("
13752 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
13753 > _ \n
13754 > "end" (progn (electric-verilog-terminate-line) nil))
13755
13756 (define-skeleton verilog-sk-datadef
13757 "Common routine to get data definition."
13758 ()
13759 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
13760
13761 (define-skeleton verilog-sk-input
13762 "Insert an input definition."
13763 ()
13764 > "input [" '(verilog-sk-datadef))
13765
13766 (define-skeleton verilog-sk-output
13767 "Insert an output definition."
13768 ()
13769 > "output [" '(verilog-sk-datadef))
13770
13771 (define-skeleton verilog-sk-inout
13772 "Insert an inout definition."
13773 ()
13774 > "inout [" '(verilog-sk-datadef))
13775
13776 (defvar verilog-sk-signal nil)
13777 (define-skeleton verilog-sk-def-reg
13778 "Insert a reg definition."
13779 ()
13780 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations-auto) )
13781
13782 (defun verilog-sk-define-signal ()
13783 "Insert a definition of signal under point at top of module."
13784 (interactive "*")
13785 (let* ((sig-re "[a-zA-Z0-9_]*")
13786 (v1 (buffer-substring
13787 (save-excursion
13788 (skip-chars-backward sig-re)
13789 (point))
13790 (save-excursion
13791 (skip-chars-forward sig-re)
13792 (point)))))
13793 (if (not (member v1 verilog-keywords))
13794 (save-excursion
13795 (setq verilog-sk-signal v1)
13796 (verilog-beg-of-defun)
13797 (verilog-end-of-statement)
13798 (verilog-forward-syntactic-ws)
13799 (verilog-sk-def-reg)
13800 (message "signal at point is %s" v1))
13801 (message "object at point (%s) is a keyword" v1))))
13802
13803 (define-skeleton verilog-sk-wire
13804 "Insert a wire definition."
13805 ()
13806 > "wire [" '(verilog-sk-datadef))
13807
13808 (define-skeleton verilog-sk-reg
13809 "Insert a reg definition."
13810 ()
13811 > "reg [" '(verilog-sk-datadef))
13812
13813 (define-skeleton verilog-sk-assign
13814 "Insert a skeleton assign statement."
13815 ()
13816 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
13817
13818 (define-skeleton verilog-sk-while
13819 "Insert a skeleton while loop statement."
13820 ()
13821 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
13822 > _ \n
13823 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
13824
13825 (define-skeleton verilog-sk-repeat
13826 "Insert a skeleton repeat loop statement."
13827 ()
13828 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
13829 > _ \n
13830 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
13831
13832 (define-skeleton verilog-sk-for
13833 "Insert a skeleton while loop statement."
13834 ()
13835 > "for ("
13836 '(verilog-sk-prompt-init) "; "
13837 '(verilog-sk-prompt-condition) "; "
13838 '(verilog-sk-prompt-inc)
13839 ") begin" \n
13840 > _ \n
13841 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
13842
13843 (define-skeleton verilog-sk-comment
13844 "Inserts three comment lines, making a display comment."
13845 ()
13846 > "/*\n"
13847 > "* " _ \n
13848 > "*/")
13849
13850 (define-skeleton verilog-sk-state-machine
13851 "Insert a state machine definition."
13852 "Name of state variable: "
13853 '(setq input "state")
13854 > "// State registers for " str | -23 \n
13855 '(setq verilog-sk-state str)
13856 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
13857 '(setq input nil)
13858 > \n
13859 > "// State FF for " verilog-sk-state \n
13860 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
13861 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
13862 > verilog-sk-state " = next_" verilog-sk-state ?; \n
13863 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
13864 > \n
13865 > "// Next State Logic for " verilog-sk-state \n
13866 > "always @ ( /*AUTOSENSE*/ ) begin\n"
13867 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
13868 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
13869 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
13870 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
13871 \f
13872
13873 ;;
13874 ;; Include file loading with mouse/return event
13875 ;;
13876 ;; idea & first impl.: M. Rouat (eldo-mode.el)
13877 ;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
13878
13879 (if (featurep 'xemacs)
13880 (require 'overlay))
13881
13882 (defconst verilog-include-file-regexp
13883 "^`include\\s-+\"\\([^\n\"]*\\)\""
13884 "Regexp that matches the include file.")
13885
13886 (defvar verilog-mode-mouse-map
13887 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
13888 (set-keymap-parent map verilog-mode-map)
13889 ;; mouse button bindings
13890 (define-key map "\r" 'verilog-load-file-at-point)
13891 (if (featurep 'xemacs)
13892 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
13893 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
13894 (if (featurep 'xemacs)
13895 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
13896 (define-key map [S-mouse-2] 'mouse-yank-at-click))
13897 map)
13898 "Map containing mouse bindings for `verilog-mode'.")
13899
13900
13901 (defun verilog-highlight-region (beg end _old-len)
13902 "Colorize included files and modules in the (changed?) region.
13903 Clicking on the middle-mouse button loads them in a buffer (as in dired)."
13904 (when (or verilog-highlight-includes
13905 verilog-highlight-modules)
13906 (save-excursion
13907 (save-match-data ;; A query-replace may call this function - do not disturb
13908 (verilog-save-buffer-state
13909 (verilog-save-scan-cache
13910 (let (end-point)
13911 (goto-char end)
13912 (setq end-point (point-at-eol))
13913 (goto-char beg)
13914 (beginning-of-line) ; scan entire line
13915 ;; delete overlays existing on this line
13916 (let ((overlays (overlays-in (point) end-point)))
13917 (while overlays
13918 (if (and
13919 (overlay-get (car overlays) 'detachable)
13920 (or (overlay-get (car overlays) 'verilog-include-file)
13921 (overlay-get (car overlays) 'verilog-inst-module)))
13922 (delete-overlay (car overlays)))
13923 (setq overlays (cdr overlays))))
13924 ;;
13925 ;; make new include overlays
13926 (when verilog-highlight-includes
13927 (while (search-forward-regexp verilog-include-file-regexp end-point t)
13928 (goto-char (match-beginning 1))
13929 (let ((ov (make-overlay (match-beginning 1) (match-end 1))))
13930 (overlay-put ov 'start-closed 't)
13931 (overlay-put ov 'end-closed 't)
13932 (overlay-put ov 'evaporate 't)
13933 (overlay-put ov 'verilog-include-file 't)
13934 (overlay-put ov 'mouse-face 'highlight)
13935 (overlay-put ov 'local-map verilog-mode-mouse-map))))
13936 ;;
13937 ;; make new module overlays
13938 (goto-char beg)
13939 ;; This scanner is syntax-fragile, so don't get bent
13940 (when verilog-highlight-modules
13941 (condition-case nil
13942 (while (verilog-re-search-forward-quick "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-point t)
13943 (save-excursion
13944 (goto-char (match-beginning 0))
13945 (unless (verilog-inside-comment-or-string-p)
13946 (verilog-read-inst-module-matcher) ;; sets match 0
13947 (let* ((ov (make-overlay (match-beginning 0) (match-end 0))))
13948 (overlay-put ov 'start-closed 't)
13949 (overlay-put ov 'end-closed 't)
13950 (overlay-put ov 'evaporate 't)
13951 (overlay-put ov 'verilog-inst-module 't)
13952 (overlay-put ov 'mouse-face 'highlight)
13953 (overlay-put ov 'local-map verilog-mode-mouse-map)))))
13954 (error nil)))
13955 ;;
13956 ;; Future highlights:
13957 ;; variables - make an Occur buffer of where referenced
13958 ;; pins - make an Occur buffer of the sig in the declaration module
13959 )))))))
13960
13961 (defun verilog-highlight-buffer ()
13962 "Colorize included files and modules across the whole buffer."
13963 ;; Invoked via verilog-mode calling font-lock then `font-lock-mode-hook'
13964 (interactive)
13965 ;; delete and remake overlays
13966 (verilog-highlight-region (point-min) (point-max) nil))
13967
13968 ;; Deprecated, but was interactive, so we'll keep it around
13969 (defalias 'verilog-colorize-include-files-buffer 'verilog-highlight-buffer)
13970
13971 ;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
13972 ;; so define this function to do more or less the same as ffap-at-mouse
13973 ;; but first resolve filename...
13974 (defun verilog-load-file-at-mouse (event)
13975 "Load file under button 2 click's EVENT.
13976 Files are checked based on `verilog-library-flags'."
13977 (interactive "@e")
13978 (save-excursion ;; implement a Verilog specific ffap-at-mouse
13979 (mouse-set-point event)
13980 (verilog-load-file-at-point t)))
13981
13982 ;; ffap isn't usable for Verilog mode. It uses library paths.
13983 ;; so define this function to do more or less the same as ffap
13984 ;; but first resolve filename...
13985 (defun verilog-load-file-at-point (&optional warn)
13986 "Load file under point.
13987 If WARN, throw warning if not found.
13988 Files are checked based on `verilog-library-flags'."
13989 (interactive)
13990 (save-excursion ;; implement a Verilog specific ffap
13991 (let ((overlays (overlays-in (point) (point)))
13992 hit)
13993 (while (and overlays (not hit))
13994 (when (overlay-get (car overlays) 'verilog-inst-module)
13995 (verilog-goto-defun-file (buffer-substring
13996 (overlay-start (car overlays))
13997 (overlay-end (car overlays))))
13998 (setq hit t))
13999 (setq overlays (cdr overlays)))
14000 ;; Include?
14001 (beginning-of-line)
14002 (when (and (not hit)
14003 (looking-at verilog-include-file-regexp))
14004 (if (and (car (verilog-library-filenames
14005 (match-string 1) (buffer-file-name)))
14006 (file-readable-p (car (verilog-library-filenames
14007 (match-string 1) (buffer-file-name)))))
14008 (find-file (car (verilog-library-filenames
14009 (match-string 1) (buffer-file-name))))
14010 (when warn
14011 (message
14012 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
14013 (match-string 1))))))))
14014
14015 ;;
14016 ;; Bug reporting
14017 ;;
14018
14019 (defun verilog-faq ()
14020 "Tell the user their current version, and where to get the FAQ etc."
14021 (interactive)
14022 (with-output-to-temp-buffer "*verilog-mode help*"
14023 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
14024 (princ "\n")
14025 (princ "For new releases, see http://www.verilog.com\n")
14026 (princ "\n")
14027 (princ "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
14028 (princ "\n")
14029 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
14030 (princ "\n")))
14031
14032 (autoload 'reporter-submit-bug-report "reporter")
14033 (defvar reporter-prompt-for-summary-p)
14034
14035 (defun verilog-submit-bug-report ()
14036 "Submit via mail a bug report on verilog-mode.el."
14037 (interactive)
14038 (let ((reporter-prompt-for-summary-p t))
14039 (reporter-submit-bug-report
14040 "mac@verilog.com, wsnyder@wsnyder.org"
14041 (concat "verilog-mode v" verilog-mode-version)
14042 '(
14043 verilog-active-low-regexp
14044 verilog-after-save-font-hook
14045 verilog-align-ifelse
14046 verilog-assignment-delay
14047 verilog-auto-arg-sort
14048 verilog-auto-declare-nettype
14049 verilog-auto-delete-trailing-whitespace
14050 verilog-auto-endcomments
14051 verilog-auto-hook
14052 verilog-auto-ignore-concat
14053 verilog-auto-indent-on-newline
14054 verilog-auto-inout-ignore-regexp
14055 verilog-auto-input-ignore-regexp
14056 verilog-auto-inst-column
14057 verilog-auto-inst-dot-name
14058 verilog-auto-inst-interfaced-ports
14059 verilog-auto-inst-param-value
14060 verilog-auto-inst-sort
14061 verilog-auto-inst-template-numbers
14062 verilog-auto-inst-vector
14063 verilog-auto-lineup
14064 verilog-auto-newline
14065 verilog-auto-output-ignore-regexp
14066 verilog-auto-read-includes
14067 verilog-auto-reset-blocking-in-non
14068 verilog-auto-reset-widths
14069 verilog-auto-save-policy
14070 verilog-auto-sense-defines-constant
14071 verilog-auto-sense-include-inputs
14072 verilog-auto-star-expand
14073 verilog-auto-star-save
14074 verilog-auto-template-warn-unused
14075 verilog-auto-tieoff-declaration
14076 verilog-auto-tieoff-ignore-regexp
14077 verilog-auto-unused-ignore-regexp
14078 verilog-auto-wire-type
14079 verilog-before-auto-hook
14080 verilog-before-delete-auto-hook
14081 verilog-before-getopt-flags-hook
14082 verilog-before-save-font-hook
14083 verilog-cache-enabled
14084 verilog-case-fold
14085 verilog-case-indent
14086 verilog-cexp-indent
14087 verilog-compiler
14088 verilog-coverage
14089 verilog-delete-auto-hook
14090 verilog-getopt-flags-hook
14091 verilog-highlight-grouping-keywords
14092 verilog-highlight-includes
14093 verilog-highlight-modules
14094 verilog-highlight-p1800-keywords
14095 verilog-highlight-translate-off
14096 verilog-indent-begin-after-if
14097 verilog-indent-declaration-macros
14098 verilog-indent-level
14099 verilog-indent-level-behavioral
14100 verilog-indent-level-declaration
14101 verilog-indent-level-directive
14102 verilog-indent-level-module
14103 verilog-indent-lists
14104 verilog-library-directories
14105 verilog-library-extensions
14106 verilog-library-files
14107 verilog-library-flags
14108 verilog-linter
14109 verilog-minimum-comment-distance
14110 verilog-mode-hook
14111 verilog-mode-release-emacs
14112 verilog-mode-version
14113 verilog-preprocessor
14114 verilog-simulator
14115 verilog-tab-always-indent
14116 verilog-tab-to-comment
14117 verilog-typedef-regexp
14118 verilog-warn-fatal
14119 )
14120 nil nil
14121 (concat "Hi Mac,
14122
14123 I want to report a bug.
14124
14125 Before I go further, I want to say that Verilog mode has changed my life.
14126 I save so much time, my files are colored nicely, my co workers respect
14127 my coding ability... until now. I'd really appreciate anything you
14128 could do to help me out with this minor deficiency in the product.
14129
14130 I've taken a look at the Verilog-Mode FAQ at
14131 http://www.veripool.org/verilog-mode-faq.html.
14132
14133 And, I've considered filing the bug on the issue tracker at
14134 http://www.veripool.org/verilog-mode-bugs
14135 since I realize that public bugs are easier for you to track,
14136 and for others to search, but would prefer to email.
14137
14138 So, to reproduce the bug, start a fresh Emacs via " invocation-name "
14139 -no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
14140 the code included below.
14141
14142 Given those lines, I expected [[Fill in here]] to happen;
14143 but instead, [[Fill in here]] happens!.
14144
14145 == The code: =="))))
14146
14147 (provide 'verilog-mode)
14148
14149 ;; Local Variables:
14150 ;; checkdoc-permit-comma-termination-flag:t
14151 ;; checkdoc-force-docstrings-flag:nil
14152 ;; End:
14153
14154 ;;; verilog-mode.el ends here