]> code.delx.au - gnu-emacs/blob - lisp/progmodes/verilog-mode.el
Merge from origin/emacs-24
[gnu-emacs] / lisp / progmodes / verilog-mode.el
1 ;;; verilog-mode.el --- major mode for editing verilog source in Emacs
2
3 ;; Copyright (C) 1996-2015 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 "2015-02-20-0d6420b-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 ;; There are known to be from newer versions of Emacs
8423 (defvar create-lockfiles))
8424
8425 (defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
8426 "For `verilog-read-sub-decls-line', add a signal."
8427 ;; sig eq t to indicate .name syntax
8428 ;;(message "vrsds: %s(%S)" port sig)
8429 (let ((dotname (eq sig t))
8430 portdata)
8431 (when sig
8432 (setq port (verilog-symbol-detick-denumber port))
8433 (setq sig (if dotname port (verilog-symbol-detick-denumber sig)))
8434 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
8435 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
8436 (unless (or (not sig)
8437 (equal sig "")) ;; Ignore .foo(1'b1) assignments
8438 (cond ((or (setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
8439 (equal "inout" verilog-read-sub-decls-gate-ios))
8440 (setq sigs-inout
8441 (cons (verilog-sig-new
8442 sig
8443 (if dotname (verilog-sig-bits portdata) vec)
8444 (concat "To/From " comment)
8445 (verilog-sig-memory portdata)
8446 nil
8447 (verilog-sig-signed portdata)
8448 (unless (member (verilog-sig-type portdata) '("wire" "reg"))
8449 (verilog-sig-type portdata))
8450 multidim nil)
8451 sigs-inout)))
8452 ((or (setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
8453 (equal "output" verilog-read-sub-decls-gate-ios))
8454 (setq sigs-out
8455 (cons (verilog-sig-new
8456 sig
8457 (if dotname (verilog-sig-bits portdata) vec)
8458 (concat "From " comment)
8459 (verilog-sig-memory portdata)
8460 nil
8461 (verilog-sig-signed portdata)
8462 ;; Though ok in SV, in V2K code, propagating the
8463 ;; "reg" in "output reg" upwards isn't legal.
8464 ;; Also for backwards compatibility we don't propagate
8465 ;; "input wire" upwards.
8466 ;; See also `verilog-signals-edit-wire-reg'.
8467 (unless (member (verilog-sig-type portdata) '("wire" "reg"))
8468 (verilog-sig-type portdata))
8469 multidim nil)
8470 sigs-out)))
8471 ((or (setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
8472 (equal "input" verilog-read-sub-decls-gate-ios))
8473 (setq sigs-in
8474 (cons (verilog-sig-new
8475 sig
8476 (if dotname (verilog-sig-bits portdata) vec)
8477 (concat "To " comment)
8478 (verilog-sig-memory portdata)
8479 nil
8480 (verilog-sig-signed portdata)
8481 (unless (member (verilog-sig-type portdata) '("wire" "reg"))
8482 (verilog-sig-type portdata))
8483 multidim nil)
8484 sigs-in)))
8485 ((setq portdata (assoc port (verilog-decls-get-interfaces submoddecls)))
8486 (setq sigs-intf
8487 (cons (verilog-sig-new
8488 sig
8489 (if dotname (verilog-sig-bits portdata) vec)
8490 (concat "To/From " comment)
8491 (verilog-sig-memory portdata)
8492 nil
8493 (verilog-sig-signed portdata)
8494 (verilog-sig-type portdata)
8495 multidim nil)
8496 sigs-intf)))
8497 ((setq portdata (and verilog-read-sub-decls-in-interfaced
8498 (assoc port (verilog-decls-get-vars submoddecls))))
8499 (setq sigs-intfd
8500 (cons (verilog-sig-new
8501 sig
8502 (if dotname (verilog-sig-bits portdata) vec)
8503 (concat "To/From " comment)
8504 (verilog-sig-memory portdata)
8505 nil
8506 (verilog-sig-signed portdata)
8507 (verilog-sig-type portdata)
8508 multidim nil)
8509 sigs-intf)))
8510 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
8511 )))))
8512
8513 (defun verilog-read-sub-decls-expr (submoddecls comment port expr)
8514 "For `verilog-read-sub-decls-line', parse a subexpression and add signals."
8515 ;;(message "vrsde: '%s'" expr)
8516 ;; Replace special /*[....]*/ comments inserted by verilog-auto-inst-port
8517 (setq expr (verilog-string-replace-matches "/\\*\\(\\[[^*]+\\]\\)\\*/" "\\1" nil nil expr))
8518 ;; Remove front operators
8519 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
8520 ;;
8521 (cond
8522 ;; {..., a, b} requires us to recurse on a,b
8523 ;; To support {#{},{#{a,b}} we'll just split everything on [{},]
8524 ((string-match "^\\s-*{\\(.*\\)}\\s-*$" expr)
8525 (unless verilog-auto-ignore-concat
8526 (let ((mlst (split-string (match-string 1 expr) "[{},]"))
8527 mstr)
8528 (while (setq mstr (pop mlst))
8529 (verilog-read-sub-decls-expr submoddecls comment port mstr)))))
8530 (t
8531 (let (sig vec multidim)
8532 ;; Remove leading reduction operators, etc
8533 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
8534 ;;(message "vrsde-ptop: '%s'" expr)
8535 (cond ;; Find \signal. Final space is part of escaped signal name
8536 ((string-match "^\\s-*\\(\\\\[^ \t\n\f]+\\s-\\)" expr)
8537 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
8538 (setq sig (match-string 1 expr)
8539 expr (substring expr (match-end 0))))
8540 ;; Find signal
8541 ((string-match "^\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" expr)
8542 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
8543 (setq sig (verilog-string-remove-spaces (match-string 1 expr))
8544 expr (substring expr (match-end 0)))))
8545 ;; Find [vector] or [multi][multi][multi][vector]
8546 (while (string-match "^\\s-*\\(\\[[^]]+\\]\\)" expr)
8547 ;;(message "vrsde-v: '%s'" (match-string 1 expr))
8548 (when vec (setq multidim (cons vec multidim)))
8549 (setq vec (match-string 1 expr)
8550 expr (substring expr (match-end 0))))
8551 ;; If found signal, and nothing unrecognized, add the signal
8552 ;;(message "vrsde-rem: '%s'" expr)
8553 (when (and sig (string-match "^\\s-*$" expr))
8554 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))))
8555
8556 (defun verilog-read-sub-decls-line (submoddecls comment)
8557 "For `verilog-read-sub-decls', read lines of port defs until none match.
8558 Inserts the list of signals found, using submodi to look up each port."
8559 (let (done port)
8560 (save-excursion
8561 (forward-line 1)
8562 (while (not done)
8563 ;; Get port name
8564 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
8565 (setq port (match-string 1))
8566 (goto-char (match-end 0)))
8567 ;; .\escaped (
8568 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
8569 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
8570 (goto-char (match-end 0)))
8571 ;; .name
8572 ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*[,)/]")
8573 (verilog-read-sub-decls-sig
8574 submoddecls comment (match-string 1) t ; sig==t for .name
8575 nil nil) ; vec multidim
8576 (setq port nil))
8577 ;; .\escaped_name
8578 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*[,)/]")
8579 (verilog-read-sub-decls-sig
8580 submoddecls comment (concat (match-string 1) " ") t ; sig==t for .name
8581 nil nil) ; vec multidim
8582 (setq port nil))
8583 ;; random
8584 ((looking-at "\\s-*\\.[^(]*(")
8585 (setq port nil) ;; skip this line
8586 (goto-char (match-end 0)))
8587 (t
8588 (setq port nil done t))) ;; Unknown, ignore rest of line
8589 ;; Get signal name. Point is at the first-non-space after (
8590 ;; We intentionally ignore (non-escaped) signals with .s in them
8591 ;; this prevents AUTOWIRE etc from noticing hierarchical sigs.
8592 (when port
8593 (cond ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*)")
8594 (verilog-read-sub-decls-sig
8595 submoddecls comment port
8596 (verilog-string-remove-spaces (match-string 1)) ; sig
8597 nil nil)) ; vec multidim
8598 ;;
8599 ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
8600 (verilog-read-sub-decls-sig
8601 submoddecls comment port
8602 (verilog-string-remove-spaces (match-string 1)) ; sig
8603 (match-string 2) nil)) ; vec multidim
8604 ;; Fastpath was above looking-at's.
8605 ;; For something more complicated invoke a parser
8606 ((looking-at "[^)]+")
8607 (verilog-read-sub-decls-expr
8608 submoddecls comment port
8609 (buffer-substring
8610 (point) (1- (progn (search-backward "(") ; start at (
8611 (verilog-forward-sexp-ign-cmt 1)
8612 (point)))))))) ; expr
8613 ;;
8614 (forward-line 1)))))
8615
8616 (defun verilog-read-sub-decls-gate (submoddecls comment submod end-inst-point)
8617 "For `verilog-read-sub-decls', read lines of UDP gate decl until none match.
8618 Inserts the list of signals found."
8619 (save-excursion
8620 (let ((iolist (cdr (assoc submod verilog-gate-ios))))
8621 (while (< (point) end-inst-point)
8622 ;; Get primitive's signal name, as will never have port, and no trailing )
8623 (cond ((looking-at "//")
8624 (search-forward "\n"))
8625 ((looking-at "/\\*")
8626 (or (search-forward "*/")
8627 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8628 ((looking-at "(\\*")
8629 ;; To advance past either "(*)" or "(* ... *)" don't forward past first *
8630 (forward-char 1)
8631 (or (search-forward "*)")
8632 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
8633 ;; On pins, parse and advance to next pin
8634 ;; Looking at pin, but *not* an // Output comment, or ) to end the inst
8635 ((looking-at "\\s-*[a-zA-Z0-9`_$({}\\\\][^,]*")
8636 (goto-char (match-end 0))
8637 (setq verilog-read-sub-decls-gate-ios (or (car iolist) "input")
8638 iolist (cdr iolist))
8639 (verilog-read-sub-decls-expr
8640 submoddecls comment "primitive_port"
8641 (match-string 0)))
8642 (t
8643 (forward-char 1)
8644 (skip-syntax-forward " ")))))))
8645
8646 (defun verilog-read-sub-decls ()
8647 "Internally parse signals going to modules under this module.
8648 Return an array of [ outputs inouts inputs ] signals for modules that are
8649 instantiated in this module. For example if declare A A (.B(SIG)) and SIG
8650 is an output, then SIG will be included in the list.
8651
8652 This only works on instantiations created with /*AUTOINST*/ converted by
8653 \\[verilog-auto-inst]. Otherwise, it would have to read in the whole
8654 component library to determine connectivity of the design.
8655
8656 One work around for this problem is to manually create // Inputs and //
8657 Outputs comments above subcell signals, for example:
8658
8659 module ModuleName (
8660 // Outputs
8661 .out (out),
8662 // Inputs
8663 .in (in));"
8664 (save-excursion
8665 (let ((end-mod-point (verilog-get-end-of-defun))
8666 st-point end-inst-point
8667 ;; below 3 modified by verilog-read-sub-decls-line
8668 sigs-out sigs-inout sigs-in sigs-intf sigs-intfd)
8669 (verilog-beg-of-defun-quick)
8670 (while (verilog-re-search-forward-quick "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
8671 (save-excursion
8672 (goto-char (match-beginning 0))
8673 (unless (verilog-inside-comment-or-string-p)
8674 ;; Attempt to snarf a comment
8675 (let* ((submod (verilog-read-inst-module))
8676 (inst (verilog-read-inst-name))
8677 (subprim (member submod verilog-gate-keywords))
8678 (comment (concat inst " of " submod ".v"))
8679 submodi submoddecls)
8680 (cond
8681 (subprim
8682 (setq submodi `primitive
8683 submoddecls (verilog-decls-new nil nil nil nil nil nil nil nil nil)
8684 comment (concat inst " of " submod))
8685 (verilog-backward-open-paren)
8686 (setq end-inst-point (save-excursion (verilog-forward-sexp-ign-cmt 1)
8687 (point))
8688 st-point (point))
8689 (forward-char 1)
8690 (verilog-read-sub-decls-gate submoddecls comment submod end-inst-point))
8691 ;; Non-primitive
8692 (t
8693 (when (setq submodi (verilog-modi-lookup submod t))
8694 (setq submoddecls (verilog-modi-get-decls submodi)
8695 verilog-read-sub-decls-gate-ios nil)
8696 (verilog-backward-open-paren)
8697 (setq end-inst-point (save-excursion (verilog-forward-sexp-ign-cmt 1)
8698 (point))
8699 st-point (point))
8700 ;; This could have used a list created by verilog-auto-inst
8701 ;; However I want it to be runnable even on user's manually added signals
8702 (let ((verilog-read-sub-decls-in-interfaced t))
8703 (while (re-search-forward "\\s *(?\\s *// Interfaced" end-inst-point t)
8704 (verilog-read-sub-decls-line submoddecls comment))) ;; Modifies sigs-ifd
8705 (goto-char st-point)
8706 (while (re-search-forward "\\s *(?\\s *// Interfaces" end-inst-point t)
8707 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
8708 (goto-char st-point)
8709 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
8710 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
8711 (goto-char st-point)
8712 (while (re-search-forward "\\s *(?\\s *// Inouts" end-inst-point t)
8713 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
8714 (goto-char st-point)
8715 (while (re-search-forward "\\s *(?\\s *// Inputs" end-inst-point t)
8716 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
8717 )))))))
8718 ;; Combine duplicate bits
8719 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
8720 (verilog-subdecls-new
8721 (verilog-signals-combine-bus (nreverse sigs-out))
8722 (verilog-signals-combine-bus (nreverse sigs-inout))
8723 (verilog-signals-combine-bus (nreverse sigs-in))
8724 (verilog-signals-combine-bus (nreverse sigs-intf))
8725 (verilog-signals-combine-bus (nreverse sigs-intfd))))))
8726
8727 (defun verilog-read-inst-pins ()
8728 "Return an array of [ pins ] for the current instantiation at point.
8729 For example if declare A A (.B(SIG)) then B will be included in the list."
8730 (save-excursion
8731 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
8732 pins pin)
8733 (verilog-backward-open-paren)
8734 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
8735 (setq pin (match-string 1))
8736 (unless (verilog-inside-comment-or-string-p)
8737 (setq pins (cons (list pin) pins))
8738 (when (looking-at "(")
8739 (verilog-forward-sexp-ign-cmt 1))))
8740 (vector pins))))
8741
8742 (defun verilog-read-arg-pins ()
8743 "Return an array of [ pins ] for the current argument declaration at point."
8744 (save-excursion
8745 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
8746 pins pin)
8747 (verilog-backward-open-paren)
8748 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
8749 (setq pin (match-string 1))
8750 (unless (verilog-inside-comment-or-string-p)
8751 (setq pins (cons (list pin) pins))))
8752 (vector pins))))
8753
8754 (defun verilog-read-auto-constants (beg end-mod-point)
8755 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
8756 ;; Insert new
8757 (save-excursion
8758 (let (sig-list tpl-end-pt)
8759 (goto-char beg)
8760 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
8761 (if (not (looking-at "\\s *("))
8762 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
8763 (search-forward "(" end-mod-point)
8764 (setq tpl-end-pt (save-excursion
8765 (backward-char 1)
8766 (verilog-forward-sexp-cmt 1) ;; Moves to paren that closes argdecl's
8767 (backward-char 1)
8768 (point)))
8769 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
8770 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
8771 sig-list)))
8772
8773 (defvar verilog-cache-has-lisp nil "True if any AUTO_LISP in buffer.")
8774 (make-variable-buffer-local 'verilog-cache-has-lisp)
8775
8776 (defun verilog-read-auto-lisp-present ()
8777 "Set `verilog-cache-has-lisp' if any AUTO_LISP in this buffer."
8778 (save-excursion
8779 (goto-char (point-min))
8780 (setq verilog-cache-has-lisp (re-search-forward "\\<AUTO_LISP(" nil t))))
8781
8782 (defun verilog-read-auto-lisp (start end)
8783 "Look for and evaluate an AUTO_LISP between START and END.
8784 Must call `verilog-read-auto-lisp-present' before this function."
8785 ;; This function is expensive for large buffers, so we cache if any AUTO_LISP exists
8786 (when verilog-cache-has-lisp
8787 (save-excursion
8788 (goto-char start)
8789 (while (re-search-forward "\\<AUTO_LISP(" end t)
8790 (backward-char)
8791 (let* ((beg-pt (prog1 (point)
8792 (verilog-forward-sexp-cmt 1))) ;; Closing paren
8793 (end-pt (point))
8794 (verilog-in-hooks t))
8795 (eval-region beg-pt end-pt nil))))))
8796
8797 (defun verilog-read-always-signals-recurse
8798 (exit-keywd rvalue temp-next)
8799 "Recursive routine for parentheses/bracket matching.
8800 EXIT-KEYWD is expression to stop at, nil if top level.
8801 RVALUE is true if at right hand side of equal.
8802 IGNORE-NEXT is true to ignore next token, fake from inside case statement."
8803 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
8804 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-list end-else-check
8805 ignore-next)
8806 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue temp-next))))
8807 (while (not (or (eobp) gotend))
8808 (cond
8809 ((looking-at "//")
8810 (search-forward "\n"))
8811 ((looking-at "/\\*")
8812 (or (search-forward "*/")
8813 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8814 ((looking-at "(\\*")
8815 ;; To advance past either "(*)" or "(* ... *)" don't forward past first *
8816 (forward-char 1)
8817 (or (search-forward "*)")
8818 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
8819 (t (setq keywd (buffer-substring-no-properties
8820 (point)
8821 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
8822 (forward-char 1))
8823 (point)))
8824 sig-last-tolk sig-tolk
8825 sig-tolk nil)
8826 ;;(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))))
8827 (cond
8828 ((equal keywd "\"")
8829 (or (re-search-forward "[^\\]\"" nil t)
8830 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
8831 ;; else at top level loop, keep parsing
8832 ((and end-else-check (equal keywd "else"))
8833 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
8834 ;; no forward movement, want to see else in lower loop
8835 (setq end-else-check nil))
8836 ;; End at top level loop
8837 ((and end-else-check (looking-at "[^ \t\n\f]"))
8838 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
8839 (setq gotend t))
8840 ;; Final statement?
8841 ((and exit-keywd (equal keywd exit-keywd))
8842 (setq gotend t)
8843 (forward-char (length keywd)))
8844 ;; Standard tokens...
8845 ((equal keywd ";")
8846 (setq ignore-next nil rvalue semi-rvalue)
8847 ;; Final statement at top level loop?
8848 (when (not exit-keywd)
8849 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
8850 (setq end-else-check t))
8851 (forward-char 1))
8852 ((equal keywd "'")
8853 (if (looking-at "'[sS]?[hdxboHDXBO]?[ \t]*[0-9a-fA-F_xzXZ?]+")
8854 (goto-char (match-end 0))
8855 (forward-char 1)))
8856 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
8857 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
8858 (setq ignore-next nil rvalue nil))
8859 ((equal "?" exit-keywd) ;; x?y:z rvalue
8860 ) ;; NOP
8861 ((equal "]" exit-keywd) ;; [x:y] rvalue
8862 ) ;; NOP
8863 (got-sig ;; label: statement
8864 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
8865 ((not rvalue) ;; begin label
8866 (setq ignore-next t rvalue nil)))
8867 (forward-char 1))
8868 ((equal keywd "=")
8869 (when got-sig
8870 ;;(if dbg (setq dbg (concat dbg (format "\t\tequal got-sig=%S got-list=%s\n" got-sig got-list))))
8871 (set got-list (cons got-sig (symbol-value got-list)))
8872 (setq got-sig nil))
8873 (when (not rvalue)
8874 (if (eq (char-before) ?< )
8875 (setq sigs-out-d (append sigs-out-d sigs-out-unk)
8876 sigs-out-unk nil)
8877 (setq sigs-out-i (append sigs-out-i sigs-out-unk)
8878 sigs-out-unk nil)))
8879 (setq ignore-next nil rvalue t)
8880 (forward-char 1))
8881 ((equal keywd "?")
8882 (forward-char 1)
8883 (verilog-read-always-signals-recurse ":" rvalue nil))
8884 ((equal keywd "[")
8885 (forward-char 1)
8886 (verilog-read-always-signals-recurse "]" t nil))
8887 ((equal keywd "(")
8888 (forward-char 1)
8889 (cond (sig-last-tolk ;; Function call; zap last signal
8890 (setq got-sig nil)))
8891 (cond ((equal last-keywd "for")
8892 ;; temp-next: Variables on LHS are lvalues, but generally we want
8893 ;; to ignore them, assuming they are loop increments
8894 (verilog-read-always-signals-recurse ";" nil t)
8895 (verilog-read-always-signals-recurse ";" t nil)
8896 (verilog-read-always-signals-recurse ")" nil nil))
8897 (t (verilog-read-always-signals-recurse ")" t nil))))
8898 ((equal keywd "begin")
8899 (skip-syntax-forward "w_")
8900 (verilog-read-always-signals-recurse "end" nil nil)
8901 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
8902 (setq ignore-next nil rvalue semi-rvalue)
8903 (if (not exit-keywd) (setq end-else-check t)))
8904 ((member keywd '("case" "casex" "casez"))
8905 (skip-syntax-forward "w_")
8906 (verilog-read-always-signals-recurse "endcase" t nil)
8907 (setq ignore-next nil rvalue semi-rvalue)
8908 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
8909 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
8910 (cond ((member keywd '("`ifdef" "`ifndef" "`elsif"))
8911 (setq ignore-next t))
8912 ((or ignore-next
8913 (member keywd verilog-keywords)
8914 (string-match "^\\$" keywd)) ;; PLI task
8915 (setq ignore-next nil))
8916 (t
8917 (setq keywd (verilog-symbol-detick-denumber keywd))
8918 (when got-sig
8919 (set got-list (cons got-sig (symbol-value got-list)))
8920 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S got-list=%S\n" got-sig got-list))))
8921 )
8922 (setq got-list (cond (temp-next 'sigs-temp)
8923 (rvalue 'sigs-in)
8924 (t 'sigs-out-unk))
8925 got-sig (if (or (not keywd)
8926 (assoc keywd (symbol-value got-list)))
8927 nil (list keywd nil nil))
8928 temp-next nil
8929 sig-tolk t)))
8930 (skip-chars-forward "a-zA-Z0-9$_.%`"))
8931 (t
8932 (forward-char 1)))
8933 ;; End of non-comment token
8934 (setq last-keywd keywd)))
8935 (skip-syntax-forward " "))
8936 ;; Append the final pending signal
8937 (when got-sig
8938 ;;(if dbg (setq dbg (concat dbg (format "\t\tfinal got-sig=%S got-list=%s\n" got-sig got-list))))
8939 (set got-list (cons got-sig (symbol-value got-list)))
8940 (setq got-sig nil))
8941 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
8942 ))
8943
8944 (defun verilog-read-always-signals ()
8945 "Parse always block at point and return list of (outputs inout inputs)."
8946 (save-excursion
8947 (let* (;;(dbg "")
8948 sigs-out-d sigs-out-i sigs-out-unk sigs-temp sigs-in)
8949 (verilog-read-always-signals-recurse nil nil nil)
8950 (setq sigs-out-i (append sigs-out-i sigs-out-unk)
8951 sigs-out-unk nil)
8952 ;;(if dbg (with-current-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg ""))
8953 ;; Return what was found
8954 (verilog-alw-new sigs-out-d sigs-out-i sigs-temp sigs-in))))
8955
8956 (defun verilog-read-instants ()
8957 "Parse module at point and return list of ( ( file instance ) ... )."
8958 (verilog-beg-of-defun-quick)
8959 (let* ((end-mod-point (verilog-get-end-of-defun))
8960 (state nil)
8961 (instants-list nil))
8962 (save-excursion
8963 (while (< (point) end-mod-point)
8964 ;; Stay at level 0, no comments
8965 (while (progn
8966 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
8967 (or (> (car state) 0) ; in parens
8968 (nth 5 state) ; comment
8969 ))
8970 (forward-line 1))
8971 (beginning-of-line)
8972 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
8973 ;;(if (looking-at "^\\(.+\\)$")
8974 (let ((module (match-string 1))
8975 (instant (match-string 2)))
8976 (if (not (member module verilog-keywords))
8977 (setq instants-list (cons (list module instant) instants-list)))))
8978 (forward-line 1)))
8979 instants-list))
8980
8981
8982 (defun verilog-read-auto-template-middle ()
8983 "With point in middle of an AUTO_TEMPLATE, parse it.
8984 Returns REGEXP and list of ( (signal_name connection_name)... )."
8985 (save-excursion
8986 ;; Find beginning
8987 (let ((tpl-regexp "\\([0-9]+\\)")
8988 (lineno -1) ; -1 to offset for the AUTO_TEMPLATE's newline
8989 (templateno 0)
8990 tpl-sig-list tpl-wild-list tpl-end-pt rep)
8991 ;; Parse "REGEXP"
8992 ;; We reserve @"..." for future lisp expressions that evaluate
8993 ;; once-per-AUTOINST
8994 (when (looking-at "\\s-*\"\\([^\"]*\\)\"")
8995 (setq tpl-regexp (match-string 1))
8996 (goto-char (match-end 0)))
8997 (search-forward "(")
8998 ;; Parse lines in the template
8999 (when (or verilog-auto-inst-template-numbers
9000 verilog-auto-template-warn-unused)
9001 (save-excursion
9002 (let ((pre-pt (point)))
9003 (goto-char (point-min))
9004 (while (search-forward "AUTO_TEMPLATE" pre-pt t)
9005 (setq templateno (1+ templateno)))
9006 (while (< (point) pre-pt)
9007 (forward-line 1)
9008 (setq lineno (1+ lineno))))))
9009 (setq tpl-end-pt (save-excursion
9010 (backward-char 1)
9011 (verilog-forward-sexp-cmt 1) ;; Moves to paren that closes argdecl's
9012 (backward-char 1)
9013 (point)))
9014 ;;
9015 (while (< (point) tpl-end-pt)
9016 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
9017 (setq tpl-sig-list
9018 (cons (list
9019 (match-string-no-properties 1)
9020 (match-string-no-properties 2)
9021 templateno lineno)
9022 tpl-sig-list))
9023 (goto-char (match-end 0)))
9024 ;; Regexp form??
9025 ((looking-at
9026 ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
9027 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
9028 (setq rep (match-string-no-properties 3))
9029 (goto-char (match-end 0))
9030 (setq tpl-wild-list
9031 (cons (list
9032 (concat "^"
9033 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
9034 (match-string 1))
9035 "$")
9036 rep
9037 templateno lineno)
9038 tpl-wild-list)))
9039 ((looking-at "[ \t\f]+")
9040 (goto-char (match-end 0)))
9041 ((looking-at "\n")
9042 (setq lineno (1+ lineno))
9043 (goto-char (match-end 0)))
9044 ((looking-at "//")
9045 (search-forward "\n")
9046 (setq lineno (1+ lineno)))
9047 ((looking-at "/\\*")
9048 (forward-char 2)
9049 (or (search-forward "*/")
9050 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
9051 (t
9052 (error "%s: AUTO_TEMPLATE parsing error: %s"
9053 (verilog-point-text)
9054 (progn (looking-at ".*$") (match-string 0))))))
9055 ;; Return
9056 (vector tpl-regexp
9057 (list tpl-sig-list tpl-wild-list)))))
9058
9059 (defun verilog-read-auto-template (module)
9060 "Look for an auto_template for the instantiation of the given MODULE.
9061 If found returns `verilog-read-auto-template-inside' structure."
9062 (save-excursion
9063 ;; Find beginning
9064 (let ((pt (point)))
9065 ;; Note this search is expensive, as we hunt from mod-begin to point
9066 ;; for every instantiation. Likewise in verilog-read-auto-lisp.
9067 ;; So, we look first for an exact string rather than a slow regexp.
9068 ;; Someday we may keep a cache of every template, but this would also
9069 ;; need to record the relative position of each AUTOINST, as multiple
9070 ;; templates exist for each module, and we're inserting lines.
9071 (cond ((or
9072 ;; See also regexp in `verilog-auto-template-lint'
9073 (verilog-re-search-backward-substr
9074 "AUTO_TEMPLATE"
9075 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
9076 ;; Also try forward of this AUTOINST
9077 ;; This is for historical support; this isn't speced as working
9078 (progn
9079 (goto-char pt)
9080 (verilog-re-search-forward-substr
9081 "AUTO_TEMPLATE"
9082 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
9083 (goto-char (match-end 0))
9084 (verilog-read-auto-template-middle))
9085 ;; If no template found
9086 (t (vector "" nil))))))
9087 ;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
9088
9089 (defvar verilog-auto-template-hits nil "Successful lookups with `verilog-read-auto-template-hit'.")
9090 (make-variable-buffer-local 'verilog-auto-template-hits)
9091
9092 (defun verilog-read-auto-template-hit (tpl-ass)
9093 "Record that TPL-ASS template from `verilog-read-auto-template' was used."
9094 (when (eval-when-compile (fboundp 'make-hash-table)) ;; else feature not allowed
9095 (when verilog-auto-template-warn-unused
9096 (unless verilog-auto-template-hits
9097 (setq verilog-auto-template-hits
9098 (make-hash-table :test 'equal :rehash-size 4.0)))
9099 (puthash (vector (nth 2 tpl-ass) (nth 3 tpl-ass)) t
9100 verilog-auto-template-hits))))
9101
9102 (defun verilog-set-define (defname defvalue &optional buffer enumname)
9103 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
9104 Optionally associate it with the specified enumeration ENUMNAME."
9105 (with-current-buffer (or buffer (current-buffer))
9106 ;; Namespace intentionally short for AUTOs and compatibility
9107 (let ((mac (intern (concat "vh-" defname))))
9108 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
9109 ;; Need to define to a constant if no value given
9110 (set (make-local-variable mac)
9111 (if (equal defvalue "") "1" defvalue)))
9112 (if enumname
9113 ;; Namespace intentionally short for AUTOs and compatibility
9114 (let ((enumvar (intern (concat "venum-" enumname))))
9115 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
9116 (unless (boundp enumvar) (set enumvar nil))
9117 (add-to-list (make-local-variable enumvar) defname)))))
9118
9119 (defun verilog-read-defines (&optional filename recurse subcall)
9120 "Read `defines and parameters for the current file, or optional FILENAME.
9121 If the filename is provided, `verilog-library-flags' will be used to
9122 resolve it. If optional RECURSE is non-nil, recurse through `includes.
9123
9124 Parameters must be simple assignments to constants, or have their own
9125 \"parameter\" label rather than a list of parameters. Thus:
9126
9127 parameter X = 5, Y = 10; // Ok
9128 parameter X = {1'b1, 2'h2}; // Ok
9129 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
9130
9131 Defines must be simple text substitutions, one on a line, starting
9132 at the beginning of the line. Any ifdefs or multiline comments around the
9133 define are ignored.
9134
9135 Defines are stored inside Emacs variables using the name vh-{definename}.
9136
9137 This function is useful for setting vh-* variables. The file variables
9138 feature can be used to set defines that `verilog-mode' can see; put at the
9139 *END* of your file something like:
9140
9141 // Local Variables:
9142 // vh-macro:\"macro_definition\"
9143 // End:
9144
9145 If macros are defined earlier in the same file and you want their values,
9146 you can read them automatically (provided `enable-local-eval' is on):
9147
9148 // Local Variables:
9149 // eval:(verilog-read-defines)
9150 // eval:(verilog-read-defines \"group_standard_includes.v\")
9151 // End:
9152
9153 Note these are only read when the file is first visited, you must use
9154 \\[find-alternate-file] RET to have these take effect after editing them!
9155
9156 If you want to disable the \"Process `eval' or hook local variables\"
9157 warning message, you need to add to your init file:
9158
9159 (setq enable-local-eval t)"
9160 (let ((origbuf (current-buffer)))
9161 (save-excursion
9162 (unless subcall (verilog-getopt-flags))
9163 (when filename
9164 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
9165 (if fns
9166 (set-buffer (find-file-noselect (car fns)))
9167 (error (concat (verilog-point-text)
9168 ": Can't find verilog-read-defines file: " filename)))))
9169 (when recurse
9170 (goto-char (point-min))
9171 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
9172 (let ((inc (verilog-string-replace-matches
9173 "\"" "" nil nil (match-string-no-properties 1))))
9174 (unless (verilog-inside-comment-or-string-p)
9175 (verilog-read-defines inc recurse t)))))
9176 ;; Read `defines
9177 ;; note we don't use verilog-re... it's faster this way, and that
9178 ;; function has problems when comments are at the end of the define
9179 (goto-char (point-min))
9180 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
9181 (let ((defname (match-string-no-properties 1))
9182 (defvalue (match-string-no-properties 2)))
9183 (unless (verilog-inside-comment-or-string-p (match-beginning 0))
9184 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
9185 (verilog-set-define defname defvalue origbuf))))
9186 ;; Hack: Read parameters
9187 (goto-char (point-min))
9188 (while (re-search-forward
9189 "^\\s-*\\(parameter\\|localparam\\)\\(\\s-*\\[[^]]*\\]\\)?\\s-*" nil t)
9190 (let (enumname)
9191 ;; The primary way of getting defines is verilog-read-decls
9192 ;; However, that isn't called yet for included files, so we'll add another scheme
9193 (if (looking-at "[^\n]*\\(auto\\|synopsys\\)\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
9194 (setq enumname (match-string-no-properties 2)))
9195 (forward-comment 99999)
9196 (while (looking-at (concat "\\s-*,?\\s-*\\(?:/[/*].*?$\\)?\\s-*\\([a-zA-Z0-9_$]+\\)"
9197 "\\s-*=\\s-*\\([^;,]*\\),?\\s-*\\(/[/*].*?$\\)?\\s-*"))
9198 (unless (verilog-inside-comment-or-string-p (match-beginning 0))
9199 (verilog-set-define (match-string-no-properties 1)
9200 (match-string-no-properties 2) origbuf enumname))
9201 (goto-char (match-end 0))
9202 (forward-comment 99999)))))))
9203
9204 (defun verilog-read-includes ()
9205 "Read `includes for the current file.
9206 This will find all of the `includes which are at the beginning of lines,
9207 ignoring any ifdefs or multiline comments around them.
9208 `verilog-read-defines' is then performed on the current and each included
9209 file.
9210
9211 It is often useful put at the *END* of your file something like:
9212
9213 // Local Variables:
9214 // eval:(verilog-read-defines)
9215 // eval:(verilog-read-includes)
9216 // End:
9217
9218 Note includes are only read when the file is first visited, you must use
9219 \\[find-alternate-file] RET to have these take effect after editing them!
9220
9221 It is good to get in the habit of including all needed files in each .v
9222 file that needs it, rather than waiting for compile time. This will aid
9223 this process, Verilint, and readability. To prevent defining the same
9224 variable over and over when many modules are compiled together, put a test
9225 around the inside each include file:
9226
9227 foo.v (an include file):
9228 `ifdef _FOO_V // include if not already included
9229 `else
9230 `define _FOO_V
9231 ... contents of file
9232 `endif // _FOO_V"
9233 ;;slow: (verilog-read-defines nil t)
9234 (save-excursion
9235 (verilog-getopt-flags)
9236 (goto-char (point-min))
9237 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
9238 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
9239 (verilog-read-defines inc nil t)))))
9240
9241 (defun verilog-read-signals (&optional start end)
9242 "Return a simple list of all possible signals in the file.
9243 Bounded by optional region from START to END. Overly aggressive but fast.
9244 Some macros and such are also found and included. For dinotrace.el."
9245 (let (sigs-all keywd)
9246 (progn;save-excursion
9247 (goto-char (or start (point-min)))
9248 (setq end (or end (point-max)))
9249 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
9250 (forward-char -1)
9251 (cond
9252 ((looking-at "//")
9253 (search-forward "\n"))
9254 ((looking-at "/\\*")
9255 (search-forward "*/"))
9256 ((looking-at "(\\*")
9257 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
9258 (search-forward "*)")))
9259 ((eq ?\" (following-char))
9260 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
9261 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
9262 (goto-char (match-end 0))
9263 (setq keywd (match-string-no-properties 1))
9264 (or (member keywd verilog-keywords)
9265 (member keywd sigs-all)
9266 (setq sigs-all (cons keywd sigs-all))))
9267 (t (forward-char 1))))
9268 ;; Return list
9269 sigs-all)))
9270
9271 ;;
9272 ;; Argument file parsing
9273 ;;
9274
9275 (defun verilog-getopt (arglist)
9276 "Parse -f, -v etc arguments in ARGLIST list or string."
9277 (unless (listp arglist) (setq arglist (list arglist)))
9278 (let ((space-args '())
9279 arg next-param)
9280 ;; Split on spaces, so users can pass whole command lines
9281 (while arglist
9282 (setq arg (car arglist)
9283 arglist (cdr arglist))
9284 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
9285 (setq space-args (append space-args
9286 (list (match-string-no-properties 1 arg))))
9287 (setq arg (match-string 2 arg))))
9288 ;; Parse arguments
9289 (while space-args
9290 (setq arg (car space-args)
9291 space-args (cdr space-args))
9292 (cond
9293 ;; Need another arg
9294 ((equal arg "-f")
9295 (setq next-param arg))
9296 ((equal arg "-v")
9297 (setq next-param arg))
9298 ((equal arg "-y")
9299 (setq next-param arg))
9300 ;; +libext+(ext1)+(ext2)...
9301 ((string-match "^\\+libext\\+\\(.*\\)" arg)
9302 (setq arg (match-string 1 arg))
9303 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
9304 (verilog-add-list-unique `verilog-library-extensions
9305 (match-string 1 arg))
9306 (setq arg (match-string 2 arg))))
9307 ;;
9308 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
9309 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
9310 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
9311 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
9312 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
9313 ;;
9314 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
9315 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
9316 (verilog-add-list-unique `verilog-library-directories
9317 (match-string 1 (substitute-in-file-name arg))))
9318 ;; Ignore
9319 ((equal "+librescan" arg))
9320 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
9321 ;; Second parameters
9322 ((equal next-param "-f")
9323 (setq next-param nil)
9324 (verilog-getopt-file (substitute-in-file-name arg)))
9325 ((equal next-param "-v")
9326 (setq next-param nil)
9327 (verilog-add-list-unique `verilog-library-files
9328 (substitute-in-file-name arg)))
9329 ((equal next-param "-y")
9330 (setq next-param nil)
9331 (verilog-add-list-unique `verilog-library-directories
9332 (substitute-in-file-name arg)))
9333 ;; Filename
9334 ((string-match "^[^-+]" arg)
9335 (verilog-add-list-unique `verilog-library-files
9336 (substitute-in-file-name arg)))
9337 ;; Default - ignore; no warning
9338 ))))
9339 ;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
9340
9341 (defun verilog-getopt-file (filename)
9342 "Read Verilog options from the specified FILENAME."
9343 (save-excursion
9344 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
9345 (orig-buffer (current-buffer))
9346 line)
9347 (if fns
9348 (set-buffer (find-file-noselect (car fns)))
9349 (error (concat (verilog-point-text)
9350 ": Can't find verilog-getopt-file -f file: " filename)))
9351 (goto-char (point-min))
9352 (while (not (eobp))
9353 (setq line (buffer-substring (point) (point-at-eol)))
9354 (forward-line 1)
9355 (when (string-match "//" line)
9356 (setq line (substring line 0 (match-beginning 0))))
9357 (with-current-buffer orig-buffer ; Variables are buffer-local, so need right context.
9358 (verilog-getopt line))))))
9359
9360 (defun verilog-getopt-flags ()
9361 "Convert `verilog-library-flags' into standard library variables."
9362 ;; If the flags are local, then all the outputs should be local also
9363 (when (local-variable-p `verilog-library-flags (current-buffer))
9364 (mapc 'make-local-variable '(verilog-library-extensions
9365 verilog-library-directories
9366 verilog-library-files
9367 verilog-library-flags)))
9368 ;; Allow user to customize
9369 (verilog-run-hooks 'verilog-before-getopt-flags-hook)
9370 ;; Process arguments
9371 (verilog-getopt verilog-library-flags)
9372 ;; Allow user to customize
9373 (verilog-run-hooks 'verilog-getopt-flags-hook))
9374
9375 (defun verilog-add-list-unique (varref object)
9376 "Append to VARREF list the given OBJECT,
9377 unless it is already a member of the variable's list."
9378 (unless (member object (symbol-value varref))
9379 (set varref (append (symbol-value varref) (list object))))
9380 varref)
9381 ;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
9382
9383 (defun verilog-current-flags ()
9384 "Convert `verilog-library-flags' and similar variables to command line.
9385 Used for __FLAGS__ in `verilog-expand-command'."
9386 (let ((cmd (mapconcat `concat verilog-library-flags " ")))
9387 (when (equal cmd "")
9388 (setq cmd (concat
9389 "+libext+" (mapconcat `concat verilog-library-extensions "+")
9390 (mapconcat (lambda (i) (concat " -y " i " +incdir+" i))
9391 verilog-library-directories "")
9392 (mapconcat (lambda (i) (concat " -v " i))
9393 verilog-library-files ""))))
9394 cmd))
9395 ;;(verilog-current-flags)
9396
9397 \f
9398 ;;
9399 ;; Cached directory support
9400 ;;
9401
9402 (defvar verilog-dir-cache-preserving nil
9403 "If true, the directory cache is enabled, and file system changes are ignored.
9404 See `verilog-dir-exists-p' and `verilog-dir-files'.")
9405
9406 ;; If adding new cached variable, add also to verilog-preserve-dir-cache
9407 (defvar verilog-dir-cache-list nil
9408 "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
9409 (defvar verilog-dir-cache-lib-filenames nil
9410 "Cached data for `verilog-library-filenames'.")
9411
9412 (defmacro verilog-preserve-dir-cache (&rest body)
9413 "Execute the BODY forms, allowing directory cache preservation within BODY.
9414 This means that changes inside BODY made to the file system will not be
9415 seen by the `verilog-dir-files' and related functions."
9416 `(let ((verilog-dir-cache-preserving (current-buffer))
9417 verilog-dir-cache-list
9418 verilog-dir-cache-lib-filenames)
9419 (progn ,@body)))
9420
9421 (defun verilog-dir-files (dirname)
9422 "Return all filenames in the DIRNAME directory.
9423 Relative paths depend on the `default-directory'.
9424 Results are cached if inside `verilog-preserve-dir-cache'."
9425 (unless verilog-dir-cache-preserving
9426 (setq verilog-dir-cache-list nil)) ;; Cache disabled
9427 ;; We don't use expand-file-name on the dirname to make key, as it's slow
9428 (let* ((cache-key (list dirname default-directory))
9429 (fass (assoc cache-key verilog-dir-cache-list))
9430 exp-dirname data)
9431 (cond (fass ;; Return data from cache hit
9432 (nth 1 fass))
9433 (t
9434 (setq exp-dirname (expand-file-name dirname)
9435 data (and (file-directory-p exp-dirname)
9436 (directory-files exp-dirname nil nil nil)))
9437 ;; Note we also encache nil for non-existing dirs.
9438 (setq verilog-dir-cache-list (cons (list cache-key data)
9439 verilog-dir-cache-list))
9440 data))))
9441 ;; Miss-and-hit test:
9442 ;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
9443 ;; (prin1 (verilog-dir-files ".")) nil)
9444
9445 (defun verilog-dir-file-exists-p (filename)
9446 "Return true if FILENAME exists.
9447 Like `file-exists-p' but results are cached if inside
9448 `verilog-preserve-dir-cache'."
9449 (let* ((dirname (file-name-directory filename))
9450 ;; Correct for file-name-nondirectory returning same if no slash.
9451 (dirnamed (if (or (not dirname) (equal dirname filename))
9452 default-directory dirname))
9453 (flist (verilog-dir-files dirnamed)))
9454 (and flist
9455 (member (file-name-nondirectory filename) flist)
9456 t)))
9457 ;;(verilog-dir-file-exists-p "verilog-mode.el")
9458 ;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
9459
9460 \f
9461 ;;
9462 ;; Module name lookup
9463 ;;
9464
9465 (defun verilog-module-inside-filename-p (module filename)
9466 "Return modi if MODULE is specified inside FILENAME, else nil.
9467 Allows version control to check out the file if need be."
9468 (and (or (file-exists-p filename)
9469 (and (fboundp 'vc-backend)
9470 (vc-backend filename)))
9471 (let (modi type)
9472 (with-current-buffer (find-file-noselect filename)
9473 (save-excursion
9474 (goto-char (point-min))
9475 (while (and
9476 ;; It may be tempting to look for verilog-defun-re,
9477 ;; don't, it slows things down a lot!
9478 (verilog-re-search-forward-quick "\\<\\(module\\|interface\\|program\\)\\>" nil t)
9479 (setq type (match-string-no-properties 0))
9480 (verilog-re-search-forward-quick "[(;]" nil t))
9481 (if (equal module (verilog-read-module-name))
9482 (setq modi (verilog-modi-new module filename (point) type))))
9483 modi)))))
9484
9485 (defun verilog-is-number (symbol)
9486 "Return true if SYMBOL is number-like."
9487 (or (string-match "^[0-9 \t:]+$" symbol)
9488 (string-match "^[---]*[0-9]+$" symbol)
9489 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
9490
9491 (defun verilog-symbol-detick (symbol wing-it)
9492 "Return an expanded SYMBOL name without any defines.
9493 If the variable vh-{symbol} is defined, return that value.
9494 If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
9495 (while (and symbol (string-match "^`" symbol))
9496 (setq symbol (substring symbol 1))
9497 (setq symbol
9498 ;; Namespace intentionally short for AUTOs and compatibility
9499 (if (boundp (intern (concat "vh-" symbol)))
9500 ;; Emacs has a bug where boundp on a buffer-local
9501 ;; variable in only one buffer returns t in another.
9502 ;; This can confuse, so check for nil.
9503 ;; Namespace intentionally short for AUTOs and compatibility
9504 (let ((val (eval (intern (concat "vh-" symbol)))))
9505 (if (eq val nil)
9506 (if wing-it symbol nil)
9507 val))
9508 (if wing-it symbol nil))))
9509 symbol)
9510 ;;(verilog-symbol-detick "`mod" nil)
9511
9512 (defun verilog-symbol-detick-denumber (symbol)
9513 "Return SYMBOL with defines converted and any numbers dropped to nil."
9514 (when (string-match "^`" symbol)
9515 ;; This only will work if the define is a simple signal, not
9516 ;; something like a[b]. Sorry, it should be substituted into the parser
9517 (setq symbol
9518 (verilog-string-replace-matches
9519 "\[[^0-9: \t]+\]" "" nil nil
9520 (or (verilog-symbol-detick symbol nil)
9521 (if verilog-auto-sense-defines-constant
9522 "0"
9523 symbol)))))
9524 (if (verilog-is-number symbol)
9525 nil
9526 symbol))
9527
9528 (defun verilog-symbol-detick-text (text)
9529 "Return TEXT without any known defines.
9530 If the variable vh-{symbol} is defined, substitute that value."
9531 (let ((ok t) symbol val)
9532 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
9533 (setq symbol (match-string 1 text))
9534 ;;(message symbol)
9535 (cond ((and
9536 ;; Namespace intentionally short for AUTOs and compatibility
9537 (boundp (intern (concat "vh-" symbol)))
9538 ;; Emacs has a bug where boundp on a buffer-local
9539 ;; variable in only one buffer returns t in another.
9540 ;; This can confuse, so check for nil.
9541 ;; Namespace intentionally short for AUTOs and compatibility
9542 (setq val (eval (intern (concat "vh-" symbol)))))
9543 (setq text (replace-match val nil nil text)))
9544 (t (setq ok nil)))))
9545 text)
9546 ;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
9547
9548 (defun verilog-expand-dirnames (&optional dirnames)
9549 "Return a list of existing directories given a list of wildcarded DIRNAMES.
9550 Or, just the existing dirnames themselves if there are no wildcards."
9551 ;; Note this function is performance critical.
9552 ;; Do not call anything that requires disk access that cannot be cached.
9553 (interactive)
9554 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
9555 (setq dirnames (reverse dirnames)) ; not nreverse
9556 (let ((dirlist nil)
9557 pattern dirfile dirfiles dirname root filename rest basefile)
9558 (while dirnames
9559 (setq dirname (substitute-in-file-name (car dirnames))
9560 dirnames (cdr dirnames))
9561 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
9562 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
9563 "\\(.*\\)") ;; rest
9564 dirname)
9565 (setq root (match-string 1 dirname)
9566 filename (match-string 2 dirname)
9567 rest (match-string 3 dirname)
9568 pattern filename)
9569 ;; now replace those * and ? with .+ and .
9570 ;; use ^ and /> to get only whole file names
9571 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
9572 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
9573 pattern (concat "^" pattern "$")
9574 dirfiles (verilog-dir-files root))
9575 (while dirfiles
9576 (setq basefile (car dirfiles)
9577 dirfile (expand-file-name (concat root basefile rest))
9578 dirfiles (cdr dirfiles))
9579 (if (and (string-match pattern basefile)
9580 ;; Don't allow abc/*/rtl to match abc/rtl via ..
9581 (not (equal basefile "."))
9582 (not (equal basefile ".."))
9583 (file-directory-p dirfile))
9584 (setq dirlist (cons dirfile dirlist)))))
9585 ;; Defaults
9586 (t
9587 (if (file-directory-p dirname)
9588 (setq dirlist (cons dirname dirlist))))))
9589 dirlist))
9590 ;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
9591
9592 (defun verilog-library-filenames (filename &optional current check-ext)
9593 "Return a search path to find the given FILENAME or module name.
9594 Uses the optional CURRENT filename or variable `buffer-file-name', plus
9595 `verilog-library-directories' and `verilog-library-extensions'
9596 variables to build the path. With optional CHECK-EXT also check
9597 `verilog-library-extensions'."
9598 (unless current (setq current (buffer-file-name)))
9599 (unless verilog-dir-cache-preserving
9600 (setq verilog-dir-cache-lib-filenames nil))
9601 (let* ((cache-key (list filename current check-ext))
9602 (fass (assoc cache-key verilog-dir-cache-lib-filenames))
9603 chkdirs chkdir chkexts fn outlist)
9604 (cond (fass ;; Return data from cache hit
9605 (nth 1 fass))
9606 (t
9607 ;; Note this expand can't be easily cached, as we need to
9608 ;; pick up buffer-local variables for newly read sub-module files
9609 (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
9610 (while chkdirs
9611 (setq chkdir (expand-file-name (car chkdirs)
9612 (file-name-directory current))
9613 chkexts (if check-ext verilog-library-extensions `("")))
9614 (while chkexts
9615 (setq fn (expand-file-name (concat filename (car chkexts))
9616 chkdir))
9617 ;;(message "Check for %s" fn)
9618 (if (verilog-dir-file-exists-p fn)
9619 (setq outlist (cons (expand-file-name
9620 fn (file-name-directory current))
9621 outlist)))
9622 (setq chkexts (cdr chkexts)))
9623 (setq chkdirs (cdr chkdirs)))
9624 (setq outlist (nreverse outlist))
9625 (setq verilog-dir-cache-lib-filenames
9626 (cons (list cache-key outlist)
9627 verilog-dir-cache-lib-filenames))
9628 outlist))))
9629
9630 (defun verilog-module-filenames (module current)
9631 "Return a search path to find the given MODULE name.
9632 Uses the CURRENT filename, `verilog-library-extensions',
9633 `verilog-library-directories' and `verilog-library-files'
9634 variables to build the path."
9635 ;; Return search locations for it
9636 (append (list current) ; first, current buffer
9637 (verilog-library-filenames module current t)
9638 verilog-library-files)) ; finally, any libraries
9639
9640 ;;
9641 ;; Module Information
9642 ;;
9643 ;; Many of these functions work on "modi" a module information structure
9644 ;; A modi is: [module-name-string file-name begin-point]
9645
9646 (defvar verilog-cache-enabled t
9647 "Non-nil enables caching of signals, etc. Set to nil for debugging to make things SLOW!")
9648
9649 (defvar verilog-modi-cache-list nil
9650 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
9651 For speeding up verilog-modi-get-* commands.
9652 Buffer-local.")
9653 (make-variable-buffer-local 'verilog-modi-cache-list)
9654
9655 (defvar verilog-modi-cache-preserve-tick nil
9656 "Modification tick after which the cache is still considered valid.
9657 Use `verilog-preserve-modi-cache' to set it.")
9658 (defvar verilog-modi-cache-preserve-buffer nil
9659 "Modification tick after which the cache is still considered valid.
9660 Use `verilog-preserve-modi-cache' to set it.")
9661 (defvar verilog-modi-cache-current-enable nil
9662 "Non-nil means allow caching `verilog-modi-current', set by let().")
9663 (defvar verilog-modi-cache-current nil
9664 "Currently active `verilog-modi-current', if any, set by let().")
9665 (defvar verilog-modi-cache-current-max nil
9666 "Current endmodule point for `verilog-modi-cache-current', if any.")
9667
9668 (defun verilog-modi-current ()
9669 "Return the modi structure for the module currently at point, possibly cached."
9670 (cond ((and verilog-modi-cache-current
9671 (>= (point) (verilog-modi-get-point verilog-modi-cache-current))
9672 (<= (point) verilog-modi-cache-current-max))
9673 ;; Slow assertion, for debugging the cache:
9674 ;;(or (equal verilog-modi-cache-current (verilog-modi-current-get)) (debug))
9675 verilog-modi-cache-current)
9676 (verilog-modi-cache-current-enable
9677 (setq verilog-modi-cache-current (verilog-modi-current-get)
9678 verilog-modi-cache-current-max
9679 ;; The cache expires when we pass "endmodule" as then the
9680 ;; current modi may change to the next module
9681 ;; This relies on the AUTOs generally inserting, not deleting text
9682 (save-excursion
9683 (verilog-re-search-forward-quick verilog-end-defun-re nil nil)))
9684 verilog-modi-cache-current)
9685 (t
9686 (verilog-modi-current-get))))
9687
9688 (defun verilog-modi-current-get ()
9689 "Return the modi structure for the module currently at point."
9690 (let* (name type pt)
9691 ;; read current module's name
9692 (save-excursion
9693 (verilog-re-search-backward-quick verilog-defun-re nil nil)
9694 (setq type (match-string-no-properties 0))
9695 (verilog-re-search-forward-quick "(" nil nil)
9696 (setq name (verilog-read-module-name))
9697 (setq pt (point)))
9698 ;; return modi - note this vector built two places
9699 (verilog-modi-new name (or (buffer-file-name) (current-buffer)) pt type)))
9700
9701 (defvar verilog-modi-lookup-cache nil "Hash of (modulename modi).")
9702 (make-variable-buffer-local 'verilog-modi-lookup-cache)
9703 (defvar verilog-modi-lookup-last-current nil "Cache of `current-buffer' at last lookup.")
9704 (defvar verilog-modi-lookup-last-tick nil "Cache of `buffer-chars-modified-tick' at last lookup.")
9705
9706 (defun verilog-modi-lookup (module allow-cache &optional ignore-error)
9707 "Find the file and point at which MODULE is defined.
9708 If ALLOW-CACHE is set, check and remember cache of previous lookups.
9709 Return modi if successful, else print message unless IGNORE-ERROR is true."
9710 (let* ((current (or (buffer-file-name) (current-buffer)))
9711 modi)
9712 ;; Check cache
9713 ;;(message "verilog-modi-lookup: %s" module)
9714 (cond ((and verilog-modi-lookup-cache
9715 verilog-cache-enabled
9716 allow-cache
9717 (setq modi (gethash module verilog-modi-lookup-cache))
9718 (equal verilog-modi-lookup-last-current current)
9719 ;; If hit is in current buffer, then tick must match
9720 (or (equal verilog-modi-lookup-last-tick (buffer-chars-modified-tick))
9721 (not (equal current (verilog-modi-file-or-buffer modi)))))
9722 ;;(message "verilog-modi-lookup: HIT %S" modi)
9723 modi)
9724 ;; Miss
9725 (t (let* ((realname (verilog-symbol-detick module t))
9726 (orig-filenames (verilog-module-filenames realname current))
9727 (filenames orig-filenames)
9728 mif)
9729 (while (and filenames (not mif))
9730 (if (not (setq mif (verilog-module-inside-filename-p realname (car filenames))))
9731 (setq filenames (cdr filenames))))
9732 ;; mif has correct form to become later elements of modi
9733 (cond (mif (setq modi mif))
9734 (t (setq modi nil)
9735 (or ignore-error
9736 (error (concat (verilog-point-text)
9737 ": Can't locate " module " module definition"
9738 (if (not (equal module realname))
9739 (concat " (Expanded macro to " realname ")")
9740 "")
9741 "\n Check the verilog-library-directories variable."
9742 "\n I looked in (if not listed, doesn't exist):\n\t"
9743 (mapconcat 'concat orig-filenames "\n\t"))))))
9744 (when (eval-when-compile (fboundp 'make-hash-table))
9745 (unless verilog-modi-lookup-cache
9746 (setq verilog-modi-lookup-cache
9747 (make-hash-table :test 'equal :rehash-size 4.0)))
9748 (puthash module modi verilog-modi-lookup-cache))
9749 (setq verilog-modi-lookup-last-current current
9750 verilog-modi-lookup-last-tick (buffer-chars-modified-tick)))))
9751 modi))
9752
9753 (defun verilog-modi-filename (modi)
9754 "Filename of MODI, or name of buffer if it's never been saved."
9755 (if (bufferp (verilog-modi-file-or-buffer modi))
9756 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
9757 (buffer-name (verilog-modi-file-or-buffer modi)))
9758 (verilog-modi-file-or-buffer modi)))
9759
9760 (defun verilog-modi-goto (modi)
9761 "Move point/buffer to specified MODI."
9762 (or modi (error "Passed unfound modi to goto, check earlier"))
9763 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
9764 (verilog-modi-file-or-buffer modi)
9765 (find-file-noselect (verilog-modi-file-or-buffer modi))))
9766 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
9767 (verilog-mode))
9768 (goto-char (verilog-modi-get-point modi)))
9769
9770 (defun verilog-goto-defun-file (module)
9771 "Move point to the file at which a given MODULE is defined."
9772 (interactive "sGoto File for Module: ")
9773 (let* ((modi (verilog-modi-lookup module nil)))
9774 (when modi
9775 (verilog-modi-goto modi)
9776 (switch-to-buffer (current-buffer)))))
9777
9778 (defun verilog-modi-cache-results (modi function)
9779 "Run on MODI the given FUNCTION. Locate the module in a file.
9780 Cache the output of function so next call may have faster access."
9781 (let (fass)
9782 (save-excursion ;; Cache is buffer-local so can't avoid this.
9783 (verilog-modi-goto modi)
9784 (if (and (setq fass (assoc (list modi function)
9785 verilog-modi-cache-list))
9786 ;; Destroy caching when incorrect; Modified or file changed
9787 (not (and verilog-cache-enabled
9788 (or (equal (buffer-chars-modified-tick) (nth 1 fass))
9789 (and verilog-modi-cache-preserve-tick
9790 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
9791 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
9792 (equal (visited-file-modtime) (nth 2 fass)))))
9793 (setq verilog-modi-cache-list nil
9794 fass nil))
9795 (cond (fass
9796 ;; Return data from cache hit
9797 (nth 3 fass))
9798 (t
9799 ;; Read from file
9800 ;; Clear then restore any highlighting to make emacs19 happy
9801 (let (func-returns)
9802 (verilog-save-font-mods
9803 (setq func-returns (funcall function)))
9804 ;; Cache for next time
9805 (setq verilog-modi-cache-list
9806 (cons (list (list modi function)
9807 (buffer-chars-modified-tick)
9808 (visited-file-modtime)
9809 func-returns)
9810 verilog-modi-cache-list))
9811 func-returns))))))
9812
9813 (defun verilog-modi-cache-add (modi function element sig-list)
9814 "Add function return results to the module cache.
9815 Update MODI's cache for given FUNCTION so that the return ELEMENT of that
9816 function now contains the additional SIG-LIST parameters."
9817 (let (fass)
9818 (save-excursion
9819 (verilog-modi-goto modi)
9820 (if (setq fass (assoc (list modi function)
9821 verilog-modi-cache-list))
9822 (let ((func-returns (nth 3 fass)))
9823 (aset func-returns element
9824 (append sig-list (aref func-returns element))))))))
9825
9826 (defmacro verilog-preserve-modi-cache (&rest body)
9827 "Execute the BODY forms, allowing cache preservation within BODY.
9828 This means that changes to the buffer will not result in the cache being
9829 flushed. If the changes affect the modsig state, they must call the
9830 modsig-cache-add-* function, else the results of later calls may be
9831 incorrect. Without this, changes are assumed to be adding/removing signals
9832 and invalidating the cache."
9833 `(let ((verilog-modi-cache-preserve-tick (buffer-chars-modified-tick))
9834 (verilog-modi-cache-preserve-buffer (current-buffer)))
9835 (progn ,@body)))
9836
9837
9838 (defun verilog-modi-modport-lookup-one (modi name &optional ignore-error)
9839 "Given a MODI, return the declarations related to the given modport NAME."
9840 ;; Recursive routine - see below
9841 (let* ((realname (verilog-symbol-detick name t))
9842 (modport (assoc name (verilog-decls-get-modports (verilog-modi-get-decls modi)))))
9843 (or modport ignore-error
9844 (error (concat (verilog-point-text)
9845 ": Can't locate " name " modport definition"
9846 (if (not (equal name realname))
9847 (concat " (Expanded macro to " realname ")")
9848 ""))))
9849 (let* ((decls (verilog-modport-decls modport))
9850 (clks (verilog-modport-clockings modport)))
9851 ;; Now expand any clocking's
9852 (while clks
9853 (setq decls (verilog-decls-append
9854 decls
9855 (verilog-modi-modport-lookup-one modi (car clks) ignore-error)))
9856 (setq clks (cdr clks)))
9857 decls)))
9858
9859 (defun verilog-modi-modport-lookup (modi name-re &optional ignore-error)
9860 "Given a MODI, return the declarations related to the given modport NAME-RE.
9861 If the modport points to any clocking blocks, expand the signals to include
9862 those clocking block's signals."
9863 ;; Recursive routine - see below
9864 (let* ((mod-decls (verilog-modi-get-decls modi))
9865 (clks (verilog-decls-get-modports mod-decls))
9866 (name-re (concat "^" name-re "$"))
9867 (decls (verilog-decls-new nil nil nil nil nil nil nil nil nil)))
9868 ;; Pull in all modports
9869 (while clks
9870 (when (string-match name-re (verilog-modport-name (car clks)))
9871 (setq decls (verilog-decls-append
9872 decls
9873 (verilog-modi-modport-lookup-one modi (verilog-modport-name (car clks)) ignore-error))))
9874 (setq clks (cdr clks)))
9875 decls))
9876
9877 (defun verilog-signals-matching-enum (in-list enum)
9878 "Return all signals in IN-LIST matching the given ENUM."
9879 (let (out-list)
9880 (while in-list
9881 (if (equal (verilog-sig-enum (car in-list)) enum)
9882 (setq out-list (cons (car in-list) out-list)))
9883 (setq in-list (cdr in-list)))
9884 ;; New scheme
9885 ;; Namespace intentionally short for AUTOs and compatibility
9886 (let* ((enumvar (intern (concat "venum-" enum)))
9887 (enumlist (and (boundp enumvar) (eval enumvar))))
9888 (while enumlist
9889 (add-to-list 'out-list (list (car enumlist)))
9890 (setq enumlist (cdr enumlist))))
9891 (nreverse out-list)))
9892
9893 (defun verilog-signals-matching-regexp (in-list regexp)
9894 "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
9895 (if (or (not regexp) (equal regexp ""))
9896 in-list
9897 (let ((case-fold-search verilog-case-fold)
9898 out-list)
9899 (while in-list
9900 (if (string-match regexp (verilog-sig-name (car in-list)))
9901 (setq out-list (cons (car in-list) out-list)))
9902 (setq in-list (cdr in-list)))
9903 (nreverse out-list))))
9904
9905 (defun verilog-signals-not-matching-regexp (in-list regexp)
9906 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
9907 (if (or (not regexp) (equal regexp ""))
9908 in-list
9909 (let ((case-fold-search verilog-case-fold)
9910 out-list)
9911 (while in-list
9912 (if (not (string-match regexp (verilog-sig-name (car in-list))))
9913 (setq out-list (cons (car in-list) out-list)))
9914 (setq in-list (cdr in-list)))
9915 (nreverse out-list))))
9916
9917 (defun verilog-signals-matching-dir-re (in-list decl-type regexp)
9918 "Return all signals in IN-LIST matching the given DECL-TYPE and REGEXP,
9919 if non-nil."
9920 (if (or (not regexp) (equal regexp ""))
9921 in-list
9922 (let (out-list to-match)
9923 (while in-list
9924 ;; Note verilog-insert-one-definition matches on this order
9925 (setq to-match (concat
9926 decl-type
9927 " " (verilog-sig-signed (car in-list))
9928 " " (verilog-sig-multidim (car in-list))
9929 (verilog-sig-bits (car in-list))))
9930 (if (string-match regexp to-match)
9931 (setq out-list (cons (car in-list) out-list)))
9932 (setq in-list (cdr in-list)))
9933 (nreverse out-list))))
9934
9935 (defun verilog-signals-edit-wire-reg (in-list)
9936 "Return all signals in IN-LIST with wire/reg data types made blank."
9937 (mapcar (lambda (sig)
9938 (when (member (verilog-sig-type sig) '("wire" "reg"))
9939 (verilog-sig-type-set sig nil))
9940 sig) in-list))
9941
9942 ;; Combined
9943 (defun verilog-decls-get-signals (decls)
9944 "Return all declared signals in DECLS, excluding 'assign' statements."
9945 (append
9946 (verilog-decls-get-outputs decls)
9947 (verilog-decls-get-inouts decls)
9948 (verilog-decls-get-inputs decls)
9949 (verilog-decls-get-vars decls)
9950 (verilog-decls-get-consts decls)
9951 (verilog-decls-get-gparams decls)))
9952
9953 (defun verilog-decls-get-ports (decls)
9954 (append
9955 (verilog-decls-get-outputs decls)
9956 (verilog-decls-get-inouts decls)
9957 (verilog-decls-get-inputs decls)))
9958
9959 (defun verilog-decls-get-iovars (decls)
9960 (append
9961 (verilog-decls-get-vars decls)
9962 (verilog-decls-get-outputs decls)
9963 (verilog-decls-get-inouts decls)
9964 (verilog-decls-get-inputs decls)))
9965
9966 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
9967 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
9968 (defsubst verilog-modi-cache-add-inouts (modi sig-list)
9969 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
9970 (defsubst verilog-modi-cache-add-inputs (modi sig-list)
9971 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
9972 (defsubst verilog-modi-cache-add-vars (modi sig-list)
9973 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
9974 (defsubst verilog-modi-cache-add-gparams (modi sig-list)
9975 (verilog-modi-cache-add modi 'verilog-read-decls 7 sig-list))
9976
9977 \f
9978 ;;
9979 ;; Auto creation utilities
9980 ;;
9981
9982 (defun verilog-auto-re-search-do (search-for func)
9983 "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
9984 (goto-char (point-min))
9985 (while (verilog-re-search-forward-quick search-for nil t)
9986 (funcall func)))
9987
9988 (defun verilog-insert-one-definition (sig type indent-pt)
9989 "Print out a definition for SIG of the given TYPE,
9990 with appropriate INDENT-PT indentation."
9991 (indent-to indent-pt)
9992 ;; Note verilog-signals-matching-dir-re matches on this order
9993 (insert type)
9994 (when (verilog-sig-modport sig)
9995 (insert "." (verilog-sig-modport sig)))
9996 (when (verilog-sig-signed sig)
9997 (insert " " (verilog-sig-signed sig)))
9998 (when (verilog-sig-multidim sig)
9999 (insert " " (verilog-sig-multidim-string sig)))
10000 (when (verilog-sig-bits sig)
10001 (insert " " (verilog-sig-bits sig)))
10002 (indent-to (max 24 (+ indent-pt 16)))
10003 (unless (= (char-syntax (preceding-char)) ?\ )
10004 (insert " ")) ; Need space between "]name" if indent-to did nothing
10005 (insert (verilog-sig-name sig))
10006 (when (verilog-sig-memory sig)
10007 (insert " " (verilog-sig-memory sig))))
10008
10009 (defun verilog-insert-definition (modi sigs direction indent-pt v2k &optional dont-sort)
10010 "Print out a definition for MODI's list of SIGS of the given DIRECTION,
10011 with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
10012 format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output.
10013 When MODI is non-null, also add to modi-cache, for tracking."
10014 (when modi
10015 (cond ((equal direction "wire")
10016 (verilog-modi-cache-add-vars modi sigs))
10017 ((equal direction "reg")
10018 (verilog-modi-cache-add-vars modi sigs))
10019 ((equal direction "output")
10020 (verilog-modi-cache-add-outputs modi sigs)
10021 (when verilog-auto-declare-nettype
10022 (verilog-modi-cache-add-vars modi sigs)))
10023 ((equal direction "input")
10024 (verilog-modi-cache-add-inputs modi sigs)
10025 (when verilog-auto-declare-nettype
10026 (verilog-modi-cache-add-vars modi sigs)))
10027 ((equal direction "inout")
10028 (verilog-modi-cache-add-inouts modi sigs)
10029 (when verilog-auto-declare-nettype
10030 (verilog-modi-cache-add-vars modi sigs)))
10031 ((equal direction "interface"))
10032 ((equal direction "parameter")
10033 (verilog-modi-cache-add-gparams modi sigs))
10034 (t
10035 (error "Unsupported verilog-insert-definition direction: %s" direction))))
10036 (or dont-sort
10037 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
10038 (while sigs
10039 (let ((sig (car sigs)))
10040 (verilog-insert-one-definition
10041 sig
10042 ;; Want "type x" or "output type x", not "wire type x"
10043 (cond ((or (verilog-sig-type sig)
10044 verilog-auto-wire-type)
10045 (concat
10046 (when (member direction '("input" "output" "inout"))
10047 (concat direction " "))
10048 (or (verilog-sig-type sig)
10049 verilog-auto-wire-type)))
10050 ((and verilog-auto-declare-nettype
10051 (member direction '("input" "output" "inout")))
10052 (concat direction " " verilog-auto-declare-nettype))
10053 (t
10054 direction))
10055 indent-pt)
10056 (insert (if v2k "," ";"))
10057 (if (or (not (verilog-sig-comment sig))
10058 (equal "" (verilog-sig-comment sig)))
10059 (insert "\n")
10060 (indent-to (max 48 (+ indent-pt 40)))
10061 (verilog-insert "// " (verilog-sig-comment sig) "\n"))
10062 (setq sigs (cdr sigs)))))
10063
10064 (eval-when-compile
10065 (if (not (boundp 'indent-pt))
10066 (defvar indent-pt nil "Local used by insert-indent")))
10067
10068 (defun verilog-insert-indent (&rest stuff)
10069 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
10070 Presumes that any newlines end a list element."
10071 (let ((need-indent t))
10072 (while stuff
10073 (if need-indent (indent-to indent-pt))
10074 (setq need-indent nil)
10075 (verilog-insert (car stuff))
10076 (setq need-indent (string-match "\n$" (car stuff))
10077 stuff (cdr stuff)))))
10078 ;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
10079
10080 (defun verilog-forward-or-insert-line ()
10081 "Move forward a line, unless at EOB, then insert a newline."
10082 (if (eobp) (insert "\n")
10083 (forward-line)))
10084
10085 (defun verilog-repair-open-comma ()
10086 "Insert comma if previous argument is other than an open parenthesis or endif."
10087 ;; We can't just search backward for ) as it might be inside another expression.
10088 ;; Also want "`ifdef X input foo `endif" to just leave things to the human to deal with
10089 (save-excursion
10090 (verilog-backward-syntactic-ws-quick)
10091 (when (and (not (save-excursion ;; Not beginning (, or existing ,
10092 (backward-char 1)
10093 (looking-at "[(,]")))
10094 (not (save-excursion ;; Not `endif, or user define
10095 (backward-char 1)
10096 (skip-chars-backward "[a-zA-Z0-9_`]")
10097 (looking-at "`"))))
10098 (insert ","))))
10099
10100 (defun verilog-repair-close-comma ()
10101 "If point is at a comma followed by a close parenthesis, fix it.
10102 This repairs those mis-inserted by an AUTOARG."
10103 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
10104 (save-excursion
10105 (verilog-forward-close-paren)
10106 (backward-char 1)
10107 (verilog-backward-syntactic-ws-quick)
10108 (backward-char 1)
10109 (when (looking-at ",")
10110 (delete-char 1))))
10111
10112 (defun verilog-make-width-expression (range-exp)
10113 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
10114 ;; strip off the []
10115 (cond ((not range-exp)
10116 "1")
10117 (t
10118 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
10119 (setq range-exp (match-string 1 range-exp)))
10120 (cond ((not range-exp)
10121 "1")
10122 ;; [#:#] We can compute a numeric result
10123 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
10124 range-exp)
10125 (int-to-string
10126 (1+ (abs (- (string-to-number (match-string 1 range-exp))
10127 (string-to-number (match-string 2 range-exp)))))))
10128 ;; [PARAM-1:0] can just return PARAM
10129 ((string-match "^\\s *\\([a-zA-Z_][a-zA-Z0-9_]*\\)\\s *-\\s *1\\s *:\\s *0\\s *$" range-exp)
10130 (match-string 1 range-exp))
10131 ;; [arbitrary] need math
10132 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
10133 (concat "(1+(" (match-string 1 range-exp) ")"
10134 (if (equal "0" (match-string 2 range-exp))
10135 "" ;; Don't bother with -(0)
10136 (concat "-(" (match-string 2 range-exp) ")"))
10137 ")"))
10138 (t nil)))))
10139 ;;(verilog-make-width-expression "`A:`B")
10140
10141 (defun verilog-simplify-range-expression (expr)
10142 "Return a simplified range expression with constants eliminated from EXPR."
10143 ;; Note this is always called with brackets; ie [z] or [z:z]
10144 (if (not (string-match "[---+*()]" expr))
10145 expr ;; short-circuit
10146 (let ((out expr)
10147 (last-pass ""))
10148 (while (not (equal last-pass out))
10149 (setq last-pass out)
10150 ;; Prefix regexp needs beginning of match, or some symbol of
10151 ;; lesser or equal precedence. We assume the [:]'s exist in expr.
10152 ;; Ditto the end.
10153 (while (string-match
10154 (concat "\\([[({:*+-]\\)" ; - must be last
10155 "(\\<\\([0-9A-Za-z_]+\\))"
10156 "\\([])}:*+-]\\)")
10157 out)
10158 (setq out (replace-match "\\1\\2\\3" nil nil out)))
10159 (while (string-match
10160 (concat "\\([[({:*+-]\\)" ; - must be last
10161 "\\$clog2\\s *(\\<\\([0-9]+\\))"
10162 "\\([])}:*+-]\\)")
10163 out)
10164 (setq out (replace-match
10165 (concat
10166 (match-string 1 out)
10167 (int-to-string (verilog-clog2 (string-to-number (match-string 2 out))))
10168 (match-string 3 out))
10169 nil nil out)))
10170 ;; For precedence do * before +/-
10171 (while (string-match
10172 (concat "\\([[({:*+-]\\)"
10173 "\\([0-9]+\\)\\s *\\([*]\\)\\s *\\([0-9]+\\)"
10174 "\\([])}:*+-]\\)")
10175 out)
10176 (setq out (replace-match
10177 (concat (match-string 1 out)
10178 (int-to-string (* (string-to-number (match-string 2 out))
10179 (string-to-number (match-string 4 out))))
10180 (match-string 5 out))
10181 nil nil out)))
10182 (while (string-match
10183 (concat "\\([[({:+-]\\)" ; No * here as higher prec
10184 "\\([0-9]+\\)\\s *\\([---+]\\)\\s *\\([0-9]+\\)"
10185 "\\([])}:+-]\\)")
10186 out)
10187 (let ((pre (match-string 1 out))
10188 (lhs (string-to-number (match-string 2 out)))
10189 (rhs (string-to-number (match-string 4 out)))
10190 (post (match-string 5 out))
10191 val)
10192 (when (equal pre "-")
10193 (setq lhs (- lhs)))
10194 (setq val (if (equal (match-string 3 out) "-")
10195 (- lhs rhs)
10196 (+ lhs rhs))
10197 out (replace-match
10198 (concat (if (and (equal pre "-")
10199 (< val 0))
10200 "" ;; Not "--20" but just "-20"
10201 pre)
10202 (int-to-string val)
10203 post)
10204 nil nil out)) )))
10205 out)))
10206
10207 ;;(verilog-simplify-range-expression "[1:3]") ;; 1
10208 ;;(verilog-simplify-range-expression "[(1):3]") ;; 1
10209 ;;(verilog-simplify-range-expression "[(((16)+1)+1+(1+1))]") ;;20
10210 ;;(verilog-simplify-range-expression "[(2*3+6*7)]") ;; 48
10211 ;;(verilog-simplify-range-expression "[(FOO*4-1*2)]") ;; FOO*4-2
10212 ;;(verilog-simplify-range-expression "[(FOO*4+1-1)]") ;; FOO*4+0
10213 ;;(verilog-simplify-range-expression "[(func(BAR))]") ;; func(BAR)
10214 ;;(verilog-simplify-range-expression "[FOO-1+1-1+1]") ;; FOO-0
10215 ;;(verilog-simplify-range-expression "[$clog2(2)]") ;; 1
10216 ;;(verilog-simplify-range-expression "[$clog2(7)]") ;; 3
10217
10218 (defun verilog-clog2 (value)
10219 "Compute $clog2 - ceiling log2 of VALUE."
10220 (if (< value 1)
10221 0
10222 (ceiling (/ (log value) (log 2)))))
10223
10224 (defun verilog-typedef-name-p (variable-name)
10225 "Return true if the VARIABLE-NAME is a type definition."
10226 (when verilog-typedef-regexp
10227 (verilog-string-match-fold verilog-typedef-regexp variable-name)))
10228 \f
10229 ;;
10230 ;; Auto deletion
10231 ;;
10232
10233 (defun verilog-delete-autos-lined ()
10234 "Delete autos that occupy multiple lines, between begin and end comments."
10235 ;; The newline must not have a comment property, so we must
10236 ;; delete the end auto's newline, not the first newline
10237 (forward-line 1)
10238 (let ((pt (point)))
10239 (when (and
10240 (looking-at "\\s-*// Beginning")
10241 (search-forward "// End of automatic" nil t))
10242 ;; End exists
10243 (end-of-line)
10244 (forward-line 1)
10245 (delete-region pt (point)))))
10246
10247 (defun verilog-delete-empty-auto-pair ()
10248 "Delete begin/end auto pair at point, if empty."
10249 (forward-line 0)
10250 (when (looking-at (concat "\\s-*// Beginning of automatic.*\n"
10251 "\\s-*// End of automatics\n"))
10252 (delete-region (point) (save-excursion (forward-line 2) (point)))))
10253
10254 (defun verilog-forward-close-paren ()
10255 "Find the close parenthesis that match the current point.
10256 Ignore other close parenthesis with matching open parens."
10257 (let ((parens 1))
10258 (while (> parens 0)
10259 (unless (verilog-re-search-forward-quick "[()]" nil t)
10260 (error "%s: Mismatching ()" (verilog-point-text)))
10261 (cond ((= (preceding-char) ?\( )
10262 (setq parens (1+ parens)))
10263 ((= (preceding-char) ?\) )
10264 (setq parens (1- parens)))))))
10265
10266 (defun verilog-backward-open-paren ()
10267 "Find the open parenthesis that match the current point.
10268 Ignore other open parenthesis with matching close parens."
10269 (let ((parens 1))
10270 (while (> parens 0)
10271 (unless (verilog-re-search-backward-quick "[()]" nil t)
10272 (error "%s: Mismatching ()" (verilog-point-text)))
10273 (cond ((= (following-char) ?\) )
10274 (setq parens (1+ parens)))
10275 ((= (following-char) ?\( )
10276 (setq parens (1- parens)))))))
10277
10278 (defun verilog-backward-open-bracket ()
10279 "Find the open bracket that match the current point.
10280 Ignore other open bracket with matching close bracket."
10281 (let ((parens 1))
10282 (while (> parens 0)
10283 (unless (verilog-re-search-backward-quick "[][]" nil t)
10284 (error "%s: Mismatching []" (verilog-point-text)))
10285 (cond ((= (following-char) ?\] )
10286 (setq parens (1+ parens)))
10287 ((= (following-char) ?\[ )
10288 (setq parens (1- parens)))))))
10289
10290 (defun verilog-delete-to-paren ()
10291 "Delete the automatic inst/sense/arg created by autos.
10292 Deletion stops at the matching end parenthesis, outside comments."
10293 (delete-region (point)
10294 (save-excursion
10295 (verilog-backward-open-paren)
10296 (verilog-forward-sexp-ign-cmt 1) ;; Moves to paren that closes argdecl's
10297 (backward-char 1)
10298 (point))))
10299
10300 (defun verilog-auto-star-safe ()
10301 "Return if a .* AUTOINST is safe to delete or expand.
10302 It was created by the AUTOS themselves, or by the user."
10303 (and verilog-auto-star-expand
10304 (looking-at
10305 (concat "[ \t\n\f,]*\\([)]\\|// " verilog-inst-comment-re "\\)"))))
10306
10307 (defun verilog-delete-auto-star-all ()
10308 "Delete a .* AUTOINST, if it is safe."
10309 (when (verilog-auto-star-safe)
10310 (verilog-delete-to-paren)))
10311
10312 (defun verilog-delete-auto-star-implicit ()
10313 "Delete all .* implicit connections created by `verilog-auto-star'.
10314 This function will be called automatically at save unless
10315 `verilog-auto-star-save' is set, any non-templated expanded pins will be
10316 removed."
10317 (interactive)
10318 (let (paren-pt indent have-close-paren)
10319 (save-excursion
10320 (goto-char (point-min))
10321 ;; We need to match these even outside of comments.
10322 ;; For reasonable performance, we don't check if inside comments, sorry.
10323 (while (re-search-forward "// Implicit \\.\\*" nil t)
10324 (setq paren-pt (point))
10325 (beginning-of-line)
10326 (setq have-close-paren
10327 (save-excursion
10328 (when (search-forward ");" paren-pt t)
10329 (setq indent (current-indentation))
10330 t)))
10331 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
10332 (when have-close-paren
10333 ;; Delete extra commentary
10334 (save-excursion
10335 (while (progn
10336 (forward-line -1)
10337 (looking-at (concat "\\s *//\\s *" verilog-inst-comment-re "\n")))
10338 (delete-region (match-beginning 0) (match-end 0))))
10339 ;; If it is simple, we can put the ); on the same line as the last text
10340 (let ((rtn-pt (point)))
10341 (save-excursion
10342 (while (progn (backward-char 1)
10343 (looking-at "[ \t\n\f]")))
10344 (when (looking-at ",")
10345 (delete-region (+ 1 (point)) rtn-pt))))
10346 (when (bolp)
10347 (indent-to indent))
10348 (insert ");\n")
10349 ;; Still need to kill final comma - always is one as we put one after the .*
10350 (re-search-backward ",")
10351 (delete-char 1))))))
10352
10353 (defun verilog-delete-auto ()
10354 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
10355 Use \\[verilog-auto] to re-insert the updated AUTOs.
10356
10357 The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
10358 called before and after this function, respectively."
10359 (interactive)
10360 (save-excursion
10361 (if (buffer-file-name)
10362 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
10363 (verilog-save-no-change-functions
10364 (verilog-save-scan-cache
10365 ;; Allow user to customize
10366 (verilog-run-hooks 'verilog-before-delete-auto-hook)
10367
10368 ;; Remove those that have multi-line insertions, possibly with parameters
10369 ;; We allow anything beginning with AUTO, so that users can add their own
10370 ;; patterns
10371 (verilog-auto-re-search-do
10372 (concat "/\\*AUTO[A-Za-z0-9_]+"
10373 ;; Optional parens or quoted parameter or .* for (((...)))
10374 "\\(\\|([^)]*)\\|(\"[^\"]*\")\\).*?"
10375 "\\*/")
10376 'verilog-delete-autos-lined)
10377 ;; Remove those that are in parenthesis
10378 (verilog-auto-re-search-do
10379 (concat "/\\*"
10380 (eval-when-compile
10381 (verilog-regexp-words
10382 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
10383 "AUTOSENSE")))
10384 "\\*/")
10385 'verilog-delete-to-paren)
10386 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
10387 (verilog-auto-re-search-do "\\.\\*"
10388 'verilog-delete-auto-star-all)
10389 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
10390 (goto-char (point-min))
10391 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)\\([ \tLT0-9]*\\| LHS: .*\\)?$" nil t)
10392 (replace-match ""))
10393
10394 ;; Final customize
10395 (verilog-run-hooks 'verilog-delete-auto-hook)))))
10396 \f
10397 ;;
10398 ;; Auto inject
10399 ;;
10400
10401 (defun verilog-inject-auto ()
10402 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
10403
10404 Any always @ blocks with sensitivity lists that match computed lists will
10405 be replaced with /*AS*/ comments.
10406
10407 Any cells will get /*AUTOINST*/ added to the end of the pin list.
10408 Pins with have identical names will be deleted.
10409
10410 Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
10411 support adding new ports. You may wish to delete older ports yourself.
10412
10413 For example:
10414
10415 module ExampInject (i, o);
10416 input i;
10417 input j;
10418 output o;
10419 always @ (i or j)
10420 o = i | j;
10421 InstModule instName
10422 (.foobar(baz),
10423 j(j));
10424 endmodule
10425
10426 Typing \\[verilog-inject-auto] will make this into:
10427
10428 module ExampInject (i, o/*AUTOARG*/
10429 // Inputs
10430 j);
10431 input i;
10432 output o;
10433 always @ (/*AS*/i or j)
10434 o = i | j;
10435 InstModule instName
10436 (.foobar(baz),
10437 /*AUTOINST*/
10438 // Outputs
10439 j(j));
10440 endmodule"
10441 (interactive)
10442 (verilog-auto t))
10443
10444 (defun verilog-inject-arg ()
10445 "Inject AUTOARG into new code. See `verilog-inject-auto'."
10446 ;; Presume one module per file.
10447 (save-excursion
10448 (goto-char (point-min))
10449 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
10450 (let ((endmodp (save-excursion
10451 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
10452 (point))))
10453 ;; See if there's already a comment .. inside a comment so not verilog-re-search
10454 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
10455 (verilog-re-search-forward-quick ";" nil t)
10456 (backward-char 1)
10457 (verilog-backward-syntactic-ws-quick)
10458 (backward-char 1) ; Moves to paren that closes argdecl's
10459 (when (looking-at ")")
10460 (verilog-insert "/*AUTOARG*/")))))))
10461
10462 (defun verilog-inject-sense ()
10463 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
10464 (save-excursion
10465 (goto-char (point-min))
10466 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
10467 (let* ((start-pt (point))
10468 (modi (verilog-modi-current))
10469 (moddecls (verilog-modi-get-decls modi))
10470 pre-sigs
10471 got-sigs)
10472 (backward-char 1)
10473 (verilog-forward-sexp-ign-cmt 1)
10474 (backward-char 1) ;; End )
10475 (when (not (verilog-re-search-backward-quick "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
10476 (setq pre-sigs (verilog-signals-from-signame
10477 (verilog-read-signals start-pt (point)))
10478 got-sigs (verilog-auto-sense-sigs moddecls nil))
10479 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
10480 (verilog-signals-not-in got-sigs pre-sigs)))
10481 (delete-region start-pt (point))
10482 (verilog-insert "/*AS*/")))))))
10483
10484 (defun verilog-inject-inst ()
10485 "Inject AUTOINST into new code. See `verilog-inject-auto'."
10486 (save-excursion
10487 (goto-char (point-min))
10488 ;; It's hard to distinguish modules; we'll instead search for pins.
10489 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
10490 (verilog-backward-open-paren) ;; Inst start
10491 (cond
10492 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
10493 (forward-char 1)
10494 (verilog-forward-close-paren)) ;; Parameters done
10495 (t
10496 (forward-char 1)
10497 (let ((indent-pt (+ (current-column)))
10498 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
10499 (cond ((verilog-re-search-forward-quick "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
10500 (goto-char end-pt)) ;; Already there, continue search with next instance
10501 (t
10502 ;; Delete identical interconnect
10503 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
10504 (while (verilog-re-search-forward-quick "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
10505 (delete-region (match-beginning 0) (match-end 0))
10506 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
10507 (while (or (looking-at "[ \t\n\f,]+")
10508 (looking-at "//[^\n]*"))
10509 (delete-region (match-beginning 0) (match-end 0))
10510 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
10511 (verilog-forward-close-paren)
10512 (backward-char 1)
10513 ;; Not verilog-re-search, as we don't want to strip comments
10514 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
10515 (delete-region (match-beginning 0) (match-end 0)))
10516 (verilog-insert "\n")
10517 (verilog-insert-indent "/*AUTOINST*/")))))))))
10518 \f
10519 ;;
10520 ;; Auto diff
10521 ;;
10522
10523 (defun verilog-diff-buffers-p (b1 b2 &optional whitespace)
10524 "Return nil if buffers B1 and B2 have same contents.
10525 Else, return point in B1 that first mismatches.
10526 If optional WHITESPACE true, ignore whitespace."
10527 (save-excursion
10528 (let* ((case-fold-search nil) ;; compare-buffer-substrings cares
10529 (p1 (with-current-buffer b1 (goto-char (point-min))))
10530 (p2 (with-current-buffer b2 (goto-char (point-min))))
10531 (maxp1 (with-current-buffer b1 (point-max)))
10532 (maxp2 (with-current-buffer b2 (point-max)))
10533 (op1 -1) (op2 -1)
10534 progress size)
10535 (while (not (and (eq p1 op1) (eq p2 op2)))
10536 ;; If both windows have whitespace optionally skip over it.
10537 (when whitespace
10538 ;; skip-syntax-* doesn't count \n
10539 (with-current-buffer b1
10540 (goto-char p1)
10541 (skip-chars-forward " \t\n\r\f\v")
10542 (setq p1 (point)))
10543 (with-current-buffer b2
10544 (goto-char p2)
10545 (skip-chars-forward " \t\n\r\f\v")
10546 (setq p2 (point))))
10547 (setq size (min (- maxp1 p1) (- maxp2 p2)))
10548 (setq progress (compare-buffer-substrings b2 p2 (+ size p2)
10549 b1 p1 (+ size p1)))
10550 (setq progress (if (zerop progress) size (1- (abs progress))))
10551 (setq op1 p1 op2 p2
10552 p1 (+ p1 progress)
10553 p2 (+ p2 progress)))
10554 ;; Return value
10555 (if (and (eq p1 maxp1) (eq p2 maxp2))
10556 nil p1))))
10557
10558 (defun verilog-diff-file-with-buffer (f1 b2 &optional whitespace show)
10559 "View the differences between file F1 and buffer B2.
10560 This requires the external program `diff-command' to be in your `exec-path',
10561 and uses `diff-switches' in which you may want to have \"-u\" flag.
10562 Ignores WHITESPACE if t, and writes output to stdout if SHOW."
10563 ;; Similar to `diff-buffer-with-file' but works on XEmacs, and doesn't
10564 ;; call `diff' as `diff' has different calling semantics on different
10565 ;; versions of Emacs.
10566 (if (not (file-exists-p f1))
10567 (message "Buffer %s has no associated file on disc" (buffer-name b2))
10568 (with-temp-buffer "*Verilog-Diff*"
10569 (let ((outbuf (current-buffer))
10570 (f2 (make-temp-file "vm-diff-auto-")))
10571 (unwind-protect
10572 (progn
10573 (with-current-buffer b2
10574 (save-restriction
10575 (widen)
10576 (write-region (point-min) (point-max) f2 nil 'nomessage)))
10577 (call-process diff-command nil outbuf t
10578 diff-switches ;; User may want -u in diff-switches
10579 (if whitespace "-b" "")
10580 f1 f2)
10581 ;; Print out results. Alternatively we could have call-processed
10582 ;; ourself, but this way we can reuse diff switches
10583 (when show
10584 (with-current-buffer outbuf (message "%s" (buffer-string))))))
10585 (sit-for 0)
10586 (when (file-exists-p f2)
10587 (delete-file f2))))))
10588
10589 (defun verilog-diff-report (b1 b2 diffpt)
10590 "Report differences detected with `verilog-diff-auto'.
10591 Differences are between buffers B1 and B2, starting at point
10592 DIFFPT. This function is called via `verilog-diff-function'."
10593 (let ((name1 (with-current-buffer b1 (buffer-file-name))))
10594 (verilog-warn "%s:%d: Difference in AUTO expansion found"
10595 name1 (with-current-buffer b1
10596 (count-lines (point-min) diffpt)))
10597 (cond (noninteractive
10598 (verilog-diff-file-with-buffer name1 b2 t t))
10599 (t
10600 (ediff-buffers b1 b2)))))
10601
10602 (defun verilog-diff-auto ()
10603 "Expand AUTOs in a temporary buffer and indicate any change.
10604 Whitespace is ignored when detecting differences, but once a
10605 difference is detected, whitespace differences may be shown.
10606
10607 To call this from the command line, see \\[verilog-batch-diff-auto].
10608
10609 The action on differences is selected with
10610 `verilog-diff-function'. The default is `verilog-diff-report'
10611 which will report an error and run `ediff' in interactive mode,
10612 or `diff' in batch mode."
10613 (interactive)
10614 (let ((b1 (current-buffer)) b2 diffpt
10615 (name1 (buffer-file-name))
10616 (newname "*Verilog-Diff*"))
10617 (save-excursion
10618 (when (get-buffer newname)
10619 (kill-buffer newname))
10620 (setq b2 (let (buffer-file-name) ;; Else clone is upset
10621 (clone-buffer newname)))
10622 (with-current-buffer b2
10623 ;; auto requires the filename, but can't have same filename in two
10624 ;; buffers; so override both b1 and b2's names
10625 (let ((buffer-file-name name1))
10626 (unwind-protect
10627 (progn
10628 (with-current-buffer b1 (setq buffer-file-name nil))
10629 (verilog-auto)
10630 (when (not verilog-auto-star-save)
10631 (verilog-delete-auto-star-implicit)))
10632 ;; Restore name if unwind
10633 (with-current-buffer b1 (setq buffer-file-name name1)))))
10634 ;;
10635 (setq diffpt (verilog-diff-buffers-p b1 b2 t))
10636 (cond ((not diffpt)
10637 (unless noninteractive (message "AUTO expansion identical"))
10638 (kill-buffer newname)) ;; Nice to cleanup after oneself
10639 (t
10640 (funcall verilog-diff-function b1 b2 diffpt)))
10641 ;; Return result of compare
10642 diffpt)))
10643
10644 \f
10645 ;;
10646 ;; Auto save
10647 ;;
10648
10649 (defun verilog-auto-save-check ()
10650 "On saving see if we need auto update."
10651 (cond ((not verilog-auto-save-policy)) ; disabled
10652 ((not (save-excursion
10653 (save-match-data
10654 (let ((case-fold-search nil))
10655 (goto-char (point-min))
10656 (re-search-forward "AUTO" nil t))))))
10657 ((eq verilog-auto-save-policy 'force)
10658 (verilog-auto))
10659 ((not (buffer-modified-p)))
10660 ((eq verilog-auto-update-tick (buffer-chars-modified-tick))) ; up-to-date
10661 ((eq verilog-auto-save-policy 'detect)
10662 (verilog-auto))
10663 (t
10664 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
10665 (verilog-auto))
10666 ;; Don't ask again if didn't update
10667 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))))
10668 (when (not verilog-auto-star-save)
10669 (verilog-delete-auto-star-implicit))
10670 nil) ;; Always return nil -- we don't write the file ourselves
10671
10672 (defun verilog-auto-read-locals ()
10673 "Return file local variable segment at bottom of file."
10674 (save-excursion
10675 (goto-char (point-max))
10676 (if (re-search-backward "Local Variables:" nil t)
10677 (buffer-substring-no-properties (point) (point-max))
10678 "")))
10679
10680 (defun verilog-auto-reeval-locals (&optional force)
10681 "Read file local variable segment at bottom of file if it has changed.
10682 If FORCE, always reread it."
10683 (let ((curlocal (verilog-auto-read-locals)))
10684 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
10685 (set (make-local-variable 'verilog-auto-last-file-locals) curlocal)
10686 ;; Note this may cause this function to be recursively invoked,
10687 ;; because hack-local-variables may call (verilog-mode)
10688 ;; The above when statement will prevent it from recursing forever.
10689 (hack-local-variables)
10690 t)))
10691 \f
10692 ;;
10693 ;; Auto creation
10694 ;;
10695
10696 (defun verilog-auto-arg-ports (sigs message indent-pt)
10697 "Print a list of ports for AUTOARG.
10698 Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
10699 (when sigs
10700 (when verilog-auto-arg-sort
10701 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
10702 (insert "\n")
10703 (indent-to indent-pt)
10704 (insert message)
10705 (insert "\n")
10706 (let ((space ""))
10707 (indent-to indent-pt)
10708 (while sigs
10709 (cond ((equal verilog-auto-arg-format 'single)
10710 (insert space)
10711 (indent-to indent-pt)
10712 (setq space "\n"))
10713 ;; verilog-auto-arg-format 'packed
10714 ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
10715 (insert "\n")
10716 (indent-to indent-pt)
10717 (setq space " "))
10718 (t
10719 (insert space)
10720 (setq space " ")))
10721 (insert (verilog-sig-name (car sigs)) ",")
10722 (setq sigs (cdr sigs))))))
10723
10724 (defun verilog-auto-arg ()
10725 "Expand AUTOARG statements.
10726 Replace the argument declarations at the beginning of the
10727 module with ones automatically derived from input and output
10728 statements. This can be dangerous if the module is instantiated
10729 using position-based connections, so use only name-based when
10730 instantiating the resulting module. Long lines are split based
10731 on the `fill-column', see \\[set-fill-column].
10732
10733 Limitations:
10734 Concatenation and outputting partial buses is not supported.
10735
10736 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10737
10738 For example:
10739
10740 module ExampArg (/*AUTOARG*/);
10741 input i;
10742 output o;
10743 endmodule
10744
10745 Typing \\[verilog-auto] will make this into:
10746
10747 module ExampArg (/*AUTOARG*/
10748 // Outputs
10749 o,
10750 // Inputs
10751 i
10752 );
10753 input i;
10754 output o;
10755 endmodule
10756
10757 The argument declarations may be printed in declaration order to
10758 best suit order based instantiations, or alphabetically, based on
10759 the `verilog-auto-arg-sort' variable.
10760
10761 Formatting is controlled with `verilog-auto-arg-format' variable.
10762
10763 Any ports declared between the ( and /*AUTOARG*/ are presumed to be
10764 predeclared and are not redeclared by AUTOARG. AUTOARG will make a
10765 conservative guess on adding a comma for the first signal, if you have
10766 any ifdefs or complicated expressions before the AUTOARG you will need
10767 to choose the comma yourself.
10768
10769 Avoid declaring ports manually, as it makes code harder to maintain."
10770 (save-excursion
10771 (let* ((modi (verilog-modi-current))
10772 (moddecls (verilog-modi-get-decls modi))
10773 (skip-pins (aref (verilog-read-arg-pins) 0)))
10774 (verilog-repair-open-comma)
10775 (verilog-auto-arg-ports (verilog-signals-not-in
10776 (verilog-decls-get-outputs moddecls)
10777 skip-pins)
10778 "// Outputs"
10779 verilog-indent-level-declaration)
10780 (verilog-auto-arg-ports (verilog-signals-not-in
10781 (verilog-decls-get-inouts moddecls)
10782 skip-pins)
10783 "// Inouts"
10784 verilog-indent-level-declaration)
10785 (verilog-auto-arg-ports (verilog-signals-not-in
10786 (verilog-decls-get-inputs moddecls)
10787 skip-pins)
10788 "// Inputs"
10789 verilog-indent-level-declaration)
10790 (verilog-repair-close-comma)
10791 (unless (eq (char-before) ?/ )
10792 (insert "\n"))
10793 (indent-to verilog-indent-level-declaration))))
10794
10795 (defun verilog-auto-assign-modport ()
10796 "Expand AUTOASSIGNMODPORT statements, as part of \\[verilog-auto].
10797 Take input/output/inout statements from the specified interface
10798 and modport and use to build assignments into the modport, for
10799 making verification modules that connect to UVM interfaces.
10800
10801 The first parameter is the name of an interface.
10802
10803 The second parameter is a regexp of modports to read from in
10804 that interface.
10805
10806 The third parameter is the instance name to use to dot reference into.
10807
10808 The optional fourth parameter is a regular expression, and only
10809 signals matching the regular expression will be included.
10810
10811 Limitations:
10812
10813 Interface names must be resolvable to filenames. See `verilog-auto-inst'.
10814
10815 Inouts are not supported, as assignments must be unidirectional.
10816
10817 If a signal is part of the interface header and in both a
10818 modport and the interface itself, it will not be listed. (As
10819 this would result in a syntax error when the connections are
10820 made.)
10821
10822 See the example in `verilog-auto-inout-modport'."
10823 (save-excursion
10824 (let* ((params (verilog-read-auto-params 3 4))
10825 (submod (nth 0 params))
10826 (modport-re (nth 1 params))
10827 (inst-name (nth 2 params))
10828 (regexp (nth 3 params))
10829 direction-re submodi) ;; direction argument not supported until requested
10830 ;; Lookup position, etc of co-module
10831 ;; Note this may raise an error
10832 (when (setq submodi (verilog-modi-lookup submod t))
10833 (let* ((indent-pt (current-indentation))
10834 (submoddecls (verilog-modi-get-decls submodi))
10835 (submodportdecls (verilog-modi-modport-lookup submodi modport-re))
10836 (sig-list-i (verilog-signals-in ;; Decls doesn't have data types, must resolve
10837 (verilog-decls-get-vars submoddecls)
10838 (verilog-signals-not-in
10839 (verilog-decls-get-inputs submodportdecls)
10840 (verilog-decls-get-ports submoddecls))))
10841 (sig-list-o (verilog-signals-in ;; Decls doesn't have data types, must resolve
10842 (verilog-decls-get-vars submoddecls)
10843 (verilog-signals-not-in
10844 (verilog-decls-get-outputs submodportdecls)
10845 (verilog-decls-get-ports submoddecls)))))
10846 (forward-line 1)
10847 (setq sig-list-i (verilog-signals-edit-wire-reg
10848 (verilog-signals-matching-dir-re
10849 (verilog-signals-matching-regexp sig-list-i regexp)
10850 "input" direction-re))
10851 sig-list-o (verilog-signals-edit-wire-reg
10852 (verilog-signals-matching-dir-re
10853 (verilog-signals-matching-regexp sig-list-o regexp)
10854 "output" direction-re)))
10855 (setq sig-list-i (sort (copy-alist sig-list-i) `verilog-signals-sort-compare))
10856 (setq sig-list-o (sort (copy-alist sig-list-o) `verilog-signals-sort-compare))
10857 (when (or sig-list-i sig-list-o)
10858 (verilog-insert-indent "// Beginning of automatic assignments from modport\n")
10859 ;; Don't sort them so an upper AUTOINST will match the main module
10860 (let ((sigs sig-list-o))
10861 (while sigs
10862 (verilog-insert-indent "assign " (verilog-sig-name (car sigs))
10863 " = " inst-name
10864 "." (verilog-sig-name (car sigs)) ";\n")
10865 (setq sigs (cdr sigs))))
10866 (let ((sigs sig-list-i))
10867 (while sigs
10868 (verilog-insert-indent "assign " inst-name
10869 "." (verilog-sig-name (car sigs))
10870 " = " (verilog-sig-name (car sigs)) ";\n")
10871 (setq sigs (cdr sigs))))
10872 (verilog-insert-indent "// End of automatics\n")))))))
10873
10874 (defun verilog-auto-inst-port-map (_port-st)
10875 nil)
10876
10877 (defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
10878 (defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
10879 (defvar vl-modport nil "See `verilog-auto-inst'.") ; Prevent compile warning
10880 (defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
10881 (defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
10882 (defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
10883 (defvar vl-bits nil "See `verilog-auto-inst'.") ; Prevent compile warning
10884 (defvar vl-mbits nil "See `verilog-auto-inst'.") ; Prevent compile warning
10885
10886 (defun verilog-auto-inst-port (port-st indent-pt moddecls tpl-list tpl-num for-star par-values)
10887 "Print out an instantiation connection for this PORT-ST.
10888 Insert to INDENT-PT, use template TPL-LIST.
10889 @ are instantiation numbers, replaced with TPL-NUM.
10890 @\"(expression @)\" are evaluated, with @ as a variable.
10891 If FOR-STAR add comment it is a .* expansion.
10892 If PAR-VALUES replace final strings with these parameter values."
10893 (let* ((port (verilog-sig-name port-st))
10894 (tpl-ass (or (assoc port (car tpl-list))
10895 (verilog-auto-inst-port-map port-st)))
10896 ;; vl-* are documented for user use
10897 (vl-name (verilog-sig-name port-st))
10898 (vl-width (verilog-sig-width port-st))
10899 (vl-modport (verilog-sig-modport port-st))
10900 (vl-mbits (if (verilog-sig-multidim port-st)
10901 (verilog-sig-multidim-string port-st) ""))
10902 (vl-bits (if (or verilog-auto-inst-vector
10903 (not (assoc port (verilog-decls-get-signals moddecls)))
10904 (not (equal (verilog-sig-bits port-st)
10905 (verilog-sig-bits
10906 (assoc port (verilog-decls-get-signals moddecls))))))
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 (and vl-modport
10936 ;; .modport cannot be added if attachment is
10937 ;; already declared as modport, VCS croaks
10938 (let ((sig (assoc port (verilog-decls-get-interfaces moddecls))))
10939 (not (and sig (verilog-sig-modport sig)))))
10940 (concat "." vl-modport) "")
10941 dflt-bits))
10942 ;; Find template
10943 (cond (tpl-ass ; Template of exact port name
10944 (setq tpl-net (nth 1 tpl-ass)))
10945 ((nth 1 tpl-list) ; Wildcards in template, search them
10946 (let ((wildcards (nth 1 tpl-list)))
10947 (while wildcards
10948 (when (string-match (nth 0 (car wildcards)) port)
10949 (setq tpl-ass (car wildcards) ; so allow @ parsing
10950 tpl-net (replace-match (nth 1 (car wildcards))
10951 t nil port)))
10952 (setq wildcards (cdr wildcards))))))
10953 ;; Parse Templated variable
10954 (when tpl-ass
10955 ;; Evaluate @"(lispcode)"
10956 (when (string-match "@\".*[^\\]\"" tpl-net)
10957 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
10958 (setq tpl-net
10959 (concat
10960 (substring tpl-net 0 (match-beginning 0))
10961 (save-match-data
10962 (let* ((expr (match-string 1 tpl-net))
10963 (value
10964 (progn
10965 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
10966 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
10967 (prin1 (eval (car (read-from-string expr)))
10968 (lambda (_ch) ())))))
10969 (if (numberp value) (setq value (number-to-string value)))
10970 value))
10971 (substring tpl-net (match-end 0))))))
10972 ;; Replace @ and [] magic variables in final output
10973 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
10974 (setq tpl-net (verilog-string-replace-matches "\\[\\]\\[\\]" dflt-bits nil nil tpl-net))
10975 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
10976 ;; Insert it
10977 (indent-to indent-pt)
10978 (insert "." port)
10979 (unless (and verilog-auto-inst-dot-name
10980 (equal port tpl-net))
10981 (indent-to verilog-auto-inst-column)
10982 (insert "(" tpl-net ")"))
10983 (insert ",")
10984 (cond (tpl-ass
10985 (verilog-read-auto-template-hit tpl-ass)
10986 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
10987 verilog-auto-inst-column))
10988 ;; verilog-insert requires the complete comment in one call - including the newline
10989 (cond ((equal verilog-auto-inst-template-numbers `lhs)
10990 (verilog-insert " // Templated"
10991 " LHS: " (nth 0 tpl-ass)
10992 "\n"))
10993 (verilog-auto-inst-template-numbers
10994 (verilog-insert " // Templated"
10995 " T" (int-to-string (nth 2 tpl-ass))
10996 " L" (int-to-string (nth 3 tpl-ass))
10997 "\n"))
10998 (t
10999 (verilog-insert " // Templated\n"))))
11000 (for-star
11001 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
11002 verilog-auto-inst-column))
11003 (verilog-insert " // Implicit .\*\n")) ;For some reason the . or * must be escaped...
11004 (t
11005 (insert "\n")))))
11006 ;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
11007 ;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
11008 ;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
11009
11010 (defun verilog-auto-inst-port-list (sig-list indent-pt moddecls tpl-list tpl-num for-star par-values)
11011 "For `verilog-auto-inst' print a list of ports using `verilog-auto-inst-port'."
11012 (when verilog-auto-inst-sort
11013 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare)))
11014 (mapc (lambda (port)
11015 (verilog-auto-inst-port port indent-pt moddecls
11016 tpl-list tpl-num for-star par-values))
11017 sig-list))
11018
11019 (defun verilog-auto-inst-first ()
11020 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
11021 ;; Do we need a trailing comma?
11022 ;; There maybe an ifdef or something similar before us. What a mess. Thus
11023 ;; to avoid trouble we only insert on preceding ) or *.
11024 ;; Insert first port on new line
11025 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
11026 (save-excursion
11027 (verilog-re-search-backward-quick "[^ \t\n\f]" nil nil)
11028 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
11029 (forward-char 1)
11030 (insert ","))))
11031
11032 (defun verilog-auto-star ()
11033 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
11034
11035 If `verilog-auto-star-expand' is set, .* pins are treated if they were
11036 AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
11037 will also ignore any .* that are not last in your pin list (this prevents
11038 it from deleting pins following the .* when it expands the AUTOINST.)
11039
11040 On writing your file, unless `verilog-auto-star-save' is set, any
11041 non-templated expanded pins will be removed. You may do this at any time
11042 with \\[verilog-delete-auto-star-implicit].
11043
11044 If you are converting a module to use .* for the first time, you may wish
11045 to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
11046
11047 See `verilog-auto-inst' for examples, templates, and more information."
11048 (when (verilog-auto-star-safe)
11049 (verilog-auto-inst)))
11050
11051 (defun verilog-auto-inst ()
11052 "Expand AUTOINST statements, as part of \\[verilog-auto].
11053 Replace the pin connections to an instantiation or interface
11054 declaration with ones automatically derived from the module or
11055 interface header of the instantiated item.
11056
11057 If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
11058 and delete them before saving unless `verilog-auto-star-save' is set.
11059 See `verilog-auto-star' for more information.
11060
11061 The pins are printed in declaration order or alphabetically,
11062 based on the `verilog-auto-inst-sort' variable.
11063
11064 Limitations:
11065 Module names must be resolvable to filenames by adding a
11066 `verilog-library-extensions', and being found in the same directory, or
11067 by changing the variable `verilog-library-flags' or
11068 `verilog-library-directories'. Macros `modname are translated through the
11069 vh-{name} Emacs variable, if that is not found, it just ignores the `.
11070
11071 In templates you must have one signal per line, ending in a ), or ));,
11072 and have proper () nesting, including a final ); to end the template.
11073
11074 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
11075
11076 SystemVerilog multidimensional input/output has only experimental support.
11077
11078 SystemVerilog .name syntax is used if `verilog-auto-inst-dot-name' is set.
11079
11080 Parameters referenced by the instantiation will remain symbolic, unless
11081 `verilog-auto-inst-param-value' is set.
11082
11083 Gate primitives (and/or) may have AUTOINST for the purpose of
11084 AUTOWIRE declarations, etc. Gates are the only case when
11085 position based connections are passed.
11086
11087 The array part of arrayed instances are ignored; this may
11088 result in undesirable default AUTOINST connections; use a
11089 template instead.
11090
11091 For example, first take the submodule InstModule.v:
11092
11093 module InstModule (o,i);
11094 output [31:0] o;
11095 input i;
11096 wire [31:0] o = {32{i}};
11097 endmodule
11098
11099 This is then used in an upper level module:
11100
11101 module ExampInst (o,i);
11102 output o;
11103 input i;
11104 InstModule instName
11105 (/*AUTOINST*/);
11106 endmodule
11107
11108 Typing \\[verilog-auto] will make this into:
11109
11110 module ExampInst (o,i);
11111 output o;
11112 input i;
11113 InstModule instName
11114 (/*AUTOINST*/
11115 // Outputs
11116 .ov (ov[31:0]),
11117 // Inputs
11118 .i (i));
11119 endmodule
11120
11121 Where the list of inputs and outputs came from the inst module.
11122 \f
11123 Exceptions:
11124
11125 Unless you are instantiating a module multiple times, or the module is
11126 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
11127 It just makes for unmaintainable code. To sanitize signal names, try
11128 vrename from URL `http://www.veripool.org'.
11129
11130 When you need to violate this suggestion there are two ways to list
11131 exceptions, placing them before the AUTOINST, or using templates.
11132
11133 Any ports defined before the /*AUTOINST*/ are not included in the list of
11134 automatics. This is similar to making a template as described below, but
11135 is restricted to simple connections just like you normally make. Also note
11136 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
11137 you have the appropriate // Input or // Output comment, and exactly the
11138 same line formatting as AUTOINST itself uses.
11139
11140 InstModule instName
11141 (// Inputs
11142 .i (my_i_dont_mess_with_it),
11143 /*AUTOINST*/
11144 // Outputs
11145 .ov (ov[31:0]));
11146
11147 \f
11148 Templates:
11149
11150 For multiple instantiations based upon a single template, create a
11151 commented out template:
11152
11153 /* InstModule AUTO_TEMPLATE (
11154 .sig3 (sigz[]),
11155 );
11156 */
11157
11158 Templates go ABOVE the instantiation(s). When an instantiation is
11159 expanded `verilog-mode' simply searches up for the closest template.
11160 Thus you can have multiple templates for the same module, just alternate
11161 between the template for an instantiation and the instantiation itself.
11162 (For backward compatibility if no template is found above, it
11163 will also look below, but do not use this behavior in new designs.)
11164
11165 The module name must be the same as the name of the module in the
11166 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
11167 words and capitalized. Only signals that must be different for each
11168 instantiation need to be listed.
11169
11170 Inside a template, a [] in a connection name (with nothing else
11171 inside the brackets) will be replaced by the same bus subscript
11172 as it is being connected to, or the [] will be removed if it is
11173 a single bit signal.
11174
11175 Inside a template, a [][] in a connection name will behave
11176 similarly to a [] for scalar or single-dimensional connection;
11177 for a multidimensional connection it will print a comment
11178 similar to that printed when a template is not used. Generally
11179 it is a good idea to do this for all connections in a template,
11180 as then they will work for any width signal, and with AUTOWIRE.
11181 See PTL_BUS becoming PTL_BUSNEW below.
11182
11183 Inside a template, a [] in a connection name (with nothing else inside
11184 the brackets) will be replaced by the same bus subscript as it is being
11185 connected to, or the [] will be removed if it is a single bit signal.
11186 Generally it is a good idea to do this for all connections in a template,
11187 as then they will work for any width signal, and with AUTOWIRE. See
11188 PTL_BUS becoming PTL_BUSNEW below.
11189
11190 If you have a complicated template, set `verilog-auto-inst-template-numbers'
11191 to see which regexps are matching. Don't leave that mode set after
11192 debugging is completed though, it will result in lots of extra differences
11193 and merge conflicts.
11194
11195 Setting `verilog-auto-template-warn-unused' will report errors
11196 if any template lines are unused.
11197
11198 For example:
11199
11200 /* InstModule AUTO_TEMPLATE (
11201 .ptl_bus (ptl_busnew[]),
11202 );
11203 */
11204 InstModule ms2m (/*AUTOINST*/);
11205
11206 Typing \\[verilog-auto] will make this into:
11207
11208 InstModule ms2m (/*AUTOINST*/
11209 // Outputs
11210 .NotInTemplate (NotInTemplate),
11211 .ptl_bus (ptl_busnew[3:0]), // Templated
11212 ....
11213
11214 \f
11215 Multiple Module Templates:
11216
11217 The same template lines can be applied to multiple modules with
11218 the syntax as follows:
11219
11220 /* InstModuleA AUTO_TEMPLATE
11221 InstModuleB AUTO_TEMPLATE
11222 InstModuleC AUTO_TEMPLATE
11223 InstModuleD AUTO_TEMPLATE (
11224 .ptl_bus (ptl_busnew[]),
11225 );
11226 */
11227
11228 Note there is only one AUTO_TEMPLATE opening parenthesis.
11229 \f
11230 @ Templates:
11231
11232 It is common to instantiate a cell multiple times, so templates make it
11233 trivial to substitute part of the cell name into the connection name.
11234
11235 /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
11236 .sig1 (sigx[@]),
11237 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
11238 );
11239 */
11240
11241 If no regular expression is provided immediately after the AUTO_TEMPLATE
11242 keyword, then the @ character in any connection names will be replaced
11243 with the instantiation number; the first digits found in the cell's
11244 instantiation name.
11245
11246 If a regular expression is provided, the @ character will be replaced
11247 with the first \(\) grouping that matches against the cell name. Using a
11248 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
11249 regexp is provided. If you use multiple layers of parenthesis,
11250 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
11251 characters after test and before _, whereas
11252 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
11253 match.
11254
11255 For example:
11256
11257 /* InstModule AUTO_TEMPLATE (
11258 .ptl_mapvalidx (ptl_mapvalid[@]),
11259 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
11260 );
11261 */
11262 InstModule ms2m (/*AUTOINST*/);
11263
11264 Typing \\[verilog-auto] will make this into:
11265
11266 InstModule ms2m (/*AUTOINST*/
11267 // Outputs
11268 .ptl_mapvalidx (ptl_mapvalid[2]),
11269 .ptl_mapvalidp1x (ptl_mapvalid[3]));
11270
11271 Note the @ character was replaced with the 2 from \"ms2m\".
11272
11273 Alternatively, using a regular expression for @:
11274
11275 /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
11276 .ptl_mapvalidx (@_ptl_mapvalid),
11277 .ptl_mapvalidp1x (ptl_mapvalid_@),
11278 );
11279 */
11280 InstModule ms2_FOO (/*AUTOINST*/);
11281 InstModule ms2_BAR (/*AUTOINST*/);
11282
11283 Typing \\[verilog-auto] will make this into:
11284
11285 InstModule ms2_FOO (/*AUTOINST*/
11286 // Outputs
11287 .ptl_mapvalidx (FOO_ptl_mapvalid),
11288 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
11289 InstModule ms2_BAR (/*AUTOINST*/
11290 // Outputs
11291 .ptl_mapvalidx (BAR_ptl_mapvalid),
11292 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
11293
11294 \f
11295 Regexp Templates:
11296
11297 A template entry of the form
11298
11299 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
11300
11301 will apply an Emacs style regular expression search for any port beginning
11302 in pci_req followed by numbers and ending in _l and connecting that to
11303 the pci_req_jtag_[] net, with the bus subscript coming from what matches
11304 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
11305
11306 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
11307 does the same thing. (Note a @ in the connection/replacement text is
11308 completely different -- still use \\1 there!) Thus this is the same as
11309 the above template:
11310
11311 .pci_req@_l (pci_req_jtag_[\\1]),
11312
11313 Here's another example to remove the _l, useful when naming conventions
11314 specify _ alone to mean active low. Note the use of [] to keep the bus
11315 subscript:
11316
11317 .\\(.*\\)_l (\\1_[]),
11318 \f
11319 Lisp Templates:
11320
11321 First any regular expression template is expanded.
11322
11323 If the syntax @\"( ... )\" is found in a connection, the expression in
11324 quotes will be evaluated as a Lisp expression, with @ replaced by the
11325 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
11326 4 into the brackets. Quote all double-quotes inside the expression with
11327 a leading backslash (\\\"...\\\"); or if the Lisp template is also a
11328 regexp template backslash the backslash quote (\\\\\"...\\\\\").
11329
11330 There are special variables defined that are useful in these
11331 Lisp functions:
11332
11333 vl-name Name portion of the input/output port.
11334 vl-bits Bus bits portion of the input/output port ('[2:0]').
11335 vl-mbits Multidimensional array bits for port ('[2:0][3:0]').
11336 vl-width Width of the input/output port ('3' for [2:0]).
11337 May be a (...) expression if bits isn't a constant.
11338 vl-dir Direction of the pin input/output/inout/interface.
11339 vl-modport The modport, if an interface with a modport.
11340 vl-cell-type Module name/type of the cell ('InstModule').
11341 vl-cell-name Instance name of the cell ('instName').
11342
11343 Normal Lisp variables may be used in expressions. See
11344 `verilog-read-defines' which can set vh-{definename} variables for use
11345 here. Also, any comments of the form:
11346
11347 /*AUTO_LISP(setq foo 1)*/
11348
11349 will evaluate any Lisp expression inside the parenthesis between the
11350 beginning of the buffer and the point of the AUTOINST. This allows
11351 functions to be defined or variables to be changed between instantiations.
11352 (See also `verilog-auto-insert-lisp' if you want the output from your
11353 lisp function to be inserted.)
11354
11355 Note that when using lisp expressions errors may occur when @ is not a
11356 number; you may need to use the standard Emacs Lisp functions
11357 `number-to-string' and `string-to-number'.
11358
11359 After the evaluation is completed, @ substitution and [] substitution
11360 occur.
11361
11362 For more information see the \\[verilog-faq] and forums at URL
11363 `http://www.veripool.org'."
11364 (save-excursion
11365 ;; Find beginning
11366 (let* ((pt (point))
11367 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
11368 (indent-pt (save-excursion (verilog-backward-open-paren)
11369 (1+ (current-column))))
11370 (verilog-auto-inst-column (max verilog-auto-inst-column
11371 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
11372 (modi (verilog-modi-current))
11373 (moddecls (verilog-modi-get-decls modi))
11374 submod submodi submoddecls
11375 inst skip-pins tpl-list tpl-num did-first par-values)
11376
11377 ;; Find module name that is instantiated
11378 (setq submod (verilog-read-inst-module)
11379 inst (verilog-read-inst-name)
11380 vl-cell-type submod
11381 vl-cell-name inst
11382 skip-pins (aref (verilog-read-inst-pins) 0))
11383
11384 ;; Parse any AUTO_LISP() before here
11385 (verilog-read-auto-lisp (point-min) pt)
11386
11387 ;; Read parameters (after AUTO_LISP)
11388 (setq par-values (and verilog-auto-inst-param-value
11389 (verilog-read-inst-param-value)))
11390
11391 ;; Lookup position, etc of submodule
11392 ;; Note this may raise an error
11393 (when (and (not (member submod verilog-gate-keywords))
11394 (setq submodi (verilog-modi-lookup submod t)))
11395 (setq submoddecls (verilog-modi-get-decls submodi))
11396 ;; If there's a number in the instantiation, it may be an argument to the
11397 ;; automatic variable instantiation program.
11398 (let* ((tpl-info (verilog-read-auto-template submod))
11399 (tpl-regexp (aref tpl-info 0)))
11400 (setq tpl-num (if (verilog-string-match-fold tpl-regexp inst)
11401 (match-string 1 inst)
11402 "")
11403 tpl-list (aref tpl-info 1)))
11404 ;; Find submodule's signals and dump
11405 (let ((sig-list (and (equal (verilog-modi-get-type submodi) "interface")
11406 (verilog-signals-not-in
11407 (verilog-decls-get-vars submoddecls)
11408 skip-pins)))
11409 (vl-dir "interfaced"))
11410 (when (and sig-list
11411 verilog-auto-inst-interfaced-ports)
11412 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11413 ;; Note these are searched for in verilog-read-sub-decls.
11414 (verilog-insert-indent "// Interfaced\n")
11415 (verilog-auto-inst-port-list sig-list indent-pt moddecls
11416 tpl-list tpl-num for-star par-values)))
11417 (let ((sig-list (verilog-signals-not-in
11418 (verilog-decls-get-interfaces submoddecls)
11419 skip-pins))
11420 (vl-dir "interface"))
11421 (when sig-list
11422 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11423 ;; Note these are searched for in verilog-read-sub-decls.
11424 (verilog-insert-indent "// Interfaces\n")
11425 (verilog-auto-inst-port-list sig-list indent-pt moddecls
11426 tpl-list tpl-num for-star par-values)))
11427 (let ((sig-list (verilog-signals-not-in
11428 (verilog-decls-get-outputs submoddecls)
11429 skip-pins))
11430 (vl-dir "output"))
11431 (when sig-list
11432 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11433 (verilog-insert-indent "// Outputs\n")
11434 (verilog-auto-inst-port-list sig-list indent-pt moddecls
11435 tpl-list tpl-num for-star par-values)))
11436 (let ((sig-list (verilog-signals-not-in
11437 (verilog-decls-get-inouts submoddecls)
11438 skip-pins))
11439 (vl-dir "inout"))
11440 (when sig-list
11441 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11442 (verilog-insert-indent "// Inouts\n")
11443 (verilog-auto-inst-port-list sig-list indent-pt moddecls
11444 tpl-list tpl-num for-star par-values)))
11445 (let ((sig-list (verilog-signals-not-in
11446 (verilog-decls-get-inputs submoddecls)
11447 skip-pins))
11448 (vl-dir "input"))
11449 (when sig-list
11450 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11451 (verilog-insert-indent "// Inputs\n")
11452 (verilog-auto-inst-port-list sig-list indent-pt moddecls
11453 tpl-list tpl-num for-star par-values)))
11454 ;; Kill extra semi
11455 (save-excursion
11456 (cond (did-first
11457 (re-search-backward "," pt t)
11458 (delete-char 1)
11459 (insert ");")
11460 (search-forward "\n") ;; Added by inst-port
11461 (delete-char -1)
11462 (if (search-forward ")" nil t) ;; From user, moved up a line
11463 (delete-char -1))
11464 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
11465 (delete-char -1)))))))))
11466
11467 (defun verilog-auto-inst-param ()
11468 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
11469 Replace the parameter connections to an instantiation with ones
11470 automatically derived from the module header of the instantiated netlist.
11471
11472 See \\[verilog-auto-inst] for limitations, and templates to customize the
11473 output.
11474
11475 For example, first take the submodule InstModule.v:
11476
11477 module InstModule (o,i);
11478 parameter PAR;
11479 endmodule
11480
11481 This is then used in an upper level module:
11482
11483 module ExampInst (o,i);
11484 parameter PAR;
11485 InstModule #(/*AUTOINSTPARAM*/)
11486 instName (/*AUTOINST*/);
11487 endmodule
11488
11489 Typing \\[verilog-auto] will make this into:
11490
11491 module ExampInst (o,i);
11492 output o;
11493 input i;
11494 InstModule #(/*AUTOINSTPARAM*/
11495 // Parameters
11496 .PAR (PAR));
11497 instName (/*AUTOINST*/);
11498 endmodule
11499
11500 Where the list of parameter connections come from the inst module.
11501 \f
11502 Templates:
11503
11504 You can customize the parameter connections using AUTO_TEMPLATEs,
11505 just as you would with \\[verilog-auto-inst]."
11506 (save-excursion
11507 ;; Find beginning
11508 (let* ((pt (point))
11509 (indent-pt (save-excursion (verilog-backward-open-paren)
11510 (1+ (current-column))))
11511 (verilog-auto-inst-column (max verilog-auto-inst-column
11512 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
11513 (modi (verilog-modi-current))
11514 (moddecls (verilog-modi-get-decls modi))
11515 submod submodi submoddecls
11516 inst skip-pins tpl-list tpl-num did-first)
11517 ;; Find module name that is instantiated
11518 (setq submod (save-excursion
11519 ;; Get to the point where AUTOINST normally is to read the module
11520 (verilog-re-search-forward-quick "[(;]" nil nil)
11521 (verilog-read-inst-module))
11522 inst (save-excursion
11523 ;; Get to the point where AUTOINST normally is to read the module
11524 (verilog-re-search-forward-quick "[(;]" nil nil)
11525 (verilog-read-inst-name))
11526 vl-cell-type submod
11527 vl-cell-name inst
11528 skip-pins (aref (verilog-read-inst-pins) 0))
11529
11530 ;; Parse any AUTO_LISP() before here
11531 (verilog-read-auto-lisp (point-min) pt)
11532
11533 ;; Lookup position, etc of submodule
11534 ;; Note this may raise an error
11535 (when (setq submodi (verilog-modi-lookup submod t))
11536 (setq submoddecls (verilog-modi-get-decls submodi))
11537 ;; If there's a number in the instantiation, it may be an argument to the
11538 ;; automatic variable instantiation program.
11539 (let* ((tpl-info (verilog-read-auto-template submod))
11540 (tpl-regexp (aref tpl-info 0)))
11541 (setq tpl-num (if (verilog-string-match-fold tpl-regexp inst)
11542 (match-string 1 inst)
11543 "")
11544 tpl-list (aref tpl-info 1)))
11545 ;; Find submodule's signals and dump
11546 (let ((sig-list (verilog-signals-not-in
11547 (verilog-decls-get-gparams submoddecls)
11548 skip-pins))
11549 (vl-dir "parameter"))
11550 (when sig-list
11551 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
11552 ;; Note these are searched for in verilog-read-sub-decls.
11553 (verilog-insert-indent "// Parameters\n")
11554 (verilog-auto-inst-port-list sig-list indent-pt moddecls
11555 tpl-list tpl-num nil nil)))
11556 ;; Kill extra semi
11557 (save-excursion
11558 (cond (did-first
11559 (re-search-backward "," pt t)
11560 (delete-char 1)
11561 (insert ")")
11562 (search-forward "\n") ;; Added by inst-port
11563 (delete-char -1)
11564 (if (search-forward ")" nil t) ;; From user, moved up a line
11565 (delete-char -1)))))))))
11566
11567 (defun verilog-auto-reg ()
11568 "Expand AUTOREG statements, as part of \\[verilog-auto].
11569 Make reg statements for any output that isn't already declared,
11570 and isn't a wire output from a block. `verilog-auto-wire-type'
11571 may be used to change the datatype of the declarations.
11572
11573 Limitations:
11574 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11575
11576 This does NOT work on memories, declare those yourself.
11577
11578 An example:
11579
11580 module ExampReg (o,i);
11581 output o;
11582 input i;
11583 /*AUTOREG*/
11584 always o = i;
11585 endmodule
11586
11587 Typing \\[verilog-auto] will make this into:
11588
11589 module ExampReg (o,i);
11590 output o;
11591 input i;
11592 /*AUTOREG*/
11593 // Beginning of automatic regs (for this module's undeclared outputs)
11594 reg o;
11595 // End of automatics
11596 always o = i;
11597 endmodule"
11598 (save-excursion
11599 ;; Point must be at insertion point.
11600 (let* ((indent-pt (current-indentation))
11601 (modi (verilog-modi-current))
11602 (moddecls (verilog-modi-get-decls modi))
11603 (modsubdecls (verilog-modi-get-sub-decls modi))
11604 (sig-list (verilog-signals-not-in
11605 (verilog-decls-get-outputs moddecls)
11606 (append (verilog-signals-with ;; ignore typed signals
11607 'verilog-sig-type
11608 (verilog-decls-get-outputs moddecls))
11609 (verilog-decls-get-vars moddecls)
11610 (verilog-decls-get-assigns moddecls)
11611 (verilog-decls-get-consts moddecls)
11612 (verilog-decls-get-gparams moddecls)
11613 (verilog-subdecls-get-interfaced modsubdecls)
11614 (verilog-subdecls-get-outputs modsubdecls)
11615 (verilog-subdecls-get-inouts modsubdecls)))))
11616 (when sig-list
11617 (verilog-forward-or-insert-line)
11618 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
11619 (verilog-insert-definition modi sig-list "reg" indent-pt nil)
11620 (verilog-insert-indent "// End of automatics\n")))))
11621
11622 (defun verilog-auto-reg-input ()
11623 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
11624 Make reg statements instantiation inputs that aren't already declared.
11625 This is useful for making a top level shell for testing the module that is
11626 to be instantiated.
11627
11628 Limitations:
11629 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
11630
11631 This does NOT work on memories, declare those yourself.
11632
11633 An example (see `verilog-auto-inst' for what else is going on here):
11634
11635 module ExampRegInput (o,i);
11636 output o;
11637 input i;
11638 /*AUTOREGINPUT*/
11639 InstModule instName
11640 (/*AUTOINST*/);
11641 endmodule
11642
11643 Typing \\[verilog-auto] will make this into:
11644
11645 module ExampRegInput (o,i);
11646 output o;
11647 input i;
11648 /*AUTOREGINPUT*/
11649 // Beginning of automatic reg inputs (for undeclared ...
11650 reg [31:0] iv; // From inst of inst.v
11651 // End of automatics
11652 InstModule instName
11653 (/*AUTOINST*/
11654 // Outputs
11655 .o (o[31:0]),
11656 // Inputs
11657 .iv (iv));
11658 endmodule"
11659 (save-excursion
11660 ;; Point must be at insertion point.
11661 (let* ((indent-pt (current-indentation))
11662 (modi (verilog-modi-current))
11663 (moddecls (verilog-modi-get-decls modi))
11664 (modsubdecls (verilog-modi-get-sub-decls modi))
11665 (sig-list (verilog-signals-combine-bus
11666 (verilog-signals-not-in
11667 (append (verilog-subdecls-get-inputs modsubdecls)
11668 (verilog-subdecls-get-inouts modsubdecls))
11669 (append (verilog-decls-get-signals moddecls)
11670 (verilog-decls-get-assigns moddecls))))))
11671 (when sig-list
11672 (verilog-forward-or-insert-line)
11673 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
11674 (verilog-insert-definition modi sig-list "reg" indent-pt nil)
11675 (verilog-insert-indent "// End of automatics\n")))))
11676
11677 (defun verilog-auto-logic-setup ()
11678 "Prepare variables due to AUTOLOGIC."
11679 (unless verilog-auto-wire-type
11680 (set (make-local-variable 'verilog-auto-wire-type)
11681 "logic")))
11682
11683 (defun verilog-auto-logic ()
11684 "Expand AUTOLOGIC statements, as part of \\[verilog-auto].
11685 Make wire statements using the SystemVerilog logic keyword.
11686 This is currently equivalent to:
11687
11688 /*AUTOWIRE*/
11689
11690 with the below at the bottom of the file
11691
11692 // Local Variables:
11693 // verilog-auto-logic-type:\"logic\"
11694 // End:
11695
11696 In the future AUTOLOGIC may declare additional identifiers,
11697 while AUTOWIRE will not."
11698 (save-excursion
11699 (verilog-auto-logic-setup)
11700 (verilog-auto-wire)))
11701
11702 (defun verilog-auto-wire ()
11703 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
11704 Make wire statements for instantiations outputs that aren't
11705 already declared. `verilog-auto-wire-type' may be used to change
11706 the datatype of the declarations.
11707
11708 Limitations:
11709 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
11710 and all buses must have widths, such as those from AUTOINST, or using []
11711 in AUTO_TEMPLATEs.
11712
11713 This does NOT work on memories or SystemVerilog .name connections,
11714 declare those yourself.
11715
11716 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
11717 determine how to bus together. This occurs when you have ports with
11718 non-numeric or non-sequential bus subscripts. If Verilog mode
11719 mis-guessed, you'll have to declare them yourself.
11720
11721 An example (see `verilog-auto-inst' for what else is going on here):
11722
11723 module ExampWire (o,i);
11724 output o;
11725 input i;
11726 /*AUTOWIRE*/
11727 InstModule instName
11728 (/*AUTOINST*/);
11729 endmodule
11730
11731 Typing \\[verilog-auto] will make this into:
11732
11733 module ExampWire (o,i);
11734 output o;
11735 input i;
11736 /*AUTOWIRE*/
11737 // Beginning of automatic wires
11738 wire [31:0] ov; // From inst of inst.v
11739 // End of automatics
11740 InstModule instName
11741 (/*AUTOINST*/
11742 // Outputs
11743 .ov (ov[31:0]),
11744 // Inputs
11745 .i (i));
11746 wire o = | ov;
11747 endmodule"
11748 (save-excursion
11749 ;; Point must be at insertion point.
11750 (let* ((indent-pt (current-indentation))
11751 (modi (verilog-modi-current))
11752 (moddecls (verilog-modi-get-decls modi))
11753 (modsubdecls (verilog-modi-get-sub-decls modi))
11754 (sig-list (verilog-signals-combine-bus
11755 (verilog-signals-not-in
11756 (append (verilog-subdecls-get-outputs modsubdecls)
11757 (verilog-subdecls-get-inouts modsubdecls))
11758 (verilog-decls-get-signals moddecls)))))
11759 (when sig-list
11760 (verilog-forward-or-insert-line)
11761 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
11762 (verilog-insert-definition modi sig-list "wire" indent-pt nil)
11763 (verilog-insert-indent "// End of automatics\n")
11764 ;; We used to optionally call verilog-pretty-declarations and
11765 ;; verilog-pretty-expr here, but it's too slow on huge modules,
11766 ;; plus makes everyone's module change. Finally those call
11767 ;; syntax-ppss which is broken when change hooks are disabled.
11768 ))))
11769
11770 (defun verilog-auto-output ()
11771 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
11772 Make output statements for any output signal from an /*AUTOINST*/ that
11773 isn't an input to another AUTOINST. This is useful for modules which
11774 only instantiate other modules.
11775
11776 Limitations:
11777 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11778
11779 If placed inside the parenthesis of a module declaration, it creates
11780 Verilog 2001 style, else uses Verilog 1995 style.
11781
11782 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
11783 instantiation, all bets are off. (For example due to an AUTO_TEMPLATE).
11784
11785 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
11786
11787 Types are added to declarations if an AUTOLOGIC or
11788 `verilog-auto-wire-type' is set to logic.
11789
11790 Signals matching `verilog-auto-output-ignore-regexp' are not included.
11791
11792 An example (see `verilog-auto-inst' for what else is going on here):
11793
11794 module ExampOutput (ov,i);
11795 input i;
11796 /*AUTOOUTPUT*/
11797 InstModule instName
11798 (/*AUTOINST*/);
11799 endmodule
11800
11801 Typing \\[verilog-auto] will make this into:
11802
11803 module ExampOutput (ov,i);
11804 input i;
11805 /*AUTOOUTPUT*/
11806 // Beginning of automatic outputs (from unused autoinst outputs)
11807 output [31:0] ov; // From inst of inst.v
11808 // End of automatics
11809 InstModule instName
11810 (/*AUTOINST*/
11811 // Outputs
11812 .ov (ov[31:0]),
11813 // Inputs
11814 .i (i));
11815 endmodule
11816
11817 You may also provide an optional regular expression, in which case only
11818 signals matching the regular expression will be included. For example the
11819 same expansion will result from only extracting outputs starting with ov:
11820
11821 /*AUTOOUTPUT(\"^ov\")*/"
11822 (save-excursion
11823 ;; Point must be at insertion point.
11824 (let* ((indent-pt (current-indentation))
11825 (params (verilog-read-auto-params 0 1))
11826 (regexp (nth 0 params))
11827 (v2k (verilog-in-paren-quick))
11828 (modi (verilog-modi-current))
11829 (moddecls (verilog-modi-get-decls modi))
11830 (modsubdecls (verilog-modi-get-sub-decls modi))
11831 (sig-list (verilog-signals-not-in
11832 (verilog-subdecls-get-outputs modsubdecls)
11833 (append (verilog-decls-get-outputs moddecls)
11834 (verilog-decls-get-inouts moddecls)
11835 (verilog-decls-get-inputs moddecls)
11836 (verilog-subdecls-get-inputs modsubdecls)
11837 (verilog-subdecls-get-inouts modsubdecls)))))
11838 (when regexp
11839 (setq sig-list (verilog-signals-matching-regexp
11840 sig-list regexp)))
11841 (setq sig-list (verilog-signals-not-matching-regexp
11842 sig-list verilog-auto-output-ignore-regexp))
11843 (verilog-forward-or-insert-line)
11844 (when v2k (verilog-repair-open-comma))
11845 (when sig-list
11846 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
11847 (verilog-insert-definition modi sig-list "output" indent-pt v2k)
11848 (verilog-insert-indent "// End of automatics\n"))
11849 (when v2k (verilog-repair-close-comma)))))
11850
11851 (defun verilog-auto-output-every ()
11852 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
11853 Make output statements for any signals that aren't primary inputs or
11854 outputs already. This makes every signal in the design an output. This is
11855 useful to get Synopsys to preserve every signal in the design, since it
11856 won't optimize away the outputs.
11857
11858 An example:
11859
11860 module ExampOutputEvery (o,i,tempa,tempb);
11861 output o;
11862 input i;
11863 /*AUTOOUTPUTEVERY*/
11864 wire tempa = i;
11865 wire tempb = tempa;
11866 wire o = tempb;
11867 endmodule
11868
11869 Typing \\[verilog-auto] will make this into:
11870
11871 module ExampOutputEvery (o,i,tempa,tempb);
11872 output o;
11873 input i;
11874 /*AUTOOUTPUTEVERY*/
11875 // Beginning of automatic outputs (every signal)
11876 output tempb;
11877 output tempa;
11878 // End of automatics
11879 wire tempa = i;
11880 wire tempb = tempa;
11881 wire o = tempb;
11882 endmodule
11883
11884 You may also provide an optional regular expression, in which case only
11885 signals matching the regular expression will be included. For example the
11886 same expansion will result from only extracting outputs starting with ov:
11887
11888 /*AUTOOUTPUTEVERY(\"^ov\")*/"
11889 (save-excursion
11890 ;;Point must be at insertion point
11891 (let* ((indent-pt (current-indentation))
11892 (params (verilog-read-auto-params 0 1))
11893 (regexp (nth 0 params))
11894 (v2k (verilog-in-paren-quick))
11895 (modi (verilog-modi-current))
11896 (moddecls (verilog-modi-get-decls modi))
11897 (sig-list (verilog-signals-combine-bus
11898 (verilog-signals-not-in
11899 (verilog-decls-get-signals moddecls)
11900 (verilog-decls-get-ports moddecls)))))
11901 (when regexp
11902 (setq sig-list (verilog-signals-matching-regexp
11903 sig-list regexp)))
11904 (setq sig-list (verilog-signals-not-matching-regexp
11905 sig-list verilog-auto-output-ignore-regexp))
11906 (verilog-forward-or-insert-line)
11907 (when v2k (verilog-repair-open-comma))
11908 (when sig-list
11909 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
11910 (verilog-insert-definition modi sig-list "output" indent-pt v2k)
11911 (verilog-insert-indent "// End of automatics\n"))
11912 (when v2k (verilog-repair-close-comma)))))
11913
11914 (defun verilog-auto-input ()
11915 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
11916 Make input statements for any input signal into an /*AUTOINST*/ that
11917 isn't declared elsewhere inside the module. This is useful for modules which
11918 only instantiate other modules.
11919
11920 Limitations:
11921 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
11922
11923 If placed inside the parenthesis of a module declaration, it creates
11924 Verilog 2001 style, else uses Verilog 1995 style.
11925
11926 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
11927 instantiation, all bets are off. (For example due to an AUTO_TEMPLATE).
11928
11929 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
11930
11931 Types are added to declarations if an AUTOLOGIC or
11932 `verilog-auto-wire-type' is set to logic.
11933
11934 Signals matching `verilog-auto-input-ignore-regexp' are not included.
11935
11936 An example (see `verilog-auto-inst' for what else is going on here):
11937
11938 module ExampInput (ov,i);
11939 output [31:0] ov;
11940 /*AUTOINPUT*/
11941 InstModule instName
11942 (/*AUTOINST*/);
11943 endmodule
11944
11945 Typing \\[verilog-auto] will make this into:
11946
11947 module ExampInput (ov,i);
11948 output [31:0] ov;
11949 /*AUTOINPUT*/
11950 // Beginning of automatic inputs (from unused autoinst inputs)
11951 input i; // From inst of inst.v
11952 // End of automatics
11953 InstModule instName
11954 (/*AUTOINST*/
11955 // Outputs
11956 .ov (ov[31:0]),
11957 // Inputs
11958 .i (i));
11959 endmodule
11960
11961 You may also provide an optional regular expression, in which case only
11962 signals matching the regular expression will be included. For example the
11963 same expansion will result from only extracting inputs starting with i:
11964
11965 /*AUTOINPUT(\"^i\")*/"
11966 (save-excursion
11967 (let* ((indent-pt (current-indentation))
11968 (params (verilog-read-auto-params 0 1))
11969 (regexp (nth 0 params))
11970 (v2k (verilog-in-paren-quick))
11971 (modi (verilog-modi-current))
11972 (moddecls (verilog-modi-get-decls modi))
11973 (modsubdecls (verilog-modi-get-sub-decls modi))
11974 (sig-list (verilog-signals-not-in
11975 (verilog-subdecls-get-inputs modsubdecls)
11976 (append (verilog-decls-get-inputs moddecls)
11977 (verilog-decls-get-inouts moddecls)
11978 (verilog-decls-get-outputs moddecls)
11979 (verilog-decls-get-vars moddecls)
11980 (verilog-decls-get-consts moddecls)
11981 (verilog-decls-get-gparams moddecls)
11982 (verilog-subdecls-get-interfaced modsubdecls)
11983 (verilog-subdecls-get-outputs modsubdecls)
11984 (verilog-subdecls-get-inouts modsubdecls)))))
11985 (when regexp
11986 (setq sig-list (verilog-signals-matching-regexp
11987 sig-list regexp)))
11988 (setq sig-list (verilog-signals-not-matching-regexp
11989 sig-list verilog-auto-input-ignore-regexp))
11990 (verilog-forward-or-insert-line)
11991 (when v2k (verilog-repair-open-comma))
11992 (when sig-list
11993 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
11994 (verilog-insert-definition modi sig-list "input" indent-pt v2k)
11995 (verilog-insert-indent "// End of automatics\n"))
11996 (when v2k (verilog-repair-close-comma)))))
11997
11998 (defun verilog-auto-inout ()
11999 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
12000 Make inout statements for any inout signal in an /*AUTOINST*/ that
12001 isn't declared elsewhere inside the module.
12002
12003 Limitations:
12004 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
12005
12006 If placed inside the parenthesis of a module declaration, it creates
12007 Verilog 2001 style, else uses Verilog 1995 style.
12008
12009 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
12010 instantiation, all bets are off. (For example due to an AUTO_TEMPLATE).
12011
12012 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
12013
12014 Types are added to declarations if an AUTOLOGIC or
12015 `verilog-auto-wire-type' is set to logic.
12016
12017 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
12018
12019 An example (see `verilog-auto-inst' for what else is going on here):
12020
12021 module ExampInout (ov,i);
12022 input i;
12023 /*AUTOINOUT*/
12024 InstModule instName
12025 (/*AUTOINST*/);
12026 endmodule
12027
12028 Typing \\[verilog-auto] will make this into:
12029
12030 module ExampInout (ov,i);
12031 input i;
12032 /*AUTOINOUT*/
12033 // Beginning of automatic inouts (from unused autoinst inouts)
12034 inout [31:0] ov; // From inst of inst.v
12035 // End of automatics
12036 InstModule instName
12037 (/*AUTOINST*/
12038 // Inouts
12039 .ov (ov[31:0]),
12040 // Inputs
12041 .i (i));
12042 endmodule
12043
12044 You may also provide an optional regular expression, in which case only
12045 signals matching the regular expression will be included. For example the
12046 same expansion will result from only extracting inouts starting with i:
12047
12048 /*AUTOINOUT(\"^i\")*/"
12049 (save-excursion
12050 ;; Point must be at insertion point.
12051 (let* ((indent-pt (current-indentation))
12052 (params (verilog-read-auto-params 0 1))
12053 (regexp (nth 0 params))
12054 (v2k (verilog-in-paren-quick))
12055 (modi (verilog-modi-current))
12056 (moddecls (verilog-modi-get-decls modi))
12057 (modsubdecls (verilog-modi-get-sub-decls modi))
12058 (sig-list (verilog-signals-not-in
12059 (verilog-subdecls-get-inouts modsubdecls)
12060 (append (verilog-decls-get-outputs moddecls)
12061 (verilog-decls-get-inouts moddecls)
12062 (verilog-decls-get-inputs moddecls)
12063 (verilog-subdecls-get-inputs modsubdecls)
12064 (verilog-subdecls-get-outputs modsubdecls)))))
12065 (when regexp
12066 (setq sig-list (verilog-signals-matching-regexp
12067 sig-list regexp)))
12068 (setq sig-list (verilog-signals-not-matching-regexp
12069 sig-list verilog-auto-inout-ignore-regexp))
12070 (verilog-forward-or-insert-line)
12071 (when v2k (verilog-repair-open-comma))
12072 (when sig-list
12073 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
12074 (verilog-insert-definition modi sig-list "inout" indent-pt v2k)
12075 (verilog-insert-indent "// End of automatics\n"))
12076 (when v2k (verilog-repair-close-comma)))))
12077
12078 (defun verilog-auto-inout-module (&optional complement all-in)
12079 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
12080 Take input/output/inout statements from the specified module and insert
12081 into the current module. This is useful for making null templates and
12082 shell modules which need to have identical I/O with another module.
12083 Any I/O which are already defined in this module will not be redefined.
12084 For the complement of this function, see `verilog-auto-inout-comp',
12085 and to make monitors with all inputs, see `verilog-auto-inout-in'.
12086
12087 Limitations:
12088 If placed inside the parenthesis of a module declaration, it creates
12089 Verilog 2001 style, else uses Verilog 1995 style.
12090
12091 Concatenation and outputting partial buses is not supported.
12092
12093 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12094
12095 Signals are not inserted in the same order as in the original module,
12096 though they will appear to be in the same order to an AUTOINST
12097 instantiating either module.
12098
12099 Signals declared as \"output reg\" or \"output wire\" etc will
12100 lose the wire/reg declaration so that shell modules may
12101 generate those outputs differently. However, \"output logic\"
12102 is propagated.
12103
12104 An example:
12105
12106 module ExampShell (/*AUTOARG*/);
12107 /*AUTOINOUTMODULE(\"ExampMain\")*/
12108 endmodule
12109
12110 module ExampMain (i,o,io);
12111 input i;
12112 output o;
12113 inout io;
12114 endmodule
12115
12116 Typing \\[verilog-auto] will make this into:
12117
12118 module ExampShell (/*AUTOARG*/i,o,io);
12119 /*AUTOINOUTMODULE(\"ExampMain\")*/
12120 // Beginning of automatic in/out/inouts (from specific module)
12121 output o;
12122 inout io;
12123 input i;
12124 // End of automatics
12125 endmodule
12126
12127 You may also provide an optional regular expression, in which case only
12128 signals matching the regular expression will be included. For example the
12129 same expansion will result from only extracting signals starting with i:
12130
12131 /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/
12132
12133 You may also provide an optional third argument regular
12134 expression, in which case only signals which have that pin
12135 direction and data type matching that regular expression will be
12136 included. This matches against everything before the signal name
12137 in the declaration, for example against \"input\" (single bit),
12138 \"output logic\" (direction and type) or \"output
12139 [1:0]\" (direction and implicit type). You also probably want to
12140 skip spaces in your regexp.
12141
12142 For example, the below will result in matching the output \"o\"
12143 against the previous example's module:
12144
12145 /*AUTOINOUTMODULE(\"ExampMain\",\"\",\"^output.*\")*/"
12146 (save-excursion
12147 (let* ((params (verilog-read-auto-params 1 3))
12148 (submod (nth 0 params))
12149 (regexp (nth 1 params))
12150 (direction-re (nth 2 params))
12151 submodi)
12152 ;; Lookup position, etc of co-module
12153 ;; Note this may raise an error
12154 (when (setq submodi (verilog-modi-lookup submod t))
12155 (let* ((indent-pt (current-indentation))
12156 (v2k (verilog-in-paren-quick))
12157 (modi (verilog-modi-current))
12158 (moddecls (verilog-modi-get-decls modi))
12159 (submoddecls (verilog-modi-get-decls submodi))
12160 (sig-list-i (verilog-signals-not-in
12161 (cond (all-in
12162 (append
12163 (verilog-decls-get-inputs submoddecls)
12164 (verilog-decls-get-inouts submoddecls)
12165 (verilog-decls-get-outputs submoddecls)))
12166 (complement
12167 (verilog-decls-get-outputs submoddecls))
12168 (t (verilog-decls-get-inputs submoddecls)))
12169 (append (verilog-decls-get-inputs moddecls))))
12170 (sig-list-o (verilog-signals-not-in
12171 (cond (all-in nil)
12172 (complement
12173 (verilog-decls-get-inputs submoddecls))
12174 (t (verilog-decls-get-outputs submoddecls)))
12175 (append (verilog-decls-get-outputs moddecls))))
12176 (sig-list-io (verilog-signals-not-in
12177 (cond (all-in nil)
12178 (t (verilog-decls-get-inouts submoddecls)))
12179 (append (verilog-decls-get-inouts moddecls))))
12180 (sig-list-if (verilog-signals-not-in
12181 (verilog-decls-get-interfaces submoddecls)
12182 (append (verilog-decls-get-interfaces moddecls)))))
12183 (forward-line 1)
12184 (setq sig-list-i (verilog-signals-edit-wire-reg
12185 (verilog-signals-matching-dir-re
12186 (verilog-signals-matching-regexp sig-list-i regexp)
12187 "input" direction-re))
12188 sig-list-o (verilog-signals-edit-wire-reg
12189 (verilog-signals-matching-dir-re
12190 (verilog-signals-matching-regexp sig-list-o regexp)
12191 "output" direction-re))
12192 sig-list-io (verilog-signals-edit-wire-reg
12193 (verilog-signals-matching-dir-re
12194 (verilog-signals-matching-regexp sig-list-io regexp)
12195 "inout" direction-re))
12196 sig-list-if (verilog-signals-matching-dir-re
12197 (verilog-signals-matching-regexp sig-list-if regexp)
12198 "interface" direction-re))
12199 (when v2k (verilog-repair-open-comma))
12200 (when (or sig-list-i sig-list-o sig-list-io sig-list-if)
12201 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
12202 ;; Don't sort them so an upper AUTOINST will match the main module
12203 (verilog-insert-definition modi sig-list-o "output" indent-pt v2k t)
12204 (verilog-insert-definition modi sig-list-io "inout" indent-pt v2k t)
12205 (verilog-insert-definition modi sig-list-i "input" indent-pt v2k t)
12206 (verilog-insert-definition modi sig-list-if "interface" indent-pt v2k t)
12207 (verilog-insert-indent "// End of automatics\n"))
12208 (when v2k (verilog-repair-close-comma)))))))
12209
12210 (defun verilog-auto-inout-comp ()
12211 "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
12212 Take input/output/inout statements from the specified module and
12213 insert the inverse into the current module (inputs become outputs
12214 and vice-versa.) This is useful for making test and stimulus
12215 modules which need to have complementing I/O with another module.
12216 Any I/O which are already defined in this module will not be
12217 redefined. For the complement of this function, see
12218 `verilog-auto-inout-module'.
12219
12220 Limitations:
12221 If placed inside the parenthesis of a module declaration, it creates
12222 Verilog 2001 style, else uses Verilog 1995 style.
12223
12224 Concatenation and outputting partial buses is not supported.
12225
12226 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12227
12228 Signals are not inserted in the same order as in the original module,
12229 though they will appear to be in the same order to an AUTOINST
12230 instantiating either module.
12231
12232 An example:
12233
12234 module ExampShell (/*AUTOARG*/);
12235 /*AUTOINOUTCOMP(\"ExampMain\")*/
12236 endmodule
12237
12238 module ExampMain (i,o,io);
12239 input i;
12240 output o;
12241 inout io;
12242 endmodule
12243
12244 Typing \\[verilog-auto] will make this into:
12245
12246 module ExampShell (/*AUTOARG*/i,o,io);
12247 /*AUTOINOUTCOMP(\"ExampMain\")*/
12248 // Beginning of automatic in/out/inouts (from specific module)
12249 output i;
12250 inout io;
12251 input o;
12252 // End of automatics
12253 endmodule
12254
12255 You may also provide an optional regular expression, in which case only
12256 signals matching the regular expression will be included. For example the
12257 same expansion will result from only extracting signals starting with i:
12258
12259 /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/
12260
12261 You may also provide an optional third argument regular
12262 expression, in which case only signals which have that pin
12263 direction and data type matching that regular expression will be
12264 included. This matches against everything before the signal name
12265 in the declaration, for example against \"input\" (single bit),
12266 \"output logic\" (direction and type) or \"output
12267 [1:0]\" (direction and implicit type). You also probably want to
12268 skip spaces in your regexp.
12269
12270 For example, the below will result in matching the output \"o\"
12271 against the previous example's module:
12272
12273 /*AUTOINOUTCOMP(\"ExampMain\",\"\",\"^output.*\")*/"
12274 (verilog-auto-inout-module t nil))
12275
12276 (defun verilog-auto-inout-in ()
12277 "Expand AUTOINOUTIN statements, as part of \\[verilog-auto].
12278 Take input/output/inout statements from the specified module and
12279 insert them as all inputs into the current module. This is
12280 useful for making monitor modules which need to see all signals
12281 as inputs based on another module. Any I/O which are already
12282 defined in this module will not be redefined. See also
12283 `verilog-auto-inout-module'.
12284
12285 Limitations:
12286 If placed inside the parenthesis of a module declaration, it creates
12287 Verilog 2001 style, else uses Verilog 1995 style.
12288
12289 Concatenation and outputting partial buses is not supported.
12290
12291 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12292
12293 Signals are not inserted in the same order as in the original module,
12294 though they will appear to be in the same order to an AUTOINST
12295 instantiating either module.
12296
12297 An example:
12298
12299 module ExampShell (/*AUTOARG*/);
12300 /*AUTOINOUTIN(\"ExampMain\")*/
12301 endmodule
12302
12303 module ExampMain (i,o,io);
12304 input i;
12305 output o;
12306 inout io;
12307 endmodule
12308
12309 Typing \\[verilog-auto] will make this into:
12310
12311 module ExampShell (/*AUTOARG*/i,o,io);
12312 /*AUTOINOUTIN(\"ExampMain\")*/
12313 // Beginning of automatic in/out/inouts (from specific module)
12314 input i;
12315 input io;
12316 input o;
12317 // End of automatics
12318 endmodule
12319
12320 You may also provide an optional regular expression, in which case only
12321 signals matching the regular expression will be included. For example the
12322 same expansion will result from only extracting signals starting with i:
12323
12324 /*AUTOINOUTIN(\"ExampMain\",\"^i\")*/"
12325 (verilog-auto-inout-module nil t))
12326
12327 (defun verilog-auto-inout-param ()
12328 "Expand AUTOINOUTPARAM statements, as part of \\[verilog-auto].
12329 Take input/output/inout statements from the specified module and insert
12330 into the current module. This is useful for making null templates and
12331 shell modules which need to have identical I/O with another module.
12332 Any I/O which are already defined in this module will not be redefined.
12333 For the complement of this function, see `verilog-auto-inout-comp',
12334 and to make monitors with all inputs, see `verilog-auto-inout-in'.
12335
12336 Limitations:
12337 If placed inside the parenthesis of a module declaration, it creates
12338 Verilog 2001 style, else uses Verilog 1995 style.
12339
12340 Module names must be resolvable to filenames. See `verilog-auto-inst'.
12341
12342 Parameters are inserted in the same order as in the original module.
12343
12344 Parameters do not have values, which is SystemVerilog 2009 syntax.
12345
12346 An example:
12347
12348 module ExampShell ();
12349 /*AUTOINOUTPARAM(\"ExampMain\")*/
12350 endmodule
12351
12352 module ExampMain ();
12353 parameter PARAM = 22;
12354 endmodule
12355
12356 Typing \\[verilog-auto] will make this into:
12357
12358 module ExampShell (/*AUTOARG*/i,o,io);
12359 /*AUTOINOUTPARAM(\"ExampMain\")*/
12360 // Beginning of automatic parameters (from specific module)
12361 parameter PARAM;
12362 // End of automatics
12363 endmodule
12364
12365 You may also provide an optional regular expression, in which case only
12366 parameters matching the regular expression will be included. For example the
12367 same expansion will result from only extracting parameters starting with i:
12368
12369 /*AUTOINOUTPARAM(\"ExampMain\",\"^i\")*/"
12370 (save-excursion
12371 (let* ((params (verilog-read-auto-params 1 2))
12372 (submod (nth 0 params))
12373 (regexp (nth 1 params))
12374 submodi)
12375 ;; Lookup position, etc of co-module
12376 ;; Note this may raise an error
12377 (when (setq submodi (verilog-modi-lookup submod t))
12378 (let* ((indent-pt (current-indentation))
12379 (v2k (verilog-in-paren-quick))
12380 (modi (verilog-modi-current))
12381 (moddecls (verilog-modi-get-decls modi))
12382 (submoddecls (verilog-modi-get-decls submodi))
12383 (sig-list-p (verilog-signals-not-in
12384 (verilog-decls-get-gparams submoddecls)
12385 (append (verilog-decls-get-gparams moddecls)))))
12386 (forward-line 1)
12387 (setq sig-list-p (verilog-signals-matching-regexp sig-list-p regexp))
12388 (when v2k (verilog-repair-open-comma))
12389 (when sig-list-p
12390 (verilog-insert-indent "// Beginning of automatic parameters (from specific module)\n")
12391 ;; Don't sort them so an upper AUTOINST will match the main module
12392 (verilog-insert-definition modi sig-list-p "parameter" indent-pt v2k t)
12393 (verilog-insert-indent "// End of automatics\n"))
12394 (when v2k (verilog-repair-close-comma)))))))
12395
12396 (defun verilog-auto-inout-modport ()
12397 "Expand AUTOINOUTMODPORT statements, as part of \\[verilog-auto].
12398 Take input/output/inout statements from the specified interface
12399 and modport and insert into the current module. This is useful
12400 for making verification modules that connect to UVM interfaces.
12401
12402 The first parameter is the name of an interface.
12403
12404 The second parameter is a regexp of modports to read from in
12405 that interface.
12406
12407 The optional third parameter is a regular expression, and only
12408 signals matching the regular expression will be included.
12409
12410 Limitations:
12411 If placed inside the parenthesis of a module declaration, it creates
12412 Verilog 2001 style, else uses Verilog 1995 style.
12413
12414 Interface names must be resolvable to filenames. See `verilog-auto-inst'.
12415
12416 As with other autos, any inputs/outputs declared in the module
12417 will suppress the AUTO from redeclaring an inputs/outputs by
12418 the same name.
12419
12420 An example:
12421
12422 interface ExampIf
12423 ( input logic clk );
12424 logic req_val;
12425 logic [7:0] req_dat;
12426 clocking mon_clkblk @(posedge clk);
12427 input req_val;
12428 input req_dat;
12429 endclocking
12430 modport mp(clocking mon_clkblk);
12431 endinterface
12432
12433 module ExampMain
12434 ( input clk,
12435 /*AUTOINOUTMODPORT(\"ExampIf\" \"mp\")*/
12436 // Beginning of automatic in/out/inouts (from modport)
12437 input [7:0] req_dat,
12438 input req_val
12439 // End of automatics
12440 );
12441 /*AUTOASSIGNMODPORT(\"ExampIf\" \"mp\")*/
12442 endmodule
12443
12444 Typing \\[verilog-auto] will make this into:
12445
12446 ...
12447 module ExampMain
12448 ( input clk,
12449 /*AUTOINOUTMODPORT(\"ExampIf\" \"mp\")*/
12450 // Beginning of automatic in/out/inouts (from modport)
12451 input req_dat,
12452 input req_val
12453 // End of automatics
12454 );
12455
12456 If the modport is part of a UVM monitor/driver class, this
12457 creates a wrapper module that may be used to instantiate the
12458 driver/monitor using AUTOINST in the testbench."
12459 (save-excursion
12460 (let* ((params (verilog-read-auto-params 2 3))
12461 (submod (nth 0 params))
12462 (modport-re (nth 1 params))
12463 (regexp (nth 2 params))
12464 direction-re submodi) ;; direction argument not supported until requested
12465 ;; Lookup position, etc of co-module
12466 ;; Note this may raise an error
12467 (when (setq submodi (verilog-modi-lookup submod t))
12468 (let* ((indent-pt (current-indentation))
12469 (v2k (verilog-in-paren-quick))
12470 (modi (verilog-modi-current))
12471 (moddecls (verilog-modi-get-decls modi))
12472 (submoddecls (verilog-modi-get-decls submodi))
12473 (submodportdecls (verilog-modi-modport-lookup submodi modport-re))
12474 (sig-list-i (verilog-signals-in ;; Decls doesn't have data types, must resolve
12475 (verilog-decls-get-vars submoddecls)
12476 (verilog-signals-not-in
12477 (verilog-decls-get-inputs submodportdecls)
12478 (append (verilog-decls-get-ports submoddecls)
12479 (verilog-decls-get-ports moddecls)))))
12480 (sig-list-o (verilog-signals-in ;; Decls doesn't have data types, must resolve
12481 (verilog-decls-get-vars submoddecls)
12482 (verilog-signals-not-in
12483 (verilog-decls-get-outputs submodportdecls)
12484 (append (verilog-decls-get-ports submoddecls)
12485 (verilog-decls-get-ports moddecls)))))
12486 (sig-list-io (verilog-signals-in ;; Decls doesn't have data types, must resolve
12487 (verilog-decls-get-vars submoddecls)
12488 (verilog-signals-not-in
12489 (verilog-decls-get-inouts submodportdecls)
12490 (append (verilog-decls-get-ports submoddecls)
12491 (verilog-decls-get-ports moddecls))))))
12492 (forward-line 1)
12493 (setq sig-list-i (verilog-signals-edit-wire-reg
12494 (verilog-signals-matching-dir-re
12495 (verilog-signals-matching-regexp sig-list-i regexp)
12496 "input" direction-re))
12497 sig-list-o (verilog-signals-edit-wire-reg
12498 (verilog-signals-matching-dir-re
12499 (verilog-signals-matching-regexp sig-list-o regexp)
12500 "output" direction-re))
12501 sig-list-io (verilog-signals-edit-wire-reg
12502 (verilog-signals-matching-dir-re
12503 (verilog-signals-matching-regexp sig-list-io regexp)
12504 "inout" direction-re)))
12505 (when v2k (verilog-repair-open-comma))
12506 (when (or sig-list-i sig-list-o sig-list-io)
12507 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from modport)\n")
12508 ;; Don't sort them so an upper AUTOINST will match the main module
12509 (verilog-insert-definition modi sig-list-o "output" indent-pt v2k t)
12510 (verilog-insert-definition modi sig-list-io "inout" indent-pt v2k t)
12511 (verilog-insert-definition modi sig-list-i "input" indent-pt v2k t)
12512 (verilog-insert-indent "// End of automatics\n"))
12513 (when v2k (verilog-repair-close-comma)))))))
12514
12515 (defun verilog-auto-insert-lisp ()
12516 "Expand AUTOINSERTLISP statements, as part of \\[verilog-auto].
12517 The Lisp code provided is called before other AUTOS are expanded,
12518 and the Lisp code generally will call `insert` to insert text
12519 into the current file beginning on the line after the
12520 AUTOINSERTLISP.
12521
12522 See also AUTOINSERTLAST and `verilog-auto-insert-last' which
12523 executes after (as opposed to before) other AUTOs.
12524
12525 See also AUTO_LISP, which takes a Lisp expression and evaluates
12526 it during `verilog-auto-inst' but does not insert any text.
12527
12528 An example:
12529
12530 module ExampInsertLisp;
12531 /*AUTOINSERTLISP(my-verilog-insert-hello \"world\")*/
12532 endmodule
12533
12534 // For this example we declare the function in the
12535 // module's file itself. Often you'd define it instead
12536 // in a site-start.el or init file.
12537 /*
12538 Local Variables:
12539 eval:
12540 (defun my-verilog-insert-hello (who)
12541 (insert (concat \"initial $write(\\\"hello \" who \"\\\");\\n\")))
12542 End:
12543 */
12544
12545 Typing \\[verilog-auto] will call my-verilog-insert-hello and
12546 expand the above into:
12547
12548 // Beginning of automatic insert lisp
12549 initial $write(\"hello world\");
12550 // End of automatics
12551
12552 You can also call an external program and insert the returned
12553 text:
12554
12555 /*AUTOINSERTLISP(insert (shell-command-to-string \"echo //hello\"))*/
12556 // Beginning of automatic insert lisp
12557 //hello
12558 // End of automatics"
12559 (save-excursion
12560 ;; Point is at end of /*AUTO...*/
12561 (let* ((indent-pt (current-indentation))
12562 (cmd-end-pt (save-excursion (search-backward ")")
12563 (forward-char)
12564 (point))) ;; Closing paren
12565 (cmd-beg-pt (save-excursion (goto-char cmd-end-pt)
12566 (backward-sexp 1) ;; Inside comment
12567 (point))) ;; Beginning paren
12568 (cmd (buffer-substring-no-properties cmd-beg-pt cmd-end-pt)))
12569 (verilog-forward-or-insert-line)
12570 ;; Some commands don't move point (like insert-file) so we always
12571 ;; add the begin/end comments, then delete it if not needed
12572 (verilog-insert-indent "// Beginning of automatic insert lisp\n")
12573 (verilog-insert-indent "// End of automatics\n")
12574 (forward-line -1)
12575 (eval (read cmd))
12576 (forward-line -1)
12577 (setq verilog-scan-cache-tick nil) ;; Clear cache; inserted unknown text
12578 (verilog-delete-empty-auto-pair))))
12579
12580 (defun verilog-auto-insert-last ()
12581 "Expand AUTOINSERTLAST statements, as part of \\[verilog-auto].
12582 The Lisp code provided is called after all other AUTOS have been
12583 expanded, and the Lisp code generally will call `insert` to
12584 insert text into the current file beginning on the line after the
12585 AUTOINSERTLAST.
12586
12587 Other than when called (after AUTOs are expanded), the functionality
12588 is otherwise identical to AUTOINSERTLISP and `verilog-auto-insert-lisp' which
12589 executes before (as opposed to after) other AUTOs.
12590
12591 See `verilog-auto-insert-lisp' for examples."
12592 (verilog-auto-insert-lisp))
12593
12594 (defun verilog-auto-sense-sigs (moddecls presense-sigs)
12595 "Return list of signals for current AUTOSENSE block."
12596 (let* ((sigss (save-excursion
12597 (search-forward ")")
12598 (verilog-read-always-signals)))
12599 (sig-list (verilog-signals-not-params
12600 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
12601 (append (and (not verilog-auto-sense-include-inputs)
12602 (verilog-alw-get-outputs-delayed sigss))
12603 (and (not verilog-auto-sense-include-inputs)
12604 (verilog-alw-get-outputs-immediate sigss))
12605 (verilog-alw-get-temps sigss)
12606 (verilog-decls-get-consts moddecls)
12607 (verilog-decls-get-gparams moddecls)
12608 presense-sigs)))))
12609 sig-list))
12610
12611 (defun verilog-auto-sense ()
12612 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
12613 Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
12614 with one automatically derived from all inputs declared in the always
12615 statement. Signals that are generated within the same always block are NOT
12616 placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
12617 Long lines are split based on the `fill-column', see \\[set-fill-column].
12618
12619 Limitations:
12620 Verilog does not allow memories (multidimensional arrays) in sensitivity
12621 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
12622
12623 Constant signals:
12624 AUTOSENSE cannot always determine if a `define is a constant or a signal
12625 (it could be in an include file for example). If a `define or other signal
12626 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
12627 declaration anywhere in the module (parenthesis are required):
12628
12629 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
12630
12631 Better yet, use a parameter, which will be understood to be constant
12632 automatically.
12633
12634 OOps!
12635 If AUTOSENSE makes a mistake, please report it. (First try putting
12636 a begin/end after your always!) As a workaround, if a signal that
12637 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
12638 If a signal should be in the sensitivity list wasn't, placing it before
12639 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
12640 autos are updated (or added if it occurs there already).
12641
12642 An example:
12643
12644 always @ (/*AS*/) begin
12645 /* AUTO_CONSTANT (`constant) */
12646 outin = ina | inb | `constant;
12647 out = outin;
12648 end
12649
12650 Typing \\[verilog-auto] will make this into:
12651
12652 always @ (/*AS*/ina or inb) begin
12653 /* AUTO_CONSTANT (`constant) */
12654 outin = ina | inb | `constant;
12655 out = outin;
12656 end
12657
12658 Note in Verilog 2001, you can often get the same result from the new @*
12659 operator. (This was added to the language in part due to AUTOSENSE!)
12660
12661 always @* begin
12662 outin = ina | inb | `constant;
12663 out = outin;
12664 end"
12665 (save-excursion
12666 ;; Find beginning
12667 (let* ((start-pt (save-excursion
12668 (verilog-re-search-backward-quick "(" nil t)
12669 (point)))
12670 (indent-pt (save-excursion
12671 (or (and (goto-char start-pt) (1+ (current-column)))
12672 (current-indentation))))
12673 (modi (verilog-modi-current))
12674 (moddecls (verilog-modi-get-decls modi))
12675 (sig-memories (verilog-signals-memory
12676 (verilog-decls-get-vars moddecls)))
12677 sig-list not-first presense-sigs)
12678 ;; Read signals in always, eliminate outputs from sense list
12679 (setq presense-sigs (verilog-signals-from-signame
12680 (save-excursion
12681 (verilog-read-signals start-pt (point)))))
12682 (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
12683 (when sig-memories
12684 (let ((tlen (length sig-list)))
12685 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
12686 (if (not (eq tlen (length sig-list))) (verilog-insert " /*memory or*/ "))))
12687 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
12688 (save-excursion (goto-char (point))
12689 (verilog-re-search-backward-quick "[a-zA-Z0-9$_.%`]+" start-pt t)
12690 (verilog-re-search-backward-quick "\\s-" start-pt t)
12691 (while (looking-at "\\s-`endif")
12692 (verilog-re-search-backward-quick "[a-zA-Z0-9$_.%`]+" start-pt t)
12693 (verilog-re-search-backward-quick "\\s-" start-pt t))
12694 (not (looking-at "\\s-or\\b"))))
12695 (setq not-first t))
12696 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
12697 (while sig-list
12698 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
12699 (insert "\n")
12700 (indent-to indent-pt)
12701 (if not-first (insert "or ")))
12702 (not-first (insert " or ")))
12703 (insert (verilog-sig-name (car sig-list)))
12704 (setq sig-list (cdr sig-list)
12705 not-first t)))))
12706
12707 (defun verilog-auto-reset ()
12708 "Expand AUTORESET statements, as part of \\[verilog-auto].
12709 Replace the /*AUTORESET*/ comment with code to initialize all
12710 registers set elsewhere in the always block.
12711
12712 Limitations:
12713 AUTORESET will not clear memories.
12714
12715 AUTORESET uses <= if the signal has a <= assignment in the block,
12716 else it uses =.
12717
12718 If <= is used, all = assigned variables are ignored if
12719 `verilog-auto-reset-blocking-in-non' is nil; they are presumed
12720 to be temporaries.
12721
12722 /*AUTORESET*/ presumes that any signals mentioned between the previous
12723 begin/case/if statement and the AUTORESET comment are being reset manually
12724 and should not be automatically reset. This includes omitting any signals
12725 used on the right hand side of assignments.
12726
12727 By default, AUTORESET will include the width of the signal in the
12728 autos, SystemVerilog designs may want to change this. To control
12729 this behavior, see `verilog-auto-reset-widths'. In some cases
12730 AUTORESET must use a '0 assignment and it will print NOWIDTH; use
12731 `verilog-auto-reset-widths' unbased to prevent this.
12732
12733 AUTORESET ties signals to deasserted, which is presumed to be zero.
12734 Signals that match `verilog-active-low-regexp' will be deasserted by tying
12735 them to a one.
12736
12737 AUTORESET may try to reset arrays or structures that cannot be
12738 reset by a simple assignment, resulting in compile errors. This
12739 is a feature to be taken as a hint that you need to reset these
12740 signals manually (or put them into a \"`ifdef NEVER signal<=`0;
12741 `endif\" so Verilog-Mode ignores them.)
12742
12743 An example:
12744
12745 always @(posedge clk or negedge reset_l) begin
12746 if (!reset_l) begin
12747 c <= 1;
12748 /*AUTORESET*/
12749 end
12750 else begin
12751 a <= in_a;
12752 b <= in_b;
12753 c <= in_c;
12754 end
12755 end
12756
12757 Typing \\[verilog-auto] will make this into:
12758
12759 always @(posedge core_clk or negedge reset_l) begin
12760 if (!reset_l) begin
12761 c <= 1;
12762 /*AUTORESET*/
12763 // Beginning of autoreset for uninitialized flops
12764 a <= 0;
12765 b = 0; // if `verilog-auto-reset-blocking-in-non' true
12766 // End of automatics
12767 end
12768 else begin
12769 a <= in_a;
12770 b = in_b;
12771 c <= in_c;
12772 end
12773 end"
12774
12775 (interactive)
12776 (save-excursion
12777 ;; Find beginning
12778 (let* ((indent-pt (current-indentation))
12779 (modi (verilog-modi-current))
12780 (moddecls (verilog-modi-get-decls modi))
12781 (all-list (verilog-decls-get-signals moddecls))
12782 sigss sig-list dly-list prereset-sigs)
12783 ;; Read signals in always, eliminate outputs from reset list
12784 (setq prereset-sigs (verilog-signals-from-signame
12785 (save-excursion
12786 (verilog-read-signals
12787 (save-excursion
12788 (verilog-re-search-backward-quick
12789 "\\(@\\|\\<\\(begin\\|if\\|case\\|always\\(_latch\\|_ff\\|_comb\\)?\\)\\>\\)" nil t)
12790 (point))
12791 (point)))))
12792 (save-excursion
12793 (verilog-re-search-backward-quick "\\(@\\|\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\)\\>\\)" nil t)
12794 (setq sigss (verilog-read-always-signals)))
12795 (setq dly-list (verilog-alw-get-outputs-delayed sigss))
12796 (setq sig-list (verilog-signals-not-in (append
12797 (verilog-alw-get-outputs-delayed sigss)
12798 (when (or (not (verilog-alw-get-uses-delayed sigss))
12799 verilog-auto-reset-blocking-in-non)
12800 (verilog-alw-get-outputs-immediate sigss)))
12801 (append
12802 (verilog-alw-get-temps sigss)
12803 prereset-sigs)))
12804 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
12805 (when sig-list
12806 (insert "\n");
12807 (verilog-insert-indent "// Beginning of autoreset for uninitialized flops\n");
12808 (while sig-list
12809 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
12810 (car sig-list))))
12811 (indent-to indent-pt)
12812 (insert (verilog-sig-name sig)
12813 (if (assoc (verilog-sig-name sig) dly-list)
12814 (concat " <= " verilog-assignment-delay)
12815 " = ")
12816 (verilog-sig-tieoff sig)
12817 ";\n")
12818 (setq sig-list (cdr sig-list))))
12819 (verilog-insert-indent "// End of automatics")))))
12820
12821 (defun verilog-auto-tieoff ()
12822 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
12823 Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
12824 signals to deasserted.
12825
12826 /*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
12827 input/output list as another module, but no internals. Specifically, it
12828 finds all outputs in the module, and if that input is not otherwise declared
12829 as a register or wire, creates a tieoff.
12830
12831 AUTORESET ties signals to deasserted, which is presumed to be zero.
12832 Signals that match `verilog-active-low-regexp' will be deasserted by tying
12833 them to a one.
12834
12835 You can add signals you do not want included in AUTOTIEOFF with
12836 `verilog-auto-tieoff-ignore-regexp'.
12837
12838 `verilog-auto-wire-type' may be used to change the datatype of
12839 the declarations.
12840
12841 `verilog-auto-reset-widths' may be used to change how the tieoff
12842 value's width is generated.
12843
12844 An example of making a stub for another module:
12845
12846 module ExampStub (/*AUTOINST*/);
12847 /*AUTOINOUTPARAM(\"Foo\")*/
12848 /*AUTOINOUTMODULE(\"Foo\")*/
12849 /*AUTOTIEOFF*/
12850 // verilator lint_off UNUSED
12851 wire _unused_ok = &{1'b0,
12852 /*AUTOUNUSED*/
12853 1'b0};
12854 // verilator lint_on UNUSED
12855 endmodule
12856
12857 Typing \\[verilog-auto] will make this into:
12858
12859 module ExampStub (/*AUTOINST*/...);
12860 /*AUTOINOUTPARAM(\"Foo\")*/
12861 /*AUTOINOUTMODULE(\"Foo\")*/
12862 // Beginning of autotieoff
12863 output [2:0] foo;
12864 // End of automatics
12865
12866 /*AUTOTIEOFF*/
12867 // Beginning of autotieoff
12868 wire [2:0] foo = 3'b0;
12869 // End of automatics
12870 ...
12871 endmodule"
12872 (interactive)
12873 (save-excursion
12874 ;; Find beginning
12875 (let* ((indent-pt (current-indentation))
12876 (modi (verilog-modi-current))
12877 (moddecls (verilog-modi-get-decls modi))
12878 (modsubdecls (verilog-modi-get-sub-decls modi))
12879 (sig-list (verilog-signals-not-in
12880 (verilog-decls-get-outputs moddecls)
12881 (append (verilog-decls-get-vars moddecls)
12882 (verilog-decls-get-assigns moddecls)
12883 (verilog-decls-get-consts moddecls)
12884 (verilog-decls-get-gparams moddecls)
12885 (verilog-subdecls-get-interfaced modsubdecls)
12886 (verilog-subdecls-get-outputs modsubdecls)
12887 (verilog-subdecls-get-inouts modsubdecls)))))
12888 (setq sig-list (verilog-signals-not-matching-regexp
12889 sig-list verilog-auto-tieoff-ignore-regexp))
12890 (when sig-list
12891 (verilog-forward-or-insert-line)
12892 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
12893 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
12894 (verilog-modi-cache-add-vars modi sig-list) ; Before we trash list
12895 (while sig-list
12896 (let ((sig (car sig-list)))
12897 (cond ((equal verilog-auto-tieoff-declaration "assign")
12898 (indent-to indent-pt)
12899 (insert "assign " (verilog-sig-name sig)))
12900 (t
12901 (verilog-insert-one-definition sig verilog-auto-tieoff-declaration indent-pt)))
12902 (indent-to (max 48 (+ indent-pt 40)))
12903 (insert "= " (verilog-sig-tieoff sig)
12904 ";\n")
12905 (setq sig-list (cdr sig-list))))
12906 (verilog-insert-indent "// End of automatics\n")))))
12907
12908 (defun verilog-auto-undef ()
12909 "Expand AUTOUNDEF statements, as part of \\[verilog-auto].
12910 Take any `defines since the last AUTOUNDEF in the current file
12911 and create `undefs for them. This is used to insure that
12912 file-local defines do not pollute the global `define name space.
12913
12914 Limitations:
12915 AUTOUNDEF presumes any identifier following `define is the
12916 name of a define. Any `ifdefs are ignored.
12917
12918 AUTOUNDEF suppresses creating an `undef for any define that was
12919 `undefed before the AUTOUNDEF. This may be used to work around
12920 the ignoring of `ifdefs as shown below.
12921
12922 An example:
12923
12924 `define XX_FOO
12925 `define M_BAR(x)
12926 `define M_BAZ
12927 ...
12928 `ifdef NEVER
12929 `undef M_BAZ // Emacs will see this and not `undef M_BAZ
12930 `endif
12931 ...
12932 /*AUTOUNDEF*/
12933
12934 Typing \\[verilog-auto] will make this into:
12935
12936 ...
12937 /*AUTOUNDEF*/
12938 // Beginning of automatic undefs
12939 `undef XX_FOO
12940 `undef M_BAR
12941 // End of automatics
12942
12943 You may also provide an optional regular expression, in which case only
12944 defines the regular expression will be undefed."
12945 (save-excursion
12946 (let* ((params (verilog-read-auto-params 0 1))
12947 (regexp (nth 0 params))
12948 (indent-pt (current-indentation))
12949 (end-pt (point))
12950 defs def)
12951 (save-excursion
12952 ;; Scan from start of file, or last AUTOUNDEF
12953 (or (verilog-re-search-backward-quick "/\\*AUTOUNDEF\\>" end-pt t)
12954 (goto-char (point-min)))
12955 (while (verilog-re-search-forward-quick
12956 "`\\(define\\|undef\\)\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" end-pt t)
12957 (cond ((equal (match-string-no-properties 1) "define")
12958 (setq def (match-string-no-properties 2))
12959 (when (and (or (not regexp)
12960 (string-match regexp def))
12961 (not (member def defs))) ;; delete-dups not in 21.1
12962 (setq defs (cons def defs))))
12963 (t
12964 (setq defs (delete (match-string-no-properties 2) defs))))))
12965 ;; Insert
12966 (setq defs (sort defs 'string<))
12967 (when defs
12968 (verilog-forward-or-insert-line)
12969 (verilog-insert-indent "// Beginning of automatic undefs\n")
12970 (while defs
12971 (verilog-insert-indent "`undef " (car defs) "\n")
12972 (setq defs (cdr defs)))
12973 (verilog-insert-indent "// End of automatics\n")))))
12974
12975 (defun verilog-auto-unused ()
12976 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
12977 Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
12978 input and inout signals.
12979
12980 /*AUTOUNUSED*/ is used to make stub modules; modules that have the same
12981 input/output list as another module, but no internals. Specifically, it
12982 finds all inputs and inouts in the module, and if that input is not otherwise
12983 used, adds it to a comma separated list.
12984
12985 The comma separated list is intended to be used to create a _unused_ok
12986 signal. Using the exact name \"_unused_ok\" for name of the temporary
12987 signal is recommended as it will insure maximum forward compatibility, it
12988 also makes lint warnings easy to understand; ignore any unused warnings
12989 with \"unused\" in the signal name.
12990
12991 To reduce simulation time, the _unused_ok signal should be forced to a
12992 constant to prevent wiggling. The easiest thing to do is use a
12993 reduction-and with 1'b0 as shown.
12994
12995 This way all unused signals are in one place, making it convenient to add
12996 your tool's specific pragmas around the assignment to disable any unused
12997 warnings.
12998
12999 You can add signals you do not want included in AUTOUNUSED with
13000 `verilog-auto-unused-ignore-regexp'.
13001
13002 An example of making a stub for another module:
13003
13004 module ExampStub (/*AUTOINST*/);
13005 /*AUTOINOUTPARAM(\"Examp\")*/
13006 /*AUTOINOUTMODULE(\"Examp\")*/
13007 /*AUTOTIEOFF*/
13008 // verilator lint_off UNUSED
13009 wire _unused_ok = &{1'b0,
13010 /*AUTOUNUSED*/
13011 1'b0};
13012 // verilator lint_on UNUSED
13013 endmodule
13014
13015 Typing \\[verilog-auto] will make this into:
13016
13017 ...
13018 // verilator lint_off UNUSED
13019 wire _unused_ok = &{1'b0,
13020 /*AUTOUNUSED*/
13021 // Beginning of automatics
13022 unused_input_a,
13023 unused_input_b,
13024 unused_input_c,
13025 // End of automatics
13026 1'b0};
13027 // verilator lint_on UNUSED
13028 endmodule"
13029 (interactive)
13030 (save-excursion
13031 ;; Find beginning
13032 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
13033 (modi (verilog-modi-current))
13034 (moddecls (verilog-modi-get-decls modi))
13035 (modsubdecls (verilog-modi-get-sub-decls modi))
13036 (sig-list (verilog-signals-not-in
13037 (append (verilog-decls-get-inputs moddecls)
13038 (verilog-decls-get-inouts moddecls))
13039 (append (verilog-subdecls-get-inputs modsubdecls)
13040 (verilog-subdecls-get-inouts modsubdecls)))))
13041 (setq sig-list (verilog-signals-not-matching-regexp
13042 sig-list verilog-auto-unused-ignore-regexp))
13043 (when sig-list
13044 (verilog-forward-or-insert-line)
13045 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
13046 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
13047 (while sig-list
13048 (let ((sig (car sig-list)))
13049 (indent-to indent-pt)
13050 (insert (verilog-sig-name sig) ",\n")
13051 (setq sig-list (cdr sig-list))))
13052 (verilog-insert-indent "// End of automatics\n")))))
13053
13054 (defun verilog-enum-ascii (signm elim-regexp)
13055 "Convert an enum name SIGNM to an ascii string for insertion.
13056 Remove user provided prefix ELIM-REGEXP."
13057 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
13058 (let ((case-fold-search t))
13059 ;; All upper becomes all lower for readability
13060 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
13061
13062 (defun verilog-auto-ascii-enum ()
13063 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
13064 Create a register to contain the ASCII decode of an enumerated signal type.
13065 This will allow trace viewers to show the ASCII name of states.
13066
13067 First, parameters are built into an enumeration using the synopsys enum
13068 comment. The comment must be between the keyword and the symbol.
13069 \(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
13070
13071 Next, registers which that enum applies to are also tagged with the same
13072 enum.
13073
13074 Finally, an AUTOASCIIENUM command is used.
13075
13076 The first parameter is the name of the signal to be decoded.
13077
13078 The second parameter is the name to store the ASCII code into. For the
13079 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
13080 a signal that is just for simulation, and the magic characters _ascii
13081 tell viewers like Dinotrace to display in ASCII format.
13082
13083 The third optional parameter is a string which will be removed
13084 from the state names. It defaults to \"\" which removes nothing.
13085
13086 The fourth optional parameter is \"onehot\" to force one-hot
13087 decoding. If unspecified, if and only if the first parameter
13088 width is 2^(number of states in enum) and does NOT match the
13089 width of the enum, the signal is assumed to be a one-hot
13090 decode. Otherwise, it's a normal encoded state vector.
13091
13092 `verilog-auto-wire-type' may be used to change the datatype of
13093 the declarations.
13094
13095 \"auto enum\" may be used in place of \"synopsys enum\".
13096
13097 An example:
13098
13099 //== State enumeration
13100 parameter [2:0] // synopsys enum state_info
13101 SM_IDLE = 3'b000,
13102 SM_SEND = 3'b001,
13103 SM_WAIT1 = 3'b010;
13104 //== State variables
13105 reg [2:0] /* synopsys enum state_info */
13106 state_r; /* synopsys state_vector state_r */
13107 reg [2:0] /* synopsys enum state_info */
13108 state_e1;
13109
13110 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
13111
13112 Typing \\[verilog-auto] will make this into:
13113
13114 ... same front matter ...
13115
13116 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
13117 // Beginning of automatic ASCII enum decoding
13118 reg [39:0] state_ascii_r; // Decode of state_r
13119 always @(state_r) begin
13120 case ({state_r})
13121 SM_IDLE: state_ascii_r = \"idle \";
13122 SM_SEND: state_ascii_r = \"send \";
13123 SM_WAIT1: state_ascii_r = \"wait1\";
13124 default: state_ascii_r = \"%Erro\";
13125 endcase
13126 end
13127 // End of automatics"
13128 (save-excursion
13129 (let* ((params (verilog-read-auto-params 2 4))
13130 (undecode-name (nth 0 params))
13131 (ascii-name (nth 1 params))
13132 (elim-regexp (and (nth 2 params)
13133 (not (equal (nth 2 params) ""))
13134 (nth 2 params)))
13135 (one-hot-flag (nth 3 params))
13136 ;;
13137 (indent-pt (current-indentation))
13138 (modi (verilog-modi-current))
13139 (moddecls (verilog-modi-get-decls modi))
13140 ;;
13141 (sig-list-consts (append (verilog-decls-get-consts moddecls)
13142 (verilog-decls-get-gparams moddecls)))
13143 (sig-list-all (verilog-decls-get-iovars moddecls))
13144 ;;
13145 (undecode-sig (or (assoc undecode-name sig-list-all)
13146 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
13147 (undecode-enum (or (verilog-sig-enum undecode-sig)
13148 (error "%s: Signal %s does not have an enum tag" (verilog-point-text) undecode-name)))
13149 ;;
13150 (enum-sigs (verilog-signals-not-in
13151 (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
13152 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum))
13153 nil))
13154 ;;
13155 (one-hot (or
13156 (string-match "onehot" (or one-hot-flag ""))
13157 (and ;; width(enum) != width(sig)
13158 (or (not (verilog-sig-bits (car enum-sigs)))
13159 (not (equal (verilog-sig-width (car enum-sigs))
13160 (verilog-sig-width undecode-sig))))
13161 ;; count(enums) == width(sig)
13162 (equal (number-to-string (length enum-sigs))
13163 (verilog-sig-width undecode-sig)))))
13164 (enum-chars 0)
13165 (ascii-chars 0))
13166 ;;
13167 ;; Find number of ascii chars needed
13168 (let ((tmp-sigs enum-sigs))
13169 (while tmp-sigs
13170 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
13171 ascii-chars (max ascii-chars (length (verilog-enum-ascii
13172 (verilog-sig-name (car tmp-sigs))
13173 elim-regexp)))
13174 tmp-sigs (cdr tmp-sigs))))
13175 ;;
13176 (verilog-forward-or-insert-line)
13177 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
13178 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
13179 (concat "Decode of " undecode-name) nil nil))))
13180 (verilog-insert-definition modi decode-sig-list "reg" indent-pt nil))
13181 ;;
13182 (verilog-insert-indent "always @(" undecode-name ") begin\n")
13183 (setq indent-pt (+ indent-pt verilog-indent-level))
13184 (verilog-insert-indent "case ({" undecode-name "})\n")
13185 (setq indent-pt (+ indent-pt verilog-case-indent))
13186 ;;
13187 (let ((tmp-sigs enum-sigs)
13188 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n"
13189 (+ (if one-hot 9 1) (max 8 enum-chars))
13190 ascii-name ascii-chars))
13191 (errname (substring "%Error" 0 (min 6 ascii-chars))))
13192 (while tmp-sigs
13193 (verilog-insert-indent
13194 (concat
13195 (format chrfmt
13196 (concat (if one-hot "(")
13197 ;; Use enum-sigs length as that's numeric
13198 ;; verilog-sig-width undecode-sig might not be.
13199 (if one-hot (number-to-string (length enum-sigs)))
13200 ;; We use a shift instead of var[index]
13201 ;; so that a non-one hot value will show as error.
13202 (if one-hot "'b1<<")
13203 (verilog-sig-name (car tmp-sigs))
13204 (if one-hot ")") ":")
13205 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
13206 elim-regexp))))
13207 (setq tmp-sigs (cdr tmp-sigs)))
13208 (verilog-insert-indent (format chrfmt "default:" errname)))
13209 ;;
13210 (setq indent-pt (- indent-pt verilog-case-indent))
13211 (verilog-insert-indent "endcase\n")
13212 (setq indent-pt (- indent-pt verilog-indent-level))
13213 (verilog-insert-indent "end\n"
13214 "// End of automatics\n"))))
13215
13216 (defun verilog-auto-templated-rel ()
13217 "Replace Templated relative line numbers with absolute line numbers.
13218 Internal use only. This hacks around the line numbers in AUTOINST Templates
13219 being different from the final output's line numbering."
13220 (let ((templateno 0) (template-line (list 0)) (buf-line 1))
13221 ;; Find line number each template is on
13222 ;; Count lines as we go, as otherwise it's O(n^2) to use count-lines
13223 (goto-char (point-min))
13224 (while (not (eobp))
13225 (when (looking-at ".*AUTO_TEMPLATE")
13226 (setq templateno (1+ templateno))
13227 (setq template-line (cons buf-line template-line)))
13228 (setq buf-line (1+ buf-line))
13229 (forward-line 1))
13230 (setq template-line (nreverse template-line))
13231 ;; Replace T# L# with absolute line number
13232 (goto-char (point-min))
13233 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
13234 (replace-match
13235 (concat " Templated "
13236 (int-to-string (+ (nth (string-to-number (match-string 1))
13237 template-line)
13238 (string-to-number (match-string 2)))))
13239 t t))))
13240
13241 (defun verilog-auto-template-lint ()
13242 "Check AUTO_TEMPLATEs for unused lines.
13243 Enable with `verilog-auto-template-warn-unused'."
13244 (let ((name1 (or (buffer-file-name) (buffer-name))))
13245 (save-excursion
13246 (goto-char (point-min))
13247 (while (re-search-forward
13248 "^\\s-*/?\\*?\\s-*[a-zA-Z0-9`_$]+\\s-+AUTO_TEMPLATE" nil t)
13249 (let* ((tpl-info (verilog-read-auto-template-middle))
13250 (tpl-list (aref tpl-info 1))
13251 (tlines (append (nth 0 tpl-list) (nth 1 tpl-list)))
13252 tpl-ass)
13253 (while tlines
13254 (setq tpl-ass (car tlines)
13255 tlines (cdr tlines))
13256 ;;;
13257 (unless (or (not (eval-when-compile (fboundp 'make-hash-table))) ;; Not supported, no warning
13258 (not verilog-auto-template-hits)
13259 (gethash (vector (nth 2 tpl-ass) (nth 3 tpl-ass))
13260 verilog-auto-template-hits))
13261 (verilog-warn-error "%s:%d: AUTO_TEMPLATE line unused: \".%s (%s)\""
13262 name1
13263 (+ (elt tpl-ass 3) ;; Template line number
13264 (count-lines (point-min) (point)))
13265 (elt tpl-ass 0) (elt tpl-ass 1))
13266 )))))))
13267
13268 \f
13269 ;;
13270 ;; Auto top level
13271 ;;
13272
13273 (defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing an arg
13274 "Expand AUTO statements.
13275 Look for any /*AUTO...*/ commands in the code, as used in
13276 instantiations or argument headers. Update the list of signals
13277 following the /*AUTO...*/ command.
13278
13279 Use \\[verilog-delete-auto] to remove the AUTOs.
13280
13281 Use \\[verilog-diff-auto] to see differences in AUTO expansion.
13282
13283 Use \\[verilog-inject-auto] to insert AUTOs for the first time.
13284
13285 Use \\[verilog-faq] for a pointer to frequently asked questions.
13286
13287 For new users, we recommend setting `verilog-case-fold' to nil
13288 and `verilog-auto-arg-sort' to t.
13289
13290 The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
13291 called before and after this function, respectively.
13292
13293 For example:
13294 module ModuleName (/*AUTOARG*/);
13295 /*AUTOINPUT*/
13296 /*AUTOOUTPUT*/
13297 /*AUTOWIRE*/
13298 /*AUTOREG*/
13299 InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
13300
13301 You can also update the AUTOs from the shell using:
13302 emacs --batch <filenames.v> -f verilog-batch-auto
13303 Or fix indentation with:
13304 emacs --batch <filenames.v> -f verilog-batch-indent
13305 Likewise, you can delete or inject AUTOs with:
13306 emacs --batch <filenames.v> -f verilog-batch-delete-auto
13307 emacs --batch <filenames.v> -f verilog-batch-inject-auto
13308 Or check if AUTOs have the same expansion
13309 emacs --batch <filenames.v> -f verilog-batch-diff-auto
13310
13311 Using \\[describe-function], see also:
13312 `verilog-auto-arg' for AUTOARG module instantiations
13313 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
13314 `verilog-auto-assign-modport' for AUTOASSIGNMODPORT assignment to/from modport
13315 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
13316 `verilog-auto-inout-comp' for AUTOINOUTCOMP copy complemented i/o
13317 `verilog-auto-inout-in' for AUTOINOUTIN inputs for all i/o
13318 `verilog-auto-inout-modport' for AUTOINOUTMODPORT i/o from an interface modport
13319 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
13320 `verilog-auto-inout-param' for AUTOINOUTPARAM copying params from elsewhere
13321 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
13322 `verilog-auto-insert-lisp' for AUTOINSERTLISP insert code from lisp function
13323 `verilog-auto-insert-last' for AUTOINSERTLAST insert code from lisp function
13324 `verilog-auto-inst' for AUTOINST instantiation pins
13325 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
13326 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
13327 `verilog-auto-logic' for AUTOLOGIC declaring logic signals
13328 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
13329 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
13330 `verilog-auto-reg' for AUTOREG registers
13331 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
13332 `verilog-auto-reset' for AUTORESET flop resets
13333 `verilog-auto-sense' for AUTOSENSE or AS always sensitivity lists
13334 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
13335 `verilog-auto-undef' for AUTOUNDEF `undef of local `defines
13336 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
13337 `verilog-auto-wire' for AUTOWIRE instantiation wires
13338
13339 `verilog-read-defines' for reading `define values
13340 `verilog-read-includes' for reading `includes
13341
13342 If you have bugs with these autos, please file an issue at
13343 URL `http://www.veripool.org/verilog-mode' or contact the AUTOAUTHOR
13344 Wilson Snyder (wsnyder@wsnyder.org)."
13345 (interactive)
13346 (unless noninteractive (message "Updating AUTOs..."))
13347 (if (fboundp 'dinotrace-unannotate-all)
13348 (dinotrace-unannotate-all))
13349 (verilog-save-font-mods
13350 (let ((oldbuf (if (not (buffer-modified-p))
13351 (buffer-string)))
13352 (case-fold-search verilog-case-fold)
13353 ;; Cache directories; we don't write new files, so can't change
13354 (verilog-dir-cache-preserving t)
13355 ;; Cache current module
13356 (verilog-modi-cache-current-enable t)
13357 (verilog-modi-cache-current-max (point-min)) ; IE it's invalid
13358 verilog-modi-cache-current)
13359 (unwind-protect
13360 ;; Disable change hooks for speed
13361 ;; This let can't be part of above let; must restore
13362 ;; after-change-functions before font-lock resumes
13363 (verilog-save-no-change-functions
13364 (verilog-save-scan-cache
13365 (save-excursion
13366 ;; Wipe cache; otherwise if we AUTOed a block above this one,
13367 ;; we'll misremember we have generated IOs, confusing AUTOOUTPUT
13368 (setq verilog-modi-cache-list nil)
13369 ;; Local state
13370 (setq verilog-auto-template-hits nil)
13371 ;; If we're not in verilog-mode, change syntax table so parsing works right
13372 (unless (eq major-mode `verilog-mode) (verilog-mode))
13373 ;; Allow user to customize
13374 (verilog-run-hooks 'verilog-before-auto-hook)
13375 ;; Try to save the user from needing to revert-file to reread file local-variables
13376 (verilog-auto-reeval-locals)
13377 (verilog-read-auto-lisp-present)
13378 (verilog-read-auto-lisp (point-min) (point-max))
13379 (verilog-getopt-flags)
13380 ;; From here on out, we can cache anything we read from disk
13381 (verilog-preserve-dir-cache
13382 ;; These two may seem obvious to do always, but on large includes it can be way too slow
13383 (when verilog-auto-read-includes
13384 (verilog-read-includes)
13385 (verilog-read-defines nil nil t))
13386 ;; Setup variables due to SystemVerilog expansion
13387 (verilog-auto-re-search-do "/\\*AUTOLOGIC\\*/" 'verilog-auto-logic-setup)
13388 ;; This particular ordering is important
13389 ;; INST: Lower modules correct, no internal dependencies, FIRST
13390 (verilog-preserve-modi-cache
13391 ;; Clear existing autos else we'll be screwed by existing ones
13392 (verilog-delete-auto)
13393 ;; Injection if appropriate
13394 (when inject
13395 (verilog-inject-inst)
13396 (verilog-inject-sense)
13397 (verilog-inject-arg))
13398 ;;
13399 ;; Do user inserts first, so their code can insert AUTOs
13400 (verilog-auto-re-search-do "/\\*AUTOINSERTLISP(.*?)\\*/"
13401 'verilog-auto-insert-lisp)
13402 ;; Expand instances before need the signals the instances input/output
13403 (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
13404 (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
13405 (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
13406 ;; Doesn't matter when done, but combine it with a common changer
13407 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
13408 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
13409 ;; Must be done before autoin/out as creates a reg
13410 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM(.*?)\\*/" 'verilog-auto-ascii-enum)
13411 ;;
13412 ;; first in/outs from other files
13413 (verilog-auto-re-search-do "/\\*AUTOINOUTMODPORT(.*?)\\*/" 'verilog-auto-inout-modport)
13414 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE(.*?)\\*/" 'verilog-auto-inout-module)
13415 (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP(.*?)\\*/" 'verilog-auto-inout-comp)
13416 (verilog-auto-re-search-do "/\\*AUTOINOUTIN(.*?)\\*/" 'verilog-auto-inout-in)
13417 (verilog-auto-re-search-do "/\\*AUTOINOUTPARAM(.*?)\\*/" 'verilog-auto-inout-param)
13418 ;; next in/outs which need previous sucked inputs first
13419 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((.*?)\\)?\\*/" 'verilog-auto-output)
13420 (verilog-auto-re-search-do "/\\*AUTOINPUT\\((.*?)\\)?\\*/" 'verilog-auto-input)
13421 (verilog-auto-re-search-do "/\\*AUTOINOUT\\((.*?)\\)?\\*/" 'verilog-auto-inout)
13422 ;; Then tie off those in/outs
13423 (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
13424 ;; These can be anywhere after AUTOINSERTLISP
13425 (verilog-auto-re-search-do "/\\*AUTOUNDEF\\((.*?)\\)?\\*/" 'verilog-auto-undef)
13426 ;; Wires/regs must be after inputs/outputs
13427 (verilog-auto-re-search-do "/\\*AUTOASSIGNMODPORT(.*?)\\*/" 'verilog-auto-assign-modport)
13428 (verilog-auto-re-search-do "/\\*AUTOLOGIC\\*/" 'verilog-auto-logic)
13429 (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
13430 (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
13431 (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
13432 ;; outputevery needs AUTOOUTPUTs done first
13433 (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\((.*?)\\)?\\*/" 'verilog-auto-output-every)
13434 ;; After we've created all new variables
13435 (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
13436 ;; Must be after all inputs outputs are generated
13437 (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
13438 ;; User inserts
13439 (verilog-auto-re-search-do "/\\*AUTOINSERTLAST(.*?)\\*/" 'verilog-auto-insert-last)
13440 ;; Fix line numbers (comments only)
13441 (when verilog-auto-inst-template-numbers
13442 (verilog-auto-templated-rel))
13443 (when verilog-auto-template-warn-unused
13444 (verilog-auto-template-lint))))
13445 ;;
13446 (verilog-run-hooks 'verilog-auto-hook)
13447 ;;
13448 (when verilog-auto-delete-trailing-whitespace
13449 (verilog-delete-trailing-whitespace))
13450 ;;
13451 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))
13452 ;;
13453 ;; If end result is same as when started, clear modified flag
13454 (cond ((and oldbuf (equal oldbuf (buffer-string)))
13455 (set-buffer-modified-p nil)
13456 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
13457 (t (unless noninteractive (message "Updating AUTOs...done"))))
13458 ;; End of after-change protection
13459 )))
13460 ;; Unwind forms
13461 ;; Currently handled in verilog-save-font-mods
13462 ))))
13463 \f
13464
13465 ;;
13466 ;; Skeleton based code insertion
13467 ;;
13468 (defvar verilog-template-map
13469 (let ((map (make-sparse-keymap)))
13470 (define-key map "a" 'verilog-sk-always)
13471 (define-key map "b" 'verilog-sk-begin)
13472 (define-key map "c" 'verilog-sk-case)
13473 (define-key map "f" 'verilog-sk-for)
13474 (define-key map "g" 'verilog-sk-generate)
13475 (define-key map "h" 'verilog-sk-header)
13476 (define-key map "i" 'verilog-sk-initial)
13477 (define-key map "j" 'verilog-sk-fork)
13478 (define-key map "m" 'verilog-sk-module)
13479 (define-key map "o" 'verilog-sk-ovm-class)
13480 (define-key map "p" 'verilog-sk-primitive)
13481 (define-key map "r" 'verilog-sk-repeat)
13482 (define-key map "s" 'verilog-sk-specify)
13483 (define-key map "t" 'verilog-sk-task)
13484 (define-key map "u" 'verilog-sk-uvm-object)
13485 (define-key map "w" 'verilog-sk-while)
13486 (define-key map "x" 'verilog-sk-casex)
13487 (define-key map "z" 'verilog-sk-casez)
13488 (define-key map "?" 'verilog-sk-if)
13489 (define-key map ":" 'verilog-sk-else-if)
13490 (define-key map "/" 'verilog-sk-comment)
13491 (define-key map "A" 'verilog-sk-assign)
13492 (define-key map "F" 'verilog-sk-function)
13493 (define-key map "I" 'verilog-sk-input)
13494 (define-key map "O" 'verilog-sk-output)
13495 (define-key map "S" 'verilog-sk-state-machine)
13496 (define-key map "=" 'verilog-sk-inout)
13497 (define-key map "U" 'verilog-sk-uvm-component)
13498 (define-key map "W" 'verilog-sk-wire)
13499 (define-key map "R" 'verilog-sk-reg)
13500 (define-key map "D" 'verilog-sk-define-signal)
13501 map)
13502 "Keymap used in Verilog mode for smart template operations.")
13503
13504
13505 ;;
13506 ;; Place the templates into Verilog Mode. They may be inserted under any key.
13507 ;; C-c C-t will be the default. If you use templates a lot, you
13508 ;; may want to consider moving the binding to another key in your init
13509 ;; file.
13510 ;;
13511 ;; Note \C-c and letter are reserved for users
13512 (define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
13513
13514 ;;; ---- statement skeletons ------------------------------------------
13515
13516 (define-skeleton verilog-sk-prompt-condition
13517 "Prompt for the loop condition."
13518 "[condition]: " str )
13519
13520 (define-skeleton verilog-sk-prompt-init
13521 "Prompt for the loop init statement."
13522 "[initial statement]: " str )
13523
13524 (define-skeleton verilog-sk-prompt-inc
13525 "Prompt for the loop increment statement."
13526 "[increment statement]: " str )
13527
13528 (define-skeleton verilog-sk-prompt-name
13529 "Prompt for the name of something."
13530 "[name]: " str)
13531
13532 (define-skeleton verilog-sk-prompt-clock
13533 "Prompt for the name of something."
13534 "name and edge of clock(s): " str)
13535
13536 (defvar verilog-sk-reset nil)
13537 (defun verilog-sk-prompt-reset ()
13538 "Prompt for the name of a state machine reset."
13539 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
13540
13541
13542 (define-skeleton verilog-sk-prompt-state-selector
13543 "Prompt for the name of a state machine selector."
13544 "name of selector (eg {a,b,c,d}): " str )
13545
13546 (define-skeleton verilog-sk-prompt-output
13547 "Prompt for the name of something."
13548 "output: " str)
13549
13550 (define-skeleton verilog-sk-prompt-msb
13551 "Prompt for most significant bit specification."
13552 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
13553
13554 (define-skeleton verilog-sk-prompt-lsb
13555 "Prompt for least significant bit specification."
13556 "lsb:" str )
13557
13558 (defvar verilog-sk-p nil)
13559 (define-skeleton verilog-sk-prompt-width
13560 "Prompt for a width specification."
13561 ()
13562 (progn
13563 (setq verilog-sk-p (point))
13564 (verilog-sk-prompt-msb)
13565 (if (> (point) verilog-sk-p) "] " " ")))
13566
13567 (defun verilog-sk-header ()
13568 "Insert a descriptive header at the top of the file.
13569 See also `verilog-header' for an alternative format."
13570 (interactive "*")
13571 (save-excursion
13572 (goto-char (point-min))
13573 (verilog-sk-header-tmpl)))
13574
13575 (define-skeleton verilog-sk-header-tmpl
13576 "Insert a comment block containing the module title, author, etc."
13577 "[Description]: "
13578 "// -*- Mode: Verilog -*-"
13579 "\n// Filename : " (buffer-name)
13580 "\n// Description : " str
13581 "\n// Author : " (user-full-name)
13582 "\n// Created On : " (current-time-string)
13583 "\n// Last Modified By: " (user-full-name)
13584 "\n// Last Modified On: " (current-time-string)
13585 "\n// Update Count : 0"
13586 "\n// Status : Unknown, Use with caution!"
13587 "\n")
13588
13589 (define-skeleton verilog-sk-module
13590 "Insert a module definition."
13591 ()
13592 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
13593 > _ \n
13594 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
13595
13596 ;;; ------------------------------------------------------------------------
13597 ;;; Define a default OVM class, with macros and new()
13598 ;;; ------------------------------------------------------------------------
13599
13600 (define-skeleton verilog-sk-ovm-class
13601 "Insert a class definition"
13602 ()
13603 > "class " (setq name (skeleton-read "Name: ")) " extends " (skeleton-read "Extends: ") ";" \n
13604 > _ \n
13605 > "`ovm_object_utils_begin(" name ")" \n
13606 > (- verilog-indent-level) " `ovm_object_utils_end" \n
13607 > _ \n
13608 > "function new(string name=\"" name "\");" \n
13609 > "super.new(name);" \n
13610 > (- verilog-indent-level) "endfunction" \n
13611 > _ \n
13612 > "endclass" (progn (electric-verilog-terminate-line) nil))
13613
13614 (define-skeleton verilog-sk-uvm-object
13615 "Insert a class definition"
13616 ()
13617 > "class " (setq name (skeleton-read "Name: ")) " extends " (skeleton-read "Extends: ") ";" \n
13618 > _ \n
13619 > "`uvm_object_utils_begin(" name ")" \n
13620 > (- verilog-indent-level) "`uvm_object_utils_end" \n
13621 > _ \n
13622 > "function new(string name=\"" name "\");" \n
13623 > "super.new(name);" \n
13624 > (- verilog-indent-level) "endfunction" \n
13625 > _ \n
13626 > "endclass" (progn (electric-verilog-terminate-line) nil))
13627
13628 (define-skeleton verilog-sk-uvm-component
13629 "Insert a class definition"
13630 ()
13631 > "class " (setq name (skeleton-read "Name: ")) " extends " (skeleton-read "Extends: ") ";" \n
13632 > _ \n
13633 > "`uvm_component_utils_begin(" name ")" \n
13634 > (- verilog-indent-level) "`uvm_component_utils_end" \n
13635 > _ \n
13636 > "function new(string name=\"\", uvm_component parent);" \n
13637 > "super.new(name, parent);" \n
13638 > (- verilog-indent-level) "endfunction" \n
13639 > _ \n
13640 > "endclass" (progn (electric-verilog-terminate-line) nil))
13641
13642 (define-skeleton verilog-sk-primitive
13643 "Insert a task definition."
13644 ()
13645 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
13646 > _ \n
13647 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
13648
13649 (define-skeleton verilog-sk-task
13650 "Insert a task definition."
13651 ()
13652 > "task " '(verilog-sk-prompt-name) & ?; \n
13653 > _ \n
13654 > "begin" \n
13655 > \n
13656 > (- verilog-indent-level-behavioral) "end" \n
13657 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
13658
13659 (define-skeleton verilog-sk-function
13660 "Insert a function definition."
13661 ()
13662 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
13663 > _ \n
13664 > "begin" \n
13665 > \n
13666 > (- verilog-indent-level-behavioral) "end" \n
13667 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
13668
13669 (define-skeleton verilog-sk-always
13670 "Insert always block. Uses the minibuffer to prompt
13671 for sensitivity list."
13672 ()
13673 > "always @ ( /*AUTOSENSE*/ ) begin\n"
13674 > _ \n
13675 > (- verilog-indent-level-behavioral) "end" \n >
13676 )
13677
13678 (define-skeleton verilog-sk-initial
13679 "Insert an initial block."
13680 ()
13681 > "initial begin\n"
13682 > _ \n
13683 > (- verilog-indent-level-behavioral) "end" \n > )
13684
13685 (define-skeleton verilog-sk-specify
13686 "Insert specify block. "
13687 ()
13688 > "specify\n"
13689 > _ \n
13690 > (- verilog-indent-level-behavioral) "endspecify" \n > )
13691
13692 (define-skeleton verilog-sk-generate
13693 "Insert generate block. "
13694 ()
13695 > "generate\n"
13696 > _ \n
13697 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
13698
13699 (define-skeleton verilog-sk-begin
13700 "Insert begin end block. Uses the minibuffer to prompt for name."
13701 ()
13702 > "begin" '(verilog-sk-prompt-name) \n
13703 > _ \n
13704 > (- verilog-indent-level-behavioral) "end" )
13705
13706 (define-skeleton verilog-sk-fork
13707 "Insert a fork join block."
13708 ()
13709 > "fork\n"
13710 > "begin" \n
13711 > _ \n
13712 > (- verilog-indent-level-behavioral) "end" \n
13713 > "begin" \n
13714 > \n
13715 > (- verilog-indent-level-behavioral) "end" \n
13716 > (- verilog-indent-level-behavioral) "join" \n
13717 > )
13718
13719
13720 (define-skeleton verilog-sk-case
13721 "Build skeleton case statement, prompting for the selector expression,
13722 and the case items."
13723 "[selector expression]: "
13724 > "case (" str ") " \n
13725 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
13726 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
13727
13728 (define-skeleton verilog-sk-casex
13729 "Build skeleton casex statement, prompting for the selector expression,
13730 and the case items."
13731 "[selector expression]: "
13732 > "casex (" str ") " \n
13733 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
13734 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
13735
13736 (define-skeleton verilog-sk-casez
13737 "Build skeleton casez statement, prompting for the selector expression,
13738 and the case items."
13739 "[selector expression]: "
13740 > "casez (" str ") " \n
13741 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
13742 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
13743
13744 (define-skeleton verilog-sk-if
13745 "Insert a skeleton if statement."
13746 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
13747 > _ \n
13748 > (- verilog-indent-level-behavioral) "end " \n )
13749
13750 (define-skeleton verilog-sk-else-if
13751 "Insert a skeleton else if statement."
13752 > (verilog-indent-line) "else if ("
13753 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
13754 > _ \n
13755 > "end" (progn (electric-verilog-terminate-line) nil))
13756
13757 (define-skeleton verilog-sk-datadef
13758 "Common routine to get data definition."
13759 ()
13760 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
13761
13762 (define-skeleton verilog-sk-input
13763 "Insert an input definition."
13764 ()
13765 > "input [" '(verilog-sk-datadef))
13766
13767 (define-skeleton verilog-sk-output
13768 "Insert an output definition."
13769 ()
13770 > "output [" '(verilog-sk-datadef))
13771
13772 (define-skeleton verilog-sk-inout
13773 "Insert an inout definition."
13774 ()
13775 > "inout [" '(verilog-sk-datadef))
13776
13777 (defvar verilog-sk-signal nil)
13778 (define-skeleton verilog-sk-def-reg
13779 "Insert a reg definition."
13780 ()
13781 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations-auto) )
13782
13783 (defun verilog-sk-define-signal ()
13784 "Insert a definition of signal under point at top of module."
13785 (interactive "*")
13786 (let* ((sig-re "[a-zA-Z0-9_]*")
13787 (v1 (buffer-substring
13788 (save-excursion
13789 (skip-chars-backward sig-re)
13790 (point))
13791 (save-excursion
13792 (skip-chars-forward sig-re)
13793 (point)))))
13794 (if (not (member v1 verilog-keywords))
13795 (save-excursion
13796 (setq verilog-sk-signal v1)
13797 (verilog-beg-of-defun)
13798 (verilog-end-of-statement)
13799 (verilog-forward-syntactic-ws)
13800 (verilog-sk-def-reg)
13801 (message "signal at point is %s" v1))
13802 (message "object at point (%s) is a keyword" v1))))
13803
13804 (define-skeleton verilog-sk-wire
13805 "Insert a wire definition."
13806 ()
13807 > "wire [" '(verilog-sk-datadef))
13808
13809 (define-skeleton verilog-sk-reg
13810 "Insert a reg definition."
13811 ()
13812 > "reg [" '(verilog-sk-datadef))
13813
13814 (define-skeleton verilog-sk-assign
13815 "Insert a skeleton assign statement."
13816 ()
13817 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
13818
13819 (define-skeleton verilog-sk-while
13820 "Insert a skeleton while loop statement."
13821 ()
13822 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
13823 > _ \n
13824 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
13825
13826 (define-skeleton verilog-sk-repeat
13827 "Insert a skeleton repeat loop statement."
13828 ()
13829 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
13830 > _ \n
13831 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
13832
13833 (define-skeleton verilog-sk-for
13834 "Insert a skeleton while loop statement."
13835 ()
13836 > "for ("
13837 '(verilog-sk-prompt-init) "; "
13838 '(verilog-sk-prompt-condition) "; "
13839 '(verilog-sk-prompt-inc)
13840 ") begin" \n
13841 > _ \n
13842 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
13843
13844 (define-skeleton verilog-sk-comment
13845 "Inserts three comment lines, making a display comment."
13846 ()
13847 > "/*\n"
13848 > "* " _ \n
13849 > "*/")
13850
13851 (define-skeleton verilog-sk-state-machine
13852 "Insert a state machine definition."
13853 "Name of state variable: "
13854 '(setq input "state")
13855 > "// State registers for " str | -23 \n
13856 '(setq verilog-sk-state str)
13857 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
13858 '(setq input nil)
13859 > \n
13860 > "// State FF for " verilog-sk-state \n
13861 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
13862 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
13863 > verilog-sk-state " = next_" verilog-sk-state ?; \n
13864 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
13865 > \n
13866 > "// Next State Logic for " verilog-sk-state \n
13867 > "always @ ( /*AUTOSENSE*/ ) begin\n"
13868 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
13869 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
13870 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
13871 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
13872 \f
13873
13874 ;;
13875 ;; Include file loading with mouse/return event
13876 ;;
13877 ;; idea & first impl.: M. Rouat (eldo-mode.el)
13878 ;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
13879
13880 (if (featurep 'xemacs)
13881 (require 'overlay))
13882
13883 (defconst verilog-include-file-regexp
13884 "^`include\\s-+\"\\([^\n\"]*\\)\""
13885 "Regexp that matches the include file.")
13886
13887 (defvar verilog-mode-mouse-map
13888 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
13889 (set-keymap-parent map verilog-mode-map)
13890 ;; mouse button bindings
13891 (define-key map "\r" 'verilog-load-file-at-point)
13892 (if (featurep 'xemacs)
13893 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
13894 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
13895 (if (featurep 'xemacs)
13896 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
13897 (define-key map [S-mouse-2] 'mouse-yank-at-click))
13898 map)
13899 "Map containing mouse bindings for `verilog-mode'.")
13900
13901
13902 (defun verilog-highlight-region (beg end _old-len)
13903 "Colorize included files and modules in the (changed?) region.
13904 Clicking on the middle-mouse button loads them in a buffer (as in dired)."
13905 (when (or verilog-highlight-includes
13906 verilog-highlight-modules)
13907 (save-excursion
13908 (save-match-data ;; A query-replace may call this function - do not disturb
13909 (verilog-save-buffer-state
13910 (verilog-save-scan-cache
13911 (let (end-point)
13912 (goto-char end)
13913 (setq end-point (point-at-eol))
13914 (goto-char beg)
13915 (beginning-of-line) ; scan entire line
13916 ;; delete overlays existing on this line
13917 (let ((overlays (overlays-in (point) end-point)))
13918 (while overlays
13919 (if (and
13920 (overlay-get (car overlays) 'detachable)
13921 (or (overlay-get (car overlays) 'verilog-include-file)
13922 (overlay-get (car overlays) 'verilog-inst-module)))
13923 (delete-overlay (car overlays)))
13924 (setq overlays (cdr overlays))))
13925 ;;
13926 ;; make new include overlays
13927 (when verilog-highlight-includes
13928 (while (search-forward-regexp verilog-include-file-regexp end-point t)
13929 (goto-char (match-beginning 1))
13930 (let ((ov (make-overlay (match-beginning 1) (match-end 1))))
13931 (overlay-put ov 'start-closed 't)
13932 (overlay-put ov 'end-closed 't)
13933 (overlay-put ov 'evaporate 't)
13934 (overlay-put ov 'verilog-include-file 't)
13935 (overlay-put ov 'mouse-face 'highlight)
13936 (overlay-put ov 'local-map verilog-mode-mouse-map))))
13937 ;;
13938 ;; make new module overlays
13939 (goto-char beg)
13940 ;; This scanner is syntax-fragile, so don't get bent
13941 (when verilog-highlight-modules
13942 (condition-case nil
13943 (while (verilog-re-search-forward-quick "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-point t)
13944 (save-excursion
13945 (goto-char (match-beginning 0))
13946 (unless (verilog-inside-comment-or-string-p)
13947 (verilog-read-inst-module-matcher) ;; sets match 0
13948 (let* ((ov (make-overlay (match-beginning 0) (match-end 0))))
13949 (overlay-put ov 'start-closed 't)
13950 (overlay-put ov 'end-closed 't)
13951 (overlay-put ov 'evaporate 't)
13952 (overlay-put ov 'verilog-inst-module 't)
13953 (overlay-put ov 'mouse-face 'highlight)
13954 (overlay-put ov 'local-map verilog-mode-mouse-map)))))
13955 (error nil)))
13956 ;;
13957 ;; Future highlights:
13958 ;; variables - make an Occur buffer of where referenced
13959 ;; pins - make an Occur buffer of the sig in the declaration module
13960 )))))))
13961
13962 (defun verilog-highlight-buffer ()
13963 "Colorize included files and modules across the whole buffer."
13964 ;; Invoked via verilog-mode calling font-lock then `font-lock-mode-hook'
13965 (interactive)
13966 ;; delete and remake overlays
13967 (verilog-highlight-region (point-min) (point-max) nil))
13968
13969 ;; Deprecated, but was interactive, so we'll keep it around
13970 (defalias 'verilog-colorize-include-files-buffer 'verilog-highlight-buffer)
13971
13972 ;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
13973 ;; so define this function to do more or less the same as ffap-at-mouse
13974 ;; but first resolve filename...
13975 (defun verilog-load-file-at-mouse (event)
13976 "Load file under button 2 click's EVENT.
13977 Files are checked based on `verilog-library-flags'."
13978 (interactive "@e")
13979 (save-excursion ;; implement a Verilog specific ffap-at-mouse
13980 (mouse-set-point event)
13981 (verilog-load-file-at-point t)))
13982
13983 ;; ffap isn't usable for Verilog mode. It uses library paths.
13984 ;; so define this function to do more or less the same as ffap
13985 ;; but first resolve filename...
13986 (defun verilog-load-file-at-point (&optional warn)
13987 "Load file under point.
13988 If WARN, throw warning if not found.
13989 Files are checked based on `verilog-library-flags'."
13990 (interactive)
13991 (save-excursion ;; implement a Verilog specific ffap
13992 (let ((overlays (overlays-in (point) (point)))
13993 hit)
13994 (while (and overlays (not hit))
13995 (when (overlay-get (car overlays) 'verilog-inst-module)
13996 (verilog-goto-defun-file (buffer-substring
13997 (overlay-start (car overlays))
13998 (overlay-end (car overlays))))
13999 (setq hit t))
14000 (setq overlays (cdr overlays)))
14001 ;; Include?
14002 (beginning-of-line)
14003 (when (and (not hit)
14004 (looking-at verilog-include-file-regexp))
14005 (if (and (car (verilog-library-filenames
14006 (match-string 1) (buffer-file-name)))
14007 (file-readable-p (car (verilog-library-filenames
14008 (match-string 1) (buffer-file-name)))))
14009 (find-file (car (verilog-library-filenames
14010 (match-string 1) (buffer-file-name))))
14011 (when warn
14012 (message
14013 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
14014 (match-string 1))))))))
14015
14016 ;;
14017 ;; Bug reporting
14018 ;;
14019
14020 (defun verilog-faq ()
14021 "Tell the user their current version, and where to get the FAQ etc."
14022 (interactive)
14023 (with-output-to-temp-buffer "*verilog-mode help*"
14024 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
14025 (princ "\n")
14026 (princ "For new releases, see http://www.verilog.com\n")
14027 (princ "\n")
14028 (princ "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
14029 (princ "\n")
14030 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
14031 (princ "\n")))
14032
14033 (autoload 'reporter-submit-bug-report "reporter")
14034 (defvar reporter-prompt-for-summary-p)
14035
14036 (defun verilog-submit-bug-report ()
14037 "Submit via mail a bug report on verilog-mode.el."
14038 (interactive)
14039 (let ((reporter-prompt-for-summary-p t))
14040 (reporter-submit-bug-report
14041 "mac@verilog.com, wsnyder@wsnyder.org"
14042 (concat "verilog-mode v" verilog-mode-version)
14043 '(
14044 verilog-active-low-regexp
14045 verilog-after-save-font-hook
14046 verilog-align-ifelse
14047 verilog-assignment-delay
14048 verilog-auto-arg-sort
14049 verilog-auto-declare-nettype
14050 verilog-auto-delete-trailing-whitespace
14051 verilog-auto-endcomments
14052 verilog-auto-hook
14053 verilog-auto-ignore-concat
14054 verilog-auto-indent-on-newline
14055 verilog-auto-inout-ignore-regexp
14056 verilog-auto-input-ignore-regexp
14057 verilog-auto-inst-column
14058 verilog-auto-inst-dot-name
14059 verilog-auto-inst-interfaced-ports
14060 verilog-auto-inst-param-value
14061 verilog-auto-inst-sort
14062 verilog-auto-inst-template-numbers
14063 verilog-auto-inst-vector
14064 verilog-auto-lineup
14065 verilog-auto-newline
14066 verilog-auto-output-ignore-regexp
14067 verilog-auto-read-includes
14068 verilog-auto-reset-blocking-in-non
14069 verilog-auto-reset-widths
14070 verilog-auto-save-policy
14071 verilog-auto-sense-defines-constant
14072 verilog-auto-sense-include-inputs
14073 verilog-auto-star-expand
14074 verilog-auto-star-save
14075 verilog-auto-template-warn-unused
14076 verilog-auto-tieoff-declaration
14077 verilog-auto-tieoff-ignore-regexp
14078 verilog-auto-unused-ignore-regexp
14079 verilog-auto-wire-type
14080 verilog-before-auto-hook
14081 verilog-before-delete-auto-hook
14082 verilog-before-getopt-flags-hook
14083 verilog-before-save-font-hook
14084 verilog-cache-enabled
14085 verilog-case-fold
14086 verilog-case-indent
14087 verilog-cexp-indent
14088 verilog-compiler
14089 verilog-coverage
14090 verilog-delete-auto-hook
14091 verilog-getopt-flags-hook
14092 verilog-highlight-grouping-keywords
14093 verilog-highlight-includes
14094 verilog-highlight-modules
14095 verilog-highlight-p1800-keywords
14096 verilog-highlight-translate-off
14097 verilog-indent-begin-after-if
14098 verilog-indent-declaration-macros
14099 verilog-indent-level
14100 verilog-indent-level-behavioral
14101 verilog-indent-level-declaration
14102 verilog-indent-level-directive
14103 verilog-indent-level-module
14104 verilog-indent-lists
14105 verilog-library-directories
14106 verilog-library-extensions
14107 verilog-library-files
14108 verilog-library-flags
14109 verilog-linter
14110 verilog-minimum-comment-distance
14111 verilog-mode-hook
14112 verilog-mode-release-emacs
14113 verilog-mode-version
14114 verilog-preprocessor
14115 verilog-simulator
14116 verilog-tab-always-indent
14117 verilog-tab-to-comment
14118 verilog-typedef-regexp
14119 verilog-warn-fatal
14120 )
14121 nil nil
14122 (concat "Hi Mac,
14123
14124 I want to report a bug.
14125
14126 Before I go further, I want to say that Verilog mode has changed my life.
14127 I save so much time, my files are colored nicely, my co workers respect
14128 my coding ability... until now. I'd really appreciate anything you
14129 could do to help me out with this minor deficiency in the product.
14130
14131 I've taken a look at the Verilog-Mode FAQ at
14132 http://www.veripool.org/verilog-mode-faq.html.
14133
14134 And, I've considered filing the bug on the issue tracker at
14135 http://www.veripool.org/verilog-mode-bugs
14136 since I realize that public bugs are easier for you to track,
14137 and for others to search, but would prefer to email.
14138
14139 So, to reproduce the bug, start a fresh Emacs via " invocation-name "
14140 -no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
14141 the code included below.
14142
14143 Given those lines, I expected [[Fill in here]] to happen;
14144 but instead, [[Fill in here]] happens!.
14145
14146 == The code: =="))))
14147
14148 (provide 'verilog-mode)
14149
14150 ;; Local Variables:
14151 ;; checkdoc-permit-comma-termination-flag:t
14152 ;; checkdoc-force-docstrings-flag:nil
14153 ;; End:
14154
14155 ;;; verilog-mode.el ends here