]> code.delx.au - gnu-emacs/blob - lisp/progmodes/verilog-mode.el
Merge from emacs-23
[gnu-emacs] / lisp / progmodes / verilog-mode.el
1 ;; verilog-mode.el --- major mode for editing verilog source in Emacs
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 ;; Author: Michael McNamara (mac@verilog.com),
7 ;; Wilson Snyder (wsnyder@wsnyder.org)
8 ;; Please see our web sites:
9 ;; http://www.verilog.com
10 ;; http://www.veripool.org
11 ;;
12 ;; Keywords: languages
13
14 ;; Yoni Rabkin <yoni@rabkins.net> contacted the maintainer of this
15 ;; file on 19/3/2008, and the maintainer agreed that when a bug is
16 ;; filed in the Emacs bug reporting system against this file, a copy
17 ;; of the bug report be sent to the maintainer's email address.
18
19 ;; This code supports Emacs 21.1 and later
20 ;; And XEmacs 21.1 and later
21 ;; Please do not make changes that break Emacs 21. Thanks!
22 ;;
23 ;;
24
25 ;; This file is part of GNU Emacs.
26
27 ;; GNU Emacs is free software: you can redistribute it and/or modify
28 ;; it under the terms of the GNU General Public License as published by
29 ;; the Free Software Foundation, either version 3 of the License, or
30 ;; (at your option) any later version.
31
32 ;; GNU Emacs is distributed in the hope that it will be useful,
33 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
34 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 ;; GNU General Public License for more details.
36
37 ;; You should have received a copy of the GNU General Public License
38 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
39
40 ;;; Commentary:
41
42 ;; This mode borrows heavily from the Pascal-mode and the cc-mode of Emacs
43
44 ;; USAGE
45 ;; =====
46
47 ;; A major mode for editing Verilog HDL source code. When you have
48 ;; entered Verilog mode, you may get more info by pressing C-h m. You
49 ;; may also get online help describing various functions by: C-h f
50 ;; <Name of function you want described>
51
52 ;; KNOWN BUGS / BUG REPORTS
53 ;; =======================
54
55 ;; Verilog is a rapidly evolving language, and hence this mode is
56 ;; under continuous development. Hence this is beta code, and likely
57 ;; has bugs. Please report any issues to the issue tracker at
58 ;; http://www.veripool.org/verilog-mode
59 ;; Please use verilog-submit-bug-report to submit a report; type C-c
60 ;; C-b to invoke this and as a result I will have a much easier time
61 ;; of reproducing the bug you find, and hence fixing it.
62
63 ;; INSTALLING THE MODE
64 ;; ===================
65
66 ;; An older version of this mode may be already installed as a part of
67 ;; your environment, and one method of updating would be to update
68 ;; your Emacs environment. Sometimes this is difficult for local
69 ;; political/control reasons, and hence you can always install a
70 ;; private copy (or even a shared copy) which overrides the system
71 ;; default.
72
73 ;; You can get step by step help in installing this file by going to
74 ;; <http://www.verilog.com/emacs_install.html>
75
76 ;; The short list of installation instructions are: To set up
77 ;; automatic Verilog mode, put this file in your load path, and put
78 ;; the following in code (please un comment it first!) in your
79 ;; .emacs, or in your site's site-load.el
80
81 ; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
82 ; (add-to-list 'auto-mode-alist '("\\.[ds]?vh?\\'" . verilog-mode))
83
84 ;; Be sure to examine at the help for verilog-auto, and the other
85 ;; verilog-auto-* functions for some major coding time savers.
86 ;;
87 ;; If you want to customize Verilog mode to fit your needs better,
88 ;; you may add the below lines (the values of the variables presented
89 ;; here are the defaults). Note also that if you use an Emacs that
90 ;; supports custom, it's probably better to use the custom menu to
91 ;; edit these. If working as a member of a large team these settings
92 ;; should be common across all users (in a site-start file), or set
93 ;; in Local Variables in every file. Otherwise, different people's
94 ;; AUTO expansion may result different whitespace changes.
95 ;;
96 ; ;; Enable syntax highlighting of **all** languages
97 ; (global-font-lock-mode t)
98 ;
99 ; ;; User customization for Verilog mode
100 ; (setq verilog-indent-level 3
101 ; verilog-indent-level-module 3
102 ; verilog-indent-level-declaration 3
103 ; verilog-indent-level-behavioral 3
104 ; verilog-indent-level-directive 1
105 ; verilog-case-indent 2
106 ; verilog-auto-newline t
107 ; verilog-auto-indent-on-newline t
108 ; verilog-tab-always-indent t
109 ; verilog-auto-endcomments t
110 ; verilog-minimum-comment-distance 40
111 ; verilog-indent-begin-after-if t
112 ; verilog-auto-lineup 'declarations
113 ; verilog-highlight-p1800-keywords nil
114 ; verilog-linter "my_lint_shell_command"
115 ; )
116
117 ;; \f
118
119 ;;; History:
120 ;;
121 ;; See commit history at http://www.veripool.org/verilog-mode.html
122 ;; (This section is required to appease checkdoc.)
123
124 ;;; Code:
125
126 ;; This variable will always hold the version number of the mode
127 (defconst verilog-mode-version "650"
128 "Version of this Verilog mode.")
129 (defconst verilog-mode-release-date "2010-11-05-GNU"
130 "Release date of this Verilog mode.")
131 (defconst verilog-mode-release-emacs t
132 "If non-nil, this version of Verilog mode was released with Emacs itself.")
133
134 (defun verilog-version ()
135 "Inform caller of the version of this file."
136 (interactive)
137 (message "Using verilog-mode version %s" verilog-mode-version))
138
139 ;; Insure we have certain packages, and deal with it if we don't
140 ;; Be sure to note which Emacs flavor and version added each feature.
141 (eval-when-compile
142 ;; Provide stuff if we are XEmacs
143 (when (featurep 'xemacs)
144 (condition-case nil
145 (require 'easymenu)
146 (error nil))
147 (condition-case nil
148 (require 'regexp-opt)
149 (error nil))
150 ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
151 (condition-case nil
152 (load "skeleton")
153 (error nil))
154 (condition-case nil
155 (if (fboundp 'when)
156 nil ;; fab
157 (defmacro when (cond &rest body)
158 (list 'if cond (cons 'progn body))))
159 (error nil))
160 (condition-case nil
161 (if (fboundp 'unless)
162 nil ;; fab
163 (defmacro unless (cond &rest body)
164 (cons 'if (cons cond (cons nil body)))))
165 (error nil))
166 (condition-case nil
167 (if (fboundp 'store-match-data)
168 nil ;; fab
169 (defmacro store-match-data (&rest args) nil))
170 (error nil))
171 (condition-case nil
172 (if (fboundp 'char-before)
173 nil ;; great
174 (defmacro char-before (&rest body)
175 (char-after (1- (point)))))
176 (error nil))
177 (condition-case nil
178 (require 'custom)
179 (error nil))
180 (condition-case nil
181 (if (fboundp 'match-string-no-properties)
182 nil ;; great
183 (defsubst match-string-no-properties (num &optional string)
184 "Return string of text matched by last search, without text properties.
185 NUM specifies which parenthesized expression in the last regexp.
186 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
187 Zero means the entire text matched by the whole regexp or whole string.
188 STRING should be given if the last search was by `string-match' on STRING."
189 (if (match-beginning num)
190 (if string
191 (let ((result
192 (substring string
193 (match-beginning num) (match-end num))))
194 (set-text-properties 0 (length result) nil result)
195 result)
196 (buffer-substring-no-properties (match-beginning num)
197 (match-end num)
198 (current-buffer)))))
199 )
200 (error nil))
201 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
202 nil ;; We've got what we needed
203 ;; We have the old custom-library, hack around it!
204 (defmacro defgroup (&rest args) nil)
205 (defmacro customize (&rest args)
206 (message
207 "Sorry, Customize is not available with this version of Emacs"))
208 (defmacro defcustom (var value doc &rest args)
209 `(defvar ,var ,value ,doc))
210 )
211 (if (fboundp 'defface)
212 nil ; great!
213 (defmacro defface (var values doc &rest args)
214 `(make-face ,var))
215 )
216
217 (if (and (featurep 'custom) (fboundp 'customize-group))
218 nil ;; We've got what we needed
219 ;; We have an intermediate custom-library, hack around it!
220 (defmacro customize-group (var &rest args)
221 `(customize ,var))
222 )
223
224 (unless (boundp 'inhibit-point-motion-hooks)
225 (defvar inhibit-point-motion-hooks nil))
226 (unless (boundp 'deactivate-mark)
227 (defvar deactivate-mark nil))
228 )
229 ;;
230 ;; OK, do this stuff if we are NOT XEmacs:
231 (unless (featurep 'xemacs)
232 (unless (fboundp 'region-active-p)
233 (defmacro region-active-p ()
234 `(and transient-mark-mode mark-active))))
235 )
236
237 ;; Provide a regular expression optimization routine, using regexp-opt
238 ;; if provided by the user's elisp libraries
239 (eval-and-compile
240 ;; The below were disabled when GNU Emacs 22 was released;
241 ;; perhaps some still need to be there to support Emacs 21.
242 (if (featurep 'xemacs)
243 (if (fboundp 'regexp-opt)
244 ;; regexp-opt is defined, does it take 3 or 2 arguments?
245 (if (fboundp 'function-max-args)
246 (let ((args (function-max-args `regexp-opt)))
247 (cond
248 ((eq args 3) ;; It takes 3
249 (condition-case nil ; Hide this defun from emacses
250 ;with just a two input regexp
251 (defun verilog-regexp-opt (a b)
252 "Deal with differing number of required arguments for `regexp-opt'.
253 Call 'regexp-opt' on A and B."
254 (regexp-opt a b 't))
255 (error nil))
256 )
257 ((eq args 2) ;; It takes 2
258 (defun verilog-regexp-opt (a b)
259 "Call 'regexp-opt' on A and B."
260 (regexp-opt a b))
261 )
262 (t nil)))
263 ;; We can't tell; assume it takes 2
264 (defun verilog-regexp-opt (a b)
265 "Call 'regexp-opt' on A and B."
266 (regexp-opt a b))
267 )
268 ;; There is no regexp-opt, provide our own
269 (defun verilog-regexp-opt (strings &optional paren shy)
270 (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
271 (concat open (mapconcat 'regexp-quote strings "\\|") close)))
272 )
273 ;; Emacs.
274 (defalias 'verilog-regexp-opt 'regexp-opt)))
275
276 (eval-and-compile
277 ;; Both xemacs and emacs
278 (condition-case nil
279 (unless (fboundp 'buffer-chars-modified-tick) ;; Emacs 22 added
280 (defmacro buffer-chars-modified-tick () (buffer-modified-tick)))
281 (error nil)))
282
283 (eval-when-compile
284 (defun verilog-regexp-words (a)
285 "Call 'regexp-opt' with word delimiters for the words A."
286 (concat "\\<" (verilog-regexp-opt a t) "\\>")))
287 (defun verilog-regexp-words (a)
288 "Call 'regexp-opt' with word delimiters for the words A."
289 ;; The FAQ references this function, so user LISP sometimes calls it
290 (concat "\\<" (verilog-regexp-opt a t) "\\>"))
291
292 (defun verilog-easy-menu-filter (menu)
293 "Filter `easy-menu-define' MENU to support new features."
294 (cond ((not (featurep 'xemacs))
295 menu) ;; GNU Emacs - passthru
296 ;; Xemacs doesn't support :help. Strip it.
297 ;; Recursively filter the a submenu
298 ((listp menu)
299 (mapcar 'verilog-easy-menu-filter menu))
300 ;; Look for [:help "blah"] and remove
301 ((vectorp menu)
302 (let ((i 0) (out []))
303 (while (< i (length menu))
304 (if (equal `:help (aref menu i))
305 (setq i (+ 2 i))
306 (setq out (vconcat out (vector (aref menu i)))
307 i (1+ i))))
308 out))
309 (t menu))) ;; Default - ok
310 ;;(verilog-easy-menu-filter
311 ;; `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
312 ;; "----" ["MB" nil :help "Help MB"]))
313
314 (defun verilog-customize ()
315 "Customize variables and other settings used by Verilog-Mode."
316 (interactive)
317 (customize-group 'verilog-mode))
318
319 (defun verilog-font-customize ()
320 "Customize fonts used by Verilog-Mode."
321 (interactive)
322 (if (fboundp 'customize-apropos)
323 (customize-apropos "font-lock-*" 'faces)))
324
325 (defun verilog-booleanp (value)
326 "Return t if VALUE is boolean.
327 This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
328 This function may be removed when Emacs 21 is no longer supported."
329 (or (equal value t) (equal value nil)))
330
331 (defun verilog-insert-last-command-event ()
332 "Insert the `last-command-event'."
333 (insert (if (featurep 'xemacs)
334 ;; XEmacs 21.5 doesn't like last-command-event
335 last-command-char
336 ;; And GNU Emacs 22 has obsoleted last-command-char
337 last-command-event)))
338
339 (defalias 'verilog-syntax-ppss
340 (if (fboundp 'syntax-ppss) 'syntax-ppss
341 (lambda (&optional pos) (parse-partial-sexp (point-min) (or pos (point))))))
342
343 (defgroup verilog-mode nil
344 "Facilitates easy editing of Verilog source text."
345 :version "22.2"
346 :group 'languages)
347
348 ; (defgroup verilog-mode-fonts nil
349 ; "Facilitates easy customization fonts used in Verilog source text"
350 ; :link '(customize-apropos "font-lock-*" 'faces)
351 ; :group 'verilog-mode)
352
353 (defgroup verilog-mode-indent nil
354 "Customize indentation and highlighting of Verilog source text."
355 :group 'verilog-mode)
356
357 (defgroup verilog-mode-actions nil
358 "Customize actions on Verilog source text."
359 :group 'verilog-mode)
360
361 (defgroup verilog-mode-auto nil
362 "Customize AUTO actions when expanding Verilog source text."
363 :group 'verilog-mode)
364
365 (defvar verilog-debug nil
366 "If set, enable debug messages for `verilog-mode' internals.")
367
368 (defcustom verilog-linter
369 "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
370 "*Unix program and arguments to call to run a lint checker on Verilog source.
371 Depending on the `verilog-set-compile-command', this may be invoked when
372 you type \\[compile]. When the compile completes, \\[next-error] will take
373 you to the next lint error."
374 :type 'string
375 :group 'verilog-mode-actions)
376 ;; We don't mark it safe, as it's used as a shell command
377
378 (defcustom verilog-coverage
379 "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
380 "*Program and arguments to use to annotate for coverage Verilog source.
381 Depending on the `verilog-set-compile-command', this may be invoked when
382 you type \\[compile]. When the compile completes, \\[next-error] will take
383 you to the next lint error."
384 :type 'string
385 :group 'verilog-mode-actions)
386 ;; We don't mark it safe, as it's used as a shell command
387
388 (defcustom verilog-simulator
389 "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
390 "*Program and arguments to use to interpret Verilog source.
391 Depending on the `verilog-set-compile-command', this may be invoked when
392 you type \\[compile]. When the compile completes, \\[next-error] will take
393 you to the next lint error."
394 :type 'string
395 :group 'verilog-mode-actions)
396 ;; We don't mark it safe, as it's used as a shell command
397
398 (defcustom verilog-compiler
399 "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
400 "*Program and arguments to use to compile Verilog source.
401 Depending on the `verilog-set-compile-command', this may be invoked when
402 you type \\[compile]. When the compile completes, \\[next-error] will take
403 you to the next lint error."
404 :type 'string
405 :group 'verilog-mode-actions)
406 ;; We don't mark it safe, as it's used as a shell command
407
408 (defcustom verilog-preprocessor
409 ;; Very few tools give preprocessed output, so we'll default to Verilog-Perl
410 "vppreproc __FLAGS__ __FILE__"
411 "*Program and arguments to use to preprocess Verilog source.
412 This is invoked with `verilog-preprocess', and depending on the
413 `verilog-set-compile-command', may also be invoked when you type
414 \\[compile]. When the compile completes, \\[next-error] will
415 take you to the next lint error."
416 :type 'string
417 :group 'verilog-mode-actions)
418 ;; We don't mark it safe, as it's used as a shell command
419
420 (defvar verilog-preprocess-history nil
421 "History for `verilog-preprocess'.")
422
423 (defvar verilog-tool 'verilog-linter
424 "Which tool to use for building compiler-command.
425 Either nil, `verilog-linter, `verilog-compiler,
426 `verilog-coverage, `verilog-preprocessor, or `verilog-simulator.
427 Alternatively use the \"Choose Compilation Action\" menu. See
428 `verilog-set-compile-command' for more information.")
429
430 (defcustom verilog-highlight-translate-off nil
431 "*Non-nil means background-highlight code excluded from translation.
432 That is, all code between \"// synopsys translate_off\" and
433 \"// synopsys translate_on\" is highlighted using a different background color
434 \(face `verilog-font-lock-translate-off-face').
435
436 Note: This will slow down on-the-fly fontification (and thus editing).
437
438 Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
439 entry \"Fontify Buffer\"). XEmacs: turn off and on font locking."
440 :type 'boolean
441 :group 'verilog-mode-indent)
442 ;; Note we don't use :safe, as that would break on Emacsen before 22.0.
443 (put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
444
445 (defcustom verilog-auto-lineup 'declarations
446 "*Type of statements to lineup across multiple lines.
447 If 'all' is selected, then all line ups described below are done.
448
449 If 'declaration', then just declarations are lined up with any
450 preceding declarations, taking into account widths and the like,
451 so or example the code:
452 reg [31:0] a;
453 reg b;
454 would become
455 reg [31:0] a;
456 reg b;
457
458 If 'assignment', then assignments are lined up with any preceding
459 assignments, so for example the code
460 a_long_variable <= b + c;
461 d = e + f;
462 would become
463 a_long_variable <= b + c;
464 d = e + f;
465
466 In order to speed up editing, large blocks of statements are lined up
467 only when a \\[verilog-pretty-expr] is typed; and large blocks of declarations
468 are lineup only when \\[verilog-pretty-declarations] is typed."
469
470 :type '(radio (const :tag "Line up Assignments and Declarations" all)
471 (const :tag "Line up Assignment statements" assignments )
472 (const :tag "Line up Declarations" declarations)
473 (function :tag "Other"))
474 :group 'verilog-mode-indent )
475
476 (defcustom verilog-indent-level 3
477 "*Indentation of Verilog statements with respect to containing block."
478 :group 'verilog-mode-indent
479 :type 'integer)
480 (put 'verilog-indent-level 'safe-local-variable 'integerp)
481
482 (defcustom verilog-indent-level-module 3
483 "*Indentation of Module level Verilog statements (eg always, initial).
484 Set to 0 to get initial and always statements lined up on the left side of
485 your screen."
486 :group 'verilog-mode-indent
487 :type 'integer)
488 (put 'verilog-indent-level-module 'safe-local-variable 'integerp)
489
490 (defcustom verilog-indent-level-declaration 3
491 "*Indentation of declarations with respect to containing block.
492 Set to 0 to get them list right under containing block."
493 :group 'verilog-mode-indent
494 :type 'integer)
495 (put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
496
497 (defcustom verilog-indent-declaration-macros nil
498 "*How to treat macro expansions in a declaration.
499 If nil, indent as:
500 input [31:0] a;
501 input `CP;
502 output c;
503 If non nil, treat as:
504 input [31:0] a;
505 input `CP ;
506 output c;"
507 :group 'verilog-mode-indent
508 :type 'boolean)
509 (put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
510
511 (defcustom verilog-indent-lists t
512 "*How to treat indenting items in a list.
513 If t (the default), indent as:
514 always @( posedge a or
515 reset ) begin
516
517 If nil, treat as:
518 always @( posedge a or
519 reset ) begin"
520 :group 'verilog-mode-indent
521 :type 'boolean)
522 (put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
523
524 (defcustom verilog-indent-level-behavioral 3
525 "*Absolute indentation of first begin in a task or function block.
526 Set to 0 to get such code to start at the left side of the screen."
527 :group 'verilog-mode-indent
528 :type 'integer)
529 (put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
530
531 (defcustom verilog-indent-level-directive 1
532 "*Indentation to add to each level of `ifdef declarations.
533 Set to 0 to have all directives start at the left side of the screen."
534 :group 'verilog-mode-indent
535 :type 'integer)
536 (put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
537
538 (defcustom verilog-cexp-indent 2
539 "*Indentation of Verilog statements split across lines."
540 :group 'verilog-mode-indent
541 :type 'integer)
542 (put 'verilog-cexp-indent 'safe-local-variable 'integerp)
543
544 (defcustom verilog-case-indent 2
545 "*Indentation for case statements."
546 :group 'verilog-mode-indent
547 :type 'integer)
548 (put 'verilog-case-indent 'safe-local-variable 'integerp)
549
550 (defcustom verilog-auto-newline t
551 "*True means automatically newline after semicolons."
552 :group 'verilog-mode-indent
553 :type 'boolean)
554 (put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
555
556 (defcustom verilog-auto-indent-on-newline t
557 "*True means automatically indent line after newline."
558 :group 'verilog-mode-indent
559 :type 'boolean)
560 (put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
561
562 (defcustom verilog-tab-always-indent t
563 "*True means TAB should always re-indent the current line.
564 A nil value means TAB will only reindent when at the beginning of the line."
565 :group 'verilog-mode-indent
566 :type 'boolean)
567 (put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
568
569 (defcustom verilog-tab-to-comment nil
570 "*True means TAB moves to the right hand column in preparation for a comment."
571 :group 'verilog-mode-actions
572 :type 'boolean)
573 (put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
574
575 (defcustom verilog-indent-begin-after-if t
576 "*If true, indent begin statements following if, else, while, for and repeat.
577 Otherwise, line them up."
578 :group 'verilog-mode-indent
579 :type 'boolean)
580 (put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
581
582
583 (defcustom verilog-align-ifelse nil
584 "*If true, align `else' under matching `if'.
585 Otherwise else is lined up with first character on line holding matching if."
586 :group 'verilog-mode-indent
587 :type 'boolean)
588 (put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
589
590 (defcustom verilog-minimum-comment-distance 10
591 "*Minimum distance (in lines) between begin and end required before a comment.
592 Setting this variable to zero results in every end acquiring a comment; the
593 default avoids too many redundant comments in tight quarters."
594 :group 'verilog-mode-indent
595 :type 'integer)
596 (put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
597
598 (defcustom verilog-highlight-p1800-keywords nil
599 "*True means highlight words newly reserved by IEEE-1800.
600 These will appear in `verilog-font-lock-p1800-face' in order to gently
601 suggest changing where these words are used as variables to something else.
602 A nil value means highlight these words as appropriate for the SystemVerilog
603 IEEE-1800 standard. Note that changing this will require restarting Emacs
604 to see the effect as font color choices are cached by Emacs."
605 :group 'verilog-mode-indent
606 :type 'boolean)
607 (put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
608
609 (defcustom verilog-highlight-grouping-keywords nil
610 "*True means highlight grouping keywords 'begin' and 'end' more dramatically.
611 If false, these words are in the `font-lock-type-face'; if True then they are in
612 `verilog-font-lock-ams-face'. Some find that special highlighting on these
613 grouping constructs allow the structure of the code to be understood at a glance."
614 :group 'verilog-mode-indent
615 :type 'boolean)
616 (put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
617
618 (defcustom verilog-highlight-modules nil
619 "*True means highlight module statements for `verilog-load-file-at-point'.
620 When true, mousing over module names will allow jumping to the
621 module definition. If false, this is not supported. Setting
622 this is experimental, and may lead to bad performance."
623 :group 'verilog-mode-indent
624 :type 'boolean)
625 (put 'verilog-highlight-modules 'safe-local-variable 'verilog-booleanp)
626
627 (defcustom verilog-highlight-includes t
628 "*True means highlight module statements for `verilog-load-file-at-point'.
629 When true, mousing over include file names will allow jumping to the
630 file referenced. If false, this is not supported."
631 :group 'verilog-mode-indent
632 :type 'boolean)
633 (put 'verilog-highlight-includes 'safe-local-variable 'verilog-booleanp)
634
635 (defcustom verilog-auto-endcomments t
636 "*True means insert a comment /* ... */ after 'end's.
637 The name of the function or case will be set between the braces."
638 :group 'verilog-mode-actions
639 :type 'boolean)
640 (put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
641
642 (defcustom verilog-auto-ignore-concat nil
643 "*True means ignore signals in {...} concatenations for AUTOWIRE etc.
644 This will exclude signals referenced as pin connections in {...}
645 from AUTOWIRE, AUTOOUTPUT and friends. This flag should be set
646 for backward compatibility only and not set in new designs; it
647 may be removed in future versions."
648 :group 'verilog-mode-actions
649 :type 'boolean)
650 (put 'verilog-auto-ignore-concat 'safe-local-variable 'verilog-booleanp)
651
652 (defcustom verilog-auto-read-includes nil
653 "*True means to automatically read includes before AUTOs.
654 This will do a `verilog-read-defines' and `verilog-read-includes' before
655 each AUTO expansion. This makes it easier to embed defines and includes,
656 but can result in very slow reading times if there are many or large
657 include files."
658 :group 'verilog-mode-actions
659 :type 'boolean)
660 (put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
661
662 (defcustom verilog-auto-save-policy nil
663 "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
664 A value of `force' will always do a \\[verilog-auto] automatically if
665 needed on every save. A value of `detect' will do \\[verilog-auto]
666 automatically when it thinks necessary. A value of `ask' will query the
667 user when it thinks updating is needed.
668
669 You should not rely on the 'ask or 'detect policies, they are safeguards
670 only. They do not detect when AUTOINSTs need to be updated because a
671 sub-module's port list has changed."
672 :group 'verilog-mode-actions
673 :type '(choice (const nil) (const ask) (const detect) (const force)))
674
675 (defcustom verilog-auto-star-expand t
676 "*Non-nil indicates to expand a SystemVerilog .* instance ports.
677 They will be expanded in the same way as if there was a AUTOINST in the
678 instantiation. See also `verilog-auto-star' and `verilog-auto-star-save'."
679 :group 'verilog-mode-actions
680 :type 'boolean)
681 (put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
682
683 (defcustom verilog-auto-star-save nil
684 "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
685 A nil value indicates direct connections will be removed before saving.
686 Only meaningful to those created due to `verilog-auto-star-expand' being set.
687
688 Instead of setting this, you may want to use /*AUTOINST*/, which will
689 always be saved."
690 :group 'verilog-mode-actions
691 :type 'boolean)
692 (put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
693
694 (defvar verilog-auto-update-tick nil
695 "Modification tick at which autos were last performed.")
696
697 (defvar verilog-auto-last-file-locals nil
698 "Text from file-local-variables during last evaluation.")
699
700 ;;; Compile support
701 (require 'compile)
702 (defvar verilog-error-regexp-added nil)
703
704 (defvar verilog-error-regexp-emacs-alist
705 '(
706 (verilog-xl-1
707 "\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
708 (verilog-xl-2
709 "([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 3)
710 (verilog-IES
711 ".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)" 2 3)
712 (verilog-surefire-1
713 "[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
714 (verilog-surefire-2
715 "\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\),\\s-+\\(line \\)?\\([0-9]+\\):" 2 4 )
716 (verilog-verbose
717 "\
718 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
719 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
720 (verilog-xsim
721 "\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
722 (verilog-vcs-1
723 "\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
724 (verilog-vcs-2
725 "Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
726 (verilog-vcs-3
727 "\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
728 (verilog-vcs-4
729 "syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
730 (verilog-verilator
731 "%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
732 (verilog-leda
733 "^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 2)
734 )
735 "List of regexps for Verilog compilers.
736 See `compilation-error-regexp-alist' for the formatting. For Emacs 22+.")
737
738 (defvar verilog-error-regexp-xemacs-alist
739 ;; Emacs form is '((v-tool "re" 1 2) ...)
740 ;; XEmacs form is '(verilog ("re" 1 2) ...)
741 ;; So we can just map from Emacs to Xemacs
742 (cons 'verilog (mapcar 'cdr verilog-error-regexp-emacs-alist))
743 "List of regexps for Verilog compilers.
744 See `compilation-error-regexp-alist-alist' for the formatting. For XEmacs.")
745
746 (defvar verilog-error-font-lock-keywords
747 '(
748 ;; verilog-xl-1
749 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
750 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
751 ;; verilog-xl-2
752 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 bold t)
753 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 3 bold t)
754 ;; verilog-IES (nc-verilog)
755 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
756 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 3 bold t)
757 ;; verilog-surefire-1
758 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
759 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
760 ;; verilog-surefire-2
761 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
762 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
763 ;; verilog-verbose
764 ("\
765 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
766 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
767 ("\
768 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
769 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
770 ;; verilog-vcs-1
771 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
772 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
773 ;; verilog-vcs-2
774 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
775 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
776 ;; verilog-vcs-3
777 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
778 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
779 ;; verilog-vcs-4
780 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
781 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
782 ;; verilog-verilator
783 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
784 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
785 ;; verilog-leda
786 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 bold t)
787 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 2 bold t)
788 )
789 "*Keywords to also highlight in Verilog *compilation* buffers.
790 Only used in XEmacs; GNU Emacs uses `verilog-error-regexp-emacs-alist'.")
791
792 (defcustom verilog-library-flags '("")
793 "*List of standard Verilog arguments to use for /*AUTOINST*/.
794 These arguments are used to find files for `verilog-auto', and match
795 the flags accepted by a standard Verilog-XL simulator.
796
797 -f filename Reads more `verilog-library-flags' from the filename.
798 +incdir+dir Adds the directory to `verilog-library-directories'.
799 -Idir Adds the directory to `verilog-library-directories'.
800 -y dir Adds the directory to `verilog-library-directories'.
801 +libext+.v Adds the extensions to `verilog-library-extensions'.
802 -v filename Adds the filename to `verilog-library-files'.
803
804 filename Adds the filename to `verilog-library-files'.
805 This is not recommended, -v is a better choice.
806
807 You might want these defined in each file; put at the *END* of your file
808 something like:
809
810 // Local Variables:
811 // verilog-library-flags:(\"-y dir -y otherdir\")
812 // End:
813
814 Verilog-mode attempts to detect changes to this local variable, but they
815 are only insured to be correct when the file is first visited. Thus if you
816 have problems, use \\[find-alternate-file] RET to have these take effect.
817
818 See also the variables mentioned above."
819 :group 'verilog-mode-auto
820 :type '(repeat string))
821 (put 'verilog-library-flags 'safe-local-variable 'listp)
822
823 (defcustom verilog-library-directories '(".")
824 "*List of directories when looking for files for /*AUTOINST*/.
825 The directory may be relative to the current file, or absolute.
826 Environment variables are also expanded in the directory names.
827 Having at least the current directory is a good idea.
828
829 You might want these defined in each file; put at the *END* of your file
830 something like:
831
832 // Local Variables:
833 // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
834 // End:
835
836 Verilog-mode attempts to detect changes to this local variable, but they
837 are only insured to be correct when the file is first visited. Thus if you
838 have problems, use \\[find-alternate-file] RET to have these take effect.
839
840 See also `verilog-library-flags', `verilog-library-files'
841 and `verilog-library-extensions'."
842 :group 'verilog-mode-auto
843 :type '(repeat file))
844 (put 'verilog-library-directories 'safe-local-variable 'listp)
845
846 (defcustom verilog-library-files '()
847 "*List of files to search for modules.
848 AUTOINST will use this when it needs to resolve a module name.
849 This is a complete path, usually to a technology file with many standard
850 cells defined in it.
851
852 You might want these defined in each file; put at the *END* of your file
853 something like:
854
855 // Local Variables:
856 // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
857 // End:
858
859 Verilog-mode attempts to detect changes to this local variable, but they
860 are only insured to be correct when the file is first visited. Thus if you
861 have problems, use \\[find-alternate-file] RET to have these take effect.
862
863 See also `verilog-library-flags', `verilog-library-directories'."
864 :group 'verilog-mode-auto
865 :type '(repeat directory))
866 (put 'verilog-library-files 'safe-local-variable 'listp)
867
868 (defcustom verilog-library-extensions '(".v" ".sv")
869 "*List of extensions to use when looking for files for /*AUTOINST*/.
870 See also `verilog-library-flags', `verilog-library-directories'."
871 :type '(repeat string)
872 :group 'verilog-mode-auto)
873 (put 'verilog-library-extensions 'safe-local-variable 'listp)
874
875 (defcustom verilog-active-low-regexp nil
876 "*If set, treat signals matching this regexp as active low.
877 This is used for AUTORESET and AUTOTIEOFF. For proper behavior,
878 you will probably also need `verilog-auto-reset-widths' set."
879 :group 'verilog-mode-auto
880 :type 'string)
881 (put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
882
883 (defcustom verilog-auto-sense-include-inputs nil
884 "*If true, AUTOSENSE should include all inputs.
885 If nil, only inputs that are NOT output signals in the same block are
886 included."
887 :group 'verilog-mode-auto
888 :type 'boolean)
889 (put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
890
891 (defcustom verilog-auto-sense-defines-constant nil
892 "*If true, AUTOSENSE should assume all defines represent constants.
893 When true, the defines will not be included in sensitivity lists. To
894 maintain compatibility with other sites, this should be set at the bottom
895 of each Verilog file that requires it, rather than being set globally."
896 :group 'verilog-mode-auto
897 :type 'boolean)
898 (put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
899
900 (defcustom verilog-auto-reset-widths t
901 "*If true, AUTORESET should determine the width of signals.
902 This is then used to set the width of the zero (32'h0 for example). This
903 is required by some lint tools that aren't smart enough to ignore widths of
904 the constant zero. This may result in ugly code when parameters determine
905 the MSB or LSB of a signal inside an AUTORESET."
906 :type 'boolean
907 :group 'verilog-mode-auto)
908 (put 'verilog-auto-reset-widths 'safe-local-variable 'verilog-booleanp)
909
910 (defcustom verilog-assignment-delay ""
911 "*Text used for delays in delayed assignments. Add a trailing space if set."
912 :group 'verilog-mode-auto
913 :type 'string)
914 (put 'verilog-assignment-delay 'safe-local-variable 'stringp)
915
916 (defcustom verilog-auto-arg-sort nil
917 "*If set, AUTOARG signal names will be sorted, not in delaration order.
918 Declaration order is advantageous with order based instantiations
919 and is the default for backward compatibility. Sorted order
920 reduces changes when declarations are moved around in a file, and
921 it's bad practice to rely on order based instantiations anyhow."
922 :group 'verilog-mode-auto
923 :type 'boolean)
924 (put 'verilog-auto-arg-sort 'safe-local-variable 'verilog-booleanp)
925
926 (defcustom verilog-auto-inst-dot-name nil
927 "*If true, when creating ports with AUTOINST, use .name syntax.
928 This will use \".port\" instead of \".port(port)\" when possible.
929 This is only legal in SystemVerilog files, and will confuse older
930 simulators. Setting `verilog-auto-inst-vector' to nil may also
931 be desirable to increase how often .name will be used."
932 :group 'verilog-mode-auto
933 :type 'boolean)
934 (put 'verilog-auto-inst-dot-name 'safe-local-variable 'verilog-booleanp)
935
936 (defcustom verilog-auto-inst-param-value nil
937 "*If set, AUTOINST will replace parameters with the parameter value.
938 If nil, leave parameters as symbolic names.
939
940 Parameters must be in Verilog 2001 format #(...), and if a parameter is not
941 listed as such there (as when the default value is acceptable), it will not
942 be replaced, and will remain symbolic.
943
944 For example, imagine a submodule uses parameters to declare the size of its
945 inputs. This is then used by a upper module:
946
947 module InstModule (o,i);
948 parameter WIDTH;
949 input [WIDTH-1:0] i;
950 endmodule
951
952 module ExampInst;
953 InstModule
954 #(PARAM(10))
955 instName
956 (/*AUTOINST*/
957 .i (i[PARAM-1:0]));
958
959 Note even though PARAM=10, the AUTOINST has left the parameter as a
960 symbolic name. If `verilog-auto-inst-param-value' is set, this will
961 instead expand to:
962
963 module ExampInst;
964 InstModule
965 #(PARAM(10))
966 instName
967 (/*AUTOINST*/
968 .i (i[9:0]));"
969 :group 'verilog-mode-auto
970 :type 'boolean)
971 (put 'verilog-auto-inst-param-value 'safe-local-variable 'verilog-booleanp)
972
973 (defcustom verilog-auto-inst-vector t
974 "*If true, when creating default ports with AUTOINST, use bus subscripts.
975 If nil, skip the subscript when it matches the entire bus as declared in
976 the module (AUTOWIRE signals always are subscripted, you must manually
977 declare the wire to have the subscripts removed.) Setting this to nil may
978 speed up some simulators, but is less general and harder to read, so avoid."
979 :group 'verilog-mode-auto
980 :type 'boolean)
981 (put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
982
983 (defcustom verilog-auto-inst-template-numbers nil
984 "*If true, when creating templated ports with AUTOINST, add a comment.
985 The comment will add the line number of the template that was used for that
986 port declaration. Setting this aids in debugging, but nil is suggested for
987 regular use to prevent large numbers of merge conflicts."
988 :group 'verilog-mode-auto
989 :type 'boolean)
990 (put 'verilog-auto-inst-template-numbers 'safe-local-variable 'verilog-booleanp)
991
992 (defcustom verilog-auto-inst-column 40
993 "*Indent-to column number for net name part of AUTOINST created pin."
994 :group 'verilog-mode-indent
995 :type 'integer)
996 (put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
997
998 (defcustom verilog-auto-input-ignore-regexp nil
999 "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
1000 See the \\[verilog-faq] for examples on using this."
1001 :group 'verilog-mode-auto
1002 :type 'string)
1003 (put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
1004
1005 (defcustom verilog-auto-inout-ignore-regexp nil
1006 "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
1007 See the \\[verilog-faq] for examples on using this."
1008 :group 'verilog-mode-auto
1009 :type 'string)
1010 (put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
1011
1012 (defcustom verilog-auto-output-ignore-regexp nil
1013 "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
1014 See the \\[verilog-faq] for examples on using this."
1015 :group 'verilog-mode-auto
1016 :type 'string)
1017 (put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
1018
1019 (defcustom verilog-auto-tieoff-ignore-regexp nil
1020 "*If set, when creating AUTOTIEOFF list, ignore signals matching this regexp.
1021 See the \\[verilog-faq] for examples on using this."
1022 :group 'verilog-mode-auto
1023 :type 'string)
1024 (put 'verilog-auto-tieoff-ignore-regexp 'safe-local-variable 'stringp)
1025
1026 (defcustom verilog-auto-unused-ignore-regexp nil
1027 "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
1028 See the \\[verilog-faq] for examples on using this."
1029 :group 'verilog-mode-auto
1030 :type 'string)
1031 (put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
1032
1033 (defcustom verilog-typedef-regexp nil
1034 "*If non-nil, regular expression that matches Verilog-2001 typedef names.
1035 For example, \"_t$\" matches typedefs named with _t, as in the C language."
1036 :group 'verilog-mode-auto
1037 :type 'string)
1038 (put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
1039
1040 (defcustom verilog-mode-hook 'verilog-set-compile-command
1041 "*Hook run after Verilog mode is loaded."
1042 :type 'hook
1043 :group 'verilog-mode)
1044
1045 (defcustom verilog-auto-hook nil
1046 "*Hook run after `verilog-mode' updates AUTOs."
1047 :group 'verilog-mode-auto
1048 :type 'hook)
1049
1050 (defcustom verilog-before-auto-hook nil
1051 "*Hook run before `verilog-mode' updates AUTOs."
1052 :group 'verilog-mode-auto
1053 :type 'hook)
1054
1055 (defcustom verilog-delete-auto-hook nil
1056 "*Hook run after `verilog-mode' deletes AUTOs."
1057 :group 'verilog-mode-auto
1058 :type 'hook)
1059
1060 (defcustom verilog-before-delete-auto-hook nil
1061 "*Hook run before `verilog-mode' deletes AUTOs."
1062 :group 'verilog-mode-auto
1063 :type 'hook)
1064
1065 (defcustom verilog-getopt-flags-hook nil
1066 "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
1067 :group 'verilog-mode-auto
1068 :type 'hook)
1069
1070 (defcustom verilog-before-getopt-flags-hook nil
1071 "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
1072 :group 'verilog-mode-auto
1073 :type 'hook)
1074
1075 (defvar verilog-imenu-generic-expression
1076 '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
1077 ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
1078 "Imenu expression for Verilog mode. See `imenu-generic-expression'.")
1079
1080 ;;
1081 ;; provide a verilog-header function.
1082 ;; Customization variables:
1083 ;;
1084 (defvar verilog-date-scientific-format nil
1085 "*If non-nil, dates are written in scientific format (e.g. 1997/09/17).
1086 If nil, in European format (e.g. 17.09.1997). The brain-dead American
1087 format (e.g. 09/17/1997) is not supported.")
1088
1089 (defvar verilog-company nil
1090 "*Default name of Company for Verilog header.
1091 If set will become buffer local.")
1092 (make-variable-buffer-local 'verilog-company)
1093
1094 (defvar verilog-project nil
1095 "*Default name of Project for Verilog header.
1096 If set will become buffer local.")
1097 (make-variable-buffer-local 'verilog-project)
1098
1099 (defvar verilog-mode-map
1100 (let ((map (make-sparse-keymap)))
1101 (define-key map ";" 'electric-verilog-semi)
1102 (define-key map [(control 59)] 'electric-verilog-semi-with-comment)
1103 (define-key map ":" 'electric-verilog-colon)
1104 ;;(define-key map "=" 'electric-verilog-equal)
1105 (define-key map "\`" 'electric-verilog-tick)
1106 (define-key map "\t" 'electric-verilog-tab)
1107 (define-key map "\r" 'electric-verilog-terminate-line)
1108 ;; backspace/delete key bindings
1109 (define-key map [backspace] 'backward-delete-char-untabify)
1110 (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
1111 (define-key map [delete] 'delete-char)
1112 (define-key map [(meta delete)] 'kill-word))
1113 (define-key map "\M-\C-b" 'electric-verilog-backward-sexp)
1114 (define-key map "\M-\C-f" 'electric-verilog-forward-sexp)
1115 (define-key map "\M-\r" `electric-verilog-terminate-and-indent)
1116 (define-key map "\M-\t" 'verilog-complete-word)
1117 (define-key map "\M-?" 'verilog-show-completions)
1118 (define-key map "\C-c\`" 'verilog-lint-off)
1119 (define-key map "\C-c\*" 'verilog-delete-auto-star-implicit)
1120 (define-key map "\C-c\C-r" 'verilog-label-be)
1121 (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
1122 (define-key map "\C-c=" 'verilog-pretty-expr)
1123 (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
1124 (define-key map "\M-*" 'verilog-star-comment)
1125 (define-key map "\C-c\C-c" 'verilog-comment-region)
1126 (define-key map "\C-c\C-u" 'verilog-uncomment-region)
1127 (when (featurep 'xemacs)
1128 (define-key map [(meta control h)] 'verilog-mark-defun)
1129 (define-key map "\M-\C-a" 'verilog-beg-of-defun)
1130 (define-key map "\M-\C-e" 'verilog-end-of-defun))
1131 (define-key map "\C-c\C-d" 'verilog-goto-defun)
1132 (define-key map "\C-c\C-k" 'verilog-delete-auto)
1133 (define-key map "\C-c\C-a" 'verilog-auto)
1134 (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
1135 (define-key map "\C-c\C-p" 'verilog-preprocess)
1136 (define-key map "\C-c\C-z" 'verilog-inject-auto)
1137 (define-key map "\C-c\C-e" 'verilog-expand-vector)
1138 (define-key map "\C-c\C-h" 'verilog-header)
1139 map)
1140 "Keymap used in Verilog mode.")
1141
1142 ;; menus
1143 (easy-menu-define
1144 verilog-menu verilog-mode-map "Menu for Verilog mode"
1145 (verilog-easy-menu-filter
1146 '("Verilog"
1147 ("Choose Compilation Action"
1148 ["None"
1149 (progn
1150 (setq verilog-tool nil)
1151 (verilog-set-compile-command))
1152 :style radio
1153 :selected (equal verilog-tool nil)
1154 :help "When invoking compilation, use compile-command"]
1155 ["Lint"
1156 (progn
1157 (setq verilog-tool 'verilog-linter)
1158 (verilog-set-compile-command))
1159 :style radio
1160 :selected (equal verilog-tool `verilog-linter)
1161 :help "When invoking compilation, use lint checker"]
1162 ["Coverage"
1163 (progn
1164 (setq verilog-tool 'verilog-coverage)
1165 (verilog-set-compile-command))
1166 :style radio
1167 :selected (equal verilog-tool `verilog-coverage)
1168 :help "When invoking compilation, annotate for coverage"]
1169 ["Simulator"
1170 (progn
1171 (setq verilog-tool 'verilog-simulator)
1172 (verilog-set-compile-command))
1173 :style radio
1174 :selected (equal verilog-tool `verilog-simulator)
1175 :help "When invoking compilation, interpret Verilog source"]
1176 ["Compiler"
1177 (progn
1178 (setq verilog-tool 'verilog-compiler)
1179 (verilog-set-compile-command))
1180 :style radio
1181 :selected (equal verilog-tool `verilog-compiler)
1182 :help "When invoking compilation, compile Verilog source"]
1183 ["Preprocessor"
1184 (progn
1185 (setq verilog-tool 'verilog-preprocessor)
1186 (verilog-set-compile-command))
1187 :style radio
1188 :selected (equal verilog-tool `verilog-preprocessor)
1189 :help "When invoking compilation, preprocess Verilog source, see also `verilog-preprocess'"]
1190 )
1191 ("Move"
1192 ["Beginning of function" verilog-beg-of-defun
1193 :keys "C-M-a"
1194 :help "Move backward to the beginning of the current function or procedure"]
1195 ["End of function" verilog-end-of-defun
1196 :keys "C-M-e"
1197 :help "Move forward to the end of the current function or procedure"]
1198 ["Mark function" verilog-mark-defun
1199 :keys "C-M-h"
1200 :help "Mark the current Verilog function or procedure"]
1201 ["Goto function/module" verilog-goto-defun
1202 :help "Move to specified Verilog module/task/function"]
1203 ["Move to beginning of block" electric-verilog-backward-sexp
1204 :help "Move backward over one balanced expression"]
1205 ["Move to end of block" electric-verilog-forward-sexp
1206 :help "Move forward over one balanced expression"]
1207 )
1208 ("Comments"
1209 ["Comment Region" verilog-comment-region
1210 :help "Put marked area into a comment"]
1211 ["UnComment Region" verilog-uncomment-region
1212 :help "Uncomment an area commented with Comment Region"]
1213 ["Multi-line comment insert" verilog-star-comment
1214 :help "Insert Verilog /* */ comment at point"]
1215 ["Lint error to comment" verilog-lint-off
1216 :help "Convert a Verilog linter warning line into a disable statement"]
1217 )
1218 "----"
1219 ["Compile" compile
1220 :help "Perform compilation-action (above) on the current buffer"]
1221 ["AUTO, Save, Compile" verilog-auto-save-compile
1222 :help "Recompute AUTOs, save buffer, and compile"]
1223 ["Next Compile Error" next-error
1224 :help "Visit next compilation error message and corresponding source code"]
1225 ["Ignore Lint Warning at point" verilog-lint-off
1226 :help "Convert a Verilog linter warning line into a disable statement"]
1227 "----"
1228 ["Line up declarations around point" verilog-pretty-declarations
1229 :help "Line up declarations around point"]
1230 ["Line up equations around point" verilog-pretty-expr
1231 :help "Line up expressions around point"]
1232 ["Redo/insert comments on every end" verilog-label-be
1233 :help "Label matching begin ... end statements"]
1234 ["Expand [x:y] vector line" verilog-expand-vector
1235 :help "Take a signal vector on the current line and expand it to multiple lines"]
1236 ["Insert begin-end block" verilog-insert-block
1237 :help "Insert begin ... end"]
1238 ["Complete word" verilog-complete-word
1239 :help "Complete word at point"]
1240 "----"
1241 ["Recompute AUTOs" verilog-auto
1242 :help "Expand AUTO meta-comment statements"]
1243 ["Kill AUTOs" verilog-delete-auto
1244 :help "Remove AUTO expansions"]
1245 ["Inject AUTOs" verilog-inject-auto
1246 :help "Inject AUTOs into legacy non-AUTO buffer"]
1247 ("AUTO Help..."
1248 ["AUTO General" (describe-function 'verilog-auto)
1249 :help "Help introduction on AUTOs"]
1250 ["AUTO Library Flags" (describe-variable 'verilog-library-flags)
1251 :help "Help on verilog-library-flags"]
1252 ["AUTO Library Path" (describe-variable 'verilog-library-directories)
1253 :help "Help on verilog-library-directories"]
1254 ["AUTO Library Files" (describe-variable 'verilog-library-files)
1255 :help "Help on verilog-library-files"]
1256 ["AUTO Library Extensions" (describe-variable 'verilog-library-extensions)
1257 :help "Help on verilog-library-extensions"]
1258 ["AUTO `define Reading" (describe-function 'verilog-read-defines)
1259 :help "Help on reading `defines"]
1260 ["AUTO `include Reading" (describe-function 'verilog-read-includes)
1261 :help "Help on parsing `includes"]
1262 ["AUTOARG" (describe-function 'verilog-auto-arg)
1263 :help "Help on AUTOARG - declaring module port list"]
1264 ["AUTOASCIIENUM" (describe-function 'verilog-auto-ascii-enum)
1265 :help "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
1266 ["AUTOINOUTCOMP" (describe-function 'verilog-auto-inout-comp)
1267 :help "Help on AUTOINOUTCOMP - copying complemented i/o from another file"]
1268 ["AUTOINOUTMODULE" (describe-function 'verilog-auto-inout-module)
1269 :help "Help on AUTOINOUTMODULE - copying i/o from another file"]
1270 ["AUTOINSERTLISP" (describe-function 'verilog-auto-insert-lisp)
1271 :help "Help on AUTOINSERTLISP - insert text from a lisp function"]
1272 ["AUTOINOUT" (describe-function 'verilog-auto-inout)
1273 :help "Help on AUTOINOUT - adding inouts from cells"]
1274 ["AUTOINPUT" (describe-function 'verilog-auto-input)
1275 :help "Help on AUTOINPUT - adding inputs from cells"]
1276 ["AUTOINST" (describe-function 'verilog-auto-inst)
1277 :help "Help on AUTOINST - adding pins for cells"]
1278 ["AUTOINST (.*)" (describe-function 'verilog-auto-star)
1279 :help "Help on expanding Verilog-2001 .* pins"]
1280 ["AUTOINSTPARAM" (describe-function 'verilog-auto-inst-param)
1281 :help "Help on AUTOINSTPARAM - adding parameter pins to cells"]
1282 ["AUTOOUTPUT" (describe-function 'verilog-auto-output)
1283 :help "Help on AUTOOUTPUT - adding outputs from cells"]
1284 ["AUTOOUTPUTEVERY" (describe-function 'verilog-auto-output-every)
1285 :help "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
1286 ["AUTOREG" (describe-function 'verilog-auto-reg)
1287 :help "Help on AUTOREG - declaring registers for non-wires"]
1288 ["AUTOREGINPUT" (describe-function 'verilog-auto-reg-input)
1289 :help "Help on AUTOREGINPUT - declaring inputs for non-wires"]
1290 ["AUTORESET" (describe-function 'verilog-auto-reset)
1291 :help "Help on AUTORESET - resetting always blocks"]
1292 ["AUTOSENSE" (describe-function 'verilog-auto-sense)
1293 :help "Help on AUTOSENSE - sensitivity lists for always blocks"]
1294 ["AUTOTIEOFF" (describe-function 'verilog-auto-tieoff)
1295 :help "Help on AUTOTIEOFF - tieing off unused outputs"]
1296 ["AUTOUNUSED" (describe-function 'verilog-auto-unused)
1297 :help "Help on AUTOUNUSED - terminating unused inputs"]
1298 ["AUTOWIRE" (describe-function 'verilog-auto-wire)
1299 :help "Help on AUTOWIRE - declaring wires for cells"]
1300 )
1301 "----"
1302 ["Submit bug report" verilog-submit-bug-report
1303 :help "Submit via mail a bug report on verilog-mode.el"]
1304 ["Version and FAQ" verilog-faq
1305 :help "Show the current version, and where to get the FAQ etc"]
1306 ["Customize Verilog Mode..." verilog-customize
1307 :help "Customize variables and other settings used by Verilog-Mode"]
1308 ["Customize Verilog Fonts & Colors" verilog-font-customize
1309 :help "Customize fonts used by Verilog-Mode."])))
1310
1311 (easy-menu-define
1312 verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
1313 (verilog-easy-menu-filter
1314 '("Statements"
1315 ["Header" verilog-sk-header
1316 :help "Insert a header block at the top of file"]
1317 ["Comment" verilog-sk-comment
1318 :help "Insert a comment block"]
1319 "----"
1320 ["Module" verilog-sk-module
1321 :help "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
1322 ["Primitive" verilog-sk-primitive
1323 :help "Insert a primitive .. (.. );.. endprimitive block"]
1324 "----"
1325 ["Input" verilog-sk-input
1326 :help "Insert an input declaration"]
1327 ["Output" verilog-sk-output
1328 :help "Insert an output declaration"]
1329 ["Inout" verilog-sk-inout
1330 :help "Insert an inout declaration"]
1331 ["Wire" verilog-sk-wire
1332 :help "Insert a wire declaration"]
1333 ["Reg" verilog-sk-reg
1334 :help "Insert a register declaration"]
1335 ["Define thing under point as a register" verilog-sk-define-signal
1336 :help "Define signal under point as a register at the top of the module"]
1337 "----"
1338 ["Initial" verilog-sk-initial
1339 :help "Insert an initial begin .. end block"]
1340 ["Always" verilog-sk-always
1341 :help "Insert an always @(AS) begin .. end block"]
1342 ["Function" verilog-sk-function
1343 :help "Insert a function .. begin .. end endfunction block"]
1344 ["Task" verilog-sk-task
1345 :help "Insert a task .. begin .. end endtask block"]
1346 ["Specify" verilog-sk-specify
1347 :help "Insert a specify .. endspecify block"]
1348 ["Generate" verilog-sk-generate
1349 :help "Insert a generate .. endgenerate block"]
1350 "----"
1351 ["Begin" verilog-sk-begin
1352 :help "Insert a begin .. end block"]
1353 ["If" verilog-sk-if
1354 :help "Insert an if (..) begin .. end block"]
1355 ["(if) else" verilog-sk-else-if
1356 :help "Insert an else if (..) begin .. end block"]
1357 ["For" verilog-sk-for
1358 :help "Insert a for (...) begin .. end block"]
1359 ["While" verilog-sk-while
1360 :help "Insert a while (...) begin .. end block"]
1361 ["Fork" verilog-sk-fork
1362 :help "Insert a fork begin .. end .. join block"]
1363 ["Repeat" verilog-sk-repeat
1364 :help "Insert a repeat (..) begin .. end block"]
1365 ["Case" verilog-sk-case
1366 :help "Insert a case block, prompting for details"]
1367 ["Casex" verilog-sk-casex
1368 :help "Insert a casex (...) item: begin.. end endcase block"]
1369 ["Casez" verilog-sk-casez
1370 :help "Insert a casez (...) item: begin.. end endcase block"])))
1371
1372 (defvar verilog-mode-abbrev-table nil
1373 "Abbrev table in use in Verilog-mode buffers.")
1374
1375 (define-abbrev-table 'verilog-mode-abbrev-table ())
1376
1377 ;;
1378 ;; Macros
1379 ;;
1380
1381 (defsubst verilog-within-string ()
1382 (nth 3 (parse-partial-sexp (point-at-bol) (point))))
1383
1384 (defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1385 "Replace occurrences of FROM-STRING with TO-STRING.
1386 FIXEDCASE and LITERAL as in `replace-match`. STRING is what to replace.
1387 The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1388 will break, as the o's continuously replace. xa -> x works ok though."
1389 ;; Hopefully soon to a emacs built-in
1390 (let ((start 0))
1391 (while (string-match from-string string start)
1392 (setq string (replace-match to-string fixedcase literal string)
1393 start (min (length string) (+ (match-beginning 0) (length to-string)))))
1394 string))
1395
1396 (defsubst verilog-string-remove-spaces (string)
1397 "Remove spaces surrounding STRING."
1398 (save-match-data
1399 (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1400 (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1401 string))
1402
1403 (defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1404 ; checkdoc-params: (REGEXP BOUND NOERROR)
1405 "Like `re-search-forward', but skips over match in comments or strings."
1406 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1407 (while (and
1408 (re-search-forward REGEXP BOUND NOERROR)
1409 (setq mdata (match-data))
1410 (and (verilog-skip-forward-comment-or-string)
1411 (progn
1412 (setq mdata '(nil nil))
1413 (if BOUND
1414 (< (point) BOUND)
1415 t)))))
1416 (store-match-data mdata)
1417 (match-end 0)))
1418
1419 (defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1420 ; checkdoc-params: (REGEXP BOUND NOERROR)
1421 "Like `re-search-backward', but skips over match in comments or strings."
1422 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1423 (while (and
1424 (re-search-backward REGEXP BOUND NOERROR)
1425 (setq mdata (match-data))
1426 (and (verilog-skip-backward-comment-or-string)
1427 (progn
1428 (setq mdata '(nil nil))
1429 (if BOUND
1430 (> (point) BOUND)
1431 t)))))
1432 (store-match-data mdata)
1433 (match-end 0)))
1434
1435 (defsubst verilog-re-search-forward-quick (regexp bound noerror)
1436 "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1437 but trashes match data and is faster for REGEXP that doesn't match often.
1438 This may at some point use text properties to ignore comments,
1439 so there may be a large up front penalty for the first search."
1440 (let (pt)
1441 (while (and (not pt)
1442 (re-search-forward regexp bound noerror))
1443 (if (not (verilog-inside-comment-p))
1444 (setq pt (match-end 0))))
1445 pt))
1446
1447 (defsubst verilog-re-search-backward-quick (regexp bound noerror)
1448 ; checkdoc-params: (REGEXP BOUND NOERROR)
1449 "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1450 but trashes match data and is faster for REGEXP that doesn't match often.
1451 This may at some point use text properties to ignore comments,
1452 so there may be a large up front penalty for the first search."
1453 (let (pt)
1454 (while (and (not pt)
1455 (re-search-backward regexp bound noerror))
1456 (if (not (verilog-inside-comment-p))
1457 (setq pt (match-end 0))))
1458 pt))
1459
1460 (defsubst verilog-re-search-forward-substr (substr regexp bound noerror)
1461 "Like `re-search-forward', but first search for SUBSTR constant.
1462 Then searched for the normal REGEXP (which contains SUBSTR), with given
1463 BOUND and NOERROR. The REGEXP must fit within a single line.
1464 This speeds up complicated regexp matches."
1465 ;; Problem with overlap: search-forward BAR then FOOBARBAZ won't match.
1466 ;; thus require matches to be on one line, and use beginning-of-line.
1467 (let (done)
1468 (while (and (not done)
1469 (search-forward substr bound noerror))
1470 (save-excursion
1471 (beginning-of-line)
1472 (setq done (re-search-forward regexp (point-at-eol) noerror)))
1473 (unless (and (<= (match-beginning 0) (point))
1474 (>= (match-end 0) (point)))
1475 (setq done nil)))
1476 (when done (goto-char done))
1477 done))
1478 ;;(verilog-re-search-forward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1479
1480 (defsubst verilog-re-search-backward-substr (substr regexp bound noerror)
1481 "Like `re-search-backward', but first search for SUBSTR constant.
1482 Then searched for the normal REGEXP (which contains SUBSTR), with given
1483 BOUND and NOERROR. The REGEXP must fit within a single line.
1484 This speeds up complicated regexp matches."
1485 ;; Problem with overlap: search-backward BAR then FOOBARBAZ won't match.
1486 ;; thus require matches to be on one line, and use beginning-of-line.
1487 (let (done)
1488 (while (and (not done)
1489 (search-backward substr bound noerror))
1490 (save-excursion
1491 (end-of-line)
1492 (setq done (re-search-backward regexp (point-at-bol) noerror)))
1493 (unless (and (<= (match-beginning 0) (point))
1494 (>= (match-end 0) (point)))
1495 (setq done nil)))
1496 (when done (goto-char done))
1497 done))
1498 ;;(verilog-re-search-backward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1499
1500 (defvar compile-command)
1501
1502 ;; compilation program
1503 (defun verilog-set-compile-command ()
1504 "Function to compute shell command to compile Verilog.
1505
1506 This reads `verilog-tool' and sets `compile-command'. This specifies the
1507 program that executes when you type \\[compile] or
1508 \\[verilog-auto-save-compile].
1509
1510 By default `verilog-tool' uses a Makefile if one exists in the
1511 current directory. If not, it is set to the `verilog-linter',
1512 `verilog-compiler', `verilog-coverage', `verilog-preprocessor',
1513 or `verilog-simulator' variables, as selected with the Verilog ->
1514 \"Choose Compilation Action\" menu.
1515
1516 You should set `verilog-tool' or the other variables to the path and
1517 arguments for your Verilog simulator. For example:
1518 \"vcs -p123 -O\"
1519 or a string like:
1520 \"(cd /tmp; surecov %s)\".
1521
1522 In the former case, the path to the current buffer is concat'ed to the
1523 value of `verilog-tool'; in the later, the path to the current buffer is
1524 substituted for the %s.
1525
1526 Where __FLAGS__ appears in the string `verilog-current-flags'
1527 will be substituted.
1528
1529 Where __FILE__ appears in the string, the variable
1530 `buffer-file-name' of the current buffer, without the directory
1531 portion, will be substituted."
1532 (interactive)
1533 (cond
1534 ((or (file-exists-p "makefile") ;If there is a makefile, use it
1535 (file-exists-p "Makefile"))
1536 (make-local-variable 'compile-command)
1537 (setq compile-command "make "))
1538 (t
1539 (make-local-variable 'compile-command)
1540 (setq compile-command
1541 (if verilog-tool
1542 (if (string-match "%s" (eval verilog-tool))
1543 (format (eval verilog-tool) (or buffer-file-name ""))
1544 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1545 ""))))
1546 (verilog-modify-compile-command))
1547
1548 (defun verilog-expand-command (command)
1549 "Replace meta-information in COMMAND and return it.
1550 Where __FLAGS__ appears in the string `verilog-current-flags'
1551 will be substituted. Where __FILE__ appears in the string, the
1552 current buffer's file-name, without the directory portion, will
1553 be substituted."
1554 (setq command (verilog-string-replace-matches
1555 ;; Note \\b only works if under verilog syntax table
1556 "\\b__FLAGS__\\b" (verilog-current-flags)
1557 t t command))
1558 (setq command (verilog-string-replace-matches
1559 "\\b__FILE__\\b" (file-name-nondirectory
1560 (or (buffer-file-name) ""))
1561 t t command))
1562 command)
1563
1564 (defun verilog-modify-compile-command ()
1565 "Update `compile-command' using `verilog-expand-command'."
1566 (when (and
1567 (stringp compile-command)
1568 (string-match "\\b\\(__FLAGS__\\|__FILE__\\)\\b" compile-command))
1569 (make-local-variable 'compile-command)
1570 (setq compile-command (verilog-expand-command compile-command))))
1571
1572 (if (featurep 'xemacs)
1573 ;; Following code only gets called from compilation-mode-hook on XEmacs to add error handling.
1574 (defun verilog-error-regexp-add-xemacs ()
1575 "Teach XEmacs about verilog errors.
1576 Called by `compilation-mode-hook'. This allows \\[next-error] to
1577 find the errors."
1578 (interactive)
1579 (if (boundp 'compilation-error-regexp-systems-alist)
1580 (if (and
1581 (not (equal compilation-error-regexp-systems-list 'all))
1582 (not (member compilation-error-regexp-systems-list 'verilog)))
1583 (push 'verilog compilation-error-regexp-systems-list)))
1584 (if (boundp 'compilation-error-regexp-alist-alist)
1585 (if (not (assoc 'verilog compilation-error-regexp-alist-alist))
1586 (setcdr compilation-error-regexp-alist-alist
1587 (cons verilog-error-regexp-xemacs-alist
1588 (cdr compilation-error-regexp-alist-alist)))))
1589 (if (boundp 'compilation-font-lock-keywords)
1590 (progn
1591 (make-local-variable 'compilation-font-lock-keywords)
1592 (setq compilation-font-lock-keywords verilog-error-font-lock-keywords)
1593 (font-lock-set-defaults)))
1594 ;; Need to re-run compilation-error-regexp builder
1595 (if (fboundp 'compilation-build-compilation-error-regexp-alist)
1596 (compilation-build-compilation-error-regexp-alist))
1597 ))
1598
1599 ;; Following code only gets called from compilation-mode-hook on Emacs to add error handling.
1600 (defun verilog-error-regexp-add-emacs ()
1601 "Tell Emacs compile that we are Verilog.
1602 Called by `compilation-mode-hook'. This allows \\[next-error] to
1603 find the errors."
1604 (interactive)
1605 (if (boundp 'compilation-error-regexp-alist-alist)
1606 (progn
1607 (if (not (assoc 'verilog-xl-1 compilation-error-regexp-alist-alist))
1608 (mapcar
1609 (lambda (item)
1610 (push (car item) compilation-error-regexp-alist)
1611 (push item compilation-error-regexp-alist-alist)
1612 )
1613 verilog-error-regexp-emacs-alist)))))
1614
1615 (if (featurep 'xemacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-xemacs))
1616 (if (featurep 'emacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-emacs))
1617
1618 (defconst verilog-directive-re
1619 (eval-when-compile
1620 (verilog-regexp-words
1621 '(
1622 "`case" "`default" "`define" "`else" "`elsif" "`endfor" "`endif"
1623 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1624 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1625 "`time_scale" "`undef" "`while" ))))
1626
1627 (defconst verilog-directive-re-1
1628 (concat "[ \t]*" verilog-directive-re))
1629
1630 (defconst verilog-directive-begin
1631 "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1632
1633 (defconst verilog-directive-middle
1634 "\\<`\\(else\\|elsif\\|default\\|case\\)\\>")
1635
1636 (defconst verilog-directive-end
1637 "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1638
1639 (defconst verilog-ovm-begin-re
1640 (eval-when-compile
1641 (verilog-regexp-opt
1642 '(
1643 "`ovm_component_utils_begin"
1644 "`ovm_component_param_utils_begin"
1645 "`ovm_field_utils_begin"
1646 "`ovm_object_utils_begin"
1647 "`ovm_object_param_utils_begin"
1648 "`ovm_sequence_utils_begin"
1649 "`ovm_sequencer_utils_begin"
1650 ) nil )))
1651
1652 (defconst verilog-ovm-end-re
1653 (eval-when-compile
1654 (verilog-regexp-opt
1655 '(
1656 "`ovm_component_utils_end"
1657 "`ovm_field_utils_end"
1658 "`ovm_object_utils_end"
1659 "`ovm_sequence_utils_end"
1660 "`ovm_sequencer_utils_end"
1661 ) nil )))
1662
1663 (defconst verilog-vmm-begin-re
1664 (eval-when-compile
1665 (verilog-regexp-opt
1666 '(
1667 "`vmm_data_member_begin"
1668 "`vmm_env_member_begin"
1669 "`vmm_scenario_member_begin"
1670 "`vmm_subenv_member_begin"
1671 "`vmm_xactor_member_begin"
1672 ) nil ) ) )
1673
1674 (defconst verilog-vmm-end-re
1675 (eval-when-compile
1676 (verilog-regexp-opt
1677 '(
1678 "`vmm_data_member_end"
1679 "`vmm_env_member_end"
1680 "`vmm_scenario_member_end"
1681 "`vmm_subenv_member_end"
1682 "`vmm_xactor_member_end"
1683 ) nil ) ) )
1684
1685 (defconst verilog-vmm-statement-re
1686 (eval-when-compile
1687 (verilog-regexp-opt
1688 '(
1689 ;; "`vmm_xactor_member_enum_array"
1690 "`vmm_\\(data\\|env\\|scenario\\|subenv\\|xactor\\)_member_\\(scalar\\|string\\|enum\\|vmm_data\\|channel\\|xactor\\|subenv\\|user_defined\\)\\(_array\\)?"
1691 ;; "`vmm_xactor_member_scalar_array"
1692 ;; "`vmm_xactor_member_scalar"
1693 ) nil )))
1694
1695 (defconst verilog-ovm-statement-re
1696 (eval-when-compile
1697 (verilog-regexp-opt
1698 '(
1699 ;; Statements
1700 "`DUT_ERROR"
1701 "`MESSAGE"
1702 "`dut_error"
1703 "`message"
1704 "`ovm_analysis_imp_decl"
1705 "`ovm_blocking_get_imp_decl"
1706 "`ovm_blocking_get_peek_imp_decl"
1707 "`ovm_blocking_master_imp_decl"
1708 "`ovm_blocking_peek_imp_decl"
1709 "`ovm_blocking_put_imp_decl"
1710 "`ovm_blocking_slave_imp_decl"
1711 "`ovm_blocking_transport_imp_decl"
1712 "`ovm_component_registry"
1713 "`ovm_component_registry_param"
1714 "`ovm_component_utils"
1715 "`ovm_create"
1716 "`ovm_create_seq"
1717 "`ovm_declare_sequence_lib"
1718 "`ovm_do"
1719 "`ovm_do_seq"
1720 "`ovm_do_seq_with"
1721 "`ovm_do_with"
1722 "`ovm_error"
1723 "`ovm_fatal"
1724 "`ovm_field_aa_int_byte"
1725 "`ovm_field_aa_int_byte_unsigned"
1726 "`ovm_field_aa_int_int"
1727 "`ovm_field_aa_int_int_unsigned"
1728 "`ovm_field_aa_int_integer"
1729 "`ovm_field_aa_int_integer_unsigned"
1730 "`ovm_field_aa_int_key"
1731 "`ovm_field_aa_int_longint"
1732 "`ovm_field_aa_int_longint_unsigned"
1733 "`ovm_field_aa_int_shortint"
1734 "`ovm_field_aa_int_shortint_unsigned"
1735 "`ovm_field_aa_int_string"
1736 "`ovm_field_aa_object_int"
1737 "`ovm_field_aa_object_string"
1738 "`ovm_field_aa_string_int"
1739 "`ovm_field_aa_string_string"
1740 "`ovm_field_array_int"
1741 "`ovm_field_array_object"
1742 "`ovm_field_array_string"
1743 "`ovm_field_enum"
1744 "`ovm_field_event"
1745 "`ovm_field_int"
1746 "`ovm_field_object"
1747 "`ovm_field_queue_int"
1748 "`ovm_field_queue_object"
1749 "`ovm_field_queue_string"
1750 "`ovm_field_sarray_int"
1751 "`ovm_field_string"
1752 "`ovm_field_utils"
1753 "`ovm_file"
1754 "`ovm_get_imp_decl"
1755 "`ovm_get_peek_imp_decl"
1756 "`ovm_info"
1757 "`ovm_info1"
1758 "`ovm_info2"
1759 "`ovm_info3"
1760 "`ovm_info4"
1761 "`ovm_line"
1762 "`ovm_master_imp_decl"
1763 "`ovm_msg_detail"
1764 "`ovm_non_blocking_transport_imp_decl"
1765 "`ovm_nonblocking_get_imp_decl"
1766 "`ovm_nonblocking_get_peek_imp_decl"
1767 "`ovm_nonblocking_master_imp_decl"
1768 "`ovm_nonblocking_peek_imp_decl"
1769 "`ovm_nonblocking_put_imp_decl"
1770 "`ovm_nonblocking_slave_imp_decl"
1771 "`ovm_object_registry"
1772 "`ovm_object_registry_param"
1773 "`ovm_object_utils"
1774 "`ovm_peek_imp_decl"
1775 "`ovm_phase_func_decl"
1776 "`ovm_phase_task_decl"
1777 "`ovm_print_aa_int_object"
1778 "`ovm_print_aa_string_int"
1779 "`ovm_print_aa_string_object"
1780 "`ovm_print_aa_string_string"
1781 "`ovm_print_array_int"
1782 "`ovm_print_array_object"
1783 "`ovm_print_array_string"
1784 "`ovm_print_object_queue"
1785 "`ovm_print_queue_int"
1786 "`ovm_print_string_queue"
1787 "`ovm_put_imp_decl"
1788 "`ovm_rand_send"
1789 "`ovm_rand_send_with"
1790 "`ovm_send"
1791 "`ovm_sequence_utils"
1792 "`ovm_slave_imp_decl"
1793 "`ovm_transport_imp_decl"
1794 "`ovm_update_sequence_lib"
1795 "`ovm_update_sequence_lib_and_item"
1796 "`ovm_warning"
1797 "`static_dut_error"
1798 "`static_message") nil )))
1799
1800
1801 ;;
1802 ;; Regular expressions used to calculate indent, etc.
1803 ;;
1804 (defconst verilog-symbol-re "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
1805 ;; Want to match
1806 ;; aa :
1807 ;; aa,bb :
1808 ;; a[34:32] :
1809 ;; a,
1810 ;; b :
1811
1812 (defconst verilog-label-re (concat verilog-symbol-re "\\s-*:\\s-*"))
1813 (defconst verilog-property-re
1814 (concat "\\(" verilog-label-re "\\)?"
1815 "\\(\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(assert\\)"))
1816 ;; "\\(assert\\|assume\\|cover\\)\\s-+property\\>"
1817
1818 (defconst verilog-no-indent-begin-re
1819 "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
1820
1821 (defconst verilog-ends-re
1822 ;; Parenthesis indicate type of keyword found
1823 (concat
1824 "\\(\\<else\\>\\)\\|" ; 1
1825 "\\(\\<if\\>\\)\\|" ; 2
1826 "\\(\\<assert\\>\\)\\|" ; 3
1827 "\\(\\<end\\>\\)\\|" ; 3.1
1828 "\\(\\<endcase\\>\\)\\|" ; 4
1829 "\\(\\<endfunction\\>\\)\\|" ; 5
1830 "\\(\\<endtask\\>\\)\\|" ; 6
1831 "\\(\\<endspecify\\>\\)\\|" ; 7
1832 "\\(\\<endtable\\>\\)\\|" ; 8
1833 "\\(\\<endgenerate\\>\\)\\|" ; 9
1834 "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
1835 "\\(\\<endclass\\>\\)\\|" ; 11
1836 "\\(\\<endgroup\\>\\)\\|" ; 12
1837 ;; VMM
1838 "\\(\\<`vmm_data_member_end\\>\\)\\|"
1839 "\\(\\<`vmm_env_member_end\\>\\)\\|"
1840 "\\(\\<`vmm_scenario_member_end\\>\\)\\|"
1841 "\\(\\<`vmm_subenv_member_end\\>\\)\\|"
1842 "\\(\\<`vmm_xactor_member_end\\>\\)\\|"
1843 ;; OVM
1844 "\\(\\<`ovm_component_utils_end\\>\\)\\|"
1845 "\\(\\<`ovm_field_utils_end\\>\\)\\|"
1846 "\\(\\<`ovm_object_utils_end\\>\\)\\|"
1847 "\\(\\<`ovm_sequence_utils_end\\>\\)\\|"
1848 "\\(\\<`ovm_sequencer_utils_end\\>\\)"
1849
1850 ))
1851
1852 (defconst verilog-auto-end-comment-lines-re
1853 ;; Matches to names in this list cause auto-end-commentation
1854 (concat "\\("
1855 verilog-directive-re "\\)\\|\\("
1856 (eval-when-compile
1857 (verilog-regexp-words
1858 `( "begin"
1859 "else"
1860 "end"
1861 "endcase"
1862 "endclass"
1863 "endclocking"
1864 "endgroup"
1865 "endfunction"
1866 "endmodule"
1867 "endprogram"
1868 "endprimitive"
1869 "endinterface"
1870 "endpackage"
1871 "endsequence"
1872 "endspecify"
1873 "endtable"
1874 "endtask"
1875 "join"
1876 "join_any"
1877 "join_none"
1878 "module"
1879 "macromodule"
1880 "primitive"
1881 "interface"
1882 "package")))
1883 "\\)"))
1884
1885 ;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
1886 ;;; verilog-end-block-ordered-re matches exactly the same strings.
1887 (defconst verilog-end-block-ordered-re
1888 ;; Parenthesis indicate type of keyword found
1889 (concat "\\(\\<endcase\\>\\)\\|" ; 1
1890 "\\(\\<end\\>\\)\\|" ; 2
1891 "\\(\\<end" ; 3, but not used
1892 "\\(" ; 4, but not used
1893 "\\(function\\)\\|" ; 5
1894 "\\(task\\)\\|" ; 6
1895 "\\(module\\)\\|" ; 7
1896 "\\(primitive\\)\\|" ; 8
1897 "\\(interface\\)\\|" ; 9
1898 "\\(package\\)\\|" ; 10
1899 "\\(class\\)\\|" ; 11
1900 "\\(group\\)\\|" ; 12
1901 "\\(program\\)\\|" ; 13
1902 "\\(sequence\\)\\|" ; 14
1903 "\\(clocking\\)\\|" ; 15
1904 "\\)\\>\\)"))
1905 (defconst verilog-end-block-re
1906 (eval-when-compile
1907 (verilog-regexp-words
1908
1909 `("end" ;; closes begin
1910 "endcase" ;; closes any of case, casex casez or randcase
1911 "join" "join_any" "join_none" ;; closes fork
1912 "endclass"
1913 "endtable"
1914 "endspecify"
1915 "endfunction"
1916 "endgenerate"
1917 "endtask"
1918 "endgroup"
1919 "endproperty"
1920 "endinterface"
1921 "endpackage"
1922 "endprogram"
1923 "endsequence"
1924 "endclocking"
1925 ;; OVM
1926 "`ovm_component_utils_end"
1927 "`ovm_field_utils_end"
1928 "`ovm_object_utils_end"
1929 "`ovm_sequence_utils_end"
1930 "`ovm_sequencer_utils_end"
1931 ;; VMM
1932 "`vmm_data_member_end"
1933 "`vmm_env_member_end"
1934 "`vmm_scenario_member_end"
1935 "`vmm_subenv_member_end"
1936 "`vmm_xactor_member_end"
1937 ))))
1938
1939
1940 (defconst verilog-endcomment-reason-re
1941 ;; Parenthesis indicate type of keyword found
1942 (concat
1943 "\\(\\<begin\\>\\)\\|" ; 1
1944 "\\(\\<else\\>\\)\\|" ; 2
1945 "\\(\\<end\\>\\s-+\\<else\\>\\)\\|" ; 3
1946 "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|" ; 4
1947 "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|" ; 5
1948 "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|" ; 6
1949 "\\(\\<fork\\>\\)\\|" ; 7
1950 "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
1951 "\\(\\<if\\>\\)\\|"
1952 verilog-property-re "\\|"
1953 "\\(\\(" verilog-label-re "\\)?\\<assert\\>\\)\\|"
1954 "\\(\\<clocking\\>\\)\\|"
1955 "\\(\\<task\\>\\)\\|"
1956 "\\(\\<function\\>\\)\\|"
1957 "\\(\\<initial\\>\\)\\|"
1958 "\\(\\<interface\\>\\)\\|"
1959 "\\(\\<package\\>\\)\\|"
1960 "\\(\\<final\\>\\)\\|"
1961 "\\(@\\)\\|"
1962 "\\(\\<while\\>\\)\\|"
1963 "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
1964 "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
1965 "#"))
1966
1967 (defconst verilog-named-block-re "begin[ \t]*:")
1968
1969 ;; These words begin a block which can occur inside a module which should be indented,
1970 ;; and closed with the respective word from the end-block list
1971
1972 (defconst verilog-beg-block-re
1973 (eval-when-compile
1974 (verilog-regexp-words
1975 `("begin"
1976 "case" "casex" "casez" "randcase"
1977 "clocking"
1978 "generate"
1979 "fork"
1980 "function"
1981 "property"
1982 "specify"
1983 "table"
1984 "task"
1985 ;;; OVM
1986 "`ovm_component_utils_begin"
1987 "`ovm_component_param_utils_begin"
1988 "`ovm_field_utils_begin"
1989 "`ovm_object_utils_begin"
1990 "`ovm_object_param_utils_begin"
1991 "`ovm_sequence_utils_begin"
1992 "`ovm_sequencer_utils_begin"
1993 ;; VMM
1994 "`vmm_data_member_begin"
1995 "`vmm_env_member_begin"
1996 "`vmm_scenario_member_begin"
1997 "`vmm_subenv_member_begin"
1998 "`vmm_xactor_member_begin"
1999 ))))
2000 ;; These are the same words, in a specific order in the regular
2001 ;; expression so that matching will work nicely for
2002 ;; verilog-forward-sexp and verilog-calc-indent
2003 (defconst verilog-beg-block-re-ordered
2004 ( concat "\\(\\<begin\\>\\)" ;1
2005 "\\|\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
2006 "\\|\\(\\(\\<disable\\>\\s-+\\)?fork\\>\\)" ;4,5
2007 "\\|\\(\\<class\\>\\)" ;6
2008 "\\|\\(\\<table\\>\\)" ;7
2009 "\\|\\(\\<specify\\>\\)" ;8
2010 "\\|\\(\\<function\\>\\)" ;9
2011 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<function\\>\\)" ;10
2012 "\\|\\(\\<task\\>\\)" ;14
2013 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)" ;15
2014 "\\|\\(\\<generate\\>\\)" ;18
2015 "\\|\\(\\<covergroup\\>\\)" ;16 20
2016 "\\|\\(\\(\\(\\<cover\\>\\s-+\\)\\|\\(\\<assert\\>\\s-+\\)\\)*\\<property\\>\\)" ;17 21
2017 "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;21 25
2018 "\\|\\(\\<clocking\\>\\)" ;22 27
2019 "\\|\\(\\<`ovm_[a-z_]+_begin\\>\\)" ;28
2020 "\\|\\(\\<`vmm_[a-z_]+_member_begin\\>\\)"
2021 ;;
2022
2023 ))
2024
2025 (defconst verilog-end-block-ordered-rry
2026 [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2027 "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
2028 "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2029 "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
2030 "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
2031 "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
2032 "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
2033 "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
2034 "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
2035 "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
2036 "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
2037 "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
2038 "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
2039 ] )
2040
2041 (defconst verilog-nameable-item-re
2042 (eval-when-compile
2043 (verilog-regexp-words
2044 `("begin"
2045 "fork"
2046 "join" "join_any" "join_none"
2047 "end"
2048 "endcase"
2049 "endconfig"
2050 "endclass"
2051 "endclocking"
2052 "endfunction"
2053 "endgenerate"
2054 "endmodule"
2055 "endprimitive"
2056 "endinterface"
2057 "endpackage"
2058 "endspecify"
2059 "endtable"
2060 "endtask" )
2061 )))
2062
2063 (defconst verilog-declaration-opener
2064 (eval-when-compile
2065 (verilog-regexp-words
2066 `("module" "begin" "task" "function"))))
2067
2068 (defconst verilog-declaration-prefix-re
2069 (eval-when-compile
2070 (verilog-regexp-words
2071 `(
2072 ;; port direction
2073 "inout" "input" "output" "ref"
2074 ;; changeableness
2075 "const" "static" "protected" "local"
2076 ;; parameters
2077 "localparam" "parameter" "var"
2078 ;; type creation
2079 "typedef"
2080 ))))
2081 (defconst verilog-declaration-core-re
2082 (eval-when-compile
2083 (verilog-regexp-words
2084 `(
2085 ;; port direction (by themselves)
2086 "inout" "input" "output"
2087 ;; integer_atom_type
2088 "byte" "shortint" "int" "longint" "integer" "time"
2089 ;; integer_vector_type
2090 "bit" "logic" "reg"
2091 ;; non_integer_type
2092 "shortreal" "real" "realtime"
2093 ;; net_type
2094 "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
2095 ;; misc
2096 "string" "event" "chandle" "virtual" "enum" "genvar"
2097 "struct" "union"
2098 ;; builtin classes
2099 "mailbox" "semaphore"
2100 ))))
2101 (defconst verilog-declaration-re
2102 (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
2103 (defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
2104 (defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
2105 (defconst verilog-optional-signed-range-re
2106 (concat
2107 "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
2108 (defconst verilog-macroexp-re "`\\sw+")
2109
2110 (defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
2111 (defconst verilog-declaration-re-2-no-macro
2112 (concat "\\s-*" verilog-declaration-re
2113 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2114 "\\)?"))
2115 (defconst verilog-declaration-re-2-macro
2116 (concat "\\s-*" verilog-declaration-re
2117 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2118 "\\|\\(" verilog-macroexp-re "\\)"
2119 "\\)?"))
2120 (defconst verilog-declaration-re-1-macro
2121 (concat "^" verilog-declaration-re-2-macro))
2122
2123 (defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
2124
2125 (defconst verilog-defun-re
2126 (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
2127 (defconst verilog-end-defun-re
2128 (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
2129 (defconst verilog-zero-indent-re
2130 (concat verilog-defun-re "\\|" verilog-end-defun-re))
2131
2132 (defconst verilog-behavioral-block-beg-re
2133 (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
2134 "function" "task"))))
2135 (defconst verilog-coverpoint-re "\\w+\\s*:\\s*\\(coverpoint\\|cross\\constraint\\)" )
2136 (defconst verilog-indent-re
2137 (eval-when-compile
2138 (verilog-regexp-words
2139 `(
2140 "{"
2141 "always" "always_latch" "always_ff" "always_comb"
2142 "begin" "end"
2143 ; "unique" "priority"
2144 "case" "casex" "casez" "randcase" "endcase"
2145 "class" "endclass"
2146 "clocking" "endclocking"
2147 "config" "endconfig"
2148 "covergroup" "endgroup"
2149 "fork" "join" "join_any" "join_none"
2150 "function" "endfunction"
2151 "final"
2152 "generate" "endgenerate"
2153 "initial"
2154 "interface" "endinterface"
2155 "module" "macromodule" "endmodule"
2156 "package" "endpackage"
2157 "primitive" "endprimative"
2158 "program" "endprogram"
2159 "property" "endproperty"
2160 "sequence" "randsequence" "endsequence"
2161 "specify" "endspecify"
2162 "table" "endtable"
2163 "task" "endtask"
2164 "virtual"
2165 "`case"
2166 "`default"
2167 "`define" "`undef"
2168 "`if" "`ifdef" "`ifndef" "`else" "`elsif" "`endif"
2169 "`while" "`endwhile"
2170 "`for" "`endfor"
2171 "`format"
2172 "`include"
2173 "`let"
2174 "`protect" "`endprotect"
2175 "`switch" "`endswitch"
2176 "`timescale"
2177 "`time_scale"
2178 ;; OVM Begin tokens
2179 "`ovm_component_utils_begin"
2180 "`ovm_component_param_utils_begin"
2181 "`ovm_field_utils_begin"
2182 "`ovm_object_utils_begin"
2183 "`ovm_object_param_utils_begin"
2184 "`ovm_sequence_utils_begin"
2185 "`ovm_sequencer_utils_begin"
2186 ;; OVM End tokens
2187 "`ovm_component_utils_end"
2188 "`ovm_field_utils_end"
2189 "`ovm_object_utils_end"
2190 "`ovm_sequence_utils_end"
2191 "`ovm_sequencer_utils_end"
2192 ;; VMM Begin tokens
2193 "`vmm_data_member_begin"
2194 "`vmm_env_member_begin"
2195 "`vmm_scenario_member_begin"
2196 "`vmm_subenv_member_begin"
2197 "`vmm_xactor_member_begin"
2198 ;; VMM End tokens
2199 "`vmm_data_member_end"
2200 "`vmm_env_member_end"
2201 "`vmm_scenario_member_end"
2202 "`vmm_subenv_member_end"
2203 "`vmm_xactor_member_end"
2204 ))))
2205
2206 (defconst verilog-defun-level-not-generate-re
2207 (eval-when-compile
2208 (verilog-regexp-words
2209 `( "module" "macromodule" "primitive" "class" "program"
2210 "interface" "package" "config"))))
2211
2212 (defconst verilog-defun-level-re
2213 (eval-when-compile
2214 (verilog-regexp-words
2215 (append
2216 `( "module" "macromodule" "primitive" "class" "program"
2217 "interface" "package" "config")
2218 `( "initial" "final" "always" "always_comb" "always_ff"
2219 "always_latch" "endtask" "endfunction" )))))
2220
2221 (defconst verilog-defun-level-generate-only-re
2222 (eval-when-compile
2223 (verilog-regexp-words
2224 `( "initial" "final" "always" "always_comb" "always_ff"
2225 "always_latch" "endtask" "endfunction" ))))
2226
2227 (defconst verilog-cpp-level-re
2228 (eval-when-compile
2229 (verilog-regexp-words
2230 `(
2231 "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
2232 ))))
2233 (defconst verilog-disable-fork-re "disable\\s-+fork\\>")
2234 (defconst verilog-fork-wait-re "fork\\s-+wait\\>")
2235 (defconst verilog-extended-case-re "\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?")
2236 (defconst verilog-extended-complete-re
2237 (concat "\\(\\<extern\\s-+\\|\\<\\(\\<pure\\>\\s-+\\)?virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)"
2238 "\\|\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)"
2239 "\\|\\(\\<import\\>\\s-+\\)?\"DPI-C\"\\s-+\\(function\\>\\|task\\>\\)"
2240 "\\|" verilog-extended-case-re ))
2241 (defconst verilog-basic-complete-re
2242 (eval-when-compile
2243 (verilog-regexp-words
2244 `(
2245 "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
2246 "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
2247 "if" "for" "forever" "foreach" "else" "parameter" "do" "localparam" "assert"
2248 ))))
2249 (defconst verilog-complete-reg
2250 (concat
2251 verilog-extended-complete-re
2252 "\\|"
2253 verilog-basic-complete-re))
2254
2255 (defconst verilog-end-statement-re
2256 (concat "\\(" verilog-beg-block-re "\\)\\|\\("
2257 verilog-end-block-re "\\)"))
2258
2259 (defconst verilog-endcase-re
2260 (concat verilog-extended-case-re "\\|"
2261 "\\(endcase\\)\\|"
2262 verilog-defun-re
2263 ))
2264
2265 (defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
2266 "String used to mark beginning of excluded text.")
2267 (defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
2268 "String used to mark end of excluded text.")
2269 (defconst verilog-preprocessor-re
2270 (eval-when-compile
2271 (verilog-regexp-words
2272 `(
2273 "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
2274 ))))
2275
2276 (defconst verilog-keywords
2277 '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
2278 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
2279 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
2280 "`time_scale" "`undef" "`while"
2281
2282 "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
2283 "assert" "assign" "assume" "automatic" "before" "begin" "bind"
2284 "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
2285 "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
2286 "config" "const" "constraint" "context" "continue" "cover"
2287 "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
2288 "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
2289 "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
2290 "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
2291 "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
2292 "endtask" "enum" "event" "expect" "export" "extends" "extern"
2293 "final" "first_match" "for" "force" "foreach" "forever" "fork"
2294 "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
2295 "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
2296 "include" "initial" "inout" "input" "inside" "instance" "int"
2297 "integer" "interface" "intersect" "join" "join_any" "join_none"
2298 "large" "liblist" "library" "local" "localparam" "logic"
2299 "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
2300 "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
2301 "notif0" "notif1" "null" "or" "output" "package" "packed"
2302 "parameter" "pmos" "posedge" "primitive" "priority" "program"
2303 "property" "protected" "pull0" "pull1" "pulldown" "pullup"
2304 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2305 "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
2306 "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
2307 "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
2308 "showcancelled" "signed" "small" "solve" "specify" "specparam"
2309 "static" "string" "strong0" "strong1" "struct" "super" "supply0"
2310 "supply1" "table" "tagged" "task" "this" "throughout" "time"
2311 "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
2312 "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
2313 "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
2314 "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
2315 "wire" "with" "within" "wor" "xnor" "xor"
2316 ;; 1800-2009
2317 "accept_on" "checker" "endchecker" "eventually" "global" "implies"
2318 "let" "nexttime" "reject_on" "restrict" "s_always" "s_eventually"
2319 "s_nexttime" "s_until" "s_until_with" "strong" "sync_accept_on"
2320 "sync_reject_on" "unique0" "until" "until_with" "untyped" "weak"
2321 )
2322 "List of Verilog keywords.")
2323
2324 (defconst verilog-comment-start-regexp "//\\|/\\*"
2325 "Dual comment value for `comment-start-regexp'.")
2326
2327 (defvar verilog-mode-syntax-table
2328 (let ((table (make-syntax-table)))
2329 ;; Populate the syntax TABLE.
2330 (modify-syntax-entry ?\\ "\\" table)
2331 (modify-syntax-entry ?+ "." table)
2332 (modify-syntax-entry ?- "." table)
2333 (modify-syntax-entry ?= "." table)
2334 (modify-syntax-entry ?% "." table)
2335 (modify-syntax-entry ?< "." table)
2336 (modify-syntax-entry ?> "." table)
2337 (modify-syntax-entry ?& "." table)
2338 (modify-syntax-entry ?| "." table)
2339 (modify-syntax-entry ?` "w" table)
2340 (modify-syntax-entry ?_ "w" table)
2341 (modify-syntax-entry ?\' "." table)
2342
2343 ;; Set up TABLE to handle block and line style comments.
2344 (if (featurep 'xemacs)
2345 (progn
2346 ;; XEmacs (formerly Lucid) has the best implementation
2347 (modify-syntax-entry ?/ ". 1456" table)
2348 (modify-syntax-entry ?* ". 23" table)
2349 (modify-syntax-entry ?\n "> b" table))
2350 ;; Emacs does things differently, but we can work with it
2351 (modify-syntax-entry ?/ ". 124b" table)
2352 (modify-syntax-entry ?* ". 23" table)
2353 (modify-syntax-entry ?\n "> b" table))
2354 table)
2355 "Syntax table used in Verilog mode buffers.")
2356
2357 (defvar verilog-font-lock-keywords nil
2358 "Default highlighting for Verilog mode.")
2359
2360 (defvar verilog-font-lock-keywords-1 nil
2361 "Subdued level highlighting for Verilog mode.")
2362
2363 (defvar verilog-font-lock-keywords-2 nil
2364 "Medium level highlighting for Verilog mode.
2365 See also `verilog-font-lock-extra-types'.")
2366
2367 (defvar verilog-font-lock-keywords-3 nil
2368 "Gaudy level highlighting for Verilog mode.
2369 See also `verilog-font-lock-extra-types'.")
2370 (defvar verilog-font-lock-translate-off-face
2371 'verilog-font-lock-translate-off-face
2372 "Font to use for translated off regions.")
2373 (defface verilog-font-lock-translate-off-face
2374 '((((class color)
2375 (background light))
2376 (:background "gray90" :italic t ))
2377 (((class color)
2378 (background dark))
2379 (:background "gray10" :italic t ))
2380 (((class grayscale) (background light))
2381 (:foreground "DimGray" :italic t))
2382 (((class grayscale) (background dark))
2383 (:foreground "LightGray" :italic t))
2384 (t (:italis t)))
2385 "Font lock mode face used to background highlight translate-off regions."
2386 :group 'font-lock-highlighting-faces)
2387
2388 (defvar verilog-font-lock-p1800-face
2389 'verilog-font-lock-p1800-face
2390 "Font to use for p1800 keywords.")
2391 (defface verilog-font-lock-p1800-face
2392 '((((class color)
2393 (background light))
2394 (:foreground "DarkOrange3" :bold t ))
2395 (((class color)
2396 (background dark))
2397 (:foreground "orange1" :bold t ))
2398 (t (:italic t)))
2399 "Font lock mode face used to highlight P1800 keywords."
2400 :group 'font-lock-highlighting-faces)
2401
2402 (defvar verilog-font-lock-ams-face
2403 'verilog-font-lock-ams-face
2404 "Font to use for Analog/Mixed Signal keywords.")
2405 (defface verilog-font-lock-ams-face
2406 '((((class color)
2407 (background light))
2408 (:foreground "Purple" :bold t ))
2409 (((class color)
2410 (background dark))
2411 (:foreground "orange1" :bold t ))
2412 (t (:italic t)))
2413 "Font lock mode face used to highlight AMS keywords."
2414 :group 'font-lock-highlighting-faces)
2415
2416 (defvar verilog-font-grouping-keywords-face
2417 'verilog-font-lock-grouping-keywords-face
2418 "Font to use for Verilog Grouping Keywords (such as begin..end).")
2419 (defface verilog-font-lock-grouping-keywords-face
2420 '((((class color)
2421 (background light))
2422 (:foreground "red4" :bold t ))
2423 (((class color)
2424 (background dark))
2425 (:foreground "red4" :bold t ))
2426 (t (:italic t)))
2427 "Font lock mode face used to highlight verilog grouping keywords."
2428 :group 'font-lock-highlighting-faces)
2429
2430 (let* ((verilog-type-font-keywords
2431 (eval-when-compile
2432 (verilog-regexp-opt
2433 '(
2434 "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
2435 "event" "genvar" "inout" "input" "integer" "localparam"
2436 "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
2437 "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
2438 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
2439 "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
2440 "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
2441 "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
2442 "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
2443 ) nil )))
2444
2445 (verilog-pragma-keywords
2446 (eval-when-compile
2447 (verilog-regexp-opt
2448 '("surefire" "synopsys" "rtl_synthesis" "verilint" "leda" "0in") nil
2449 )))
2450
2451 (verilog-1800-2005-keywords
2452 (eval-when-compile
2453 (verilog-regexp-opt
2454 '("alias" "assert" "assume" "automatic" "before" "bind"
2455 "bins" "binsof" "break" "byte" "cell" "chandle" "class"
2456 "clocking" "config" "const" "constraint" "context" "continue"
2457 "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
2458 "dist" "do" "edge" "endclass" "endclocking" "endconfig"
2459 "endgroup" "endprogram" "endproperty" "endsequence" "enum"
2460 "expect" "export" "extends" "extern" "first_match" "foreach"
2461 "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
2462 "illegal_bins" "import" "incdir" "include" "inside" "instance"
2463 "int" "intersect" "large" "liblist" "library" "local" "longint"
2464 "matches" "medium" "modport" "new" "noshowcancelled" "null"
2465 "packed" "program" "property" "protected" "pull0" "pull1"
2466 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2467 "randcase" "randsequence" "ref" "release" "return" "scalared"
2468 "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
2469 "specparam" "static" "string" "strong0" "strong1" "struct"
2470 "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
2471 "type" "union" "unsigned" "use" "var" "virtual" "void"
2472 "wait_order" "weak0" "weak1" "wildcard" "with" "within"
2473 ) nil )))
2474
2475 (verilog-1800-2009-keywords
2476 (eval-when-compile
2477 (verilog-regexp-opt
2478 '("accept_on" "checker" "endchecker" "eventually" "global"
2479 "implies" "let" "nexttime" "reject_on" "restrict" "s_always"
2480 "s_eventually" "s_nexttime" "s_until" "s_until_with" "strong"
2481 "sync_accept_on" "sync_reject_on" "unique0" "until"
2482 "until_with" "untyped" "weak" ) nil )))
2483
2484 (verilog-ams-keywords
2485 (eval-when-compile
2486 (verilog-regexp-opt
2487 '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
2488 "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
2489 "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
2490 "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
2491 "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
2492 "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
2493 "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
2494 "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
2495 "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
2496 "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
2497 "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
2498
2499 (verilog-font-keywords
2500 (eval-when-compile
2501 (verilog-regexp-opt
2502 '(
2503 "assign" "case" "casex" "casez" "randcase" "deassign"
2504 "default" "disable" "else" "endcase" "endfunction"
2505 "endgenerate" "endinterface" "endmodule" "endprimitive"
2506 "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
2507 "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
2508 "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
2509 "package" "endpackage" "always" "always_comb" "always_ff"
2510 "always_latch" "posedge" "primitive" "priority" "release"
2511 "repeat" "specify" "table" "task" "unique" "wait" "while"
2512 "class" "program" "endclass" "endprogram"
2513 ) nil )))
2514
2515 (verilog-font-grouping-keywords
2516 (eval-when-compile
2517 (verilog-regexp-opt
2518 '( "begin" "end" ) nil ))))
2519
2520 (setq verilog-font-lock-keywords
2521 (list
2522 ;; Fontify all builtin keywords
2523 (concat "\\<\\(" verilog-font-keywords "\\|"
2524 ;; And user/system tasks and functions
2525 "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
2526 "\\)\\>")
2527 ;; Fontify all types
2528 (if verilog-highlight-grouping-keywords
2529 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2530 'verilog-font-lock-ams-face)
2531 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2532 'font-lock-type-face))
2533 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
2534 'font-lock-type-face)
2535 ;; Fontify IEEE-1800-2005 keywords appropriately
2536 (if verilog-highlight-p1800-keywords
2537 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
2538 'verilog-font-lock-p1800-face)
2539 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
2540 'font-lock-type-face))
2541 ;; Fontify IEEE-1800-2009 keywords appropriately
2542 (if verilog-highlight-p1800-keywords
2543 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
2544 'verilog-font-lock-p1800-face)
2545 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
2546 'font-lock-type-face))
2547 ;; Fontify Verilog-AMS keywords
2548 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
2549 'verilog-font-lock-ams-face)))
2550
2551 (setq verilog-font-lock-keywords-1
2552 (append verilog-font-lock-keywords
2553 (list
2554 ;; Fontify module definitions
2555 (list
2556 "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
2557 '(1 font-lock-keyword-face)
2558 '(3 font-lock-function-name-face 'prepend))
2559 ;; Fontify function definitions
2560 (list
2561 (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
2562 '(1 font-lock-keyword-face)
2563 '(3 font-lock-constant-face prepend))
2564 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
2565 (1 font-lock-keyword-face)
2566 (2 font-lock-constant-face append))
2567 '("\\<function\\>\\s-+\\(\\sw+\\)"
2568 1 'font-lock-constant-face append))))
2569
2570 (setq verilog-font-lock-keywords-2
2571 (append verilog-font-lock-keywords-1
2572 (list
2573 ;; Fontify pragmas
2574 (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
2575 ;; Fontify escaped names
2576 '("\\(\\\\\\S-*\\s-\\)" 0 font-lock-function-name-face)
2577 ;; Fontify macro definitions/ uses
2578 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
2579 'font-lock-preprocessor-face
2580 'font-lock-type-face))
2581 ;; Fontify delays/numbers
2582 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
2583 0 font-lock-type-face append)
2584 ;; Fontify instantiation names
2585 '("\\([A-Za-z][A-Za-z0-9_]*\\)\\s-*(" 1 font-lock-function-name-face)
2586 )))
2587
2588 (setq verilog-font-lock-keywords-3
2589 (append verilog-font-lock-keywords-2
2590 (when verilog-highlight-translate-off
2591 (list
2592 ;; Fontify things in translate off regions
2593 '(verilog-match-translate-off
2594 (0 'verilog-font-lock-translate-off-face prepend))
2595 )))))
2596
2597 ;;
2598 ;; Buffer state preservation
2599
2600 (defmacro verilog-save-buffer-state (&rest body)
2601 "Execute BODY forms, saving state around insignificant change.
2602 Changes in text properties like `face' or `syntax-table' are
2603 considered insignificant. This macro allows text properties to
2604 be changed, even in a read-only buffer.
2605
2606 A change is considered significant if it affects the buffer text
2607 in any way that isn't completely restored again. Any
2608 user-visible changes to the buffer must not be within a
2609 `verilog-save-buffer-state'."
2610 ;; From c-save-buffer-state
2611 `(let* ((modified (buffer-modified-p))
2612 (buffer-undo-list t)
2613 (inhibit-read-only t)
2614 (inhibit-point-motion-hooks t)
2615 before-change-functions
2616 after-change-functions
2617 deactivate-mark
2618 buffer-file-name ; Prevent primitives checking
2619 buffer-file-truename) ; for file modification
2620 (unwind-protect
2621 (progn ,@body)
2622 (and (not modified)
2623 (buffer-modified-p)
2624 (set-buffer-modified-p nil)))))
2625
2626 (defmacro verilog-save-no-change-functions (&rest body)
2627 "Execute BODY forms, disabling all change hooks in BODY.
2628 For insigificant changes, see instead `verilog-save-buffer-state'."
2629 `(let* ((inhibit-point-motion-hooks t)
2630 before-change-functions
2631 after-change-functions)
2632 (progn ,@body)))
2633
2634 ;;
2635 ;; Comment detection and caching
2636
2637 (defvar verilog-scan-cache-preserving nil
2638 "If set, the specified buffer's comment properties are static.
2639 Buffer changes will be ignored. See `verilog-inside-comment-p'
2640 and `verilog-scan'.")
2641
2642 (defvar verilog-scan-cache-tick nil
2643 "Modification tick at which `verilog-scan' was last completed.")
2644 (make-variable-buffer-local 'verilog-scan-cache-tick)
2645
2646 (defun verilog-scan-cache-ok-p ()
2647 "Return t iff the scan cache is up to date."
2648 (or (and verilog-scan-cache-preserving
2649 (eq verilog-scan-cache-preserving (current-buffer))
2650 verilog-scan-cache-tick)
2651 (equal verilog-scan-cache-tick (buffer-chars-modified-tick))))
2652
2653 (defmacro verilog-save-scan-cache (&rest body)
2654 "Execute the BODY forms, allowing scan cache preservation within BODY.
2655 This requires that insertions must use `verilog-insert'."
2656 ;; If the buffer is out of date, trash it, as we'll not check later the tick
2657 ;; Note this must work properly if there's multiple layers of calls
2658 ;; to verilog-save-scan-cache even with differing ticks.
2659 `(progn
2660 (unless (verilog-scan-cache-ok-p) ;; Must be before let
2661 (setq verilog-scan-cache-tick nil))
2662 (let* ((verilog-scan-cache-preserving (current-buffer)))
2663 (progn ,@body))))
2664
2665 (defun verilog-scan-region (beg end)
2666 "Parse comments between BEG and END for `verilog-inside-comment-p'.
2667 This creates v-cmt properties where comments are in force."
2668 ;; Why properties and not overlays? Overlays have much slower non O(1)
2669 ;; lookup times.
2670 ;; This function is warm - called on every verilog-insert
2671 (save-excursion
2672 (save-match-data
2673 (verilog-save-buffer-state
2674 (let (pt)
2675 (goto-char beg)
2676 (while (< (point) end)
2677 (cond ((looking-at "//")
2678 (setq pt (point))
2679 (or (search-forward "\n" end t)
2680 (goto-char end))
2681 ;; "1+": The leading // or /* itself isn't considered as
2682 ;; being "inside" the comment, so that a (search-backward)
2683 ;; that lands at the start of the // won't mis-indicate
2684 ;; it's inside a comment
2685 (put-text-property (1+ pt) (point) 'v-cmt t))
2686 ((looking-at "/\\*")
2687 (setq pt (point))
2688 (or (search-forward "*/" end t)
2689 ;; No error - let later code indicate it so we can
2690 ;; use inside functions on-the-fly
2691 ;;(error "%s: Unmatched /* */, at char %d"
2692 ;; (verilog-point-text) (point))
2693 (goto-char end))
2694 (put-text-property (1+ pt) (point) 'v-cmt t))
2695 (t
2696 (forward-char 1)
2697 (if (re-search-forward "/[/*]" end t)
2698 (backward-char 2)
2699 (goto-char end))))))))))
2700
2701 (defun verilog-scan ()
2702 "Parse the buffer, marking all comments with properties.
2703 Also assumes any text inserted since `verilog-scan-cache-tick'
2704 either is ok to parse as a non-comment, or `verilog-insert' was used."
2705 (unless (verilog-scan-cache-ok-p)
2706 (save-excursion
2707 (verilog-save-buffer-state
2708 (when verilog-debug
2709 (message "Scanning %s cache=%s cachetick=%S tick=%S" (current-buffer)
2710 verilog-scan-cache-preserving verilog-scan-cache-tick
2711 (buffer-chars-modified-tick)))
2712 (remove-text-properties (point-min) (point-max) '(v-cmt nil))
2713 (verilog-scan-region (point-min) (point-max))
2714 (setq verilog-scan-cache-tick (buffer-chars-modified-tick))
2715 (when verilog-debug (message "Scaning... done"))))))
2716
2717 (defun verilog-inside-comment-p ()
2718 "Check if point inside a comment.
2719 This may require a slow pre-parse of the buffer with `verilog-scan'
2720 to establish comment properties on all text."
2721 ;; This function is very hot
2722 (verilog-scan)
2723 (get-text-property (point) 'v-cmt))
2724
2725 (defun verilog-insert (&rest stuff)
2726 "Insert STUFF arguments, tracking comments for `verilog-inside-comment-p'.
2727 Any insert that includes a comment must have the entire commente
2728 inserted using a single call to `verilog-insert'."
2729 (let ((pt (point)))
2730 (while stuff
2731 (insert (car stuff))
2732 (setq stuff (cdr stuff)))
2733 (verilog-scan-region pt (point))))
2734
2735 ;; More searching
2736
2737 (defun verilog-declaration-end ()
2738 (search-forward ";"))
2739
2740 (defun verilog-point-text (&optional pointnum)
2741 "Return text describing where POINTNUM or current point is (for errors).
2742 Use filename, if current buffer being edited shorten to just buffer name."
2743 (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
2744 (buffer-name))
2745 buffer-file-name
2746 (buffer-name))
2747 ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
2748
2749 (defun electric-verilog-backward-sexp ()
2750 "Move backward over one balanced expression."
2751 (interactive)
2752 ;; before that see if we are in a comment
2753 (verilog-backward-sexp))
2754
2755 (defun electric-verilog-forward-sexp ()
2756 "Move forward over one balanced expression."
2757 (interactive)
2758 ;; before that see if we are in a comment
2759 (verilog-forward-sexp))
2760
2761 ;;;used by hs-minor-mode
2762 (defun verilog-forward-sexp-function (arg)
2763 (if (< arg 0)
2764 (verilog-backward-sexp)
2765 (verilog-forward-sexp)))
2766
2767
2768 (defun verilog-backward-sexp ()
2769 (let ((reg)
2770 (elsec 1)
2771 (found nil)
2772 (st (point)))
2773 (if (not (looking-at "\\<"))
2774 (forward-word -1))
2775 (cond
2776 ((verilog-skip-backward-comment-or-string))
2777 ((looking-at "\\<else\\>")
2778 (setq reg (concat
2779 verilog-end-block-re
2780 "\\|\\(\\<else\\>\\)"
2781 "\\|\\(\\<if\\>\\)"))
2782 (while (and (not found)
2783 (verilog-re-search-backward reg nil 'move))
2784 (cond
2785 ((match-end 1) ; matched verilog-end-block-re
2786 ; try to leap back to matching outward block by striding across
2787 ; indent level changing tokens then immediately
2788 ; previous line governs indentation.
2789 (verilog-leap-to-head))
2790 ((match-end 2) ; else, we're in deep
2791 (setq elsec (1+ elsec)))
2792 ((match-end 3) ; found it
2793 (setq elsec (1- elsec))
2794 (if (= 0 elsec)
2795 ;; Now previous line describes syntax
2796 (setq found 't))))))
2797 ((looking-at verilog-end-block-re)
2798 (verilog-leap-to-head))
2799 ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
2800 (cond
2801 ((match-end 1)
2802 (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
2803 ((match-end 2)
2804 (verilog-re-search-backward "\\<primitive\\>" nil 'move))
2805 ((match-end 3)
2806 (verilog-re-search-backward "\\<class\\>" nil 'move))
2807 ((match-end 4)
2808 (verilog-re-search-backward "\\<program\\>" nil 'move))
2809 ((match-end 5)
2810 (verilog-re-search-backward "\\<interface\\>" nil 'move))
2811 ((match-end 6)
2812 (verilog-re-search-backward "\\<package\\>" nil 'move))
2813 (t
2814 (goto-char st)
2815 (backward-sexp 1))))
2816 (t
2817 (goto-char st)
2818 (backward-sexp)))))
2819
2820 (defun verilog-forward-sexp ()
2821 (let ((reg)
2822 (md 2)
2823 (st (point))
2824 (nest 'yes))
2825 (if (not (looking-at "\\<"))
2826 (forward-word -1))
2827 (cond
2828 ((verilog-skip-forward-comment-or-string)
2829 (verilog-forward-syntactic-ws))
2830 ((looking-at verilog-beg-block-re-ordered)
2831 (cond
2832 ((match-end 1);
2833 ;; Search forward for matching end
2834 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
2835 ((match-end 2)
2836 ;; Search forward for matching endcase
2837 (setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2838 (setq md 3) ;; ender is third item in regexp
2839 )
2840 ((match-end 4)
2841 ;; might be "disable fork" or "fork wait"
2842 (let
2843 (here)
2844 (if (looking-at verilog-fork-wait-re)
2845 (progn ;; it is a fork wait; ignore it
2846 (goto-char (match-end 0))
2847 (setq reg nil))
2848 (if (or
2849 (looking-at verilog-disable-fork-re)
2850 (and (looking-at "fork")
2851 (progn
2852 (setq here (point)) ;; sometimes a fork is just a fork
2853 (forward-word -1)
2854 (looking-at verilog-disable-fork-re))))
2855 (progn ;; it is a disable fork; ignore it
2856 (goto-char (match-end 0))
2857 (forward-word 1)
2858 (setq reg nil))
2859 (progn ;; it is a nice simple fork
2860 (goto-char here) ;; return from looking for "disable fork"
2861 ;; Search forward for matching join
2862 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))))))
2863 ((match-end 6)
2864 ;; Search forward for matching endclass
2865 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
2866
2867 ((match-end 7)
2868 ;; Search forward for matching endtable
2869 (setq reg "\\<endtable\\>" )
2870 (setq nest 'no))
2871 ((match-end 8)
2872 ;; Search forward for matching endspecify
2873 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
2874 ((match-end 9)
2875 ;; Search forward for matching endfunction
2876 (setq reg "\\<endfunction\\>" )
2877 (setq nest 'no))
2878 ((match-end 10)
2879 ;; Search forward for matching endfunction
2880 (setq reg "\\<endfunction\\>" )
2881 (setq nest 'no))
2882 ((match-end 14)
2883 ;; Search forward for matching endtask
2884 (setq reg "\\<endtask\\>" )
2885 (setq nest 'no))
2886 ((match-end 15)
2887 ;; Search forward for matching endtask
2888 (setq reg "\\<endtask\\>" )
2889 (setq nest 'no))
2890 ((match-end 19)
2891 ;; Search forward for matching endgenerate
2892 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
2893 ((match-end 20)
2894 ;; Search forward for matching endgroup
2895 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
2896 ((match-end 21)
2897 ;; Search forward for matching endproperty
2898 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
2899 ((match-end 25)
2900 ;; Search forward for matching endsequence
2901 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
2902 (setq md 3)) ; 3 to get to endsequence in the reg above
2903 ((match-end 27)
2904 ;; Search forward for matching endclocking
2905 (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
2906 (if (and reg
2907 (forward-word 1))
2908 (catch 'skip
2909 (if (eq nest 'yes)
2910 (let ((depth 1)
2911 here)
2912 (while (verilog-re-search-forward reg nil 'move)
2913 (cond
2914 ((match-end md) ; a closer in regular expression, so we are climbing out
2915 (setq depth (1- depth))
2916 (if (= 0 depth) ; we are out!
2917 (throw 'skip 1)))
2918 ((match-end 1) ; an opener in the r-e, so we are in deeper now
2919 (setq here (point)) ; remember where we started
2920 (goto-char (match-beginning 1))
2921 (cond
2922 ((looking-at verilog-fork-wait-re)
2923 (goto-char (match-end 0))) ; false alarm
2924 ((if (or
2925 (looking-at verilog-disable-fork-re)
2926 (and (looking-at "fork")
2927 (progn
2928 (forward-word -1)
2929 (looking-at verilog-disable-fork-re))))
2930 (progn ;; it is a disable fork; another false alarm
2931 (goto-char (match-end 0)))
2932 (progn ;; it is a simple fork (or has nothing to do with fork)
2933 (goto-char here)
2934 (setq depth (1+ depth))))))))))
2935 (if (verilog-re-search-forward reg nil 'move)
2936 (throw 'skip 1))))))
2937
2938 ((looking-at (concat
2939 "\\(\\<\\(macro\\)?module\\>\\)\\|"
2940 "\\(\\<primitive\\>\\)\\|"
2941 "\\(\\<class\\>\\)\\|"
2942 "\\(\\<program\\>\\)\\|"
2943 "\\(\\<interface\\>\\)\\|"
2944 "\\(\\<package\\>\\)"))
2945 (cond
2946 ((match-end 1)
2947 (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
2948 ((match-end 2)
2949 (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
2950 ((match-end 3)
2951 (verilog-re-search-forward "\\<endclass\\>" nil 'move))
2952 ((match-end 4)
2953 (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
2954 ((match-end 5)
2955 (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
2956 ((match-end 6)
2957 (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
2958 (t
2959 (goto-char st)
2960 (if (= (following-char) ?\) )
2961 (forward-char 1)
2962 (forward-sexp 1)))))
2963 (t
2964 (goto-char st)
2965 (if (= (following-char) ?\) )
2966 (forward-char 1)
2967 (forward-sexp 1))))))
2968
2969 (defun verilog-declaration-beg ()
2970 (verilog-re-search-backward verilog-declaration-re (bobp) t))
2971
2972 ;;
2973 ;;
2974 ;; Mode
2975 ;;
2976 (defvar verilog-which-tool 1)
2977 ;;;###autoload
2978 (defun verilog-mode ()
2979 "Major mode for editing Verilog code.
2980 \\<verilog-mode-map>
2981 See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
2982 AUTOs can improve coding efficiency.
2983
2984 Use \\[verilog-faq] for a pointer to frequently asked questions.
2985
2986 NEWLINE, TAB indents for Verilog code.
2987 Delete converts tabs to spaces as it moves back.
2988
2989 Supports highlighting.
2990
2991 Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
2992 with no args, if that value is non-nil.
2993
2994 Variables controlling indentation/edit style:
2995
2996 variable `verilog-indent-level' (default 3)
2997 Indentation of Verilog statements with respect to containing block.
2998 `verilog-indent-level-module' (default 3)
2999 Absolute indentation of Module level Verilog statements.
3000 Set to 0 to get initial and always statements lined up
3001 on the left side of your screen.
3002 `verilog-indent-level-declaration' (default 3)
3003 Indentation of declarations with respect to containing block.
3004 Set to 0 to get them list right under containing block.
3005 `verilog-indent-level-behavioral' (default 3)
3006 Indentation of first begin in a task or function block
3007 Set to 0 to get such code to lined up underneath the task or
3008 function keyword.
3009 `verilog-indent-level-directive' (default 1)
3010 Indentation of `ifdef/`endif blocks.
3011 `verilog-cexp-indent' (default 1)
3012 Indentation of Verilog statements broken across lines i.e.:
3013 if (a)
3014 begin
3015 `verilog-case-indent' (default 2)
3016 Indentation for case statements.
3017 `verilog-auto-newline' (default nil)
3018 Non-nil means automatically newline after semicolons and the punctuation
3019 mark after an end.
3020 `verilog-auto-indent-on-newline' (default t)
3021 Non-nil means automatically indent line after newline.
3022 `verilog-tab-always-indent' (default t)
3023 Non-nil means TAB in Verilog mode should always reindent the current line,
3024 regardless of where in the line point is when the TAB command is used.
3025 `verilog-indent-begin-after-if' (default t)
3026 Non-nil means to indent begin statements following a preceding
3027 if, else, while, for and repeat statements, if any. Otherwise,
3028 the begin is lined up with the preceding token. If t, you get:
3029 if (a)
3030 begin // amount of indent based on `verilog-cexp-indent'
3031 otherwise you get:
3032 if (a)
3033 begin
3034 `verilog-auto-endcomments' (default t)
3035 Non-nil means a comment /* ... */ is set after the ends which ends
3036 cases, tasks, functions and modules.
3037 The type and name of the object will be set between the braces.
3038 `verilog-minimum-comment-distance' (default 10)
3039 Minimum distance (in lines) between begin and end required before a comment
3040 will be inserted. Setting this variable to zero results in every
3041 end acquiring a comment; the default avoids too many redundant
3042 comments in tight quarters.
3043 `verilog-auto-lineup' (default 'declarations)
3044 List of contexts where auto lineup of code should be done.
3045
3046 Variables controlling other actions:
3047
3048 `verilog-linter' (default surelint)
3049 Unix program to call to run the lint checker. This is the default
3050 command for \\[compile-command] and \\[verilog-auto-save-compile].
3051
3052 See \\[customize] for the complete list of variables.
3053
3054 AUTO expansion functions are, in part:
3055
3056 \\[verilog-auto] Expand AUTO statements.
3057 \\[verilog-delete-auto] Remove the AUTOs.
3058 \\[verilog-inject-auto] Insert AUTOs for the first time.
3059
3060 Some other functions are:
3061
3062 \\[verilog-complete-word] Complete word with appropriate possibilities.
3063 \\[verilog-mark-defun] Mark function.
3064 \\[verilog-beg-of-defun] Move to beginning of current function.
3065 \\[verilog-end-of-defun] Move to end of current function.
3066 \\[verilog-label-be] Label matching begin ... end, fork ... join, etc statements.
3067
3068 \\[verilog-comment-region] Put marked area in a comment.
3069 \\[verilog-uncomment-region] Uncomment an area commented with \\[verilog-comment-region].
3070 \\[verilog-insert-block] Insert begin ... end.
3071 \\[verilog-star-comment] Insert /* ... */.
3072
3073 \\[verilog-sk-always] Insert an always @(AS) begin .. end block.
3074 \\[verilog-sk-begin] Insert a begin .. end block.
3075 \\[verilog-sk-case] Insert a case block, prompting for details.
3076 \\[verilog-sk-for] Insert a for (...) begin .. end block, prompting for details.
3077 \\[verilog-sk-generate] Insert a generate .. endgenerate block.
3078 \\[verilog-sk-header] Insert a header block at the top of file.
3079 \\[verilog-sk-initial] Insert an initial begin .. end block.
3080 \\[verilog-sk-fork] Insert a fork begin .. end .. join block.
3081 \\[verilog-sk-module] Insert a module .. (/*AUTOARG*/);.. endmodule block.
3082 \\[verilog-sk-primitive] Insert a primitive .. (.. );.. endprimitive block.
3083 \\[verilog-sk-repeat] Insert a repeat (..) begin .. end block.
3084 \\[verilog-sk-specify] Insert a specify .. endspecify block.
3085 \\[verilog-sk-task] Insert a task .. begin .. end endtask block.
3086 \\[verilog-sk-while] Insert a while (...) begin .. end block, prompting for details.
3087 \\[verilog-sk-casex] Insert a casex (...) item: begin.. end endcase block, prompting for details.
3088 \\[verilog-sk-casez] Insert a casez (...) item: begin.. end endcase block, prompting for details.
3089 \\[verilog-sk-if] Insert an if (..) begin .. end block.
3090 \\[verilog-sk-else-if] Insert an else if (..) begin .. end block.
3091 \\[verilog-sk-comment] Insert a comment block.
3092 \\[verilog-sk-assign] Insert an assign .. = ..; statement.
3093 \\[verilog-sk-function] Insert a function .. begin .. end endfunction block.
3094 \\[verilog-sk-input] Insert an input declaration, prompting for details.
3095 \\[verilog-sk-output] Insert an output declaration, prompting for details.
3096 \\[verilog-sk-state-machine] Insert a state machine definition, prompting for details.
3097 \\[verilog-sk-inout] Insert an inout declaration, prompting for details.
3098 \\[verilog-sk-wire] Insert a wire declaration, prompting for details.
3099 \\[verilog-sk-reg] Insert a register declaration, prompting for details.
3100 \\[verilog-sk-define-signal] Define signal under point as a register at the top of the module.
3101
3102 All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
3103 Key bindings specific to `verilog-mode-map' are:
3104
3105 \\{verilog-mode-map}"
3106 (interactive)
3107 (kill-all-local-variables)
3108 (use-local-map verilog-mode-map)
3109 (setq major-mode 'verilog-mode)
3110 (setq mode-name "Verilog")
3111 (setq local-abbrev-table verilog-mode-abbrev-table)
3112 (set (make-local-variable 'beginning-of-defun-function)
3113 'verilog-beg-of-defun)
3114 (set (make-local-variable 'end-of-defun-function)
3115 'verilog-end-of-defun)
3116 (set-syntax-table verilog-mode-syntax-table)
3117 (make-local-variable 'indent-line-function)
3118 (setq indent-line-function 'verilog-indent-line-relative)
3119 (setq comment-indent-function 'verilog-comment-indent)
3120 (make-local-variable 'parse-sexp-ignore-comments)
3121 (setq parse-sexp-ignore-comments nil)
3122 (make-local-variable 'comment-start)
3123 (make-local-variable 'comment-end)
3124 (make-local-variable 'comment-multi-line)
3125 (make-local-variable 'comment-start-skip)
3126 (setq comment-start "// "
3127 comment-end ""
3128 comment-start-skip "/\\*+ *\\|// *"
3129 comment-multi-line nil)
3130 ;; Set up for compilation
3131 (setq verilog-which-tool 1)
3132 (setq verilog-tool 'verilog-linter)
3133 (verilog-set-compile-command)
3134 (when (boundp 'hack-local-variables-hook) ;; Also modify any file-local-variables
3135 (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
3136
3137 ;; Setting up menus
3138 (when (featurep 'xemacs)
3139 (easy-menu-add verilog-stmt-menu)
3140 (easy-menu-add verilog-menu)
3141 (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
3142
3143 ;; Stuff for GNU Emacs
3144 (set (make-local-variable 'font-lock-defaults)
3145 `((verilog-font-lock-keywords verilog-font-lock-keywords-1
3146 verilog-font-lock-keywords-2
3147 verilog-font-lock-keywords-3)
3148 nil nil nil
3149 ,(if (functionp 'syntax-ppss)
3150 ;; verilog-beg-of-defun uses syntax-ppss, and syntax-ppss uses
3151 ;; font-lock-beginning-of-syntax-function, so
3152 ;; font-lock-beginning-of-syntax-function, can't use
3153 ;; verilog-beg-of-defun.
3154 nil
3155 'verilog-beg-of-defun)))
3156 ;;------------------------------------------------------------
3157 ;; now hook in 'verilog-highlight-include-files (eldo-mode.el&spice-mode.el)
3158 ;; all buffer local:
3159 (unless noninteractive ;; Else can't see the result, and change hooks are slow
3160 (when (featurep 'xemacs)
3161 (make-local-hook 'font-lock-mode-hook)
3162 (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
3163 (make-local-hook 'after-change-functions))
3164 (add-hook 'font-lock-mode-hook 'verilog-highlight-buffer t t)
3165 (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-highlight-buffer t t) ; not in Emacs
3166 (add-hook 'after-change-functions 'verilog-highlight-region t t))
3167
3168 ;; Tell imenu how to handle Verilog.
3169 (make-local-variable 'imenu-generic-expression)
3170 (setq imenu-generic-expression verilog-imenu-generic-expression)
3171 ;; Tell which-func-modes that imenu knows about verilog
3172 (when (boundp 'which-function-modes)
3173 (add-to-list 'which-func-modes 'verilog-mode))
3174 ;; hideshow support
3175 (when (boundp 'hs-special-modes-alist)
3176 (unless (assq 'verilog-mode hs-special-modes-alist)
3177 (setq hs-special-modes-alist
3178 (cons '(verilog-mode-mode "\\<begin\\>" "\\<end\\>" nil
3179 verilog-forward-sexp-function)
3180 hs-special-modes-alist))))
3181
3182 ;; Stuff for autos
3183 (add-hook 'write-contents-hooks 'verilog-auto-save-check) ; already local
3184 (run-hooks 'verilog-mode-hook))
3185 \f
3186
3187 ;;
3188 ;; Electric functions
3189 ;;
3190 (defun electric-verilog-terminate-line (&optional arg)
3191 "Terminate line and indent next line.
3192 With optional ARG, remove existing end of line comments."
3193 (interactive)
3194 ;; before that see if we are in a comment
3195 (let ((state (save-excursion (verilog-syntax-ppss))))
3196 (cond
3197 ((nth 7 state) ; Inside // comment
3198 (if (eolp)
3199 (progn
3200 (delete-horizontal-space)
3201 (newline))
3202 (progn
3203 (newline)
3204 (insert "// ")
3205 (beginning-of-line)))
3206 (verilog-indent-line))
3207 ((nth 4 state) ; Inside any comment (hence /**/)
3208 (newline)
3209 (verilog-more-comment))
3210 ((eolp)
3211 ;; First, check if current line should be indented
3212 (if (save-excursion
3213 (delete-horizontal-space)
3214 (beginning-of-line)
3215 (skip-chars-forward " \t")
3216 (if (looking-at verilog-auto-end-comment-lines-re)
3217 (let ((indent-str (verilog-indent-line)))
3218 ;; Maybe we should set some endcomments
3219 (if verilog-auto-endcomments
3220 (verilog-set-auto-endcomments indent-str arg))
3221 (end-of-line)
3222 (delete-horizontal-space)
3223 (if arg
3224 ()
3225 (newline))
3226 nil)
3227 (progn
3228 (end-of-line)
3229 (delete-horizontal-space)
3230 't)))
3231 ;; see if we should line up assignments
3232 (progn
3233 (if (or (eq 'all verilog-auto-lineup)
3234 (eq 'assignments verilog-auto-lineup))
3235 (verilog-pretty-expr t "\\(<\\|:\\)?=" ))
3236 (newline))
3237 (forward-line 1))
3238 ;; Indent next line
3239 (if verilog-auto-indent-on-newline
3240 (verilog-indent-line)))
3241 (t
3242 (newline)))))
3243
3244 (defun electric-verilog-terminate-and-indent ()
3245 "Insert a newline and indent for the next statement."
3246 (interactive)
3247 (electric-verilog-terminate-line 1))
3248
3249 (defun electric-verilog-semi ()
3250 "Insert `;' character and reindent the line."
3251 (interactive)
3252 (verilog-insert-last-command-event)
3253
3254 (if (or (verilog-in-comment-or-string-p)
3255 (verilog-in-escaped-name-p))
3256 ()
3257 (save-excursion
3258 (beginning-of-line)
3259 (verilog-forward-ws&directives)
3260 (verilog-indent-line))
3261 (if (and verilog-auto-newline
3262 (not (verilog-parenthesis-depth)))
3263 (electric-verilog-terminate-line))))
3264
3265 (defun electric-verilog-semi-with-comment ()
3266 "Insert `;' character, reindent the line and indent for comment."
3267 (interactive)
3268 (insert "\;")
3269 (save-excursion
3270 (beginning-of-line)
3271 (verilog-indent-line))
3272 (indent-for-comment))
3273
3274 (defun electric-verilog-colon ()
3275 "Insert `:' and do all indentations except line indent on this line."
3276 (interactive)
3277 (verilog-insert-last-command-event)
3278 ;; Do nothing if within string.
3279 (if (or
3280 (verilog-within-string)
3281 (not (verilog-in-case-region-p)))
3282 ()
3283 (save-excursion
3284 (let ((p (point))
3285 (lim (progn (verilog-beg-of-statement) (point))))
3286 (goto-char p)
3287 (verilog-backward-case-item lim)
3288 (verilog-indent-line)))
3289 ;; (let ((verilog-tab-always-indent nil))
3290 ;; (verilog-indent-line))
3291 ))
3292
3293 ;;(defun electric-verilog-equal ()
3294 ;; "Insert `=', and do indentation if within block."
3295 ;; (interactive)
3296 ;; (verilog-insert-last-command-event)
3297 ;; Could auto line up expressions, but not yet
3298 ;; (if (eq (car (verilog-calculate-indent)) 'block)
3299 ;; (let ((verilog-tab-always-indent nil))
3300 ;; (verilog-indent-command)))
3301 ;; )
3302
3303 (defun electric-verilog-tick ()
3304 "Insert back-tick, and indent to column 0 if this is a CPP directive."
3305 (interactive)
3306 (verilog-insert-last-command-event)
3307 (save-excursion
3308 (if (verilog-in-directive-p)
3309 (verilog-indent-line))))
3310
3311 (defun electric-verilog-tab ()
3312 "Function called when TAB is pressed in Verilog mode."
3313 (interactive)
3314 ;; If verilog-tab-always-indent, indent the beginning of the line.
3315 (cond
3316 ;; The region is active, indent it.
3317 ((and (region-active-p)
3318 (not (eq (region-beginning) (region-end))))
3319 (indent-region (region-beginning) (region-end) nil))
3320 ((or verilog-tab-always-indent
3321 (save-excursion
3322 (skip-chars-backward " \t")
3323 (bolp)))
3324 (let* ((oldpnt (point))
3325 (boi-point
3326 (save-excursion
3327 (beginning-of-line)
3328 (skip-chars-forward " \t")
3329 (verilog-indent-line)
3330 (back-to-indentation)
3331 (point))))
3332 (if (< (point) boi-point)
3333 (back-to-indentation)
3334 (cond ((not verilog-tab-to-comment))
3335 ((not (eolp))
3336 (end-of-line))
3337 (t
3338 (indent-for-comment)
3339 (when (and (eolp) (= oldpnt (point)))
3340 ; kill existing comment
3341 (beginning-of-line)
3342 (re-search-forward comment-start-skip oldpnt 'move)
3343 (goto-char (match-beginning 0))
3344 (skip-chars-backward " \t")
3345 (kill-region (point) oldpnt)))))))
3346 (t (progn (insert "\t")))))
3347
3348 \f
3349
3350 ;;
3351 ;; Interactive functions
3352 ;;
3353
3354 (defun verilog-indent-buffer ()
3355 "Indent-region the entire buffer as Verilog code.
3356 To call this from the command line, see \\[verilog-batch-indent]."
3357 (interactive)
3358 (verilog-mode)
3359 (indent-region (point-min) (point-max) nil))
3360
3361 (defun verilog-insert-block ()
3362 "Insert Verilog begin ... end; block in the code with right indentation."
3363 (interactive)
3364 (verilog-indent-line)
3365 (insert "begin")
3366 (electric-verilog-terminate-line)
3367 (save-excursion
3368 (electric-verilog-terminate-line)
3369 (insert "end")
3370 (beginning-of-line)
3371 (verilog-indent-line)))
3372
3373 (defun verilog-star-comment ()
3374 "Insert Verilog star comment at point."
3375 (interactive)
3376 (verilog-indent-line)
3377 (insert "/*")
3378 (save-excursion
3379 (newline)
3380 (insert " */"))
3381 (newline)
3382 (insert " * "))
3383
3384 (defun verilog-insert-1 (fmt max)
3385 "Use format string FMT to insert integers 0 to MAX - 1.
3386 Inserts one integer per line, at the current column. Stops early
3387 if it reaches the end of the buffer."
3388 (let ((col (current-column))
3389 (n 0))
3390 (save-excursion
3391 (while (< n max)
3392 (insert (format fmt n))
3393 (forward-line 1)
3394 ;; Note that this function does not bother to check for lines
3395 ;; shorter than col.
3396 (if (eobp)
3397 (setq n max)
3398 (setq n (1+ n))
3399 (move-to-column col))))))
3400
3401 (defun verilog-insert-indices (max)
3402 "Insert a set of indices into a rectangle.
3403 The upper left corner is defined by point. Indices begin with 0
3404 and extend to the MAX - 1. If no prefix arg is given, the user
3405 is prompted for a value. The indices are surrounded by square
3406 brackets \[]. For example, the following code with the point
3407 located after the first 'a' gives:
3408
3409 a = b a[ 0] = b
3410 a = b a[ 1] = b
3411 a = b a[ 2] = b
3412 a = b a[ 3] = b
3413 a = b ==> insert-indices ==> a[ 4] = b
3414 a = b a[ 5] = b
3415 a = b a[ 6] = b
3416 a = b a[ 7] = b
3417 a = b a[ 8] = b"
3418
3419 (interactive "NMAX: ")
3420 (verilog-insert-1 "[%3d]" max))
3421
3422 (defun verilog-generate-numbers (max)
3423 "Insert a set of generated numbers into a rectangle.
3424 The upper left corner is defined by point. The numbers are padded to three
3425 digits, starting with 000 and extending to (MAX - 1). If no prefix argument
3426 is supplied, then the user is prompted for the MAX number. Consider the
3427 following code fragment:
3428
3429 buf buf buf buf000
3430 buf buf buf buf001
3431 buf buf buf buf002
3432 buf buf buf buf003
3433 buf buf ==> generate-numbers ==> buf buf004
3434 buf buf buf buf005
3435 buf buf buf buf006
3436 buf buf buf buf007
3437 buf buf buf buf008"
3438
3439 (interactive "NMAX: ")
3440 (verilog-insert-1 "%3.3d" max))
3441
3442 (defun verilog-mark-defun ()
3443 "Mark the current Verilog function (or procedure).
3444 This puts the mark at the end, and point at the beginning."
3445 (interactive)
3446 (if (featurep 'xemacs)
3447 (progn
3448 (push-mark (point))
3449 (verilog-end-of-defun)
3450 (push-mark (point))
3451 (verilog-beg-of-defun)
3452 (if (fboundp 'zmacs-activate-region)
3453 (zmacs-activate-region)))
3454 (mark-defun)))
3455
3456 (defun verilog-comment-region (start end)
3457 ; checkdoc-params: (start end)
3458 "Put the region into a Verilog comment.
3459 The comments that are in this area are \"deformed\":
3460 `*)' becomes `!(*' and `}' becomes `!{'.
3461 These deformed comments are returned to normal if you use
3462 \\[verilog-uncomment-region] to undo the commenting.
3463
3464 The commented area starts with `verilog-exclude-str-start', and ends with
3465 `verilog-exclude-str-end'. But if you change these variables,
3466 \\[verilog-uncomment-region] won't recognize the comments."
3467 (interactive "r")
3468 (save-excursion
3469 ;; Insert start and endcomments
3470 (goto-char end)
3471 (if (and (save-excursion (skip-chars-forward " \t") (eolp))
3472 (not (save-excursion (skip-chars-backward " \t") (bolp))))
3473 (forward-line 1)
3474 (beginning-of-line))
3475 (insert verilog-exclude-str-end)
3476 (setq end (point))
3477 (newline)
3478 (goto-char start)
3479 (beginning-of-line)
3480 (insert verilog-exclude-str-start)
3481 (newline)
3482 ;; Replace end-comments within commented area
3483 (goto-char end)
3484 (save-excursion
3485 (while (re-search-backward "\\*/" start t)
3486 (replace-match "*-/" t t)))
3487 (save-excursion
3488 (let ((s+1 (1+ start)))
3489 (while (re-search-backward "/\\*" s+1 t)
3490 (replace-match "/-*" t t))))))
3491
3492 (defun verilog-uncomment-region ()
3493 "Uncomment a commented area; change deformed comments back to normal.
3494 This command does nothing if the pointer is not in a commented
3495 area. See also `verilog-comment-region'."
3496 (interactive)
3497 (save-excursion
3498 (let ((start (point))
3499 (end (point)))
3500 ;; Find the boundaries of the comment
3501 (save-excursion
3502 (setq start (progn (search-backward verilog-exclude-str-start nil t)
3503 (point)))
3504 (setq end (progn (search-forward verilog-exclude-str-end nil t)
3505 (point))))
3506 ;; Check if we're really inside a comment
3507 (if (or (equal start (point)) (<= end (point)))
3508 (message "Not standing within commented area.")
3509 (progn
3510 ;; Remove endcomment
3511 (goto-char end)
3512 (beginning-of-line)
3513 (let ((pos (point)))
3514 (end-of-line)
3515 (delete-region pos (1+ (point))))
3516 ;; Change comments back to normal
3517 (save-excursion
3518 (while (re-search-backward "\\*-/" start t)
3519 (replace-match "*/" t t)))
3520 (save-excursion
3521 (while (re-search-backward "/-\\*" start t)
3522 (replace-match "/*" t t)))
3523 ;; Remove start comment
3524 (goto-char start)
3525 (beginning-of-line)
3526 (let ((pos (point)))
3527 (end-of-line)
3528 (delete-region pos (1+ (point)))))))))
3529
3530 (defun verilog-beg-of-defun ()
3531 "Move backward to the beginning of the current function or procedure."
3532 (interactive)
3533 (verilog-re-search-backward verilog-defun-re nil 'move))
3534
3535 (defun verilog-end-of-defun ()
3536 "Move forward to the end of the current function or procedure."
3537 (interactive)
3538 (verilog-re-search-forward verilog-end-defun-re nil 'move))
3539
3540 (defun verilog-get-beg-of-defun (&optional warn)
3541 (save-excursion
3542 (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
3543 (point))
3544 (t
3545 (error "%s: Can't find module beginning" (verilog-point-text))
3546 (point-max)))))
3547 (defun verilog-get-end-of-defun (&optional warn)
3548 (save-excursion
3549 (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
3550 (point))
3551 (t
3552 (error "%s: Can't find endmodule" (verilog-point-text))
3553 (point-max)))))
3554
3555 (defun verilog-label-be (&optional arg)
3556 "Label matching begin ... end, fork ... join and case ... endcase statements.
3557 With ARG, first kill any existing labels."
3558 (interactive)
3559 (let ((cnt 0)
3560 (oldpos (point))
3561 (b (progn
3562 (verilog-beg-of-defun)
3563 (point-marker)))
3564 (e (progn
3565 (verilog-end-of-defun)
3566 (point-marker))))
3567 (goto-char (marker-position b))
3568 (if (> (- e b) 200)
3569 (message "Relabeling module..."))
3570 (while (and
3571 (> (marker-position e) (point))
3572 (verilog-re-search-forward
3573 (concat
3574 "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
3575 "\\|\\(`endif\\)\\|\\(`else\\)")
3576 nil 'move))
3577 (goto-char (match-beginning 0))
3578 (let ((indent-str (verilog-indent-line)))
3579 (verilog-set-auto-endcomments indent-str 't)
3580 (end-of-line)
3581 (delete-horizontal-space))
3582 (setq cnt (1+ cnt))
3583 (if (= 9 (% cnt 10))
3584 (message "%d..." cnt)))
3585 (goto-char oldpos)
3586 (if (or
3587 (> (- e b) 200)
3588 (> cnt 20))
3589 (message "%d lines auto commented" cnt))))
3590
3591 (defun verilog-beg-of-statement ()
3592 "Move backward to beginning of statement."
3593 (interactive)
3594 ;; Move back token by token until we see the end
3595 ;; of some ealier line.
3596 (let (h)
3597 (while
3598 ;; If the current point does not begin a new
3599 ;; statement, as in the character ahead of us is a ';', or SOF
3600 ;; or the string after us unambiguously starts a statement,
3601 ;; or the token before us unambiguously ends a statement,
3602 ;; then move back a token and test again.
3603 (not (or
3604 ;; stop if beginning of buffer
3605 (bolp)
3606 ;; stop if we find a ;
3607 (= (preceding-char) ?\;)
3608 ;; stop if we see a named coverpoint
3609 (looking-at "\\w+\\W*:\\W*\\(coverpoint\\|cross\\|constraint\\)")
3610 ;; keep going if we are in the middle of a word
3611 (not (or (looking-at "\\<") (forward-word -1)))
3612 ;; stop if we see an assertion (perhaps labled)
3613 (and
3614 (looking-at "\\(\\<\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(\\<assert\\>\\)")
3615 (progn
3616 (setq h (point))
3617 (save-excursion
3618 (verilog-backward-token)
3619 (if (looking-at verilog-label-re)
3620 (setq h (point))))
3621 (goto-char h)))
3622 ;; stop if we see a complete reg, perhaps an extended one
3623 (and
3624 (looking-at verilog-complete-reg)
3625 (let* ((p (point)))
3626 (while (and (looking-at verilog-extended-complete-re)
3627 (progn (setq p (point))
3628 (verilog-backward-token)
3629 (/= p (point)))))
3630 (goto-char p)))
3631 ;; stop if we see a complete reg (previous found extended ones)
3632 (looking-at verilog-basic-complete-re)
3633 ;; stop if previous token is an ender
3634 (save-excursion
3635 (verilog-backward-token)
3636 (or
3637 (looking-at verilog-end-block-re)
3638 (looking-at verilog-preprocessor-re))))) ;; end of test
3639 (verilog-backward-syntactic-ws)
3640 (verilog-backward-token))
3641 ;; Now point is where the previous line ended.
3642 (verilog-forward-syntactic-ws)))
3643
3644 (defun verilog-beg-of-statement-1 ()
3645 "Move backward to beginning of statement."
3646 (interactive)
3647 (if (verilog-in-comment-p)
3648 (verilog-backward-syntactic-ws))
3649 (let ((pt (point)))
3650 (catch 'done
3651 (while (not (looking-at verilog-complete-reg))
3652 (setq pt (point))
3653 (verilog-backward-syntactic-ws)
3654 (if (or (bolp)
3655 (= (preceding-char) ?\;)
3656 (save-excursion
3657 (verilog-backward-token)
3658 (looking-at verilog-ends-re)))
3659 (progn
3660 (goto-char pt)
3661 (throw 'done t))
3662 (verilog-backward-token))))
3663 (verilog-forward-syntactic-ws)))
3664 ;
3665 ; (while (and
3666 ; (not (looking-at verilog-complete-reg))
3667 ; (not (bolp))
3668 ; (not (= (preceding-char) ?\;)))
3669 ; (verilog-backward-token)
3670 ; (verilog-backward-syntactic-ws)
3671 ; (setq pt (point)))
3672 ; (goto-char pt)
3673 ; ;(verilog-forward-syntactic-ws)
3674
3675 (defun verilog-end-of-statement ()
3676 "Move forward to end of current statement."
3677 (interactive)
3678 (let ((nest 0) pos)
3679 (cond
3680 ((verilog-in-directive-p)
3681 (forward-line 1)
3682 (backward-char 1))
3683
3684 ((looking-at verilog-beg-block-re)
3685 (verilog-forward-sexp))
3686
3687 ((equal (char-after) ?\})
3688 (forward-char))
3689
3690 ;; Skip to end of statement
3691 ((condition-case nil
3692 (setq pos
3693 (catch 'found
3694 (while t
3695 (forward-sexp 1)
3696 (verilog-skip-forward-comment-or-string)
3697 (if (eolp)
3698 (forward-line 1))
3699 (cond ((looking-at "[ \t]*;")
3700 (skip-chars-forward "^;")
3701 (forward-char 1)
3702 (throw 'found (point)))
3703 ((save-excursion
3704 (forward-sexp -1)
3705 (looking-at verilog-beg-block-re))
3706 (goto-char (match-beginning 0))
3707 (throw 'found nil))
3708 ((looking-at "[ \t]*)")
3709 (throw 'found (point)))
3710 ((eobp)
3711 (throw 'found (point)))
3712 )))
3713
3714 )
3715 (error nil))
3716 (if (not pos)
3717 ;; Skip a whole block
3718 (catch 'found
3719 (while t
3720 (verilog-re-search-forward verilog-end-statement-re nil 'move)
3721 (setq nest (if (match-end 1)
3722 (1+ nest)
3723 (1- nest)))
3724 (cond ((eobp)
3725 (throw 'found (point)))
3726 ((= 0 nest)
3727 (throw 'found (verilog-end-of-statement))))))
3728 pos)))))
3729
3730 (defun verilog-in-case-region-p ()
3731 "Return true if in a case region.
3732 More specifically, point @ in the line foo : @ begin"
3733 (interactive)
3734 (save-excursion
3735 (if (and
3736 (progn (verilog-forward-syntactic-ws)
3737 (looking-at "\\<begin\\>"))
3738 (progn (verilog-backward-syntactic-ws)
3739 (= (preceding-char) ?\:)))
3740 (catch 'found
3741 (let ((nest 1))
3742 (while t
3743 (verilog-re-search-backward
3744 (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
3745 "\\(\\<endcase\\>\\)\\>")
3746 nil 'move)
3747 (cond
3748 ((match-end 3)
3749 (setq nest (1+ nest)))
3750 ((match-end 2)
3751 (if (= nest 1)
3752 (throw 'found 1))
3753 (setq nest (1- nest)))
3754 (t
3755 (throw 'found (= nest 0)))))))
3756 nil)))
3757 (defun verilog-backward-up-list (arg)
3758 "Like backward-up-list, but deal with comments."
3759 (let (saved-psic parse-sexp-ignore-comments)
3760 (setq parse-sexp-ignore-comments 1)
3761 (backward-up-list arg)
3762 (setq parse-sexp-ignore-comments saved-psic)
3763 ))
3764
3765 (defun verilog-in-struct-region-p ()
3766 "Return true if in a struct region.
3767 More specifically, in a list after a struct|union keyword."
3768 (interactive)
3769 (save-excursion
3770 (let* ((state (verilog-syntax-ppss))
3771 (depth (nth 0 state)))
3772 (if depth
3773 (progn (verilog-backward-up-list depth)
3774 (verilog-beg-of-statement)
3775 (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>"))))))
3776
3777 (defun verilog-in-generate-region-p ()
3778 "Return true if in a generate region.
3779 More specifically, after a generate and before an endgenerate."
3780 (interactive)
3781 (let ((nest 1))
3782 (save-excursion
3783 (catch 'done
3784 (while (and
3785 (/= nest 0)
3786 (verilog-re-search-backward
3787 "\\<\\(module\\)\\|\\(generate\\)\\|\\(endgenerate\\)\\>" nil 'move)
3788 (cond
3789 ((match-end 1) ; module - we have crawled out
3790 (throw 'done 1))
3791 ((match-end 2) ; generate
3792 (setq nest (1- nest)))
3793 ((match-end 3) ; endgenerate
3794 (setq nest (1+ nest))))))))
3795 (= nest 0) )) ; return nest
3796
3797 (defun verilog-in-fork-region-p ()
3798 "Return true if between a fork and join."
3799 (interactive)
3800 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
3801 (nest 1))
3802 (save-excursion
3803 (while (and
3804 (/= nest 0)
3805 (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
3806 (cond
3807 ((match-end 1) ; fork
3808 (setq nest (1- nest)))
3809 ((match-end 2) ; join
3810 (setq nest (1+ nest)))))))
3811 (= nest 0) )) ; return nest
3812
3813 (defun verilog-backward-case-item (lim)
3814 "Skip backward to nearest enclosing case item.
3815 Limit search to point LIM."
3816 (interactive)
3817 (let ((str 'nil)
3818 (lim1
3819 (progn
3820 (save-excursion
3821 (verilog-re-search-backward verilog-endcomment-reason-re
3822 lim 'move)
3823 (point)))))
3824 ;; Try to find the real :
3825 (if (save-excursion (search-backward ":" lim1 t))
3826 (let ((colon 0)
3827 b e )
3828 (while
3829 (and
3830 (< colon 1)
3831 (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
3832 lim1 'move))
3833 (cond
3834 ((match-end 1) ;; [
3835 (setq colon (1+ colon))
3836 (if (>= colon 0)
3837 (error "%s: unbalanced [" (verilog-point-text))))
3838 ((match-end 2) ;; ]
3839 (setq colon (1- colon)))
3840
3841 ((match-end 3) ;; :
3842 (setq colon (1+ colon)))))
3843 ;; Skip back to beginning of case item
3844 (skip-chars-backward "\t ")
3845 (verilog-skip-backward-comment-or-string)
3846 (setq e (point))
3847 (setq b
3848 (progn
3849 (if
3850 (verilog-re-search-backward
3851 "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
3852 (progn
3853 (cond
3854 ((match-end 1)
3855 (goto-char (match-end 1))
3856 (verilog-forward-ws&directives)
3857 (if (looking-at "(")
3858 (progn
3859 (forward-sexp)
3860 (verilog-forward-ws&directives)))
3861 (point))
3862 (t
3863 (goto-char (match-end 0))
3864 (verilog-forward-ws&directives)
3865 (point))))
3866 (error "Malformed case item"))))
3867 (setq str (buffer-substring b e))
3868 (if
3869 (setq e
3870 (string-match
3871 "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3872 (setq str (concat (substring str 0 e) "...")))
3873 str)
3874 'nil)))
3875 \f
3876
3877 ;;
3878 ;; Other functions
3879 ;;
3880
3881 (defun verilog-kill-existing-comment ()
3882 "Kill auto comment on this line."
3883 (save-excursion
3884 (let* (
3885 (e (progn
3886 (end-of-line)
3887 (point)))
3888 (b (progn
3889 (beginning-of-line)
3890 (search-forward "//" e t))))
3891 (if b
3892 (delete-region (- b 2) e)))))
3893
3894 (defconst verilog-directive-nest-re
3895 (concat "\\(`else\\>\\)\\|"
3896 "\\(`endif\\>\\)\\|"
3897 "\\(`if\\>\\)\\|"
3898 "\\(`ifdef\\>\\)\\|"
3899 "\\(`ifndef\\>\\)\\|"
3900 "\\(`elsif\\>\\)"))
3901 (defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
3902 "Add ending comment with given INDENT-STR.
3903 With KILL-EXISTING-COMMENT, remove what was there before.
3904 Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
3905 Insert `// case expr ' if this line ends a case block.
3906 Insert `// ifdef FOO ' if this line ends code conditional on FOO.
3907 Insert `// NAME ' if this line ends a function, task, module,
3908 primitive or interface named NAME."
3909 (save-excursion
3910 (cond
3911 (; Comment close preprocessor directives
3912 (and
3913 (looking-at "\\(`endif\\)\\|\\(`else\\)")
3914 (or kill-existing-comment
3915 (not (save-excursion
3916 (end-of-line)
3917 (search-backward "//" (point-at-bol) t)))))
3918 (let ((nest 1) b e
3919 m
3920 (else (if (match-end 2) "!" " ")))
3921 (end-of-line)
3922 (if kill-existing-comment
3923 (verilog-kill-existing-comment))
3924 (delete-horizontal-space)
3925 (save-excursion
3926 (backward-sexp 1)
3927 (while (and (/= nest 0)
3928 (verilog-re-search-backward verilog-directive-nest-re nil 'move))
3929 (cond
3930 ((match-end 1) ; `else
3931 (if (= nest 1)
3932 (setq else "!")))
3933 ((match-end 2) ; `endif
3934 (setq nest (1+ nest)))
3935 ((match-end 3) ; `if
3936 (setq nest (1- nest)))
3937 ((match-end 4) ; `ifdef
3938 (setq nest (1- nest)))
3939 ((match-end 5) ; `ifndef
3940 (setq nest (1- nest)))
3941 ((match-end 6) ; `elsif
3942 (if (= nest 1)
3943 (progn
3944 (setq else "!")
3945 (setq nest 0))))))
3946 (if (match-end 0)
3947 (setq
3948 m (buffer-substring
3949 (match-beginning 0)
3950 (match-end 0))
3951 b (progn
3952 (skip-chars-forward "^ \t")
3953 (verilog-forward-syntactic-ws)
3954 (point))
3955 e (progn
3956 (skip-chars-forward "a-zA-Z0-9_")
3957 (point)))))
3958 (if b
3959 (if (> (count-lines (point) b) verilog-minimum-comment-distance)
3960 (insert (concat " // " else m " " (buffer-substring b e))))
3961 (progn
3962 (insert " // unmatched `else, `elsif or `endif")
3963 (ding 't)))))
3964
3965 (; Comment close case/class/function/task/module and named block
3966 (and (looking-at "\\<end")
3967 (or kill-existing-comment
3968 (not (save-excursion
3969 (end-of-line)
3970 (search-backward "//" (point-at-bol) t)))))
3971 (let ((type (car indent-str)))
3972 (unless (eq type 'declaration)
3973 (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
3974 (if (looking-at verilog-end-block-ordered-re)
3975 (cond
3976 (;- This is a case block; search back for the start of this case
3977 (match-end 1) ;; of verilog-end-block-ordered-re
3978
3979 (let ((err 't)
3980 (str "UNMATCHED!!"))
3981 (save-excursion
3982 (verilog-leap-to-head)
3983 (cond
3984 ((looking-at "\\<randcase\\>")
3985 (setq str "randcase")
3986 (setq err nil))
3987 ((looking-at "\\(\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?\\)")
3988 (goto-char (match-end 0))
3989 (setq str (concat (match-string 0) " " (verilog-get-expr)))
3990 (setq err nil))
3991 ))
3992 (end-of-line)
3993 (if kill-existing-comment
3994 (verilog-kill-existing-comment))
3995 (delete-horizontal-space)
3996 (insert (concat " // " str ))
3997 (if err (ding 't))))
3998
3999 (;- This is a begin..end block
4000 (match-end 2) ;; of verilog-end-block-ordered-re
4001 (let ((str " // UNMATCHED !!")
4002 (err 't)
4003 (here (point))
4004 there
4005 cntx)
4006 (save-excursion
4007 (verilog-leap-to-head)
4008 (setq there (point))
4009 (if (not (match-end 0))
4010 (progn
4011 (goto-char here)
4012 (end-of-line)
4013 (if kill-existing-comment
4014 (verilog-kill-existing-comment))
4015 (delete-horizontal-space)
4016 (insert str)
4017 (ding 't))
4018 (let ((lim
4019 (save-excursion (verilog-beg-of-defun) (point)))
4020 (here (point)))
4021 (cond
4022 (;-- handle named block differently
4023 (looking-at verilog-named-block-re)
4024 (search-forward ":")
4025 (setq there (point))
4026 (setq str (verilog-get-expr))
4027 (setq err nil)
4028 (setq str (concat " // block: " str )))
4029
4030 ((verilog-in-case-region-p) ;-- handle case item differently
4031 (goto-char here)
4032 (setq str (verilog-backward-case-item lim))
4033 (setq there (point))
4034 (setq err nil)
4035 (setq str (concat " // case: " str )))
4036
4037 (;- try to find "reason" for this begin
4038 (cond
4039 (;
4040 (eq here (progn
4041 ;; (verilog-backward-token)
4042 (verilog-beg-of-statement)
4043 (point)))
4044 (setq err nil)
4045 (setq str ""))
4046 ((looking-at verilog-endcomment-reason-re)
4047 (setq there (match-end 0))
4048 (setq cntx (concat (match-string 0) " "))
4049 (cond
4050 (;- begin
4051 (match-end 1)
4052 (setq err nil)
4053 (save-excursion
4054 (if (and (verilog-continued-line)
4055 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
4056 (progn
4057 (goto-char (match-end 0))
4058 (setq there (point))
4059 (setq str
4060 (concat " // " (match-string 0) " " (verilog-get-expr))))
4061 (setq str ""))))
4062
4063 (;- else
4064 (match-end 2)
4065 (let ((nest 0)
4066 ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
4067 (catch 'skip
4068 (while (verilog-re-search-backward reg nil 'move)
4069 (cond
4070 ((match-end 1) ; begin
4071 (setq nest (1- nest)))
4072 ((match-end 2) ; end
4073 (setq nest (1+ nest)))
4074 ((match-end 3)
4075 (if (= 0 nest)
4076 (progn
4077 (goto-char (match-end 0))
4078 (setq there (point))
4079 (setq err nil)
4080 (setq str (verilog-get-expr))
4081 (setq str (concat " // else: !if" str ))
4082 (throw 'skip 1))))
4083 ((match-end 4)
4084 (if (= 0 nest)
4085 (progn
4086 (goto-char (match-end 0))
4087 (setq there (point))
4088 (setq err nil)
4089 (setq str (verilog-get-expr))
4090 (setq str (concat " // else: !assert " str ))
4091 (throw 'skip 1)))))))))
4092 (;- end else
4093 (match-end 3)
4094 (goto-char there)
4095 (let ((nest 0)
4096 (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
4097 (catch 'skip
4098 (while (verilog-re-search-backward reg nil 'move)
4099 (cond
4100 ((match-end 1) ; begin
4101 (setq nest (1- nest)))
4102 ((match-end 2) ; end
4103 (setq nest (1+ nest)))
4104 ((match-end 3)
4105 (if (= 0 nest)
4106 (progn
4107 (goto-char (match-end 0))
4108 (setq there (point))
4109 (setq err nil)
4110 (setq str (verilog-get-expr))
4111 (setq str (concat " // else: !if" str ))
4112 (throw 'skip 1))))
4113 ((match-end 4)
4114 (if (= 0 nest)
4115 (progn
4116 (goto-char (match-end 0))
4117 (setq there (point))
4118 (setq err nil)
4119 (setq str (verilog-get-expr))
4120 (setq str (concat " // else: !assert " str ))
4121 (throw 'skip 1)))))))))
4122
4123 (; always_comb, always_ff, always_latch
4124 (or (match-end 4) (match-end 5) (match-end 6))
4125 (goto-char (match-end 0))
4126 (setq there (point))
4127 (setq err nil)
4128 (setq str (concat " // " cntx )))
4129
4130 (;- task/function/initial et cetera
4131 t
4132 (match-end 0)
4133 (goto-char (match-end 0))
4134 (setq there (point))
4135 (setq err nil)
4136 (setq str (concat " // " cntx (verilog-get-expr))))
4137
4138 (;-- otherwise...
4139 (setq str " // auto-endcomment confused "))))
4140
4141 ((and
4142 (verilog-in-case-region-p) ;-- handle case item differently
4143 (progn
4144 (setq there (point))
4145 (goto-char here)
4146 (setq str (verilog-backward-case-item lim))))
4147 (setq err nil)
4148 (setq str (concat " // case: " str )))
4149
4150 ((verilog-in-fork-region-p)
4151 (setq err nil)
4152 (setq str " // fork branch" ))
4153
4154 ((looking-at "\\<end\\>")
4155 ;; HERE
4156 (forward-word 1)
4157 (verilog-forward-syntactic-ws)
4158 (setq err nil)
4159 (setq str (verilog-get-expr))
4160 (setq str (concat " // " cntx str )))
4161
4162 ))))
4163 (goto-char here)
4164 (end-of-line)
4165 (if kill-existing-comment
4166 (verilog-kill-existing-comment))
4167 (delete-horizontal-space)
4168 (if (or err
4169 (> (count-lines here there) verilog-minimum-comment-distance))
4170 (insert str))
4171 (if err (ding 't))
4172 ))))
4173 (;- this is endclass, which can be nested
4174 (match-end 11) ;; of verilog-end-block-ordered-re
4175 ;;(goto-char there)
4176 (let ((nest 0)
4177 (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
4178 string)
4179 (save-excursion
4180 (catch 'skip
4181 (while (verilog-re-search-backward reg nil 'move)
4182 (cond
4183 ((match-end 3) ; endclass
4184 (ding 't)
4185 (setq string "unmatched endclass")
4186 (throw 'skip 1))
4187
4188 ((match-end 2) ; endclass
4189 (setq nest (1+ nest)))
4190
4191 ((match-end 1) ; class
4192 (setq nest (1- nest))
4193 (if (< nest 0)
4194 (progn
4195 (goto-char (match-end 0))
4196 (let (b e)
4197 (setq b (progn
4198 (skip-chars-forward "^ \t")
4199 (verilog-forward-ws&directives)
4200 (point))
4201 e (progn
4202 (skip-chars-forward "a-zA-Z0-9_")
4203 (point)))
4204 (setq string (buffer-substring b e)))
4205 (throw 'skip 1))))
4206 ))))
4207 (end-of-line)
4208 (insert (concat " // " string ))))
4209
4210 (;- this is end{function,generate,task,module,primitive,table,generate}
4211 ;- which can not be nested.
4212 t
4213 (let (string reg (name-re nil))
4214 (end-of-line)
4215 (if kill-existing-comment
4216 (save-match-data
4217 (verilog-kill-existing-comment)))
4218 (delete-horizontal-space)
4219 (backward-sexp)
4220 (cond
4221 ((match-end 5) ;; of verilog-end-block-ordered-re
4222 (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
4223 (setq name-re "\\w+\\s-*(")
4224 )
4225 ((match-end 6) ;; of verilog-end-block-ordered-re
4226 (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
4227 ((match-end 7) ;; of verilog-end-block-ordered-re
4228 (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
4229 ((match-end 8) ;; of verilog-end-block-ordered-re
4230 (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4231 ((match-end 9) ;; of verilog-end-block-ordered-re
4232 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
4233 ((match-end 10) ;; of verilog-end-block-ordered-re
4234 (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4235 ((match-end 11) ;; of verilog-end-block-ordered-re
4236 (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4237 ((match-end 12) ;; of verilog-end-block-ordered-re
4238 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4239 ((match-end 13) ;; of verilog-end-block-ordered-re
4240 (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4241 ((match-end 14) ;; of verilog-end-block-ordered-re
4242 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4243 ((match-end 15) ;; of verilog-end-block-ordered-re
4244 (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
4245
4246 (t (error "Problem in verilog-set-auto-endcomments")))
4247 (let (b e)
4248 (save-excursion
4249 (verilog-re-search-backward reg nil 'move)
4250 (cond
4251 ((match-end 1)
4252 (setq b (progn
4253 (skip-chars-forward "^ \t")
4254 (verilog-forward-ws&directives)
4255 (if (looking-at "static\\|automatic")
4256 (progn
4257 (goto-char (match-end 0))
4258 (verilog-forward-ws&directives)))
4259 (if (and name-re (verilog-re-search-forward name-re nil 'move))
4260 (progn
4261 (goto-char (match-beginning 0))
4262 (verilog-forward-ws&directives)))
4263 (point))
4264 e (progn
4265 (skip-chars-forward "a-zA-Z0-9_")
4266 (point)))
4267 (setq string (buffer-substring b e)))
4268 (t
4269 (ding 't)
4270 (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
4271 (end-of-line)
4272 (insert (concat " // " string )))
4273 ))))))))))
4274
4275 (defun verilog-get-expr()
4276 "Grab expression at point, e.g, case ( a | b & (c ^d))."
4277 (let* ((b (progn
4278 (verilog-forward-syntactic-ws)
4279 (skip-chars-forward " \t")
4280 (point)))
4281 (e (let ((par 1))
4282 (cond
4283 ((looking-at "@")
4284 (forward-char 1)
4285 (verilog-forward-syntactic-ws)
4286 (if (looking-at "(")
4287 (progn
4288 (forward-char 1)
4289 (while (and (/= par 0)
4290 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4291 (cond
4292 ((match-end 1)
4293 (setq par (1+ par)))
4294 ((match-end 2)
4295 (setq par (1- par)))))))
4296 (point))
4297 ((looking-at "(")
4298 (forward-char 1)
4299 (while (and (/= par 0)
4300 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4301 (cond
4302 ((match-end 1)
4303 (setq par (1+ par)))
4304 ((match-end 2)
4305 (setq par (1- par)))))
4306 (point))
4307 ((looking-at "\\[")
4308 (forward-char 1)
4309 (while (and (/= par 0)
4310 (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
4311 (cond
4312 ((match-end 1)
4313 (setq par (1+ par)))
4314 ((match-end 2)
4315 (setq par (1- par)))))
4316 (verilog-forward-syntactic-ws)
4317 (skip-chars-forward "^ \t\n\f")
4318 (point))
4319 ((looking-at "/[/\\*]")
4320 b)
4321 ('t
4322 (skip-chars-forward "^: \t\n\f")
4323 (point)))))
4324 (str (buffer-substring b e)))
4325 (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
4326 (setq str (concat (substring str 0 e) "...")))
4327 str))
4328
4329 (defun verilog-expand-vector ()
4330 "Take a signal vector on the current line and expand it to multiple lines.
4331 Useful for creating tri's and other expanded fields."
4332 (interactive)
4333 (verilog-expand-vector-internal "[" "]"))
4334
4335 (defun verilog-expand-vector-internal (bra ket)
4336 "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
4337 (save-excursion
4338 (forward-line 0)
4339 (let ((signal-string (buffer-substring (point)
4340 (progn
4341 (end-of-line) (point)))))
4342 (if (string-match
4343 (concat "\\(.*\\)"
4344 (regexp-quote bra)
4345 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
4346 (regexp-quote ket)
4347 "\\(.*\\)$") signal-string)
4348 (let* ((sig-head (match-string 1 signal-string))
4349 (vec-start (string-to-number (match-string 2 signal-string)))
4350 (vec-end (if (= (match-beginning 3) (match-end 3))
4351 vec-start
4352 (string-to-number
4353 (substring signal-string (1+ (match-beginning 3))
4354 (match-end 3)))))
4355 (vec-range
4356 (if (= (match-beginning 4) (match-end 4))
4357 1
4358 (string-to-number
4359 (substring signal-string (+ 2 (match-beginning 4))
4360 (match-end 4)))))
4361 (sig-tail (match-string 5 signal-string))
4362 vec)
4363 ;; Decode vectors
4364 (setq vec nil)
4365 (if (< vec-range 0)
4366 (let ((tmp vec-start))
4367 (setq vec-start vec-end
4368 vec-end tmp
4369 vec-range (- vec-range))))
4370 (if (< vec-end vec-start)
4371 (while (<= vec-end vec-start)
4372 (setq vec (append vec (list vec-start)))
4373 (setq vec-start (- vec-start vec-range)))
4374 (while (<= vec-start vec-end)
4375 (setq vec (append vec (list vec-start)))
4376 (setq vec-start (+ vec-start vec-range))))
4377 ;;
4378 ;; Delete current line
4379 (delete-region (point) (progn (forward-line 0) (point)))
4380 ;;
4381 ;; Expand vector
4382 (while vec
4383 (insert (concat sig-head bra
4384 (int-to-string (car vec)) ket sig-tail "\n"))
4385 (setq vec (cdr vec)))
4386 (delete-char -1)
4387 ;;
4388 )))))
4389
4390 (defun verilog-strip-comments ()
4391 "Strip all comments from the Verilog code."
4392 (interactive)
4393 (goto-char (point-min))
4394 (while (re-search-forward "//" nil t)
4395 (if (verilog-within-string)
4396 (re-search-forward "\"" nil t)
4397 (if (verilog-in-star-comment-p)
4398 (re-search-forward "\*/" nil t)
4399 (let ((bpt (- (point) 2)))
4400 (end-of-line)
4401 (delete-region bpt (point))))))
4402 ;;
4403 (goto-char (point-min))
4404 (while (re-search-forward "/\\*" nil t)
4405 (if (verilog-within-string)
4406 (re-search-forward "\"" nil t)
4407 (let ((bpt (- (point) 2)))
4408 (re-search-forward "\\*/")
4409 (delete-region bpt (point))))))
4410
4411 (defun verilog-one-line ()
4412 "Convert structural Verilog instances to occupy one line."
4413 (interactive)
4414 (goto-char (point-min))
4415 (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
4416 (replace-match "\\1 " nil nil)))
4417
4418 (defun verilog-linter-name ()
4419 "Return name of linter, either surelint or verilint."
4420 (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4421 compile-command))
4422 (lint-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4423 verilog-linter)))
4424 (cond ((equal compile-word1 "surelint") `surelint)
4425 ((equal compile-word1 "verilint") `verilint)
4426 ((equal lint-word1 "surelint") `surelint)
4427 ((equal lint-word1 "verilint") `verilint)
4428 (t `surelint)))) ;; back compatibility
4429
4430 (defun verilog-lint-off ()
4431 "Convert a Verilog linter warning line into a disable statement.
4432 For example:
4433 pci_bfm_null.v, line 46: Unused input: pci_rst_
4434 becomes a comment for the appropriate tool.
4435
4436 The first word of the `compile-command' or `verilog-linter'
4437 variables is used to determine which product is being used.
4438
4439 See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
4440 (interactive)
4441 (let ((linter (verilog-linter-name)))
4442 (cond ((equal linter `surelint)
4443 (verilog-surelint-off))
4444 ((equal linter `verilint)
4445 (verilog-verilint-off))
4446 (t (error "Linter name not set")))))
4447
4448 (defvar compilation-last-buffer)
4449 (defvar next-error-last-buffer)
4450
4451 (defun verilog-surelint-off ()
4452 "Convert a SureLint warning line into a disable statement.
4453 Run from Verilog source window; assumes there is a *compile* buffer
4454 with point set appropriately.
4455
4456 For example:
4457 WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
4458 becomes:
4459 // surefire lint_line_off UDDONX"
4460 (interactive)
4461 (let ((buff (if (boundp 'next-error-last-buffer)
4462 next-error-last-buffer
4463 compilation-last-buffer)))
4464 (when (buffer-live-p buff)
4465 ;; FIXME with-current-buffer?
4466 (save-excursion
4467 (switch-to-buffer buff)
4468 (beginning-of-line)
4469 (when
4470 (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
4471 (let* ((code (match-string 2))
4472 (file (match-string 3))
4473 (line (match-string 4))
4474 (buffer (get-file-buffer file))
4475 dir filename)
4476 (unless buffer
4477 (progn
4478 (setq buffer
4479 (and (file-exists-p file)
4480 (find-file-noselect file)))
4481 (or buffer
4482 (let* ((pop-up-windows t))
4483 (let ((name (expand-file-name
4484 (read-file-name
4485 (format "Find this error in: (default %s) "
4486 file)
4487 dir file t))))
4488 (if (file-directory-p name)
4489 (setq name (expand-file-name filename name)))
4490 (setq buffer
4491 (and (file-exists-p name)
4492 (find-file-noselect name))))))))
4493 (switch-to-buffer buffer)
4494 (goto-char (point-min))
4495 (forward-line (- (string-to-number line)))
4496 (end-of-line)
4497 (catch 'already
4498 (cond
4499 ((verilog-in-slash-comment-p)
4500 (re-search-backward "//")
4501 (cond
4502 ((looking-at "// surefire lint_off_line ")
4503 (goto-char (match-end 0))
4504 (let ((lim (point-at-eol)))
4505 (if (re-search-forward code lim 'move)
4506 (throw 'already t)
4507 (insert (concat " " code)))))
4508 (t
4509 )))
4510 ((verilog-in-star-comment-p)
4511 (re-search-backward "/\*")
4512 (insert (format " // surefire lint_off_line %6s" code )))
4513 (t
4514 (insert (format " // surefire lint_off_line %6s" code ))
4515 )))))))))
4516
4517 (defun verilog-verilint-off ()
4518 "Convert a Verilint warning line into a disable statement.
4519
4520 For example:
4521 (W240) pci_bfm_null.v, line 46: Unused input: pci_rst_
4522 becomes:
4523 //Verilint 240 off // WARNING: Unused input"
4524 (interactive)
4525 (save-excursion
4526 (beginning-of-line)
4527 (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
4528 (replace-match (format
4529 ;; %3s makes numbers 1-999 line up nicely
4530 "\\1//Verilint %3s off // WARNING: \\3"
4531 (match-string 2)))
4532 (beginning-of-line)
4533 (verilog-indent-line))))
4534
4535 (defun verilog-auto-save-compile ()
4536 "Update automatics with \\[verilog-auto], save the buffer, and compile."
4537 (interactive)
4538 (verilog-auto) ; Always do it for safety
4539 (save-buffer)
4540 (compile compile-command))
4541
4542 (defun verilog-preprocess (&optional command filename)
4543 "Preprocess the buffer, similar to `compile', but leave output in Verilog-Mode.
4544 Takes optional COMMAND or defaults to `verilog-preprocessor', and
4545 FILENAME or defaults to `buffer-file-name`."
4546 (interactive
4547 (list
4548 (let ((default (verilog-expand-command verilog-preprocessor)))
4549 (set (make-local-variable `verilog-preprocessor)
4550 (read-from-minibuffer "Run Preprocessor (like this): "
4551 default nil nil
4552 'verilog-preprocess-history default)))))
4553 (unless command (setq command (verilog-expand-command verilog-preprocessor)))
4554 (let* ((fontlocked (and (boundp 'font-lock-mode) font-lock-mode))
4555 (dir (file-name-directory (or filename buffer-file-name)))
4556 (file (file-name-nondirectory (or filename buffer-file-name)))
4557 (cmd (concat "cd " dir "; " command " " file)))
4558 (with-output-to-temp-buffer "*Verilog-Preprocessed*"
4559 (with-current-buffer (get-buffer "*Verilog-Preprocessed*")
4560 (insert (concat "// " cmd "\n"))
4561 (shell-command cmd "*Verilog-Preprocessed*")
4562 (verilog-mode)
4563 ;; Without this force, it takes a few idle seconds
4564 ;; to get the color, which is very jarring
4565 (when fontlocked (font-lock-fontify-buffer))))))
4566 \f
4567
4568 ;;
4569 ;; Batch
4570 ;;
4571
4572 (defmacro verilog-batch-error-wrapper (&rest body)
4573 "Execute BODY and add error prefix to any errors found.
4574 This lets programs calling batch mode to easily extract error messages."
4575 `(condition-case err
4576 (progn ,@body)
4577 (error
4578 (error "%%Error: %s%s" (error-message-string err)
4579 (if (featurep 'xemacs) "\n" ""))))) ;; XEmacs forgets to add a newline
4580
4581 (defun verilog-batch-execute-func (funref)
4582 "Internal processing of a batch command, running FUNREF on all command arguments."
4583 (verilog-batch-error-wrapper
4584 ;; Setting global variables like that is *VERY NASTY* !!! --Stef
4585 ;; However, this function is called only when Emacs is being used as
4586 ;; a standalone language instead of as an editor, so we'll live.
4587 ;;
4588 ;; General globals needed
4589 (setq make-backup-files nil)
4590 (setq-default make-backup-files nil)
4591 (setq enable-local-variables t)
4592 (setq enable-local-eval t)
4593 ;; Make sure any sub-files we read get proper mode
4594 (setq-default major-mode 'verilog-mode)
4595 ;; Ditto files already read in
4596 (mapc (lambda (buf)
4597 (when (buffer-file-name buf)
4598 (with-current-buffer buf
4599 (verilog-mode))))
4600 (buffer-list))
4601 ;; Process the files
4602 (mapcar '(lambda (buf)
4603 (when (buffer-file-name buf)
4604 (save-excursion
4605 (if (not (file-exists-p (buffer-file-name buf)))
4606 (error
4607 (concat "File not found: " (buffer-file-name buf))))
4608 (message (concat "Processing " (buffer-file-name buf)))
4609 (set-buffer buf)
4610 (funcall funref)
4611 (save-buffer))))
4612 (buffer-list))))
4613
4614 (defun verilog-batch-auto ()
4615 "For use with --batch, perform automatic expansions as a stand-alone tool.
4616 This sets up the appropriate Verilog mode environment, updates automatics
4617 with \\[verilog-auto] on all command-line files, and saves the buffers.
4618 For proper results, multiple filenames need to be passed on the command
4619 line in bottom-up order."
4620 (unless noninteractive
4621 (error "Use verilog-batch-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4622 (verilog-batch-execute-func `verilog-auto))
4623
4624 (defun verilog-batch-delete-auto ()
4625 "For use with --batch, perform automatic deletion as a stand-alone tool.
4626 This sets up the appropriate Verilog mode environment, deletes automatics
4627 with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
4628 (unless noninteractive
4629 (error "Use verilog-batch-delete-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4630 (verilog-batch-execute-func `verilog-delete-auto))
4631
4632 (defun verilog-batch-inject-auto ()
4633 "For use with --batch, perform automatic injection as a stand-alone tool.
4634 This sets up the appropriate Verilog mode environment, injects new automatics
4635 with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
4636 For proper results, multiple filenames need to be passed on the command
4637 line in bottom-up order."
4638 (unless noninteractive
4639 (error "Use verilog-batch-inject-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4640 (verilog-batch-execute-func `verilog-inject-auto))
4641
4642 (defun verilog-batch-indent ()
4643 "For use with --batch, reindent an a entire file as a stand-alone tool.
4644 This sets up the appropriate Verilog mode environment, calls
4645 \\[verilog-indent-buffer] on all command-line files, and saves the buffers."
4646 (unless noninteractive
4647 (error "Use verilog-batch-indent only with --batch")) ;; Otherwise we'd mess up buffer modes
4648 (verilog-batch-execute-func `verilog-indent-buffer))
4649 \f
4650
4651 ;;
4652 ;; Indentation
4653 ;;
4654 (defconst verilog-indent-alist
4655 '((block . (+ ind verilog-indent-level))
4656 (case . (+ ind verilog-case-indent))
4657 (cparenexp . (+ ind verilog-indent-level))
4658 (cexp . (+ ind verilog-cexp-indent))
4659 (defun . verilog-indent-level-module)
4660 (declaration . verilog-indent-level-declaration)
4661 (directive . (verilog-calculate-indent-directive))
4662 (tf . verilog-indent-level)
4663 (behavioral . (+ verilog-indent-level-behavioral verilog-indent-level-module))
4664 (statement . ind)
4665 (cpp . 0)
4666 (comment . (verilog-comment-indent))
4667 (unknown . 3)
4668 (string . 0)))
4669
4670 (defun verilog-continued-line-1 (lim)
4671 "Return true if this is a continued line.
4672 Set point to where line starts. Limit search to point LIM."
4673 (let ((continued 't))
4674 (if (eq 0 (forward-line -1))
4675 (progn
4676 (end-of-line)
4677 (verilog-backward-ws&directives lim)
4678 (if (bobp)
4679 (setq continued nil)
4680 (setq continued (verilog-backward-token))))
4681 (setq continued nil))
4682 continued))
4683
4684 (defun verilog-calculate-indent ()
4685 "Calculate the indent of the current Verilog line.
4686 Examine previous lines. Once a line is found that is definitive as to the
4687 type of the current line, return that lines' indent level and its type.
4688 Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
4689 (save-excursion
4690 (let* ((starting_position (point))
4691 (par 0)
4692 (begin (looking-at "[ \t]*begin\\>"))
4693 (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
4694 (type (catch 'nesting
4695 ;; Keep working backwards until we can figure out
4696 ;; what type of statement this is.
4697 ;; Basically we need to figure out
4698 ;; 1) if this is a continuation of the previous line;
4699 ;; 2) are we in a block scope (begin..end)
4700
4701 ;; if we are in a comment, done.
4702 (if (verilog-in-star-comment-p)
4703 (throw 'nesting 'comment))
4704
4705 ;; if we have a directive, done.
4706 (if (save-excursion (beginning-of-line)
4707 (and (looking-at verilog-directive-re-1)
4708 (not (or (looking-at "[ \t]*`ovm_")
4709 (looking-at "[ \t]*`vmm_")))))
4710 (throw 'nesting 'directive))
4711 ;; indent structs as if there were module level
4712 (if (verilog-in-struct-p)
4713 (throw 'nesting 'block))
4714
4715 ;; unless we are in the newfangled coverpoint or constraint blocks
4716 ;; if we are in a parenthesized list, and the user likes to indent these, return.
4717 (if (and
4718 verilog-indent-lists
4719 (verilog-in-paren)
4720 (not (verilog-in-coverage-p))
4721 )
4722 (progn (setq par 1)
4723 (throw 'nesting 'block)))
4724
4725 ;; See if we are continuing a previous line
4726 (while t
4727 ;; trap out if we crawl off the top of the buffer
4728 (if (bobp) (throw 'nesting 'cpp))
4729
4730 (if (verilog-continued-line-1 lim)
4731 (let ((sp (point)))
4732 (if (and
4733 (not (looking-at verilog-complete-reg))
4734 (verilog-continued-line-1 lim))
4735 (progn (goto-char sp)
4736 (throw 'nesting 'cexp))
4737
4738 (goto-char sp))
4739
4740 (if (and begin
4741 (not verilog-indent-begin-after-if)
4742 (looking-at verilog-no-indent-begin-re))
4743 (progn
4744 (beginning-of-line)
4745 (skip-chars-forward " \t")
4746 (throw 'nesting 'statement))
4747 (progn
4748 (throw 'nesting 'cexp))))
4749 ;; not a continued line
4750 (goto-char starting_position))
4751
4752 (if (looking-at "\\<else\\>")
4753 ;; search back for governing if, striding across begin..end pairs
4754 ;; appropriately
4755 (let ((elsec 1))
4756 (while (verilog-re-search-backward verilog-ends-re nil 'move)
4757 (cond
4758 ((match-end 1) ; else, we're in deep
4759 (setq elsec (1+ elsec)))
4760 ((match-end 2) ; if
4761 (setq elsec (1- elsec))
4762 (if (= 0 elsec)
4763 (if verilog-align-ifelse
4764 (throw 'nesting 'statement)
4765 (progn ;; back up to first word on this line
4766 (beginning-of-line)
4767 (verilog-forward-syntactic-ws)
4768 (throw 'nesting 'statement)))))
4769 ((match-end 3) ; assert block
4770 (setq elsec (1- elsec))
4771 (verilog-beg-of-statement) ;; doesn't get to beginning
4772 (if (looking-at verilog-property-re)
4773 (throw 'nesting 'statement) ; We don't need an endproperty for these
4774 (throw 'nesting 'block) ;We still need a endproperty
4775 ))
4776 (t ; endblock
4777 ; try to leap back to matching outward block by striding across
4778 ; indent level changing tokens then immediately
4779 ; previous line governs indentation.
4780 (let (( reg) (nest 1))
4781 ;; verilog-ends => else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
4782 (cond
4783 ((match-end 4) ; end
4784 ;; Search back for matching begin
4785 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
4786 ((match-end 5) ; endcase
4787 ;; Search back for matching case
4788 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4789 ((match-end 6) ; endfunction
4790 ;; Search back for matching function
4791 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4792 ((match-end 7) ; endtask
4793 ;; Search back for matching task
4794 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
4795 ((match-end 8) ; endspecify
4796 ;; Search back for matching specify
4797 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4798 ((match-end 9) ; endtable
4799 ;; Search back for matching table
4800 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4801 ((match-end 10) ; endgenerate
4802 ;; Search back for matching generate
4803 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4804 ((match-end 11) ; joins
4805 ;; Search back for matching fork
4806 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
4807 ((match-end 12) ; class
4808 ;; Search back for matching class
4809 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4810 ((match-end 13) ; covergroup
4811 ;; Search back for matching covergroup
4812 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
4813 (catch 'skip
4814 (while (verilog-re-search-backward reg nil 'move)
4815 (cond
4816 ((match-end 1) ; begin
4817 (setq nest (1- nest))
4818 (if (= 0 nest)
4819 (throw 'skip 1)))
4820 ((match-end 2) ; end
4821 (setq nest (1+ nest)))))
4822 )))))))
4823 (throw 'nesting (verilog-calc-1)))
4824 );; catch nesting
4825 );; type
4826 )
4827 ;; Return type of block and indent level.
4828 (if (not type)
4829 (setq type 'cpp))
4830 (if (> par 0) ; Unclosed Parenthesis
4831 (list 'cparenexp par)
4832 (cond
4833 ((eq type 'case)
4834 (list type (verilog-case-indent-level)))
4835 ((eq type 'statement)
4836 (list type (current-column)))
4837 ((eq type 'defun)
4838 (list type 0))
4839 (t
4840 (list type (verilog-current-indent-level))))))))
4841
4842 (defun verilog-wai ()
4843 "Show matching nesting block for debugging."
4844 (interactive)
4845 (save-excursion
4846 (let* ((type (verilog-calc-1))
4847 depth)
4848 ;; Return type of block and indent level.
4849 (if (not type)
4850 (setq type 'cpp))
4851 (if (and
4852 verilog-indent-lists
4853 (not(or (verilog-in-coverage-p)
4854 (verilog-in-struct-p)))
4855 (verilog-in-paren))
4856 (setq depth 1)
4857 (cond
4858 ((eq type 'case)
4859 (setq depth (verilog-case-indent-level)))
4860 ((eq type 'statement)
4861 (setq depth (current-column)))
4862 ((eq type 'defun)
4863 (setq depth 0))
4864 (t
4865 (setq depth (verilog-current-indent-level)))))
4866 (message "You are at nesting %s depth %d" type depth))))
4867
4868 (defun verilog-calc-1 ()
4869 (catch 'nesting
4870 (let ((re (concat "\\({\\|}\\|" verilog-indent-re "\\)")))
4871 (while (verilog-re-search-backward re nil 'move)
4872 (catch 'continue
4873 (cond
4874 ((equal (char-after) ?\{)
4875 (if (verilog-at-constraint-p)
4876 (throw 'nesting 'block)))
4877
4878 ((equal (char-after) ?\})
4879 (let ((there (verilog-at-close-constraint-p)))
4880 (if there ;; we are at the } that closes a constraint. Find the { that opens it
4881 (progn
4882 (forward-char 1)
4883 (backward-list 1)
4884 (verilog-beg-of-statement)))))
4885
4886 ((looking-at verilog-beg-block-re-ordered)
4887 (cond
4888 ((match-end 2) ; *sigh* could be "unique case" or "priority casex"
4889 (let ((here (point)))
4890 (verilog-beg-of-statement)
4891 (if (looking-at verilog-extended-case-re)
4892 (throw 'nesting 'case)
4893 (goto-char here)))
4894 (throw 'nesting 'case))
4895
4896 ((match-end 4) ; *sigh* could be "disable fork"
4897 (let ((here (point)))
4898 (verilog-beg-of-statement)
4899 (if (or (looking-at verilog-disable-fork-re)
4900 (looking-at verilog-fork-wait-re))
4901 t ; this is a normal statement
4902 (progn ; or is fork, starts a new block
4903 (goto-char here)
4904 (throw 'nesting 'block)))))
4905
4906 ((match-end 27) ; *sigh* might be a clocking declaration
4907 (let ((here (point)))
4908 (if (verilog-in-paren)
4909 t ; this is a normal statement
4910 (progn ; or is fork, starts a new block
4911 (goto-char here)
4912 (throw 'nesting 'block)))))
4913
4914 ;; need to consider typedef struct here...
4915 ((looking-at "\\<class\\|struct\\|function\\|task\\>")
4916 ; *sigh* These words have an optional prefix:
4917 ; extern {virtual|protected}? function a();
4918 ; typedef class foo;
4919 ; and we don't want to confuse this with
4920 ; function a();
4921 ; property
4922 ; ...
4923 ; endfunction
4924 (verilog-beg-of-statement)
4925 (if (looking-at verilog-beg-block-re-ordered)
4926 (throw 'nesting 'block)
4927 (throw 'nesting 'defun)))
4928
4929 ((looking-at "\\<property\\>")
4930 ; *sigh*
4931 ; {assert|assume|cover} property (); are complete
4932 ; and could also be labeled: - foo: assert property
4933 ; but
4934 ; property ID () ... needs end_property
4935 (verilog-beg-of-statement)
4936 (if (looking-at verilog-property-re)
4937 (throw 'continue 'statement) ; We don't need an endproperty for these
4938 (throw 'nesting 'block) ;We still need a endproperty
4939 ))
4940
4941 (t (throw 'nesting 'block))))
4942
4943 ((looking-at verilog-end-block-re)
4944 (verilog-leap-to-head)
4945 (if (verilog-in-case-region-p)
4946 (progn
4947 (verilog-leap-to-case-head)
4948 (if (looking-at verilog-extended-case-re)
4949 (throw 'nesting 'case)))))
4950
4951 ((looking-at verilog-defun-level-re)
4952 (if (looking-at verilog-defun-level-generate-only-re)
4953 (if (verilog-in-generate-region-p)
4954 (throw 'continue 'foo) ; always block in a generate - keep looking
4955 (throw 'nesting 'defun))
4956 (throw 'nesting 'defun)))
4957
4958 ((looking-at verilog-cpp-level-re)
4959 (throw 'nesting 'cpp))
4960
4961 ((bobp)
4962 (throw 'nesting 'cpp)))))
4963
4964 (throw 'nesting 'cpp))))
4965
4966 (defun verilog-calculate-indent-directive ()
4967 "Return indentation level for directive.
4968 For speed, the searcher looks at the last directive, not the indent
4969 of the appropriate enclosing block."
4970 (let ((base -1) ;; Indent of the line that determines our indentation
4971 (ind 0)) ;; Relative offset caused by other directives (like `endif on same line as `else)
4972 ;; Start at current location, scan back for another directive
4973
4974 (save-excursion
4975 (beginning-of-line)
4976 (while (and (< base 0)
4977 (verilog-re-search-backward verilog-directive-re nil t))
4978 (cond ((save-excursion (skip-chars-backward " \t") (bolp))
4979 (setq base (current-indentation))))
4980 (cond ((and (looking-at verilog-directive-end) (< base 0)) ;; Only matters when not at BOL
4981 (setq ind (- ind verilog-indent-level-directive)))
4982 ((and (looking-at verilog-directive-middle) (>= base 0)) ;; Only matters when at BOL
4983 (setq ind (+ ind verilog-indent-level-directive)))
4984 ((looking-at verilog-directive-begin)
4985 (setq ind (+ ind verilog-indent-level-directive)))))
4986 ;; Adjust indent to starting indent of critical line
4987 (setq ind (max 0 (+ ind base))))
4988
4989 (save-excursion
4990 (beginning-of-line)
4991 (skip-chars-forward " \t")
4992 (cond ((or (looking-at verilog-directive-middle)
4993 (looking-at verilog-directive-end))
4994 (setq ind (max 0 (- ind verilog-indent-level-directive))))))
4995 ind))
4996
4997 (defun verilog-leap-to-case-head ()
4998 (let ((nest 1))
4999 (while (/= 0 nest)
5000 (verilog-re-search-backward
5001 (concat
5002 "\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?\\<case[xz]?\\>\\)"
5003 "\\|\\(\\<endcase\\>\\)" )
5004 nil 'move)
5005 (cond
5006 ((match-end 1)
5007 (let ((here (point)))
5008 (verilog-beg-of-statement)
5009 (unless (looking-at verilog-extended-case-re)
5010 (goto-char here)))
5011 (setq nest (1- nest)))
5012 ((match-end 3)
5013 (setq nest (1+ nest)))
5014 ((bobp)
5015 (ding 't)
5016 (setq nest 0))))))
5017
5018 (defun verilog-leap-to-head ()
5019 "Move point to the head of this block.
5020 Jump from end to matching begin, from endcase to matching case, and so on."
5021 (let ((reg nil)
5022 snest
5023 (nesting 'yes)
5024 (nest 1))
5025 (cond
5026 ((looking-at "\\<end\\>")
5027 ;; 1: Search back for matching begin
5028 (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
5029 "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
5030 ((looking-at "\\<endtask\\>")
5031 ;; 2: Search back for matching task
5032 (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
5033 (setq nesting 'no))
5034 ((looking-at "\\<endcase\\>")
5035 (catch 'nesting
5036 (verilog-leap-to-case-head) )
5037 (setq reg nil) ; to force skip
5038 )
5039
5040 ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
5041 ;; 4: Search back for matching fork
5042 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5043 ((looking-at "\\<endclass\\>")
5044 ;; 5: Search back for matching class
5045 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
5046 ((looking-at "\\<endtable\\>")
5047 ;; 6: Search back for matching table
5048 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
5049 ((looking-at "\\<endspecify\\>")
5050 ;; 7: Search back for matching specify
5051 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
5052 ((looking-at "\\<endfunction\\>")
5053 ;; 8: Search back for matching function
5054 (setq reg "\\(\\<function\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<function\\>\\)")
5055 (setq nesting 'no))
5056 ;;(setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
5057 ((looking-at "\\<endgenerate\\>")
5058 ;; 8: Search back for matching generate
5059 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
5060 ((looking-at "\\<endgroup\\>")
5061 ;; 10: Search back for matching covergroup
5062 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
5063 ((looking-at "\\<endproperty\\>")
5064 ;; 11: Search back for matching property
5065 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
5066 ((looking-at verilog-ovm-end-re)
5067 ;; 12: Search back for matching sequence
5068 (setq reg (concat "\\(" verilog-ovm-begin-re "\\|" verilog-ovm-end-re "\\)")))
5069 ((looking-at verilog-vmm-end-re)
5070 ;; 12: Search back for matching sequence
5071 (setq reg (concat "\\(" verilog-vmm-begin-re "\\|" verilog-vmm-end-re "\\)")))
5072 ((looking-at "\\<endinterface\\>")
5073 ;; 12: Search back for matching interface
5074 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
5075 ((looking-at "\\<endsequence\\>")
5076 ;; 12: Search back for matching sequence
5077 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
5078 ((looking-at "\\<endclocking\\>")
5079 ;; 12: Search back for matching clocking
5080 (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
5081 (if reg
5082 (catch 'skip
5083 (if (eq nesting 'yes)
5084 (let (sreg)
5085 (while (verilog-re-search-backward reg nil 'move)
5086 (cond
5087 ((match-end 1) ; begin
5088 (if (looking-at "fork")
5089 (let ((here (point)))
5090 (verilog-beg-of-statement)
5091 (unless (looking-at verilog-disable-fork-re)
5092 (goto-char here)
5093 (setq nest (1- nest))))
5094 (setq nest (1- nest)))
5095 (if (= 0 nest)
5096 ;; Now previous line describes syntax
5097 (throw 'skip 1))
5098 (if (and snest
5099 (= snest nest))
5100 (setq reg sreg)))
5101 ((match-end 2) ; end
5102 (setq nest (1+ nest)))
5103 ((match-end 3)
5104 ;; endcase, jump to case
5105 (setq snest nest)
5106 (setq nest (1+ nest))
5107 (setq sreg reg)
5108 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
5109 ((match-end 4)
5110 ;; join, jump to fork
5111 (setq snest nest)
5112 (setq nest (1+ nest))
5113 (setq sreg reg)
5114 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5115 )))
5116 ;no nesting
5117 (if (and
5118 (verilog-re-search-backward reg nil 'move)
5119 (match-end 1)) ; task -> could be virtual and/or protected
5120 (progn
5121 (verilog-beg-of-statement)
5122 (throw 'skip 1))
5123 (throw 'skip 1)))))))
5124
5125 (defun verilog-continued-line ()
5126 "Return true if this is a continued line.
5127 Set point to where line starts."
5128 (let ((continued 't))
5129 (if (eq 0 (forward-line -1))
5130 (progn
5131 (end-of-line)
5132 (verilog-backward-ws&directives)
5133 (if (bobp)
5134 (setq continued nil)
5135 (while (and continued
5136 (save-excursion
5137 (skip-chars-backward " \t")
5138 (not (bolp))))
5139 (setq continued (verilog-backward-token)))))
5140 (setq continued nil))
5141 continued))
5142
5143 (defun verilog-backward-token ()
5144 "Step backward token, returing true if this is a continued line."
5145 (interactive)
5146 (verilog-backward-syntactic-ws)
5147 (cond
5148 ((bolp)
5149 nil)
5150 (;-- Anything ending in a ; is complete
5151 (= (preceding-char) ?\;)
5152 nil)
5153 (; If a "}" is prefixed by a ";", then this is a complete statement
5154 ; i.e.: constraint foo { a = b; }
5155 (= (preceding-char) ?\})
5156 (progn
5157 (backward-char)
5158 (not(verilog-at-close-constraint-p))))
5159 (;-- constraint foo { a = b }
5160 ; is a complete statement. *sigh*
5161 (= (preceding-char) ?\{)
5162 (progn
5163 (backward-char)
5164 (not (verilog-at-constraint-p))))
5165 (;" string "
5166 (= (preceding-char) ?\")
5167 (backward-char)
5168 (verilog-skip-backward-comment-or-string)
5169 nil)
5170
5171 (; [3:4]
5172 (= (preceding-char) ?\])
5173 (backward-char)
5174 (verilog-backward-open-bracket)
5175 t)
5176
5177 (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
5178 ; also could be simply '@(foo)'
5179 ; or foo u1 #(a=8)
5180 ; (b, ... which ISN'T complete
5181 ;;;; Do we need this???
5182 (= (preceding-char) ?\))
5183 (progn
5184 (backward-char)
5185 (verilog-backward-up-list 1)
5186 (verilog-backward-syntactic-ws)
5187 (let ((back (point)))
5188 (forward-word -1)
5189 (cond
5190 ;;XX
5191 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
5192 (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
5193 ((looking-at verilog-ovm-statement-re)
5194 nil)
5195 ((looking-at verilog-ovm-begin-re)
5196 t)
5197 ((looking-at verilog-ovm-end-re)
5198 t)
5199 ;; JBA find VMM macros
5200 ((looking-at verilog-vmm-statement-re)
5201 nil )
5202 ((looking-at verilog-vmm-begin-re)
5203 t)
5204 ((looking-at verilog-vmm-end-re)
5205 nil)
5206 ;; JBA trying to catch macro lines with no ; at end
5207 ((looking-at "\\<`")
5208 nil)
5209 (t
5210 (goto-char back)
5211 (cond
5212 ((= (preceding-char) ?\@)
5213 (backward-char)
5214 (save-excursion
5215 (verilog-backward-token)
5216 (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
5217 ((= (preceding-char) ?\#)
5218 (backward-char))
5219 (t t)))))))
5220
5221 (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
5222 t
5223 (forward-word -1)
5224 (while (= (preceding-char) ?\_)
5225 (forward-word -1))
5226 (cond
5227 ((looking-at "\\<else\\>")
5228 t)
5229 ((looking-at verilog-behavioral-block-beg-re)
5230 t)
5231 ((looking-at verilog-indent-re)
5232 nil)
5233 (t
5234 (let
5235 ((back (point)))
5236 (verilog-backward-syntactic-ws)
5237 (cond
5238 ((= (preceding-char) ?\:)
5239 (backward-char)
5240 (verilog-backward-syntactic-ws)
5241 (backward-sexp)
5242 (if (looking-at verilog-nameable-item-re )
5243 nil
5244 t))
5245 ((= (preceding-char) ?\#)
5246 (backward-char)
5247 t)
5248 ((= (preceding-char) ?\`)
5249 (backward-char)
5250 t)
5251
5252 (t
5253 (goto-char back)
5254 t))))))))
5255
5256 (defun verilog-backward-syntactic-ws ()
5257 (verilog-skip-backward-comments)
5258 (forward-comment (- (buffer-size))))
5259
5260 (defun verilog-forward-syntactic-ws ()
5261 (verilog-skip-forward-comment-p)
5262 (forward-comment (buffer-size)))
5263
5264 (defun verilog-backward-ws&directives (&optional bound)
5265 "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
5266 Optional BOUND limits search."
5267 (save-restriction
5268 (let* ((bound (or bound (point-min)))
5269 (here bound)
5270 (p nil) )
5271 (if (< bound (point))
5272 (progn
5273 (let ((state (save-excursion (verilog-syntax-ppss))))
5274 (cond
5275 ((nth 7 state) ;; in // comment
5276 (verilog-re-search-backward "//" nil 'move)
5277 (skip-chars-backward "/"))
5278 ((nth 4 state) ;; in /* */ comment
5279 (verilog-re-search-backward "/\*" nil 'move))))
5280 (narrow-to-region bound (point))
5281 (while (/= here (point))
5282 (setq here (point))
5283 (verilog-skip-backward-comments)
5284 (setq p
5285 (save-excursion
5286 (beginning-of-line)
5287 (cond
5288 ((and verilog-highlight-translate-off
5289 (verilog-within-translate-off))
5290 (verilog-back-to-start-translate-off (point-min)))
5291 ((looking-at verilog-directive-re-1)
5292 (point))
5293 (t
5294 nil))))
5295 (if p (goto-char p))))))))
5296
5297 (defun verilog-forward-ws&directives (&optional bound)
5298 "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
5299 Optional BOUND limits search."
5300 (save-restriction
5301 (let* ((bound (or bound (point-max)))
5302 (here bound)
5303 jump)
5304 (if (> bound (point))
5305 (progn
5306 (let ((state (save-excursion (verilog-syntax-ppss))))
5307 (cond
5308 ((nth 7 state) ;; in // comment
5309 (end-of-line)
5310 (forward-char 1)
5311 (skip-chars-forward " \t\n\f")
5312 )
5313 ((nth 4 state) ;; in /* */ comment
5314 (verilog-re-search-forward "\*\/\\s-*" nil 'move))))
5315 (narrow-to-region (point) bound)
5316 (while (/= here (point))
5317 (setq here (point)
5318 jump nil)
5319 (forward-comment (buffer-size))
5320 (and (looking-at "\\s-*(\\*.*\\*)\\s-*") ;; Attribute
5321 (goto-char (match-end 0)))
5322 (save-excursion
5323 (beginning-of-line)
5324 (if (looking-at verilog-directive-re-1)
5325 (setq jump t)))
5326 (if jump
5327 (beginning-of-line 2))))))))
5328
5329 (defun verilog-in-comment-p ()
5330 "Return true if in a star or // comment."
5331 (let ((state (save-excursion (verilog-syntax-ppss))))
5332 (or (nth 4 state) (nth 7 state))))
5333
5334 (defun verilog-in-star-comment-p ()
5335 "Return true if in a star comment."
5336 (let ((state (save-excursion (verilog-syntax-ppss))))
5337 (and
5338 (nth 4 state) ; t if in a comment of style a // or b /**/
5339 (not
5340 (nth 7 state) ; t if in a comment of style b /**/
5341 ))))
5342
5343 (defun verilog-in-slash-comment-p ()
5344 "Return true if in a slash comment."
5345 (let ((state (save-excursion (verilog-syntax-ppss))))
5346 (nth 7 state)))
5347
5348 (defun verilog-in-comment-or-string-p ()
5349 "Return true if in a string or comment."
5350 (let ((state (save-excursion (verilog-syntax-ppss))))
5351 (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
5352
5353 (defun verilog-in-attribute-p ()
5354 "Return true if point is in an attribute (* [] attribute *)."
5355 (save-excursion
5356 (verilog-re-search-backward "\\((\\*\\)\\|\\(\\*)\\)" nil 'move)
5357 (numberp (match-beginning 1))))
5358
5359 (defun verilog-in-escaped-name-p ()
5360 "Return true if in an escaped name."
5361 (save-excursion
5362 (backward-char)
5363 (skip-chars-backward "^ \t\n\f")
5364 (if (equal (char-after (point) ) ?\\ )
5365 t
5366 nil)))
5367 (defun verilog-in-directive-p ()
5368 "Return true if in a directive."
5369 (save-excursion
5370 (beginning-of-line)
5371 (looking-at verilog-directive-re-1)))
5372
5373 (defun verilog-in-paren ()
5374 "Return true if in a parenthetical expression."
5375 (let ((state (save-excursion (verilog-syntax-ppss))))
5376 (> (nth 0 state) 0 )))
5377
5378 (defun verilog-in-struct-p ()
5379 "Return true if in a struct declaration."
5380 (interactive)
5381 (save-excursion
5382 (if (verilog-in-paren)
5383 (progn
5384 (verilog-backward-up-list 1)
5385 (verilog-at-struct-p)
5386 )
5387 nil)))
5388
5389 (defun verilog-in-coverage-p ()
5390 "Return true if in a constraint or coverpoint expression."
5391 (interactive)
5392 (save-excursion
5393 (if (verilog-in-paren)
5394 (progn
5395 (verilog-backward-up-list 1)
5396 (verilog-at-constraint-p)
5397 )
5398 nil)))
5399 (defun verilog-at-close-constraint-p ()
5400 "If at the } that closes a constraint or covergroup, return true."
5401 (if (and
5402 (equal (char-after) ?\})
5403 (verilog-in-paren))
5404
5405 (save-excursion
5406 (verilog-backward-ws&directives)
5407 (if (equal (char-before) ?\;)
5408 (point)
5409 nil))))
5410
5411 (defun verilog-at-constraint-p ()
5412 "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
5413 (if (save-excursion
5414 (and
5415 (equal (char-after) ?\{)
5416 (forward-list)
5417 (progn (backward-char 1)
5418 (verilog-backward-ws&directives)
5419 (equal (char-before) ?\;))))
5420 ;; maybe
5421 (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
5422 ;; not
5423 nil))
5424
5425 (defun verilog-at-struct-p ()
5426 "If at the { of a struct, return true, moving point to struct."
5427 (save-excursion
5428 (if (and (equal (char-after) ?\{)
5429 (verilog-backward-token))
5430 (looking-at "\\<struct\\|union\\|packed\\|\\(un\\)?signed\\>")
5431 nil)))
5432
5433 (defun verilog-parenthesis-depth ()
5434 "Return non zero if in parenthetical-expression."
5435 (save-excursion (nth 1 (verilog-syntax-ppss))))
5436
5437
5438 (defun verilog-skip-forward-comment-or-string ()
5439 "Return true if in a string or comment."
5440 (let ((state (save-excursion (verilog-syntax-ppss))))
5441 (cond
5442 ((nth 3 state) ;Inside string
5443 (search-forward "\"")
5444 t)
5445 ((nth 7 state) ;Inside // comment
5446 (forward-line 1)
5447 t)
5448 ((nth 4 state) ;Inside any comment (hence /**/)
5449 (search-forward "*/"))
5450 (t
5451 nil))))
5452
5453 (defun verilog-skip-backward-comment-or-string ()
5454 "Return true if in a string or comment."
5455 (let ((state (save-excursion (verilog-syntax-ppss))))
5456 (cond
5457 ((nth 3 state) ;Inside string
5458 (search-backward "\"")
5459 t)
5460 ((nth 7 state) ;Inside // comment
5461 (search-backward "//")
5462 (skip-chars-backward "/")
5463 t)
5464 ((nth 4 state) ;Inside /* */ comment
5465 (search-backward "/*")
5466 t)
5467 (t
5468 nil))))
5469
5470 (defun verilog-skip-backward-comments ()
5471 "Return true if a comment was skipped."
5472 (let ((more t))
5473 (while more
5474 (setq more
5475 (let ((state (save-excursion (verilog-syntax-ppss))))
5476 (cond
5477 ((nth 7 state) ;Inside // comment
5478 (search-backward "//")
5479 (skip-chars-backward "/")
5480 (skip-chars-backward " \t\n\f")
5481 t)
5482 ((nth 4 state) ;Inside /* */ comment
5483 (search-backward "/*")
5484 (skip-chars-backward " \t\n\f")
5485 t)
5486 ((and (not (bobp))
5487 (= (char-before) ?\/)
5488 (= (char-before (1- (point))) ?\*))
5489 (goto-char (- (point) 2))
5490 t) ;; Let nth 4 state handle the rest
5491 ((and (not (bobp))
5492 (= (char-before) ?\))
5493 (= (char-before (1- (point))) ?\*))
5494 (goto-char (- (point) 2))
5495 (if (search-backward "(*" nil t)
5496 (progn
5497 (skip-chars-backward " \t\n\f")
5498 t)
5499 (progn
5500 (goto-char (+ (point) 2))
5501 nil)))
5502 (t
5503 (/= (skip-chars-backward " \t\n\f") 0))))))))
5504
5505 (defun verilog-skip-forward-comment-p ()
5506 "If in comment, move to end and return true."
5507 (let* (h
5508 (state (save-excursion (verilog-syntax-ppss)))
5509 (skip (cond
5510 ((nth 3 state) ;Inside string
5511 t)
5512 ((nth 7 state) ;Inside // comment
5513 (end-of-line)
5514 (forward-char 1)
5515 t)
5516 ((nth 4 state) ;Inside /* comment
5517 (search-forward "*/")
5518 t)
5519 ((verilog-in-attribute-p) ;Inside (* attribute
5520 (search-forward "*)" nil t)
5521 t)
5522 (t nil))))
5523 (skip-chars-forward " \t\n\f")
5524 (while
5525 (cond
5526 ((looking-at "\\/\\*")
5527 (progn
5528 (setq h (point))
5529 (goto-char (match-end 0))
5530 (if (search-forward "*/" nil t)
5531 (progn
5532 (skip-chars-forward " \t\n\f")
5533 (setq skip 't))
5534 (progn
5535 (goto-char h)
5536 nil))))
5537 ((looking-at "(\\*")
5538 (progn
5539 (setq h (point))
5540 (goto-char (match-end 0))
5541 (if (search-forward "*)" nil t)
5542 (progn
5543 (skip-chars-forward " \t\n\f")
5544 (setq skip 't))
5545 (progn
5546 (goto-char h)
5547 nil))))
5548 (t nil)))
5549 skip))
5550
5551 (defun verilog-indent-line-relative ()
5552 "Cheap version of indent line.
5553 Only look at a few lines to determine indent level."
5554 (interactive)
5555 (let ((indent-str)
5556 (sp (point)))
5557 (if (looking-at "^[ \t]*$")
5558 (cond ;- A blank line; No need to be too smart.
5559 ((bobp)
5560 (setq indent-str (list 'cpp 0)))
5561 ((verilog-continued-line)
5562 (let ((sp1 (point)))
5563 (if (verilog-continued-line)
5564 (progn
5565 (goto-char sp)
5566 (setq indent-str
5567 (list 'statement (verilog-current-indent-level))))
5568 (goto-char sp1)
5569 (setq indent-str (list 'block (verilog-current-indent-level)))))
5570 (goto-char sp))
5571 ((goto-char sp)
5572 (setq indent-str (verilog-calculate-indent))))
5573 (progn (skip-chars-forward " \t")
5574 (setq indent-str (verilog-calculate-indent))))
5575 (verilog-do-indent indent-str)))
5576
5577 (defun verilog-indent-line ()
5578 "Indent for special part of code."
5579 (verilog-do-indent (verilog-calculate-indent)))
5580
5581 (defun verilog-do-indent (indent-str)
5582 (let ((type (car indent-str))
5583 (ind (car (cdr indent-str))))
5584 (cond
5585 (; handle continued exp
5586 (eq type 'cexp)
5587 (let ((here (point)))
5588 (verilog-backward-syntactic-ws)
5589 (cond
5590 ((or
5591 (= (preceding-char) ?\,)
5592 (= (preceding-char) ?\])
5593 (save-excursion
5594 (verilog-beg-of-statement-1)
5595 (looking-at verilog-declaration-re)))
5596 (let* ( fst
5597 (val
5598 (save-excursion
5599 (backward-char 1)
5600 (verilog-beg-of-statement-1)
5601 (setq fst (point))
5602 (if (looking-at verilog-declaration-re)
5603 (progn ;; we have multiple words
5604 (goto-char (match-end 0))
5605 (skip-chars-forward " \t")
5606 (cond
5607 ((and verilog-indent-declaration-macros
5608 (= (following-char) ?\`))
5609 (progn
5610 (forward-char 1)
5611 (forward-word 1)
5612 (skip-chars-forward " \t")))
5613 ((= (following-char) ?\[)
5614 (progn
5615 (forward-char 1)
5616 (verilog-backward-up-list -1)
5617 (skip-chars-forward " \t"))))
5618 (current-column))
5619 (progn
5620 (goto-char fst)
5621 (+ (current-column) verilog-cexp-indent))))))
5622 (goto-char here)
5623 (indent-line-to val)))
5624 ((= (preceding-char) ?\) )
5625 (goto-char here)
5626 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5627 (indent-line-to val)))
5628 (t
5629 (goto-char here)
5630 (let ((val))
5631 (verilog-beg-of-statement-1)
5632 (if (and (< (point) here)
5633 (verilog-re-search-forward "=[ \\t]*" here 'move))
5634 (setq val (current-column))
5635 (setq val (eval (cdr (assoc type verilog-indent-alist)))))
5636 (goto-char here)
5637 (indent-line-to val))))))
5638
5639 (; handle inside parenthetical expressions
5640 (eq type 'cparenexp)
5641 (let* ( here
5642 (val (save-excursion
5643 (verilog-backward-up-list 1)
5644 (forward-char 1)
5645 (if verilog-indent-lists
5646 (skip-chars-forward " \t")
5647 (verilog-forward-syntactic-ws))
5648 (setq here (point))
5649 (current-column)))
5650
5651 (decl (save-excursion
5652 (goto-char here)
5653 (verilog-forward-syntactic-ws)
5654 (setq here (point))
5655 (looking-at verilog-declaration-re))))
5656 (indent-line-to val)
5657 (if decl
5658 (verilog-pretty-declarations))))
5659
5660 (;-- Handle the ends
5661 (or
5662 (looking-at verilog-end-block-re )
5663 (verilog-at-close-constraint-p))
5664 (let ((val (if (eq type 'statement)
5665 (- ind verilog-indent-level)
5666 ind)))
5667 (indent-line-to val)))
5668
5669 (;-- Case -- maybe line 'em up
5670 (and (eq type 'case) (not (looking-at "^[ \t]*$")))
5671 (progn
5672 (cond
5673 ((looking-at "\\<endcase\\>")
5674 (indent-line-to ind))
5675 (t
5676 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5677 (indent-line-to val))))))
5678
5679 (;-- defun
5680 (and (eq type 'defun)
5681 (looking-at verilog-zero-indent-re))
5682 (indent-line-to 0))
5683
5684 (;-- declaration
5685 (and (or
5686 (eq type 'defun)
5687 (eq type 'block))
5688 (looking-at verilog-declaration-re))
5689 (verilog-indent-declaration ind))
5690
5691 (;-- Everything else
5692 t
5693 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5694 (indent-line-to val))))
5695
5696 (if (looking-at "[ \t]+$")
5697 (skip-chars-forward " \t"))
5698 indent-str ; Return indent data
5699 ))
5700
5701 (defun verilog-current-indent-level ()
5702 "Return the indent-level of the current statement."
5703 (save-excursion
5704 (let (par-pos)
5705 (beginning-of-line)
5706 (setq par-pos (verilog-parenthesis-depth))
5707 (while par-pos
5708 (goto-char par-pos)
5709 (beginning-of-line)
5710 (setq par-pos (verilog-parenthesis-depth)))
5711 (skip-chars-forward " \t")
5712 (current-column))))
5713
5714 (defun verilog-case-indent-level ()
5715 "Return the indent-level of the current statement.
5716 Do not count named blocks or case-statements."
5717 (save-excursion
5718 (skip-chars-forward " \t")
5719 (cond
5720 ((looking-at verilog-named-block-re)
5721 (current-column))
5722 ((and (not (looking-at verilog-extended-case-re))
5723 (looking-at "^[^:;]+[ \t]*:"))
5724 (verilog-re-search-forward ":" nil t)
5725 (skip-chars-forward " \t")
5726 (current-column))
5727 (t
5728 (current-column)))))
5729
5730 (defun verilog-indent-comment ()
5731 "Indent current line as comment."
5732 (let* ((stcol
5733 (cond
5734 ((verilog-in-star-comment-p)
5735 (save-excursion
5736 (re-search-backward "/\\*" nil t)
5737 (1+(current-column))))
5738 (comment-column
5739 comment-column )
5740 (t
5741 (save-excursion
5742 (re-search-backward "//" nil t)
5743 (current-column))))))
5744 (indent-line-to stcol)
5745 stcol))
5746
5747 (defun verilog-more-comment ()
5748 "Make more comment lines like the previous."
5749 (let* ((star 0)
5750 (stcol
5751 (cond
5752 ((verilog-in-star-comment-p)
5753 (save-excursion
5754 (setq star 1)
5755 (re-search-backward "/\\*" nil t)
5756 (1+(current-column))))
5757 (comment-column
5758 comment-column )
5759 (t
5760 (save-excursion
5761 (re-search-backward "//" nil t)
5762 (current-column))))))
5763 (progn
5764 (indent-to stcol)
5765 (if (and star
5766 (save-excursion
5767 (forward-line -1)
5768 (skip-chars-forward " \t")
5769 (looking-at "\*")))
5770 (insert "* ")))))
5771
5772 (defun verilog-comment-indent (&optional arg)
5773 "Return the column number the line should be indented to.
5774 ARG is ignored, for `comment-indent-function' compatibility."
5775 (cond
5776 ((verilog-in-star-comment-p)
5777 (save-excursion
5778 (re-search-backward "/\\*" nil t)
5779 (1+(current-column))))
5780 ( comment-column
5781 comment-column )
5782 (t
5783 (save-excursion
5784 (re-search-backward "//" nil t)
5785 (current-column)))))
5786
5787 ;;
5788
5789 (defun verilog-pretty-declarations (&optional quiet)
5790 "Line up declarations around point.
5791 Be verbose about progress unless optional QUIET set."
5792 (interactive)
5793 (let* ((m1 (make-marker))
5794 (e (point))
5795 el
5796 r
5797 (here (point))
5798 ind
5799 start
5800 startpos
5801 end
5802 endpos
5803 base-ind
5804 )
5805 (save-excursion
5806 (if (progn
5807 ; (verilog-beg-of-statement-1)
5808 (beginning-of-line)
5809 (verilog-forward-syntactic-ws)
5810 (and (not (verilog-in-directive-p)) ;; could have `define input foo
5811 (looking-at verilog-declaration-re)))
5812 (progn
5813 (if (verilog-parenthesis-depth)
5814 ;; in an argument list or parameter block
5815 (setq el (verilog-backward-up-list -1)
5816 start (progn
5817 (goto-char e)
5818 (verilog-backward-up-list 1)
5819 (forward-line) ;; ignore ( input foo,
5820 (verilog-re-search-forward verilog-declaration-re el 'move)
5821 (goto-char (match-beginning 0))
5822 (skip-chars-backward " \t")
5823 (point))
5824 startpos (set-marker (make-marker) start)
5825 end (progn
5826 (goto-char start)
5827 (verilog-backward-up-list -1)
5828 (forward-char -1)
5829 (verilog-backward-syntactic-ws)
5830 (point))
5831 endpos (set-marker (make-marker) end)
5832 base-ind (progn
5833 (goto-char start)
5834 (forward-char 1)
5835 (skip-chars-forward " \t")
5836 (current-column))
5837 )
5838 ;; in a declaration block (not in argument list)
5839 (setq
5840 start (progn
5841 (verilog-beg-of-statement-1)
5842 (while (and (looking-at verilog-declaration-re)
5843 (not (bobp)))
5844 (skip-chars-backward " \t")
5845 (setq e (point))
5846 (beginning-of-line)
5847 (verilog-backward-syntactic-ws)
5848 (backward-char)
5849 (verilog-beg-of-statement-1))
5850 e)
5851 startpos (set-marker (make-marker) start)
5852 end (progn
5853 (goto-char here)
5854 (verilog-end-of-statement)
5855 (setq e (point)) ;Might be on last line
5856 (verilog-forward-syntactic-ws)
5857 (while (looking-at verilog-declaration-re)
5858 (verilog-end-of-statement)
5859 (setq e (point))
5860 (verilog-forward-syntactic-ws))
5861 e)
5862 endpos (set-marker (make-marker) end)
5863 base-ind (progn
5864 (goto-char start)
5865 (verilog-do-indent (verilog-calculate-indent))
5866 (verilog-forward-ws&directives)
5867 (current-column))))
5868 ;; OK, start and end are set
5869 (goto-char (marker-position startpos))
5870 (if (and (not quiet)
5871 (> (- end start) 100))
5872 (message "Lining up declarations..(please stand by)"))
5873 ;; Get the beginning of line indent first
5874 (while (progn (setq e (marker-position endpos))
5875 (< (point) e))
5876 (cond
5877 ((save-excursion (skip-chars-backward " \t")
5878 (bolp))
5879 (verilog-forward-ws&directives)
5880 (indent-line-to base-ind)
5881 (verilog-forward-ws&directives)
5882 (if (< (point) e)
5883 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5884 (t
5885 (just-one-space)
5886 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5887 ;;(forward-line)
5888 )
5889 ;; Now find biggest prefix
5890 (setq ind (verilog-get-lineup-indent (marker-position startpos) endpos))
5891 ;; Now indent each line.
5892 (goto-char (marker-position startpos))
5893 (while (progn (setq e (marker-position endpos))
5894 (setq r (- e (point)))
5895 (> r 0))
5896 (setq e (point))
5897 (unless quiet (message "%d" r))
5898 ;;(verilog-do-indent (verilog-calculate-indent)))
5899 (verilog-forward-ws&directives)
5900 (cond
5901 ((or (and verilog-indent-declaration-macros
5902 (looking-at verilog-declaration-re-2-macro))
5903 (looking-at verilog-declaration-re-2-no-macro))
5904 (let ((p (match-end 0)))
5905 (set-marker m1 p)
5906 (if (verilog-re-search-forward "[[#`]" p 'move)
5907 (progn
5908 (forward-char -1)
5909 (just-one-space)
5910 (goto-char (marker-position m1))
5911 (just-one-space)
5912 (indent-to ind))
5913 (progn
5914 (just-one-space)
5915 (indent-to ind)))))
5916 ((verilog-continued-line-1 (marker-position startpos))
5917 (goto-char e)
5918 (indent-line-to ind))
5919 ((verilog-in-struct-p)
5920 ;; could have a declaration of a user defined item
5921 (goto-char e)
5922 (verilog-end-of-statement))
5923 (t ; Must be comment or white space
5924 (goto-char e)
5925 (verilog-forward-ws&directives)
5926 (forward-line -1)))
5927 (forward-line 1))
5928 (unless quiet (message "")))))))
5929
5930 (defun verilog-pretty-expr (&optional quiet myre)
5931 "Line up expressions around point, optionally QUIET with regexp MYRE."
5932 (interactive "i\nsRegular Expression: ((<|:)?=) ")
5933 (save-excursion
5934 (if (or (eq myre nil)
5935 (string-equal myre ""))
5936 (setq myre "\\(<\\|:\\)?="))
5937 ;; want to match the first <= | := | =
5938 (setq myre (concat "\\(^.*?\\)\\(" myre "\\)"))
5939 (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
5940 (beginning-of-line)
5941 (if (and (not (looking-at rexp ))
5942 (looking-at myre)
5943 (save-excursion
5944 (goto-char (match-beginning 2))
5945 (not (verilog-in-comment-or-string-p))))
5946 (let* ((here (point))
5947 (e) (r)
5948 (start
5949 (progn
5950 (beginning-of-line)
5951 (setq e (point))
5952 (verilog-backward-syntactic-ws)
5953 (beginning-of-line)
5954 (while (and (not (looking-at rexp ))
5955 (looking-at myre)
5956 (not (bobp))
5957 )
5958 (setq e (point))
5959 (verilog-backward-syntactic-ws)
5960 (beginning-of-line)
5961 ) ;Ack, need to grok `define
5962 e))
5963 (end
5964 (progn
5965 (goto-char here)
5966 (end-of-line)
5967 (setq e (point)) ;Might be on last line
5968 (verilog-forward-syntactic-ws)
5969 (beginning-of-line)
5970 (while (and
5971 (not (looking-at rexp ))
5972 (looking-at myre)
5973 (progn
5974 (end-of-line)
5975 (not (eq e (point)))))
5976 (setq e (point))
5977 (verilog-forward-syntactic-ws)
5978 (beginning-of-line)
5979 )
5980 e))
5981 (endpos (set-marker (make-marker) end))
5982 (ind)
5983 )
5984 (goto-char start)
5985 (verilog-do-indent (verilog-calculate-indent))
5986 (if (and (not quiet)
5987 (> (- end start) 100))
5988 (message "Lining up expressions..(please stand by)"))
5989
5990 ;; Set indent to minimum throughout region
5991 (while (< (point) (marker-position endpos))
5992 (beginning-of-line)
5993 (verilog-just-one-space myre)
5994 (end-of-line)
5995 (verilog-forward-syntactic-ws)
5996 )
5997
5998 ;; Now find biggest prefix
5999 (setq ind (verilog-get-lineup-indent-2 myre start endpos))
6000
6001 ;; Now indent each line.
6002 (goto-char start)
6003 (while (progn (setq e (marker-position endpos))
6004 (setq r (- e (point)))
6005 (> r 0))
6006 (setq e (point))
6007 (if (not quiet) (message "%d" r))
6008 (cond
6009 ((looking-at myre)
6010 (goto-char (match-beginning 2))
6011 (if (not (verilog-parenthesis-depth)) ;; ignore parenthesized exprs
6012 (if (eq (char-after) ?=)
6013 (indent-to (1+ ind)) ; line up the = of the <= with surrounding =
6014 (indent-to ind)
6015 )))
6016 ((verilog-continued-line-1 start)
6017 (goto-char e)
6018 (indent-line-to ind))
6019 (t ; Must be comment or white space
6020 (goto-char e)
6021 (verilog-forward-ws&directives)
6022 (forward-line -1))
6023 )
6024 (forward-line 1))
6025 (unless quiet (message ""))
6026 )))))
6027
6028 (defun verilog-just-one-space (myre)
6029 "Remove extra spaces around regular expression MYRE."
6030 (interactive)
6031 (if (and (not(looking-at verilog-complete-reg))
6032 (looking-at myre))
6033 (let ((p1 (match-end 1))
6034 (p2 (match-end 2)))
6035 (progn
6036 (goto-char p2)
6037 (if (looking-at "\\s-") (just-one-space))
6038 (goto-char p1)
6039 (forward-char -1)
6040 (if (looking-at "\\s-") (just-one-space))
6041 ))))
6042
6043 (defun verilog-indent-declaration (baseind)
6044 "Indent current lines as declaration.
6045 Line up the variable names based on previous declaration's indentation.
6046 BASEIND is the base indent to offset everything."
6047 (interactive)
6048 (let ((pos (point-marker))
6049 (lim (save-excursion
6050 ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
6051 (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
6052 (point)))
6053 (ind)
6054 (val)
6055 (m1 (make-marker)))
6056 (setq val
6057 (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6058 (indent-line-to val)
6059
6060 ;; Use previous declaration (in this module) as template.
6061 (if (or (eq 'all verilog-auto-lineup)
6062 (eq 'declarations verilog-auto-lineup))
6063 (if (verilog-re-search-backward
6064 (or (and verilog-indent-declaration-macros
6065 verilog-declaration-re-1-macro)
6066 verilog-declaration-re-1-no-macro) lim t)
6067 (progn
6068 (goto-char (match-end 0))
6069 (skip-chars-forward " \t")
6070 (setq ind (current-column))
6071 (goto-char pos)
6072 (setq val
6073 (+ baseind
6074 (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6075 (indent-line-to val)
6076 (if (and verilog-indent-declaration-macros
6077 (looking-at verilog-declaration-re-2-macro))
6078 (let ((p (match-end 0)))
6079 (set-marker m1 p)
6080 (if (verilog-re-search-forward "[[#`]" p 'move)
6081 (progn
6082 (forward-char -1)
6083 (just-one-space)
6084 (goto-char (marker-position m1))
6085 (just-one-space)
6086 (indent-to ind))
6087 (if (/= (current-column) ind)
6088 (progn
6089 (just-one-space)
6090 (indent-to ind)))))
6091 (if (looking-at verilog-declaration-re-2-no-macro)
6092 (let ((p (match-end 0)))
6093 (set-marker m1 p)
6094 (if (verilog-re-search-forward "[[`#]" p 'move)
6095 (progn
6096 (forward-char -1)
6097 (just-one-space)
6098 (goto-char (marker-position m1))
6099 (just-one-space)
6100 (indent-to ind))
6101 (if (/= (current-column) ind)
6102 (progn
6103 (just-one-space)
6104 (indent-to ind))))))))))
6105 (goto-char pos)))
6106
6107 (defun verilog-get-lineup-indent (b edpos)
6108 "Return the indent level that will line up several lines within the region.
6109 Region is defined by B and EDPOS."
6110 (save-excursion
6111 (let ((ind 0) e)
6112 (goto-char b)
6113 ;; Get rightmost position
6114 (while (progn (setq e (marker-position edpos))
6115 (< (point) e))
6116 (if (verilog-re-search-forward
6117 (or (and verilog-indent-declaration-macros
6118 verilog-declaration-re-1-macro)
6119 verilog-declaration-re-1-no-macro) e 'move)
6120 (progn
6121 (goto-char (match-end 0))
6122 (verilog-backward-syntactic-ws)
6123 (if (> (current-column) ind)
6124 (setq ind (current-column)))
6125 (goto-char (match-end 0)))))
6126 (if (> ind 0)
6127 (1+ ind)
6128 ;; No lineup-string found
6129 (goto-char b)
6130 (end-of-line)
6131 (verilog-backward-syntactic-ws)
6132 ;;(skip-chars-backward " \t")
6133 (1+ (current-column))))))
6134
6135 (defun verilog-get-lineup-indent-2 (myre b edpos)
6136 "Return the indent level that will line up several lines within the region."
6137 (save-excursion
6138 (let ((ind 0) e)
6139 (goto-char b)
6140 ;; Get rightmost position
6141 (while (progn (setq e (marker-position edpos))
6142 (< (point) e))
6143 (if (and (verilog-re-search-forward myre e 'move)
6144 (not (verilog-parenthesis-depth))) ;; skip parenthesized exprs
6145 (progn
6146 (goto-char (match-beginning 2))
6147 (verilog-backward-syntactic-ws)
6148 (if (> (current-column) ind)
6149 (setq ind (current-column)))
6150 (goto-char (match-end 0)))
6151 ))
6152 (if (> ind 0)
6153 (1+ ind)
6154 ;; No lineup-string found
6155 (goto-char b)
6156 (end-of-line)
6157 (skip-chars-backward " \t")
6158 (1+ (current-column))))))
6159
6160 (defun verilog-comment-depth (type val)
6161 "A useful mode debugging aide. TYPE and VAL are comments for insertion."
6162 (save-excursion
6163 (let
6164 ((b (prog2
6165 (beginning-of-line)
6166 (point-marker)
6167 (end-of-line)))
6168 (e (point-marker)))
6169 (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
6170 (progn
6171 (replace-match " /* -# ## */")
6172 (end-of-line))
6173 (progn
6174 (end-of-line)
6175 (insert " /* ## ## */"))))
6176 (backward-char 6)
6177 (insert
6178 (format "%s %d" type val))))
6179
6180 ;; \f
6181 ;;
6182 ;; Completion
6183 ;;
6184 (defvar verilog-str nil)
6185 (defvar verilog-all nil)
6186 (defvar verilog-pred nil)
6187 (defvar verilog-buffer-to-use nil)
6188 (defvar verilog-flag nil)
6189 (defvar verilog-toggle-completions nil
6190 "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
6191 Repeated use of \\[verilog-complete-word] will show you all of them.
6192 Normally, when there is more than one possible completion,
6193 it displays a list of all possible completions.")
6194
6195
6196 (defvar verilog-type-keywords
6197 '(
6198 "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
6199 "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
6200 "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
6201 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
6202 "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
6203 "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
6204 )
6205 "*Keywords for types used when completing a word in a declaration or parmlist.
6206 \(integer, real, reg...)")
6207
6208 (defvar verilog-cpp-keywords
6209 '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
6210 "endif")
6211 "*Keywords to complete when at first word of a line in declarative scope.
6212 \(initial, always, begin, assign...)
6213 The procedures and variables defined within the Verilog program
6214 will be completed at runtime and should not be added to this list.")
6215
6216 (defvar verilog-defun-keywords
6217 (append
6218 '(
6219 "always" "always_comb" "always_ff" "always_latch" "assign"
6220 "begin" "end" "generate" "endgenerate" "module" "endmodule"
6221 "specify" "endspecify" "function" "endfunction" "initial" "final"
6222 "task" "endtask" "primitive" "endprimitive"
6223 )
6224 verilog-type-keywords)
6225 "*Keywords to complete when at first word of a line in declarative scope.
6226 \(initial, always, begin, assign...)
6227 The procedures and variables defined within the Verilog program
6228 will be completed at runtime and should not be added to this list.")
6229
6230 (defvar verilog-block-keywords
6231 '(
6232 "begin" "break" "case" "continue" "else" "end" "endfunction"
6233 "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
6234 "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
6235 "while")
6236 "*Keywords to complete when at first word of a line in behavioral scope.
6237 \(begin, if, then, else, for, fork...)
6238 The procedures and variables defined within the Verilog program
6239 will be completed at runtime and should not be added to this list.")
6240
6241 (defvar verilog-tf-keywords
6242 '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
6243 "*Keywords to complete when at first word of a line in a task or function.
6244 \(begin, if, then, else, for, fork.)
6245 The procedures and variables defined within the Verilog program
6246 will be completed at runtime and should not be added to this list.")
6247
6248 (defvar verilog-case-keywords
6249 '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
6250 "*Keywords to complete when at first word of a line in case scope.
6251 \(begin, if, then, else, for, fork...)
6252 The procedures and variables defined within the Verilog program
6253 will be completed at runtime and should not be added to this list.")
6254
6255 (defvar verilog-separator-keywords
6256 '("else" "then" "begin")
6257 "*Keywords to complete when NOT standing at the first word of a statement.
6258 \(else, then, begin...)
6259 Variables and function names defined within the Verilog program
6260 will be completed at runtime and should not be added to this list.")
6261
6262 (defvar verilog-gate-ios
6263 ;; All these have an implied {"input"...} at the end
6264 '(("and" "output")
6265 ("buf" "output")
6266 ("bufif0" "output")
6267 ("bufif1" "output")
6268 ("cmos" "output")
6269 ("nand" "output")
6270 ("nmos" "output")
6271 ("nor" "output")
6272 ("not" "output")
6273 ("notif0" "output")
6274 ("notif1" "output")
6275 ("or" "output")
6276 ("pmos" "output")
6277 ("pulldown" "output")
6278 ("pullup" "output")
6279 ("rcmos" "output")
6280 ("rnmos" "output")
6281 ("rpmos" "output")
6282 ("rtran" "inout" "inout")
6283 ("rtranif0" "inout" "inout")
6284 ("rtranif1" "inout" "inout")
6285 ("tran" "inout" "inout")
6286 ("tranif0" "inout" "inout")
6287 ("tranif1" "inout" "inout")
6288 ("xnor" "output")
6289 ("xor" "output"))
6290 "*Map of direction for each positional argument to each gate primitive.")
6291
6292 (defvar verilog-gate-keywords (mapcar `car verilog-gate-ios)
6293 "*Keywords for gate primitives.")
6294
6295 (defun verilog-string-diff (str1 str2)
6296 "Return index of first letter where STR1 and STR2 differs."
6297 (catch 'done
6298 (let ((diff 0))
6299 (while t
6300 (if (or (> (1+ diff) (length str1))
6301 (> (1+ diff) (length str2)))
6302 (throw 'done diff))
6303 (or (equal (aref str1 diff) (aref str2 diff))
6304 (throw 'done diff))
6305 (setq diff (1+ diff))))))
6306
6307 ;; Calculate all possible completions for functions if argument is `function',
6308 ;; completions for procedures if argument is `procedure' or both functions and
6309 ;; procedures otherwise.
6310
6311 (defun verilog-func-completion (type)
6312 "Build regular expression for module/task/function names.
6313 TYPE is 'module, 'tf for task or function, or t if unknown."
6314 (if (string= verilog-str "")
6315 (setq verilog-str "[a-zA-Z_]"))
6316 (let ((verilog-str (concat (cond
6317 ((eq type 'module) "\\<\\(module\\)\\s +")
6318 ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
6319 (t "\\<\\(task\\|function\\|module\\)\\s +"))
6320 "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
6321 match)
6322
6323 (if (not (looking-at verilog-defun-re))
6324 (verilog-re-search-backward verilog-defun-re nil t))
6325 (forward-char 1)
6326
6327 ;; Search through all reachable functions
6328 (goto-char (point-min))
6329 (while (verilog-re-search-forward verilog-str (point-max) t)
6330 (progn (setq match (buffer-substring (match-beginning 2)
6331 (match-end 2)))
6332 (if (or (null verilog-pred)
6333 (funcall verilog-pred match))
6334 (setq verilog-all (cons match verilog-all)))))
6335 (if (match-beginning 0)
6336 (goto-char (match-beginning 0)))))
6337
6338 (defun verilog-get-completion-decl (end)
6339 "Macro for searching through current declaration (var, type or const)
6340 for matches of `str' and adding the occurrence tp `all' through point END."
6341 (let ((re (or (and verilog-indent-declaration-macros
6342 verilog-declaration-re-2-macro)
6343 verilog-declaration-re-2-no-macro))
6344 decl-end match)
6345 ;; Traverse lines
6346 (while (and (< (point) end)
6347 (verilog-re-search-forward re end t))
6348 ;; Traverse current line
6349 (setq decl-end (save-excursion (verilog-declaration-end)))
6350 (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
6351 (not (match-end 1)))
6352 (setq match (buffer-substring (match-beginning 0) (match-end 0)))
6353 (if (string-match (concat "\\<" verilog-str) match)
6354 (if (or (null verilog-pred)
6355 (funcall verilog-pred match))
6356 (setq verilog-all (cons match verilog-all)))))
6357 (forward-line 1)))
6358 verilog-all)
6359
6360 (defun verilog-type-completion ()
6361 "Calculate all possible completions for types."
6362 (let ((start (point))
6363 goon)
6364 ;; Search for all reachable type declarations
6365 (while (or (verilog-beg-of-defun)
6366 (setq goon (not goon)))
6367 (save-excursion
6368 (if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
6369 (point))
6370 (forward-char 1)))
6371 (verilog-re-search-forward
6372 "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
6373 start t)
6374 (not (match-end 1)))
6375 ;; Check current type declaration
6376 (verilog-get-completion-decl start))))))
6377
6378 (defun verilog-var-completion ()
6379 "Calculate all possible completions for variables (or constants)."
6380 (let ((start (point)))
6381 ;; Search for all reachable var declarations
6382 (verilog-beg-of-defun)
6383 (save-excursion
6384 ;; Check var declarations
6385 (verilog-get-completion-decl start))))
6386
6387 (defun verilog-keyword-completion (keyword-list)
6388 "Give list of all possible completions of keywords in KEYWORD-LIST."
6389 (mapcar '(lambda (s)
6390 (if (string-match (concat "\\<" verilog-str) s)
6391 (if (or (null verilog-pred)
6392 (funcall verilog-pred s))
6393 (setq verilog-all (cons s verilog-all)))))
6394 keyword-list))
6395
6396
6397 (defun verilog-completion (verilog-str verilog-pred verilog-flag)
6398 "Function passed to `completing-read', `try-completion' or `all-completions'.
6399 Called to get completion on VERILOG-STR. If VERILOG-PRED is non-nil, it
6400 must be a function to be called for every match to check if this should
6401 really be a match. If VERILOG-FLAG is t, the function returns a list of
6402 all possible completions. If VERILOG-FLAG is nil it returns a string,
6403 the longest possible completion, or t if VERILOG-STR is an exact match.
6404 If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
6405 exact match, nil otherwise."
6406 (save-excursion
6407 (let ((verilog-all nil))
6408 ;; Set buffer to use for searching labels. This should be set
6409 ;; within functions which use verilog-completions
6410 (set-buffer verilog-buffer-to-use)
6411
6412 ;; Determine what should be completed
6413 (let ((state (car (verilog-calculate-indent))))
6414 (cond ((eq state 'defun)
6415 (save-excursion (verilog-var-completion))
6416 (verilog-func-completion 'module)
6417 (verilog-keyword-completion verilog-defun-keywords))
6418
6419 ((eq state 'behavioral)
6420 (save-excursion (verilog-var-completion))
6421 (verilog-func-completion 'module)
6422 (verilog-keyword-completion verilog-defun-keywords))
6423
6424 ((eq state 'block)
6425 (save-excursion (verilog-var-completion))
6426 (verilog-func-completion 'tf)
6427 (verilog-keyword-completion verilog-block-keywords))
6428
6429 ((eq state 'case)
6430 (save-excursion (verilog-var-completion))
6431 (verilog-func-completion 'tf)
6432 (verilog-keyword-completion verilog-case-keywords))
6433
6434 ((eq state 'tf)
6435 (save-excursion (verilog-var-completion))
6436 (verilog-func-completion 'tf)
6437 (verilog-keyword-completion verilog-tf-keywords))
6438
6439 ((eq state 'cpp)
6440 (save-excursion (verilog-var-completion))
6441 (verilog-keyword-completion verilog-cpp-keywords))
6442
6443 ((eq state 'cparenexp)
6444 (save-excursion (verilog-var-completion)))
6445
6446 (t;--Anywhere else
6447 (save-excursion (verilog-var-completion))
6448 (verilog-func-completion 'both)
6449 (verilog-keyword-completion verilog-separator-keywords))))
6450
6451 ;; Now we have built a list of all matches. Give response to caller
6452 (verilog-completion-response))))
6453
6454 (defun verilog-completion-response ()
6455 (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
6456 ;; This was not called by all-completions
6457 (if (null verilog-all)
6458 ;; Return nil if there was no matching label
6459 nil
6460 ;; Get longest string common in the labels
6461 (let* ((elm (cdr verilog-all))
6462 (match (car verilog-all))
6463 (min (length match))
6464 tmp)
6465 (if (string= match verilog-str)
6466 ;; Return t if first match was an exact match
6467 (setq match t)
6468 (while (not (null elm))
6469 ;; Find longest common string
6470 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
6471 (progn
6472 (setq min tmp)
6473 (setq match (substring match 0 min))))
6474 ;; Terminate with match=t if this is an exact match
6475 (if (string= (car elm) verilog-str)
6476 (progn
6477 (setq match t)
6478 (setq elm nil))
6479 (setq elm (cdr elm)))))
6480 ;; If this is a test just for exact match, return nil ot t
6481 (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
6482 nil
6483 match))))
6484 ;; If flag is t, this was called by all-completions. Return
6485 ;; list of all possible completions
6486 (verilog-flag
6487 verilog-all)))
6488
6489 (defvar verilog-last-word-numb 0)
6490 (defvar verilog-last-word-shown nil)
6491 (defvar verilog-last-completions nil)
6492
6493 (defun verilog-complete-word ()
6494 "Complete word at current point.
6495 \(See also `verilog-toggle-completions', `verilog-type-keywords',
6496 and `verilog-separator-keywords'.)"
6497 (interactive)
6498 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
6499 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
6500 (verilog-str (buffer-substring b e))
6501 ;; The following variable is used in verilog-completion
6502 (verilog-buffer-to-use (current-buffer))
6503 (allcomp (if (and verilog-toggle-completions
6504 (string= verilog-last-word-shown verilog-str))
6505 verilog-last-completions
6506 (all-completions verilog-str 'verilog-completion)))
6507 (match (if verilog-toggle-completions
6508 "" (try-completion
6509 verilog-str (mapcar '(lambda (elm)
6510 (cons elm 0)) allcomp)))))
6511 ;; Delete old string
6512 (delete-region b e)
6513
6514 ;; Toggle-completions inserts whole labels
6515 (if verilog-toggle-completions
6516 (progn
6517 ;; Update entry number in list
6518 (setq verilog-last-completions allcomp
6519 verilog-last-word-numb
6520 (if (>= verilog-last-word-numb (1- (length allcomp)))
6521 0
6522 (1+ verilog-last-word-numb)))
6523 (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
6524 ;; Display next match or same string if no match was found
6525 (if (not (null allcomp))
6526 (insert "" verilog-last-word-shown)
6527 (insert "" verilog-str)
6528 (message "(No match)")))
6529 ;; The other form of completion does not necessarily do that.
6530
6531 ;; Insert match if found, or the original string if no match
6532 (if (or (null match) (equal match 't))
6533 (progn (insert "" verilog-str)
6534 (message "(No match)"))
6535 (insert "" match))
6536 ;; Give message about current status of completion
6537 (cond ((equal match 't)
6538 (if (not (null (cdr allcomp)))
6539 (message "(Complete but not unique)")
6540 (message "(Sole completion)")))
6541 ;; Display buffer if the current completion didn't help
6542 ;; on completing the label.
6543 ((and (not (null (cdr allcomp))) (= (length verilog-str)
6544 (length match)))
6545 (with-output-to-temp-buffer "*Completions*"
6546 (display-completion-list allcomp))
6547 ;; Wait for a key press. Then delete *Completion* window
6548 (momentary-string-display "" (point))
6549 (delete-window (get-buffer-window (get-buffer "*Completions*")))
6550 )))))
6551
6552 (defun verilog-show-completions ()
6553 "Show all possible completions at current point."
6554 (interactive)
6555 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
6556 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
6557 (verilog-str (buffer-substring b e))
6558 ;; The following variable is used in verilog-completion
6559 (verilog-buffer-to-use (current-buffer))
6560 (allcomp (if (and verilog-toggle-completions
6561 (string= verilog-last-word-shown verilog-str))
6562 verilog-last-completions
6563 (all-completions verilog-str 'verilog-completion))))
6564 ;; Show possible completions in a temporary buffer.
6565 (with-output-to-temp-buffer "*Completions*"
6566 (display-completion-list allcomp))
6567 ;; Wait for a key press. Then delete *Completion* window
6568 (momentary-string-display "" (point))
6569 (delete-window (get-buffer-window (get-buffer "*Completions*")))))
6570
6571
6572 (defun verilog-get-default-symbol ()
6573 "Return symbol around current point as a string."
6574 (save-excursion
6575 (buffer-substring (progn
6576 (skip-chars-backward " \t")
6577 (skip-chars-backward "a-zA-Z0-9_")
6578 (point))
6579 (progn
6580 (skip-chars-forward "a-zA-Z0-9_")
6581 (point)))))
6582
6583 (defun verilog-build-defun-re (str &optional arg)
6584 "Return function/task/module starting with STR as regular expression.
6585 With optional second ARG non-nil, STR is the complete name of the instruction."
6586 (if arg
6587 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
6588 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
6589
6590 (defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
6591 "Function passed to `completing-read', `try-completion' or `all-completions'.
6592 Returns a completion on any function name based on VERILOG-STR prefix. If
6593 VERILOG-PRED is non-nil, it must be a function to be called for every match
6594 to check if this should really be a match. If VERILOG-FLAG is t, the
6595 function returns a list of all possible completions. If it is nil it
6596 returns a string, the longest possible completion, or t if VERILOG-STR is
6597 an exact match. If VERILOG-FLAG is 'lambda, the function returns t if
6598 VERILOG-STR is an exact match, nil otherwise."
6599 (save-excursion
6600 (let ((verilog-all nil)
6601 match)
6602
6603 ;; Set buffer to use for searching labels. This should be set
6604 ;; within functions which use verilog-completions
6605 (set-buffer verilog-buffer-to-use)
6606
6607 (let ((verilog-str verilog-str))
6608 ;; Build regular expression for functions
6609 (if (string= verilog-str "")
6610 (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
6611 (setq verilog-str (verilog-build-defun-re verilog-str)))
6612 (goto-char (point-min))
6613
6614 ;; Build a list of all possible completions
6615 (while (verilog-re-search-forward verilog-str nil t)
6616 (setq match (buffer-substring (match-beginning 2) (match-end 2)))
6617 (if (or (null verilog-pred)
6618 (funcall verilog-pred match))
6619 (setq verilog-all (cons match verilog-all)))))
6620
6621 ;; Now we have built a list of all matches. Give response to caller
6622 (verilog-completion-response))))
6623
6624 (defun verilog-goto-defun ()
6625 "Move to specified Verilog module/interface/task/function.
6626 The default is a name found in the buffer around point.
6627 If search fails, other files are checked based on
6628 `verilog-library-flags'."
6629 (interactive)
6630 (let* ((default (verilog-get-default-symbol))
6631 ;; The following variable is used in verilog-comp-function
6632 (verilog-buffer-to-use (current-buffer))
6633 (label (if (not (string= default ""))
6634 ;; Do completion with default
6635 (completing-read (concat "Goto-Label: (default "
6636 default ") ")
6637 'verilog-comp-defun nil nil "")
6638 ;; There is no default value. Complete without it
6639 (completing-read "Goto-Label: "
6640 'verilog-comp-defun nil nil "")))
6641 pt)
6642 ;; Make sure library paths are correct, in case need to resolve module
6643 (verilog-auto-reeval-locals)
6644 (verilog-getopt-flags)
6645 ;; If there was no response on prompt, use default value
6646 (if (string= label "")
6647 (setq label default))
6648 ;; Goto right place in buffer if label is not an empty string
6649 (or (string= label "")
6650 (progn
6651 (save-excursion
6652 (goto-char (point-min))
6653 (setq pt
6654 (re-search-forward (verilog-build-defun-re label t) nil t)))
6655 (when pt
6656 (goto-char pt)
6657 (beginning-of-line))
6658 pt)
6659 (verilog-goto-defun-file label))))
6660
6661 ;; Eliminate compile warning
6662 (defvar occur-pos-list)
6663
6664 (defun verilog-showscopes ()
6665 "List all scopes in this module."
6666 (interactive)
6667 (let ((buffer (current-buffer))
6668 (linenum 1)
6669 (nlines 0)
6670 (first 1)
6671 (prevpos (point-min))
6672 (final-context-start (make-marker))
6673 (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
6674 (with-output-to-temp-buffer "*Occur*"
6675 (save-excursion
6676 (message (format "Searching for %s ..." regexp))
6677 ;; Find next match, but give up if prev match was at end of buffer.
6678 (while (and (not (= prevpos (point-max)))
6679 (verilog-re-search-forward regexp nil t))
6680 (goto-char (match-beginning 0))
6681 (beginning-of-line)
6682 (save-match-data
6683 (setq linenum (+ linenum (count-lines prevpos (point)))))
6684 (setq prevpos (point))
6685 (goto-char (match-end 0))
6686 (let* ((start (save-excursion
6687 (goto-char (match-beginning 0))
6688 (forward-line (if (< nlines 0) nlines (- nlines)))
6689 (point)))
6690 (end (save-excursion
6691 (goto-char (match-end 0))
6692 (if (> nlines 0)
6693 (forward-line (1+ nlines))
6694 (forward-line 1))
6695 (point)))
6696 (tag (format "%3d" linenum))
6697 (empty (make-string (length tag) ?\ ))
6698 tem)
6699 (save-excursion
6700 (setq tem (make-marker))
6701 (set-marker tem (point))
6702 (set-buffer standard-output)
6703 (setq occur-pos-list (cons tem occur-pos-list))
6704 (or first (zerop nlines)
6705 (insert "--------\n"))
6706 (setq first nil)
6707 (insert-buffer-substring buffer start end)
6708 (backward-char (- end start))
6709 (setq tem (if (< nlines 0) (- nlines) nlines))
6710 (while (> tem 0)
6711 (insert empty ?:)
6712 (forward-line 1)
6713 (setq tem (1- tem)))
6714 (let ((this-linenum linenum))
6715 (set-marker final-context-start
6716 (+ (point) (- (match-end 0) (match-beginning 0))))
6717 (while (< (point) final-context-start)
6718 (if (null tag)
6719 (setq tag (format "%3d" this-linenum)))
6720 (insert tag ?:)))))))
6721 (set-buffer-modified-p nil))))
6722
6723
6724 ;; Highlight helper functions
6725 (defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
6726 (defun verilog-within-translate-off ()
6727 "Return point if within translate-off region, else nil."
6728 (and (save-excursion
6729 (re-search-backward
6730 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
6731 nil t))
6732 (equal "off" (match-string 2))
6733 (point)))
6734
6735 (defun verilog-start-translate-off (limit)
6736 "Return point before translate-off directive if before LIMIT, else nil."
6737 (when (re-search-forward
6738 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6739 limit t)
6740 (match-beginning 0)))
6741
6742 (defun verilog-back-to-start-translate-off (limit)
6743 "Return point before translate-off directive if before LIMIT, else nil."
6744 (when (re-search-backward
6745 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6746 limit t)
6747 (match-beginning 0)))
6748
6749 (defun verilog-end-translate-off (limit)
6750 "Return point after translate-on directive if before LIMIT, else nil."
6751
6752 (re-search-forward (concat
6753 "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
6754
6755 (defun verilog-match-translate-off (limit)
6756 "Match a translate-off block, setting `match-data' and returning t, else nil.
6757 Bound search by LIMIT."
6758 (when (< (point) limit)
6759 (let ((start (or (verilog-within-translate-off)
6760 (verilog-start-translate-off limit)))
6761 (case-fold-search t))
6762 (when start
6763 (let ((end (or (verilog-end-translate-off limit) limit)))
6764 (set-match-data (list start end))
6765 (goto-char end))))))
6766
6767 (defun verilog-font-lock-match-item (limit)
6768 "Match, and move over, any declaration item after point.
6769 Bound search by LIMIT. Adapted from
6770 `font-lock-match-c-style-declaration-item-and-skip-to-next'."
6771 (condition-case nil
6772 (save-restriction
6773 (narrow-to-region (point-min) limit)
6774 ;; match item
6775 (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
6776 (save-match-data
6777 (goto-char (match-end 1))
6778 ;; move to next item
6779 (if (looking-at "\\(\\s-*,\\)")
6780 (goto-char (match-end 1))
6781 (end-of-line) t))))
6782 (error nil)))
6783
6784
6785 ;; Added by Subbu Meiyappan for Header
6786
6787 (defun verilog-header ()
6788 "Insert a standard Verilog file header.
6789 See also `verilog-sk-header' for an alternative format."
6790 (interactive)
6791 (let ((start (point)))
6792 (insert "\
6793 //-----------------------------------------------------------------------------
6794 // Title : <title>
6795 // Project : <project>
6796 //-----------------------------------------------------------------------------
6797 // File : <filename>
6798 // Author : <author>
6799 // Created : <credate>
6800 // Last modified : <moddate>
6801 //-----------------------------------------------------------------------------
6802 // Description :
6803 // <description>
6804 //-----------------------------------------------------------------------------
6805 // Copyright (c) <copydate> by <company> This model is the confidential and
6806 // proprietary property of <company> and the possession or use of this
6807 // file requires a written license from <company>.
6808 //------------------------------------------------------------------------------
6809 // Modification history :
6810 // <modhist>
6811 //-----------------------------------------------------------------------------
6812
6813 ")
6814 (goto-char start)
6815 (search-forward "<filename>")
6816 (replace-match (buffer-name) t t)
6817 (search-forward "<author>") (replace-match "" t t)
6818 (insert (user-full-name))
6819 (insert " <" (user-login-name) "@" (system-name) ">")
6820 (search-forward "<credate>") (replace-match "" t t)
6821 (verilog-insert-date)
6822 (search-forward "<moddate>") (replace-match "" t t)
6823 (verilog-insert-date)
6824 (search-forward "<copydate>") (replace-match "" t t)
6825 (verilog-insert-year)
6826 (search-forward "<modhist>") (replace-match "" t t)
6827 (verilog-insert-date)
6828 (insert " : created")
6829 (goto-char start)
6830 (let (string)
6831 (setq string (read-string "title: "))
6832 (search-forward "<title>")
6833 (replace-match string t t)
6834 (setq string (read-string "project: " verilog-project))
6835 (setq verilog-project string)
6836 (search-forward "<project>")
6837 (replace-match string t t)
6838 (setq string (read-string "Company: " verilog-company))
6839 (setq verilog-company string)
6840 (search-forward "<company>")
6841 (replace-match string t t)
6842 (search-forward "<company>")
6843 (replace-match string t t)
6844 (search-forward "<company>")
6845 (replace-match string t t)
6846 (search-backward "<description>")
6847 (replace-match "" t t))))
6848
6849 ;; verilog-header Uses the verilog-insert-date function
6850
6851 (defun verilog-insert-date ()
6852 "Insert date from the system."
6853 (interactive)
6854 (if verilog-date-scientific-format
6855 (insert (format-time-string "%Y/%m/%d"))
6856 (insert (format-time-string "%d.%m.%Y"))))
6857
6858 (defun verilog-insert-year ()
6859 "Insert year from the system."
6860 (interactive)
6861 (insert (format-time-string "%Y")))
6862
6863 \f
6864 ;;
6865 ;; Signal list parsing
6866 ;;
6867
6868 ;; Elements of a signal list
6869 (defsubst verilog-sig-new (name bits comment mem enum signed type multidim modport)
6870 (list name bits comment mem enum signed type multidim modport))
6871 (defsubst verilog-sig-name (sig)
6872 (car sig))
6873 (defsubst verilog-sig-bits (sig)
6874 (nth 1 sig))
6875 (defsubst verilog-sig-comment (sig)
6876 (nth 2 sig))
6877 (defsubst verilog-sig-memory (sig)
6878 (nth 3 sig))
6879 (defsubst verilog-sig-enum (sig)
6880 (nth 4 sig))
6881 (defsubst verilog-sig-signed (sig)
6882 (nth 5 sig))
6883 (defsubst verilog-sig-type (sig)
6884 (nth 6 sig))
6885 (defsubst verilog-sig-multidim (sig)
6886 (nth 7 sig))
6887 (defsubst verilog-sig-multidim-string (sig)
6888 (if (verilog-sig-multidim sig)
6889 (let ((str "") (args (verilog-sig-multidim sig)))
6890 (while args
6891 (setq str (concat str (car args)))
6892 (setq args (cdr args)))
6893 str)))
6894 (defsubst verilog-sig-modport (sig)
6895 (nth 8 sig))
6896 (defsubst verilog-sig-width (sig)
6897 (verilog-make-width-expression (verilog-sig-bits sig)))
6898
6899 (defsubst verilog-alw-new (outputs temps inputs delayed)
6900 (list outputs temps inputs delayed))
6901 (defsubst verilog-alw-get-outputs (sigs)
6902 (nth 0 sigs))
6903 (defsubst verilog-alw-get-temps (sigs)
6904 (nth 1 sigs))
6905 (defsubst verilog-alw-get-inputs (sigs)
6906 (nth 2 sigs))
6907 (defsubst verilog-alw-get-uses-delayed (sigs)
6908 (nth 3 sigs))
6909
6910 (defsubst verilog-modi-new (name fob pt type)
6911 (vector name fob pt type))
6912 (defsubst verilog-modi-name (modi)
6913 (aref modi 0))
6914 (defsubst verilog-modi-file-or-buffer (modi)
6915 (aref modi 1))
6916 (defsubst verilog-modi-get-point (modi)
6917 (aref modi 2))
6918 (defsubst verilog-modi-get-type (modi) ;; "module" or "interface"
6919 (aref modi 3))
6920 (defsubst verilog-modi-get-decls (modi)
6921 (verilog-modi-cache-results modi 'verilog-read-decls))
6922 (defsubst verilog-modi-get-sub-decls (modi)
6923 (verilog-modi-cache-results modi 'verilog-read-sub-decls))
6924
6925 ;; Signal reading for given module
6926 ;; Note these all take modi's - as returned from verilog-modi-current
6927 (defsubst verilog-decls-new (out inout in wires regs assigns consts gparams interfaces)
6928 (vector out inout in wires regs assigns consts gparams interfaces))
6929 (defsubst verilog-decls-get-outputs (decls)
6930 (aref decls 0))
6931 (defsubst verilog-decls-get-inouts (decls)
6932 (aref decls 1))
6933 (defsubst verilog-decls-get-inputs (decls)
6934 (aref decls 2))
6935 (defsubst verilog-decls-get-wires (decls)
6936 (aref decls 3))
6937 (defsubst verilog-decls-get-regs (decls)
6938 (aref decls 4))
6939 (defsubst verilog-decls-get-assigns (decls)
6940 (aref decls 5))
6941 (defsubst verilog-decls-get-consts (decls)
6942 (aref decls 6))
6943 (defsubst verilog-decls-get-gparams (decls)
6944 (aref decls 7))
6945 (defsubst verilog-decls-get-interfaces (decls)
6946 (aref decls 8))
6947
6948 (defsubst verilog-subdecls-new (out inout in intf intfd)
6949 (vector out inout in intf intfd))
6950 (defsubst verilog-subdecls-get-outputs (subdecls)
6951 (aref subdecls 0))
6952 (defsubst verilog-subdecls-get-inouts (subdecls)
6953 (aref subdecls 1))
6954 (defsubst verilog-subdecls-get-inputs (subdecls)
6955 (aref subdecls 2))
6956 (defsubst verilog-subdecls-get-interfaces (subdecls)
6957 (aref subdecls 3))
6958 (defsubst verilog-subdecls-get-interfaced (subdecls)
6959 (aref subdecls 4))
6960
6961 (defun verilog-signals-not-in (in-list not-list)
6962 "Return list of signals in IN-LIST that aren't also in NOT-LIST.
6963 Also remove any duplicates in IN-LIST.
6964 Signals must be in standard (base vector) form."
6965 ;; This function is hot, so implemented as O(1)
6966 (cond ((eval-when-compile (fboundp 'make-hash-table))
6967 (let ((ht (make-hash-table :test 'equal :rehash-size 4.0))
6968 out-list)
6969 (while not-list
6970 (puthash (car (car not-list)) t ht)
6971 (setq not-list (cdr not-list)))
6972 (while in-list
6973 (when (not (gethash (car (car in-list)) ht))
6974 (setq out-list (cons (car in-list) out-list))
6975 (puthash (car (car in-list)) t ht))
6976 (setq in-list (cdr in-list)))
6977 (nreverse out-list)))
6978 ;; Slower Fallback if no hash tables (pre Emacs 21.1/XEmacs 21.4)
6979 (t
6980 (let (out-list)
6981 (while in-list
6982 (if (not (or (assoc (car (car in-list)) not-list)
6983 (assoc (car (car in-list)) out-list)))
6984 (setq out-list (cons (car in-list) out-list)))
6985 (setq in-list (cdr in-list)))
6986 (nreverse out-list)))))
6987 ;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
6988
6989 (defun verilog-signals-memory (in-list)
6990 "Return list of signals in IN-LIST that are memoried (multidimensional)."
6991 (let (out-list)
6992 (while in-list
6993 (if (nth 3 (car in-list))
6994 (setq out-list (cons (car in-list) out-list)))
6995 (setq in-list (cdr in-list)))
6996 out-list))
6997 ;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
6998
6999 (defun verilog-signals-sort-compare (a b)
7000 "Compare signal A and B for sorting."
7001 (string< (car a) (car b)))
7002
7003 (defun verilog-signals-not-params (in-list)
7004 "Return list of signals in IN-LIST that aren't parameters or numeric constants."
7005 (let (out-list)
7006 (while in-list
7007 (unless (boundp (intern (concat "vh-" (car (car in-list)))))
7008 (setq out-list (cons (car in-list) out-list)))
7009 (setq in-list (cdr in-list)))
7010 (nreverse out-list)))
7011
7012 (defun verilog-signals-combine-bus (in-list)
7013 "Return a list of signals in IN-LIST, with busses combined.
7014 Duplicate signals are also removed. For example A[2] and A[1] become A[2:1]."
7015 (let (combo buswarn
7016 out-list
7017 sig highbit lowbit ; Temp information about current signal
7018 sv-name sv-highbit sv-lowbit ; Details about signal we are forming
7019 sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
7020 sv-modport
7021 bus)
7022 ;; Shove signals so duplicated signals will be adjacent
7023 (setq in-list (sort in-list `verilog-signals-sort-compare))
7024 (while in-list
7025 (setq sig (car in-list))
7026 ;; No current signal; form from existing details
7027 (unless sv-name
7028 (setq sv-name (verilog-sig-name sig)
7029 sv-highbit nil
7030 sv-busstring nil
7031 sv-comment (verilog-sig-comment sig)
7032 sv-memory (verilog-sig-memory sig)
7033 sv-enum (verilog-sig-enum sig)
7034 sv-signed (verilog-sig-signed sig)
7035 sv-type (verilog-sig-type sig)
7036 sv-multidim (verilog-sig-multidim sig)
7037 sv-modport (verilog-sig-modport sig)
7038 combo ""
7039 buswarn ""))
7040 ;; Extract bus details
7041 (setq bus (verilog-sig-bits sig))
7042 (cond ((and bus
7043 (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
7044 (setq highbit (string-to-number (match-string 1 bus))
7045 lowbit (string-to-number
7046 (match-string 2 bus))))
7047 (and (string-match "\\[\\([0-9]+\\)\\]" bus)
7048 (setq highbit (string-to-number (match-string 1 bus))
7049 lowbit highbit))))
7050 ;; Combine bits in bus
7051 (if sv-highbit
7052 (setq sv-highbit (max highbit sv-highbit)
7053 sv-lowbit (min lowbit sv-lowbit))
7054 (setq sv-highbit highbit
7055 sv-lowbit lowbit)))
7056 (bus
7057 ;; String, probably something like `preproc:0
7058 (setq sv-busstring bus)))
7059 ;; Peek ahead to next signal
7060 (setq in-list (cdr in-list))
7061 (setq sig (car in-list))
7062 (cond ((and sig (equal sv-name (verilog-sig-name sig)))
7063 ;; Combine with this signal
7064 (when (and sv-busstring
7065 (not (equal sv-busstring (verilog-sig-bits sig))))
7066 (when nil ;; Debugging
7067 (message (concat "Warning, can't merge into single bus "
7068 sv-name bus
7069 ", the AUTOs may be wrong")))
7070 (setq buswarn ", Couldn't Merge"))
7071 (if (verilog-sig-comment sig) (setq combo ", ..."))
7072 (setq sv-memory (or sv-memory (verilog-sig-memory sig))
7073 sv-enum (or sv-enum (verilog-sig-enum sig))
7074 sv-signed (or sv-signed (verilog-sig-signed sig))
7075 sv-type (or sv-type (verilog-sig-type sig))
7076 sv-multidim (or sv-multidim (verilog-sig-multidim sig))
7077 sv-modport (or sv-modport (verilog-sig-modport sig))))
7078 ;; Doesn't match next signal, add to queue, zero in prep for next
7079 ;; Note sig may also be nil for the last signal in the list
7080 (t
7081 (setq out-list
7082 (cons (verilog-sig-new
7083 sv-name
7084 (or sv-busstring
7085 (if sv-highbit
7086 (concat "[" (int-to-string sv-highbit) ":"
7087 (int-to-string sv-lowbit) "]")))
7088 (concat sv-comment combo buswarn)
7089 sv-memory sv-enum sv-signed sv-type sv-multidim sv-modport)
7090 out-list)
7091 sv-name nil))))
7092 ;;
7093 out-list))
7094
7095 (defun verilog-sig-tieoff (sig &optional no-width)
7096 "Return tieoff expression for given SIG, with appropriate width.
7097 Ignore width if optional NO-WIDTH is set."
7098 (let* ((width (if no-width nil (verilog-sig-width sig))))
7099 (concat
7100 (if (and verilog-active-low-regexp
7101 (string-match verilog-active-low-regexp (verilog-sig-name sig)))
7102 "~" "")
7103 (cond ((not width)
7104 "0")
7105 ((string-match "^[0-9]+$" width)
7106 (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
7107 (t
7108 (concat "{" width "{1'b0}}"))))))
7109
7110 ;;
7111 ;; Port/Wire/Etc Reading
7112 ;;
7113
7114 (defun verilog-read-inst-backward-name ()
7115 "Internal. Move point back to beginning of inst-name."
7116 (verilog-backward-open-paren)
7117 (let (done)
7118 (while (not done)
7119 (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil) ; ] isn't word boundary
7120 (cond ((looking-at ")")
7121 (verilog-backward-open-paren))
7122 (t (setq done t)))))
7123 (while (looking-at "\\]")
7124 (verilog-backward-open-bracket)
7125 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
7126 (skip-chars-backward "a-zA-Z0-9`_$"))
7127
7128 (defun verilog-read-inst-module-matcher ()
7129 "Set match data 0 with module_name when point is inside instantiation."
7130 (verilog-read-inst-backward-name)
7131 ;; Skip over instantiation name
7132 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
7133 ;; Check for parameterized instantiations
7134 (when (looking-at ")")
7135 (verilog-backward-open-paren)
7136 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
7137 (skip-chars-backward "a-zA-Z0-9'_$")
7138 (looking-at "[a-zA-Z0-9`_\$]+")
7139 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7140 (buffer-substring-no-properties (match-beginning 0) (match-end 0))
7141 ;; Caller assumes match-beginning/match-end is still set
7142 )
7143
7144 (defun verilog-read-inst-module ()
7145 "Return module_name when point is inside instantiation."
7146 (save-excursion
7147 (verilog-read-inst-module-matcher)))
7148
7149 (defun verilog-read-inst-name ()
7150 "Return instance_name when point is inside instantiation."
7151 (save-excursion
7152 (verilog-read-inst-backward-name)
7153 (looking-at "[a-zA-Z0-9`_\$]+")
7154 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7155 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
7156
7157 (defun verilog-read-module-name ()
7158 "Return module name when after its ( or ;."
7159 (save-excursion
7160 (re-search-backward "[(;]")
7161 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
7162 (skip-chars-backward "a-zA-Z0-9`_$")
7163 (looking-at "[a-zA-Z0-9`_\$]+")
7164 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7165 (verilog-symbol-detick
7166 (buffer-substring-no-properties (match-beginning 0) (match-end 0)) t)))
7167
7168 (defun verilog-read-inst-param-value ()
7169 "Return list of parameters and values when point is inside instantiation."
7170 (save-excursion
7171 (verilog-read-inst-backward-name)
7172 ;; Skip over instantiation name
7173 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
7174 ;; If there are parameterized instantiations
7175 (when (looking-at ")")
7176 (let ((end-pt (point))
7177 params
7178 param-name paren-beg-pt param-value)
7179 (verilog-backward-open-paren)
7180 (while (verilog-re-search-forward-quick "\\." end-pt t)
7181 (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
7182 (skip-chars-backward "a-zA-Z0-9'_$")
7183 (looking-at "[a-zA-Z0-9`_\$]+")
7184 (setq param-name (buffer-substring-no-properties
7185 (match-beginning 0) (match-end 0)))
7186 (verilog-re-search-forward-quick "(" nil nil)
7187 (setq paren-beg-pt (point))
7188 (verilog-forward-close-paren)
7189 (setq param-value (verilog-string-remove-spaces
7190 (buffer-substring-no-properties
7191 paren-beg-pt (1- (point)))))
7192 (setq params (cons (list param-name param-value) params)))
7193 params))))
7194
7195 (defun verilog-read-auto-params (num-param &optional max-param)
7196 "Return parameter list inside auto.
7197 Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
7198 (let ((olist))
7199 (save-excursion
7200 ;; /*AUTOPUNT("parameter", "parameter")*/
7201 (search-backward "(")
7202 (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
7203 (setq olist (cons (match-string 1) olist))
7204 (goto-char (match-end 0))))
7205 (or (eq nil num-param)
7206 (<= num-param (length olist))
7207 (error "%s: Expected %d parameters" (verilog-point-text) num-param))
7208 (if (eq max-param nil) (setq max-param num-param))
7209 (or (eq nil max-param)
7210 (>= max-param (length olist))
7211 (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
7212 (nreverse olist)))
7213
7214 (defun verilog-read-decls ()
7215 "Compute signal declaration information for the current module at point.
7216 Return a array of [outputs inouts inputs wire reg assign const]."
7217 (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
7218 (functask 0) (paren 0) (sig-paren 0) (v2kargs-ok t)
7219 in-modport
7220 sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const
7221 sigs-gparam sigs-intf
7222 vec expect-signal keywd newsig rvalue enum io signed typedefed multidim
7223 modport)
7224 (save-excursion
7225 (verilog-beg-of-defun)
7226 (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
7227 (while (< (point) end-mod-point)
7228 ;;(if dbg (setq dbg (concat dbg (format "Pt %s Vec %s C%c Kwd'%s'\n" (point) vec (following-char) keywd))))
7229 (cond
7230 ((looking-at "//")
7231 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
7232 (setq enum (match-string 1)))
7233 (search-forward "\n"))
7234 ((looking-at "/\\*")
7235 (forward-char 2)
7236 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
7237 (setq enum (match-string 1)))
7238 (or (search-forward "*/")
7239 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7240 ((looking-at "(\\*")
7241 (forward-char 2)
7242 (or (looking-at "\\s-*)") ; It's an "always @ (*)"
7243 (search-forward "*)")
7244 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7245 ((eq ?\" (following-char))
7246 (or (re-search-forward "[^\\]\"" nil t) ;; don't forward-char first, since we look for a non backslash first
7247 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
7248 ((eq ?\; (following-char))
7249 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil
7250 v2kargs-ok nil in-modport nil)
7251 (forward-char 1))
7252 ((eq ?= (following-char))
7253 (setq rvalue t newsig nil)
7254 (forward-char 1))
7255 ((and (eq ?, (following-char))
7256 (eq paren sig-paren))
7257 (setq rvalue nil)
7258 (forward-char 1))
7259 ;; ,'s can occur inside {} & funcs
7260 ((looking-at "[{(]")
7261 (setq paren (1+ paren))
7262 (forward-char 1))
7263 ((looking-at "[})]")
7264 (setq paren (1- paren))
7265 (forward-char 1)
7266 (when (< paren sig-paren)
7267 (setq expect-signal nil))) ; ) that ends variables inside v2k arg list
7268 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
7269 (goto-char (match-end 0))
7270 (cond (newsig ; Memory, not just width. Patch last signal added's memory (nth 3)
7271 (setcar (cdr (cdr (cdr newsig)))
7272 (if (verilog-sig-memory newsig)
7273 (concat (verilog-sig-memory newsig) (match-string 1))
7274 (match-string 1))))
7275 (vec ;; Multidimensional
7276 (setq multidim (cons vec multidim))
7277 (setq vec (verilog-string-replace-matches
7278 "\\s-+" "" nil nil (match-string 1))))
7279 (t ;; Bit width
7280 (setq vec (verilog-string-replace-matches
7281 "\\s-+" "" nil nil (match-string 1))))))
7282 ;; Normal or escaped identifier -- note we remember the \ if escaped
7283 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
7284 (goto-char (match-end 0))
7285 (setq keywd (match-string 1))
7286 (when (string-match "^\\\\" (match-string 1))
7287 (setq keywd (concat keywd " "))) ;; Escaped ID needs space at end
7288 ;; Add any :: package names to same identifier
7289 (while (looking-at "\\s-*::\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
7290 (goto-char (match-end 0))
7291 (setq keywd (concat keywd "::" (match-string 1)))
7292 (when (string-match "^\\\\" (match-string 1))
7293 (setq keywd (concat keywd " ")))) ;; Escaped ID needs space at end
7294 (cond ((equal keywd "input")
7295 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
7296 expect-signal 'sigs-in io t modport nil))
7297 ((equal keywd "output")
7298 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
7299 expect-signal 'sigs-out io t modport nil))
7300 ((equal keywd "inout")
7301 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
7302 expect-signal 'sigs-inout io t modport nil))
7303 ((equal keywd "parameter")
7304 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7305 expect-signal 'sigs-gparam io t modport nil))
7306 ((member keywd '("wire" "tri" "tri0" "tri1" "triand" "trior" "wand" "wor"))
7307 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7308 expect-signal 'sigs-wire modport nil)))
7309 ((member keywd '("reg" "trireg"
7310 "byte" "shortint" "int" "longint" "integer" "time"
7311 "bit" "logic"
7312 "shortreal" "real" "realtime"
7313 "string" "event" "chandle"))
7314 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7315 expect-signal 'sigs-reg modport nil)))
7316 ((equal keywd "assign")
7317 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7318 expect-signal 'sigs-assign modport nil))
7319 ((member keywd '("supply0" "supply1" "supply"
7320 "localparam" "genvar"))
7321 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7322 expect-signal 'sigs-const modport nil)))
7323 ((equal keywd "signed")
7324 (setq signed "signed"))
7325 ((member keywd '("class" "clocking" "covergroup" "function"
7326 "property" "randsequence" "sequence" "task"))
7327 (setq functask (1+ functask)))
7328 ((member keywd '("endclass" "endclocking" "endgroup" "endfunction"
7329 "endproperty" "endsequence" "endtask"))
7330 (setq functask (1- functask)))
7331 ((equal keywd "modport")
7332 (setq in-modport t))
7333 ;; Ifdef? Ignore name of define
7334 ((member keywd '("`ifdef" "`ifndef" "`elsif"))
7335 (setq rvalue t))
7336 ;; Type?
7337 ((verilog-typedef-name-p keywd)
7338 (setq typedefed keywd))
7339 ;; Interface with optional modport in v2k arglist?
7340 ;; Skip over parsing modport, and take the interface name as the type
7341 ((and v2kargs-ok
7342 (eq paren 1)
7343 (not rvalue)
7344 (looking-at "\\s-*\\(\\.\\(\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*\\)\\|\\)\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*"))
7345 (when (match-end 2) (goto-char (match-end 2)))
7346 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed keywd multidim nil sig-paren paren
7347 expect-signal 'sigs-intf io t modport (match-string 2)))
7348 ;; Ignore dotted LHS assignments: "assign foo.bar = z;"
7349 ((looking-at "\\s-*\\.")
7350 (goto-char (match-end 0))
7351 (when (not rvalue)
7352 (setq expect-signal nil)))
7353 ;; New signal, maybe?
7354 ((and expect-signal
7355 (not rvalue)
7356 (eq functask 0)
7357 (not in-modport)
7358 (not (member keywd verilog-keywords)))
7359 ;; Add new signal to expect-signal's variable
7360 (setq newsig (verilog-sig-new keywd vec nil nil enum signed typedefed multidim modport))
7361 (set expect-signal (cons newsig
7362 (symbol-value expect-signal))))))
7363 (t
7364 (forward-char 1)))
7365 (skip-syntax-forward " "))
7366 ;; Return arguments
7367 (verilog-decls-new (nreverse sigs-out)
7368 (nreverse sigs-inout)
7369 (nreverse sigs-in)
7370 (nreverse sigs-wire)
7371 (nreverse sigs-reg)
7372 (nreverse sigs-assign)
7373 (nreverse sigs-const)
7374 (nreverse sigs-gparam)
7375 (nreverse sigs-intf)))))
7376
7377 (defvar verilog-read-sub-decls-in-interfaced nil
7378 "For `verilog-read-sub-decls', process next signal as under interfaced block.")
7379
7380 (defvar verilog-read-sub-decls-gate-ios nil
7381 "For `verilog-read-sub-decls', gate IO pins remaining, nil if non-primitive.")
7382
7383 (eval-when-compile
7384 ;; Prevent compile warnings; these are let's, not globals
7385 ;; Do not remove the eval-when-compile
7386 ;; - we want a error when we are debugging this code if they are refed.
7387 (defvar sigs-in)
7388 (defvar sigs-inout)
7389 (defvar sigs-out)
7390 (defvar sigs-intf)
7391 (defvar sigs-intfd))
7392
7393 (defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
7394 "For `verilog-read-sub-decls-line', add a signal."
7395 ;; sig eq t to indicate .name syntax
7396 ;;(message "vrsds: %s(%S)" port sig)
7397 (let ((dotname (eq sig t))
7398 portdata)
7399 (when sig
7400 (setq port (verilog-symbol-detick-denumber port))
7401 (setq sig (if dotname port (verilog-symbol-detick-denumber sig)))
7402 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
7403 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
7404 (unless (or (not sig)
7405 (equal sig "")) ;; Ignore .foo(1'b1) assignments
7406 (cond ((or (setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
7407 (equal "inout" verilog-read-sub-decls-gate-ios))
7408 (setq sigs-inout
7409 (cons (verilog-sig-new
7410 sig
7411 (if dotname (verilog-sig-bits portdata) vec)
7412 (concat "To/From " comment)
7413 (verilog-sig-memory portdata)
7414 nil
7415 (verilog-sig-signed portdata)
7416 (verilog-sig-type portdata)
7417 multidim nil)
7418 sigs-inout)))
7419 ((or (setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
7420 (equal "output" verilog-read-sub-decls-gate-ios))
7421 (setq sigs-out
7422 (cons (verilog-sig-new
7423 sig
7424 (if dotname (verilog-sig-bits portdata) vec)
7425 (concat "From " comment)
7426 (verilog-sig-memory portdata)
7427 nil
7428 (verilog-sig-signed portdata)
7429 (verilog-sig-type portdata)
7430 multidim nil)
7431 sigs-out)))
7432 ((or (setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
7433 (equal "input" verilog-read-sub-decls-gate-ios))
7434 (setq sigs-in
7435 (cons (verilog-sig-new
7436 sig
7437 (if dotname (verilog-sig-bits portdata) vec)
7438 (concat "To " comment)
7439 (verilog-sig-memory portdata)
7440 nil
7441 (verilog-sig-signed portdata)
7442 (verilog-sig-type portdata)
7443 multidim nil)
7444 sigs-in)))
7445 ((setq portdata (assoc port (verilog-decls-get-interfaces submoddecls)))
7446 (setq sigs-intf
7447 (cons (verilog-sig-new
7448 sig
7449 (if dotname (verilog-sig-bits portdata) vec)
7450 (concat "To/From " comment)
7451 (verilog-sig-memory portdata)
7452 nil
7453 (verilog-sig-signed portdata)
7454 (verilog-sig-type portdata)
7455 multidim nil)
7456 sigs-intf)))
7457 ((setq portdata (and verilog-read-sub-decls-in-interfaced
7458 (or (assoc port (verilog-decls-get-regs submoddecls))
7459 (assoc port (verilog-decls-get-wires submoddecls)))))
7460 (setq sigs-intfd
7461 (cons (verilog-sig-new
7462 sig
7463 (if dotname (verilog-sig-bits portdata) vec)
7464 (concat "To/From " comment)
7465 (verilog-sig-memory portdata)
7466 nil
7467 (verilog-sig-signed portdata)
7468 (verilog-sig-type portdata)
7469 multidim nil)
7470 sigs-intf)))
7471 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
7472 )))))
7473
7474 (defun verilog-read-sub-decls-expr (submoddecls comment port expr)
7475 "For `verilog-read-sub-decls-line', parse a subexpression and add signals."
7476 ;;(message "vrsde: '%s'" expr)
7477 ;; Replace special /*[....]*/ comments inserted by verilog-auto-inst-port
7478 (setq expr (verilog-string-replace-matches "/\\*\\(\\[[^*]+\\]\\)\\*/" "\\1" nil nil expr))
7479 ;; Remove front operators
7480 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
7481 ;;
7482 (cond
7483 ;; {..., a, b} requires us to recurse on a,b
7484 ;; To support {#{},{#{a,b}} we'll just split everything on [{},]
7485 ((string-match "^\\s-*{\\(.*\\)}\\s-*$" expr)
7486 (unless verilog-auto-ignore-concat
7487 (let ((mlst (split-string (match-string 1 expr) "[{},]"))
7488 mstr)
7489 (while (setq mstr (pop mlst))
7490 (verilog-read-sub-decls-expr submoddecls comment port mstr)))))
7491 (t
7492 (let (sig vec multidim)
7493 ;; Remove leading reduction operators, etc
7494 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
7495 ;;(message "vrsde-ptop: '%s'" expr)
7496 (cond ;; Find \signal. Final space is part of escaped signal name
7497 ((string-match "^\\s-*\\(\\\\[^ \t\n\f]+\\s-\\)" expr)
7498 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
7499 (setq sig (match-string 1 expr)
7500 expr (substring expr (match-end 0))))
7501 ;; Find signal
7502 ((string-match "^\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" expr)
7503 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
7504 (setq sig (verilog-string-remove-spaces (match-string 1 expr))
7505 expr (substring expr (match-end 0)))))
7506 ;; Find [vector] or [multi][multi][multi][vector]
7507 (while (string-match "^\\s-*\\(\\[[^]]+\\]\\)" expr)
7508 ;;(message "vrsde-v: '%s'" (match-string 1 expr))
7509 (when vec (setq multidim (cons vec multidim)))
7510 (setq vec (match-string 1 expr)
7511 expr (substring expr (match-end 0))))
7512 ;; If found signal, and nothing unrecognized, add the signal
7513 ;;(message "vrsde-rem: '%s'" expr)
7514 (when (and sig (string-match "^\\s-*$" expr))
7515 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))))
7516
7517 (defun verilog-read-sub-decls-line (submoddecls comment)
7518 "For `verilog-read-sub-decls', read lines of port defs until none match.
7519 Inserts the list of signals found, using submodi to look up each port."
7520 (let (done port)
7521 (save-excursion
7522 (forward-line 1)
7523 (while (not done)
7524 ;; Get port name
7525 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
7526 (setq port (match-string 1))
7527 (goto-char (match-end 0)))
7528 ;; .\escaped (
7529 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
7530 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
7531 (goto-char (match-end 0)))
7532 ;; .name
7533 ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*[,)/]")
7534 (verilog-read-sub-decls-sig
7535 submoddecls comment (match-string 1) t ; sig==t for .name
7536 nil nil) ; vec multidim
7537 (setq port nil))
7538 ;; .\escaped_name
7539 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*[,)/]")
7540 (verilog-read-sub-decls-sig
7541 submoddecls comment (concat (match-string 1) " ") t ; sig==t for .name
7542 nil nil) ; vec multidim
7543 (setq port nil))
7544 ;; random
7545 ((looking-at "\\s-*\\.[^(]*(")
7546 (setq port nil) ;; skip this line
7547 (goto-char (match-end 0)))
7548 (t
7549 (setq port nil done t))) ;; Unknown, ignore rest of line
7550 ;; Get signal name. Point is at the first-non-space after (
7551 ;; We intentionally ignore (non-escaped) signals with .s in them
7552 ;; this prevents AUTOWIRE etc from noticing hierarchical sigs.
7553 (when port
7554 (cond ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*)")
7555 (verilog-read-sub-decls-sig
7556 submoddecls comment port
7557 (verilog-string-remove-spaces (match-string 1)) ; sig
7558 nil nil)) ; vec multidim
7559 ;;
7560 ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
7561 (verilog-read-sub-decls-sig
7562 submoddecls comment port
7563 (verilog-string-remove-spaces (match-string 1)) ; sig
7564 (match-string 2) nil)) ; vec multidim
7565 ;; Fastpath was above looking-at's.
7566 ;; For something more complicated invoke a parser
7567 ((looking-at "[^)]+")
7568 (verilog-read-sub-decls-expr
7569 submoddecls comment port
7570 (buffer-substring
7571 (point) (1- (progn (search-backward "(") ; start at (
7572 (forward-sexp 1) (point)))))))) ; expr
7573 ;;
7574 (forward-line 1)))))
7575
7576 (defun verilog-read-sub-decls-gate (submoddecls comment submod end-inst-point)
7577 "For `verilog-read-sub-decls', read lines of UDP gate decl until none match.
7578 Inserts the list of signals found."
7579 (save-excursion
7580 (let ((iolist (cdr (assoc submod verilog-gate-ios))))
7581 (while (< (point) end-inst-point)
7582 ;; Get primitive's signal name, as will never have port, and no trailing )
7583 (cond ((looking-at "//")
7584 (search-forward "\n"))
7585 ((looking-at "/\\*")
7586 (or (search-forward "*/")
7587 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7588 ((looking-at "(\\*")
7589 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7590 (search-forward "*)")
7591 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7592 ;; On pins, parse and advance to next pin
7593 ;; Looking at pin, but *not* an // Output comment, or ) to end the inst
7594 ((looking-at "\\s-*[a-zA-Z0-9`_$({}\\\\][^,]*")
7595 (goto-char (match-end 0))
7596 (setq verilog-read-sub-decls-gate-ios (or (car iolist) "input")
7597 iolist (cdr iolist))
7598 (verilog-read-sub-decls-expr
7599 submoddecls comment "primitive_port"
7600 (match-string 0)))
7601 (t
7602 (forward-char 1)
7603 (skip-syntax-forward " ")))))))
7604
7605 (defun verilog-read-sub-decls ()
7606 "Internally parse signals going to modules under this module.
7607 Return a array of [ outputs inouts inputs ] signals for modules that are
7608 instantiated in this module. For example if declare A A (.B(SIG)) and SIG
7609 is a output, then SIG will be included in the list.
7610
7611 This only works on instantiations created with /*AUTOINST*/ converted by
7612 \\[verilog-auto-inst]. Otherwise, it would have to read in the whole
7613 component library to determine connectivity of the design.
7614
7615 One work around for this problem is to manually create // Inputs and //
7616 Outputs comments above subcell signals, for example:
7617
7618 module ModuleName (
7619 // Outputs
7620 .out (out),
7621 // Inputs
7622 .in (in));"
7623 (save-excursion
7624 (let ((end-mod-point (verilog-get-end-of-defun t))
7625 st-point end-inst-point
7626 ;; below 3 modified by verilog-read-sub-decls-line
7627 sigs-out sigs-inout sigs-in sigs-intf sigs-intfd)
7628 (verilog-beg-of-defun)
7629 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
7630 (save-excursion
7631 (goto-char (match-beginning 0))
7632 (unless (verilog-inside-comment-p)
7633 ;; Attempt to snarf a comment
7634 (let* ((submod (verilog-read-inst-module))
7635 (inst (verilog-read-inst-name))
7636 (subprim (member submod verilog-gate-keywords))
7637 (comment (concat inst " of " submod ".v"))
7638 submodi submoddecls)
7639 (cond
7640 (subprim
7641 (setq submodi `primitive
7642 submoddecls (verilog-decls-new nil nil nil nil nil nil nil nil nil)
7643 comment (concat inst " of " submod))
7644 (verilog-backward-open-paren)
7645 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
7646 st-point (point))
7647 (forward-char 1)
7648 (verilog-read-sub-decls-gate submoddecls comment submod end-inst-point))
7649 ;; Non-primitive
7650 (t
7651 (when (setq submodi (verilog-modi-lookup submod t))
7652 (setq submoddecls (verilog-modi-get-decls submodi)
7653 verilog-read-sub-decls-gate-ios nil)
7654 (verilog-backward-open-paren)
7655 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
7656 st-point (point))
7657 ;; This could have used a list created by verilog-auto-inst
7658 ;; However I want it to be runnable even on user's manually added signals
7659 (let ((verilog-read-sub-decls-in-interfaced t))
7660 (while (re-search-forward "\\s *(?\\s *// Interfaced" end-inst-point t)
7661 (verilog-read-sub-decls-line submoddecls comment))) ;; Modifies sigs-ifd
7662 (goto-char st-point)
7663 (while (re-search-forward "\\s *(?\\s *// Interfaces" end-inst-point t)
7664 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
7665 (goto-char st-point)
7666 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
7667 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
7668 (goto-char st-point)
7669 (while (re-search-forward "\\s *(?\\s *// Inouts" end-inst-point t)
7670 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
7671 (goto-char st-point)
7672 (while (re-search-forward "\\s *(?\\s *// Inputs" end-inst-point t)
7673 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
7674 )))))))
7675 ;; Combine duplicate bits
7676 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
7677 (verilog-subdecls-new
7678 (verilog-signals-combine-bus (nreverse sigs-out))
7679 (verilog-signals-combine-bus (nreverse sigs-inout))
7680 (verilog-signals-combine-bus (nreverse sigs-in))
7681 (verilog-signals-combine-bus (nreverse sigs-intf))
7682 (verilog-signals-combine-bus (nreverse sigs-intfd))))))
7683
7684 (defun verilog-read-inst-pins ()
7685 "Return an array of [ pins ] for the current instantiation at point.
7686 For example if declare A A (.B(SIG)) then B will be included in the list."
7687 (save-excursion
7688 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
7689 pins pin)
7690 (verilog-backward-open-paren)
7691 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
7692 (setq pin (match-string 1))
7693 (unless (verilog-inside-comment-p)
7694 (setq pins (cons (list pin) pins))
7695 (when (looking-at "(")
7696 (forward-sexp 1))))
7697 (vector pins))))
7698
7699 (defun verilog-read-arg-pins ()
7700 "Return an array of [ pins ] for the current argument declaration at point."
7701 (save-excursion
7702 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
7703 pins pin)
7704 (verilog-backward-open-paren)
7705 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
7706 (setq pin (match-string 1))
7707 (unless (verilog-inside-comment-p)
7708 (setq pins (cons (list pin) pins))))
7709 (vector pins))))
7710
7711 (defun verilog-read-auto-constants (beg end-mod-point)
7712 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
7713 ;; Insert new
7714 (save-excursion
7715 (let (sig-list tpl-end-pt)
7716 (goto-char beg)
7717 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
7718 (if (not (looking-at "\\s *("))
7719 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
7720 (search-forward "(" end-mod-point)
7721 (setq tpl-end-pt (save-excursion
7722 (backward-char 1)
7723 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7724 (backward-char 1)
7725 (point)))
7726 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
7727 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
7728 sig-list)))
7729
7730 (defvar verilog-cache-has-lisp nil "True if any AUTO_LISP in buffer.")
7731 (make-variable-buffer-local 'verilog-cache-has-lisp)
7732
7733 (defun verilog-read-auto-lisp-present ()
7734 "Set `verilog-cache-has-lisp' if any AUTO_LISP in this buffer."
7735 (save-excursion
7736 (setq verilog-cache-has-lisp (re-search-forward "\\<AUTO_LISP(" nil t))))
7737
7738 (defun verilog-read-auto-lisp (start end)
7739 "Look for and evaluate a AUTO_LISP between START and END.
7740 Must call `verilog-read-auto-lisp-present' before this function."
7741 ;; This function is expensive for large buffers, so we cache if any AUTO_LISP exists
7742 (when verilog-cache-has-lisp
7743 (save-excursion
7744 (goto-char start)
7745 (while (re-search-forward "\\<AUTO_LISP(" end t)
7746 (backward-char)
7747 (let* ((beg-pt (prog1 (point)
7748 (forward-sexp 1))) ;; Closing paren
7749 (end-pt (point)))
7750 (eval-region beg-pt end-pt nil))))))
7751
7752 (eval-when-compile
7753 ;; Prevent compile warnings; these are let's, not globals
7754 ;; Do not remove the eval-when-compile
7755 ;; - we want a error when we are debugging this code if they are refed.
7756 (defvar sigs-in)
7757 (defvar sigs-out)
7758 (defvar sigs-temp)
7759 (defvar uses-delayed)
7760 (defvar vector-skip-list))
7761
7762 (defun verilog-read-always-signals-recurse
7763 (exit-keywd rvalue temp-next)
7764 "Recursive routine for parentheses/bracket matching.
7765 EXIT-KEYWD is expression to stop at, nil if top level.
7766 RVALUE is true if at right hand side of equal.
7767 IGNORE-NEXT is true to ignore next token, fake from inside case statement."
7768 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
7769 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-list end-else-check
7770 ignore-next)
7771 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue temp-next))))
7772 (while (not (or (eobp) gotend))
7773 (cond
7774 ((looking-at "//")
7775 (search-forward "\n"))
7776 ((looking-at "/\\*")
7777 (or (search-forward "*/")
7778 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7779 ((looking-at "(\\*")
7780 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7781 (search-forward "*)")
7782 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7783 (t (setq keywd (buffer-substring-no-properties
7784 (point)
7785 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7786 (forward-char 1))
7787 (point)))
7788 sig-last-tolk sig-tolk
7789 sig-tolk nil)
7790 ;;(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))))
7791 (cond
7792 ((equal keywd "\"")
7793 (or (re-search-forward "[^\\]\"" nil t)
7794 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
7795 ;; else at top level loop, keep parsing
7796 ((and end-else-check (equal keywd "else"))
7797 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
7798 ;; no forward movement, want to see else in lower loop
7799 (setq end-else-check nil))
7800 ;; End at top level loop
7801 ((and end-else-check (looking-at "[^ \t\n\f]"))
7802 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
7803 (setq gotend t))
7804 ;; Final statement?
7805 ((and exit-keywd (equal keywd exit-keywd))
7806 (setq gotend t)
7807 (forward-char (length keywd)))
7808 ;; Standard tokens...
7809 ((equal keywd ";")
7810 (setq ignore-next nil rvalue semi-rvalue)
7811 ;; Final statement at top level loop?
7812 (when (not exit-keywd)
7813 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
7814 (setq end-else-check t))
7815 (forward-char 1))
7816 ((equal keywd "'")
7817 (if (looking-at "'[sS]?[hdxboHDXBO]?[ \t]*[0-9a-fA-F_xzXZ?]+")
7818 (goto-char (match-end 0))
7819 (forward-char 1)))
7820 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
7821 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
7822 (setq ignore-next nil rvalue nil))
7823 ((equal "?" exit-keywd) ;; x?y:z rvalue
7824 ) ;; NOP
7825 ((equal "]" exit-keywd) ;; [x:y] rvalue
7826 ) ;; NOP
7827 (got-sig ;; label: statement
7828 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
7829 ((not rvalue) ;; begin label
7830 (setq ignore-next t rvalue nil)))
7831 (forward-char 1))
7832 ((equal keywd "=")
7833 (if (and (eq (char-before) ?< )
7834 (not rvalue))
7835 (setq uses-delayed 1))
7836 (setq ignore-next nil rvalue t)
7837 (forward-char 1))
7838 ((equal keywd "?")
7839 (forward-char 1)
7840 (verilog-read-always-signals-recurse ":" rvalue nil))
7841 ((equal keywd "[")
7842 (forward-char 1)
7843 (verilog-read-always-signals-recurse "]" t nil))
7844 ((equal keywd "(")
7845 (forward-char 1)
7846 (cond (sig-last-tolk ;; Function call; zap last signal
7847 (setq got-sig nil)))
7848 (cond ((equal last-keywd "for")
7849 ;; temp-next: Variables on LHS are lvalues, but generally we want
7850 ;; to ignore them, assuming they are loop increments
7851 (verilog-read-always-signals-recurse ";" nil t)
7852 (verilog-read-always-signals-recurse ";" t nil)
7853 (verilog-read-always-signals-recurse ")" nil nil))
7854 (t (verilog-read-always-signals-recurse ")" t nil))))
7855 ((equal keywd "begin")
7856 (skip-syntax-forward "w_")
7857 (verilog-read-always-signals-recurse "end" nil nil)
7858 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
7859 (setq ignore-next nil rvalue semi-rvalue)
7860 (if (not exit-keywd) (setq end-else-check t)))
7861 ((member keywd '("case" "casex" "casez"))
7862 (skip-syntax-forward "w_")
7863 (verilog-read-always-signals-recurse "endcase" t nil)
7864 (setq ignore-next nil rvalue semi-rvalue)
7865 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
7866 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
7867 (cond ((member keywd '("`ifdef" "`ifndef" "`elsif"))
7868 (setq ignore-next t))
7869 ((or ignore-next
7870 (member keywd verilog-keywords)
7871 (string-match "^\\$" keywd)) ;; PLI task
7872 (setq ignore-next nil))
7873 (t
7874 (setq keywd (verilog-symbol-detick-denumber keywd))
7875 (when got-sig
7876 (set got-list (cons got-sig (symbol-value got-list)))
7877 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S got-list=%S\n" got-sig got-list))))
7878 )
7879 (setq got-list (cond (temp-next 'sigs-temp)
7880 (rvalue 'sigs-in)
7881 (t 'sigs-out))
7882 got-sig (if (or (not keywd)
7883 (assoc keywd (symbol-value got-list)))
7884 nil (list keywd nil nil))
7885 temp-next nil
7886 sig-tolk t)))
7887 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7888 (t
7889 (forward-char 1)))
7890 ;; End of non-comment token
7891 (setq last-keywd keywd)))
7892 (skip-syntax-forward " "))
7893 ;; Append the final pending signal
7894 (when got-sig
7895 ;;(if dbg (setq dbg (concat dbg (format "\t\tfinal got-sig=%S got-list=%s\n" got-sig got-list))))
7896 (set got-list (cons got-sig (symbol-value got-list)))
7897 (setq got-sig nil))
7898 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
7899 ))
7900
7901 (defun verilog-read-always-signals ()
7902 "Parse always block at point and return list of (outputs inout inputs)."
7903 (save-excursion
7904 (let* (;;(dbg "")
7905 sigs-out sigs-temp sigs-in
7906 uses-delayed) ;; Found signal/rvalue; push if not function
7907 (search-forward ")")
7908 (verilog-read-always-signals-recurse nil nil nil)
7909 ;;(if dbg (with-current-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg ""))
7910 ;; Return what was found
7911 (verilog-alw-new sigs-out sigs-temp sigs-in uses-delayed))))
7912
7913 (defun verilog-read-instants ()
7914 "Parse module at point and return list of ( ( file instance ) ... )."
7915 (verilog-beg-of-defun)
7916 (let* ((end-mod-point (verilog-get-end-of-defun t))
7917 (state nil)
7918 (instants-list nil))
7919 (save-excursion
7920 (while (< (point) end-mod-point)
7921 ;; Stay at level 0, no comments
7922 (while (progn
7923 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
7924 (or (> (car state) 0) ; in parens
7925 (nth 5 state) ; comment
7926 ))
7927 (forward-line 1))
7928 (beginning-of-line)
7929 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
7930 ;;(if (looking-at "^\\(.+\\)$")
7931 (let ((module (match-string 1))
7932 (instant (match-string 2)))
7933 (if (not (member module verilog-keywords))
7934 (setq instants-list (cons (list module instant) instants-list)))))
7935 (forward-line 1)))
7936 instants-list))
7937
7938
7939 (defun verilog-read-auto-template (module)
7940 "Look for a auto_template for the instantiation of the given MODULE.
7941 If found returns the signal name connections. Return REGEXP and
7942 list of ( (signal_name connection_name)... )."
7943 (save-excursion
7944 ;; Find beginning
7945 (let ((tpl-regexp "\\([0-9]+\\)")
7946 (lineno 0)
7947 (templateno 0)
7948 (pt (point))
7949 tpl-sig-list tpl-wild-list tpl-end-pt rep)
7950 ;; Note this search is expensive, as we hunt from mod-begin to point
7951 ;; for every instantiation. Likewise in verilog-read-auto-lisp.
7952 ;; So, we look first for an exact string rather than a slow regexp.
7953 ;; Someday we may keep a cache of every template, but this would also
7954 ;; need to record the relative position of each AUTOINST, as multiple
7955 ;; templates exist for each module, and we're inserting lines.
7956 (cond ((or
7957 (verilog-re-search-backward-substr
7958 "AUTO_TEMPLATE"
7959 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
7960 ;; Also try forward of this AUTOINST
7961 ;; This is for historical support; this isn't speced as working
7962 (progn
7963 (goto-char pt)
7964 (verilog-re-search-forward-substr
7965 "AUTO_TEMPLATE"
7966 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
7967 (goto-char (match-end 0))
7968 ;; Parse "REGEXP"
7969 ;; We reserve @"..." for future lisp expressions that evaluate
7970 ;; once-per-AUTOINST
7971 (when (looking-at "\\s-*\"\\([^\"]*\\)\"")
7972 (setq tpl-regexp (match-string 1))
7973 (goto-char (match-end 0)))
7974 (search-forward "(")
7975 ;; Parse lines in the template
7976 (when verilog-auto-inst-template-numbers
7977 (save-excursion
7978 (goto-char (point-min))
7979 (while (search-forward "AUTO_TEMPLATE" nil t)
7980 (setq templateno (1+ templateno)))))
7981 (setq tpl-end-pt (save-excursion
7982 (backward-char 1)
7983 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7984 (backward-char 1)
7985 (point)))
7986 ;;
7987 (while (< (point) tpl-end-pt)
7988 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7989 (setq tpl-sig-list (cons (list
7990 (match-string-no-properties 1)
7991 (match-string-no-properties 2)
7992 templateno lineno)
7993 tpl-sig-list))
7994 (goto-char (match-end 0)))
7995 ;; Regexp form??
7996 ((looking-at
7997 ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
7998 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7999 (setq rep (match-string-no-properties 3))
8000 (goto-char (match-end 0))
8001 (setq tpl-wild-list
8002 (cons (list
8003 (concat "^"
8004 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
8005 (match-string 1))
8006 "$")
8007 rep
8008 templateno lineno)
8009 tpl-wild-list)))
8010 ((looking-at "[ \t\f]+")
8011 (goto-char (match-end 0)))
8012 ((looking-at "\n")
8013 (setq lineno (1+ lineno))
8014 (goto-char (match-end 0)))
8015 ((looking-at "//")
8016 (search-forward "\n"))
8017 ((looking-at "/\\*")
8018 (forward-char 2)
8019 (or (search-forward "*/")
8020 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8021 (t
8022 (error "%s: AUTO_TEMPLATE parsing error: %s"
8023 (verilog-point-text)
8024 (progn (looking-at ".*$") (match-string 0))))))
8025 ;; Return
8026 (vector tpl-regexp
8027 (list tpl-sig-list tpl-wild-list)))
8028 ;; If no template found
8029 (t (vector tpl-regexp nil))))))
8030 ;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
8031
8032 (defun verilog-set-define (defname defvalue &optional buffer enumname)
8033 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
8034 Optionally associate it with the specified enumeration ENUMNAME."
8035 (with-current-buffer (or buffer (current-buffer))
8036 (let ((mac (intern (concat "vh-" defname))))
8037 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
8038 ;; Need to define to a constant if no value given
8039 (set (make-local-variable mac)
8040 (if (equal defvalue "") "1" defvalue)))
8041 (if enumname
8042 (let ((enumvar (intern (concat "venum-" enumname))))
8043 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
8044 (unless (boundp enumvar) (set enumvar nil))
8045 (make-local-variable enumvar)
8046 (add-to-list enumvar defname)))))
8047
8048 (defun verilog-read-defines (&optional filename recurse subcall)
8049 "Read `defines and parameters for the current file, or optional FILENAME.
8050 If the filename is provided, `verilog-library-flags' will be used to
8051 resolve it. If optional RECURSE is non-nil, recurse through `includes.
8052
8053 Parameters must be simple assignments to constants, or have their own
8054 \"parameter\" label rather than a list of parameters. Thus:
8055
8056 parameter X = 5, Y = 10; // Ok
8057 parameter X = {1'b1, 2'h2}; // Ok
8058 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
8059
8060 Defines must be simple text substitutions, one on a line, starting
8061 at the beginning of the line. Any ifdefs or multiline comments around the
8062 define are ignored.
8063
8064 Defines are stored inside Emacs variables using the name vh-{definename}.
8065
8066 This function is useful for setting vh-* variables. The file variables
8067 feature can be used to set defines that `verilog-mode' can see; put at the
8068 *END* of your file something like:
8069
8070 // Local Variables:
8071 // vh-macro:\"macro_definition\"
8072 // End:
8073
8074 If macros are defined earlier in the same file and you want their values,
8075 you can read them automatically (provided `enable-local-eval' is on):
8076
8077 // Local Variables:
8078 // eval:(verilog-read-defines)
8079 // eval:(verilog-read-defines \"group_standard_includes.v\")
8080 // End:
8081
8082 Note these are only read when the file is first visited, you must use
8083 \\[find-alternate-file] RET to have these take effect after editing them!
8084
8085 If you want to disable the \"Process `eval' or hook local variables\"
8086 warning message, you need to add to your .emacs file:
8087
8088 (setq enable-local-eval t)"
8089 (let ((origbuf (current-buffer)))
8090 (save-excursion
8091 (unless subcall (verilog-getopt-flags))
8092 (when filename
8093 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
8094 (if fns
8095 (set-buffer (find-file-noselect (car fns)))
8096 (error (concat (verilog-point-text)
8097 ": Can't find verilog-read-defines file: " filename)))))
8098 (when recurse
8099 (goto-char (point-min))
8100 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
8101 (let ((inc (verilog-string-replace-matches
8102 "\"" "" nil nil (match-string-no-properties 1))))
8103 (unless (verilog-inside-comment-p)
8104 (verilog-read-defines inc recurse t)))))
8105 ;; Read `defines
8106 ;; note we don't use verilog-re... it's faster this way, and that
8107 ;; function has problems when comments are at the end of the define
8108 (goto-char (point-min))
8109 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
8110 (let ((defname (match-string-no-properties 1))
8111 (defvalue (match-string-no-properties 2)))
8112 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
8113 (verilog-set-define defname defvalue origbuf)))
8114 ;; Hack: Read parameters
8115 (goto-char (point-min))
8116 (while (re-search-forward
8117 "^\\s-*\\(parameter\\|localparam\\)\\(\\s-*\\[[^]]*\\]\\)?\\s-+" nil t)
8118 (let (enumname)
8119 ;; The primary way of getting defines is verilog-read-decls
8120 ;; However, that isn't called yet for included files, so we'll add another scheme
8121 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
8122 (setq enumname (match-string-no-properties 1)))
8123 (forward-comment 999)
8124 (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
8125 (verilog-set-define (match-string-no-properties 1)
8126 (match-string-no-properties 2) origbuf enumname)
8127 (goto-char (match-end 0))
8128 (forward-comment 999)))))))
8129
8130 (defun verilog-read-includes ()
8131 "Read `includes for the current file.
8132 This will find all of the `includes which are at the beginning of lines,
8133 ignoring any ifdefs or multiline comments around them.
8134 `verilog-read-defines' is then performed on the current and each included
8135 file.
8136
8137 It is often useful put at the *END* of your file something like:
8138
8139 // Local Variables:
8140 // eval:(verilog-read-defines)
8141 // eval:(verilog-read-includes)
8142 // End:
8143
8144 Note includes are only read when the file is first visited, you must use
8145 \\[find-alternate-file] RET to have these take effect after editing them!
8146
8147 It is good to get in the habit of including all needed files in each .v
8148 file that needs it, rather than waiting for compile time. This will aid
8149 this process, Verilint, and readability. To prevent defining the same
8150 variable over and over when many modules are compiled together, put a test
8151 around the inside each include file:
8152
8153 foo.v (a include):
8154 `ifdef _FOO_V // include if not already included
8155 `else
8156 `define _FOO_V
8157 ... contents of file
8158 `endif // _FOO_V"
8159 ;;slow: (verilog-read-defines nil t))
8160 (save-excursion
8161 (verilog-getopt-flags)
8162 (goto-char (point-min))
8163 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
8164 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
8165 (verilog-read-defines inc nil t)))))
8166
8167 (defun verilog-read-signals (&optional start end)
8168 "Return a simple list of all possible signals in the file.
8169 Bounded by optional region from START to END. Overly aggressive but fast.
8170 Some macros and such are also found and included. For dinotrace.el."
8171 (let (sigs-all keywd)
8172 (progn;save-excursion
8173 (goto-char (or start (point-min)))
8174 (setq end (or end (point-max)))
8175 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
8176 (forward-char -1)
8177 (cond
8178 ((looking-at "//")
8179 (search-forward "\n"))
8180 ((looking-at "/\\*")
8181 (search-forward "*/"))
8182 ((looking-at "(\\*")
8183 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
8184 (search-forward "*)")))
8185 ((eq ?\" (following-char))
8186 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
8187 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
8188 (goto-char (match-end 0))
8189 (setq keywd (match-string-no-properties 1))
8190 (or (member keywd verilog-keywords)
8191 (member keywd sigs-all)
8192 (setq sigs-all (cons keywd sigs-all))))
8193 (t (forward-char 1))))
8194 ;; Return list
8195 sigs-all)))
8196
8197 ;;
8198 ;; Argument file parsing
8199 ;;
8200
8201 (defun verilog-getopt (arglist)
8202 "Parse -f, -v etc arguments in ARGLIST list or string."
8203 (unless (listp arglist) (setq arglist (list arglist)))
8204 (let ((space-args '())
8205 arg next-param)
8206 ;; Split on spaces, so users can pass whole command lines
8207 (while arglist
8208 (setq arg (car arglist)
8209 arglist (cdr arglist))
8210 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
8211 (setq space-args (append space-args
8212 (list (match-string-no-properties 1 arg))))
8213 (setq arg (match-string 2 arg))))
8214 ;; Parse arguments
8215 (while space-args
8216 (setq arg (car space-args)
8217 space-args (cdr space-args))
8218 (cond
8219 ;; Need another arg
8220 ((equal arg "-f")
8221 (setq next-param arg))
8222 ((equal arg "-v")
8223 (setq next-param arg))
8224 ((equal arg "-y")
8225 (setq next-param arg))
8226 ;; +libext+(ext1)+(ext2)...
8227 ((string-match "^\\+libext\\+\\(.*\\)" arg)
8228 (setq arg (match-string 1 arg))
8229 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
8230 (verilog-add-list-unique `verilog-library-extensions
8231 (match-string 1 arg))
8232 (setq arg (match-string 2 arg))))
8233 ;;
8234 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
8235 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
8236 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
8237 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
8238 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
8239 ;;
8240 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
8241 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
8242 (verilog-add-list-unique `verilog-library-directories
8243 (match-string 1 (substitute-in-file-name arg))))
8244 ;; Ignore
8245 ((equal "+librescan" arg))
8246 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
8247 ;; Second parameters
8248 ((equal next-param "-f")
8249 (setq next-param nil)
8250 (verilog-getopt-file (substitute-in-file-name arg)))
8251 ((equal next-param "-v")
8252 (setq next-param nil)
8253 (verilog-add-list-unique `verilog-library-files
8254 (substitute-in-file-name arg)))
8255 ((equal next-param "-y")
8256 (setq next-param nil)
8257 (verilog-add-list-unique `verilog-library-directories
8258 (substitute-in-file-name arg)))
8259 ;; Filename
8260 ((string-match "^[^-+]" arg)
8261 (verilog-add-list-unique `verilog-library-files
8262 (substitute-in-file-name arg)))
8263 ;; Default - ignore; no warning
8264 ))))
8265 ;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
8266
8267 (defun verilog-getopt-file (filename)
8268 "Read Verilog options from the specified FILENAME."
8269 (save-excursion
8270 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
8271 (orig-buffer (current-buffer))
8272 line)
8273 (if fns
8274 (set-buffer (find-file-noselect (car fns)))
8275 (error (concat (verilog-point-text)
8276 ": Can't find verilog-getopt-file -f file: " filename)))
8277 (goto-char (point-min))
8278 (while (not (eobp))
8279 (setq line (buffer-substring (point) (point-at-eol)))
8280 (forward-line 1)
8281 (when (string-match "//" line)
8282 (setq line (substring line 0 (match-beginning 0))))
8283 (with-current-buffer orig-buffer ; Variables are buffer-local, so need right context.
8284 (verilog-getopt line))))))
8285
8286 (defun verilog-getopt-flags ()
8287 "Convert `verilog-library-flags' into standard library variables."
8288 ;; If the flags are local, then all the outputs should be local also
8289 (when (local-variable-p `verilog-library-flags (current-buffer))
8290 (mapc 'make-local-variable '(verilog-library-extensions
8291 verilog-library-directories
8292 verilog-library-files
8293 verilog-library-flags)))
8294 ;; Allow user to customize
8295 (run-hooks 'verilog-before-getopt-flags-hook)
8296 ;; Process arguments
8297 (verilog-getopt verilog-library-flags)
8298 ;; Allow user to customize
8299 (run-hooks 'verilog-getopt-flags-hook))
8300
8301 (defun verilog-add-list-unique (varref object)
8302 "Append to VARREF list the given OBJECT,
8303 unless it is already a member of the variable's list."
8304 (unless (member object (symbol-value varref))
8305 (set varref (append (symbol-value varref) (list object))))
8306 varref)
8307 ;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
8308
8309 (defun verilog-current-flags ()
8310 "Convert `verilog-library-flags' and similar variables to command line.
8311 Used for __FLAGS__ in `verilog-expand-command'."
8312 (let ((cmd (mapconcat `concat verilog-library-flags " ")))
8313 (when (equal cmd "")
8314 (setq cmd (concat
8315 "+libext+" (mapconcat `concat verilog-library-extensions "+")
8316 (mapconcat (lambda (i) (concat " -y " i " +incdir+" i))
8317 verilog-library-directories "")
8318 (mapconcat (lambda (i) (concat " -v " i))
8319 verilog-library-files ""))))
8320 cmd))
8321 ;;(verilog-current-flags)
8322
8323 \f
8324 ;;
8325 ;; Cached directory support
8326 ;;
8327
8328 (defvar verilog-dir-cache-preserving nil
8329 "If set, the directory cache is enabled, and file system changes are ignored.
8330 See `verilog-dir-exists-p' and `verilog-dir-files'.")
8331
8332 ;; If adding new cached variable, add also to verilog-preserve-dir-cache
8333 (defvar verilog-dir-cache-list nil
8334 "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
8335 (defvar verilog-dir-cache-lib-filenames nil
8336 "Cached data for `verilog-library-filenames'.")
8337
8338 (defmacro verilog-preserve-dir-cache (&rest body)
8339 "Execute the BODY forms, allowing directory cache preservation within BODY.
8340 This means that changes inside BODY made to the file system will not be
8341 seen by the `verilog-dir-files' and related functions."
8342 `(let ((verilog-dir-cache-preserving (current-buffer))
8343 verilog-dir-cache-list
8344 verilog-dir-cache-lib-filenames)
8345 (progn ,@body)))
8346
8347 (defun verilog-dir-files (dirname)
8348 "Return all filenames in the DIRNAME directory.
8349 Relative paths depend on the `default-directory'.
8350 Results are cached if inside `verilog-preserve-dir-cache'."
8351 (unless verilog-dir-cache-preserving
8352 (setq verilog-dir-cache-list nil)) ;; Cache disabled
8353 ;; We don't use expand-file-name on the dirname to make key, as it's slow
8354 (let* ((cache-key (list dirname default-directory))
8355 (fass (assoc cache-key verilog-dir-cache-list))
8356 exp-dirname data)
8357 (cond (fass ;; Return data from cache hit
8358 (nth 1 fass))
8359 (t
8360 (setq exp-dirname (expand-file-name dirname)
8361 data (and (file-directory-p exp-dirname)
8362 (directory-files exp-dirname nil nil nil)))
8363 ;; Note we also encache nil for non-existing dirs.
8364 (setq verilog-dir-cache-list (cons (list cache-key data)
8365 verilog-dir-cache-list))
8366 data))))
8367 ;; Miss-and-hit test:
8368 ;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
8369 ;; (prin1 (verilog-dir-files ".")) nil)
8370
8371 (defun verilog-dir-file-exists-p (filename)
8372 "Return true if FILENAME exists.
8373 Like `file-exists-p' but results are cached if inside
8374 `verilog-preserve-dir-cache'."
8375 (let* ((dirname (file-name-directory filename))
8376 ;; Correct for file-name-nondirectory returning same if no slash.
8377 (dirnamed (if (or (not dirname) (equal dirname filename))
8378 default-directory dirname))
8379 (flist (verilog-dir-files dirnamed)))
8380 (and flist
8381 (member (file-name-nondirectory filename) flist)
8382 t)))
8383 ;;(verilog-dir-file-exists-p "verilog-mode.el")
8384 ;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
8385
8386 \f
8387 ;;
8388 ;; Module name lookup
8389 ;;
8390
8391 (defun verilog-module-inside-filename-p (module filename)
8392 "Return modi if MODULE is specified inside FILENAME, else nil.
8393 Allows version control to check out the file if need be."
8394 (and (or (file-exists-p filename)
8395 (and (fboundp 'vc-backend)
8396 (vc-backend filename)))
8397 (let (modi type)
8398 (with-current-buffer (find-file-noselect filename)
8399 (save-excursion
8400 (goto-char (point-min))
8401 (while (and
8402 ;; It may be tempting to look for verilog-defun-re,
8403 ;; don't, it slows things down a lot!
8404 (verilog-re-search-forward-quick "\\<\\(module\\|interface\\)\\>" nil t)
8405 (setq type (match-string-no-properties 0))
8406 (verilog-re-search-forward-quick "[(;]" nil t))
8407 (if (equal module (verilog-read-module-name))
8408 (setq modi (verilog-modi-new module filename (point) type))))
8409 modi)))))
8410
8411 (defun verilog-is-number (symbol)
8412 "Return true if SYMBOL is number-like."
8413 (or (string-match "^[0-9 \t:]+$" symbol)
8414 (string-match "^[---]*[0-9]+$" symbol)
8415 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
8416
8417 (defun verilog-symbol-detick (symbol wing-it)
8418 "Return an expanded SYMBOL name without any defines.
8419 If the variable vh-{symbol} is defined, return that value.
8420 If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
8421 (while (and symbol (string-match "^`" symbol))
8422 (setq symbol (substring symbol 1))
8423 (setq symbol
8424 (if (boundp (intern (concat "vh-" symbol)))
8425 ;; Emacs has a bug where boundp on a buffer-local
8426 ;; variable in only one buffer returns t in another.
8427 ;; This can confuse, so check for nil.
8428 (let ((val (eval (intern (concat "vh-" symbol)))))
8429 (if (eq val nil)
8430 (if wing-it symbol nil)
8431 val))
8432 (if wing-it symbol nil))))
8433 symbol)
8434 ;;(verilog-symbol-detick "`mod" nil)
8435
8436 (defun verilog-symbol-detick-denumber (symbol)
8437 "Return SYMBOL with defines converted and any numbers dropped to nil."
8438 (when (string-match "^`" symbol)
8439 ;; This only will work if the define is a simple signal, not
8440 ;; something like a[b]. Sorry, it should be substituted into the parser
8441 (setq symbol
8442 (verilog-string-replace-matches
8443 "\[[^0-9: \t]+\]" "" nil nil
8444 (or (verilog-symbol-detick symbol nil)
8445 (if verilog-auto-sense-defines-constant
8446 "0"
8447 symbol)))))
8448 (if (verilog-is-number symbol)
8449 nil
8450 symbol))
8451
8452 (defun verilog-symbol-detick-text (text)
8453 "Return TEXT without any known defines.
8454 If the variable vh-{symbol} is defined, substitute that value."
8455 (let ((ok t) symbol val)
8456 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
8457 (setq symbol (match-string 1 text))
8458 ;;(message symbol)
8459 (cond ((and
8460 (boundp (intern (concat "vh-" symbol)))
8461 ;; Emacs has a bug where boundp on a buffer-local
8462 ;; variable in only one buffer returns t in another.
8463 ;; This can confuse, so check for nil.
8464 (setq val (eval (intern (concat "vh-" symbol)))))
8465 (setq text (replace-match val nil nil text)))
8466 (t (setq ok nil)))))
8467 text)
8468 ;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
8469
8470 (defun verilog-expand-dirnames (&optional dirnames)
8471 "Return a list of existing directories given a list of wildcarded DIRNAMES.
8472 Or, just the existing dirnames themselves if there are no wildcards."
8473 ;; Note this function is performance critical.
8474 ;; Do not call anything that requires disk access that cannot be cached.
8475 (interactive)
8476 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
8477 (setq dirnames (reverse dirnames)) ; not nreverse
8478 (let ((dirlist nil)
8479 pattern dirfile dirfiles dirname root filename rest basefile)
8480 (while dirnames
8481 (setq dirname (substitute-in-file-name (car dirnames))
8482 dirnames (cdr dirnames))
8483 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
8484 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
8485 "\\(.*\\)") ;; rest
8486 dirname)
8487 (setq root (match-string 1 dirname)
8488 filename (match-string 2 dirname)
8489 rest (match-string 3 dirname)
8490 pattern filename)
8491 ;; now replace those * and ? with .+ and .
8492 ;; use ^ and /> to get only whole file names
8493 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
8494 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
8495 pattern (concat "^" pattern "$")
8496 dirfiles (verilog-dir-files root))
8497 (while dirfiles
8498 (setq basefile (car dirfiles)
8499 dirfile (expand-file-name (concat root basefile rest))
8500 dirfiles (cdr dirfiles))
8501 (if (and (string-match pattern basefile)
8502 ;; Don't allow abc/*/rtl to match abc/rtl via ..
8503 (not (equal basefile "."))
8504 (not (equal basefile ".."))
8505 (file-directory-p dirfile))
8506 (setq dirlist (cons dirfile dirlist)))))
8507 ;; Defaults
8508 (t
8509 (if (file-directory-p dirname)
8510 (setq dirlist (cons dirname dirlist))))))
8511 dirlist))
8512 ;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
8513
8514 (defun verilog-library-filenames (filename &optional current check-ext)
8515 "Return a search path to find the given FILENAME or module name.
8516 Uses the optional CURRENT filename or buffer-file-name, plus
8517 `verilog-library-directories' and `verilog-library-extensions'
8518 variables to build the path. With optional CHECK-EXT also check
8519 `verilog-library-extensions'."
8520 (unless current (setq current (buffer-file-name)))
8521 (unless verilog-dir-cache-preserving
8522 (setq verilog-dir-cache-lib-filenames nil))
8523 (let* ((cache-key (list filename current check-ext))
8524 (fass (assoc cache-key verilog-dir-cache-lib-filenames))
8525 chkdirs chkdir chkexts fn outlist)
8526 (cond (fass ;; Return data from cache hit
8527 (nth 1 fass))
8528 (t
8529 ;; Note this expand can't be easily cached, as we need to
8530 ;; pick up buffer-local variables for newly read sub-module files
8531 (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
8532 (while chkdirs
8533 (setq chkdir (expand-file-name (car chkdirs)
8534 (file-name-directory current))
8535 chkexts (if check-ext verilog-library-extensions `("")))
8536 (while chkexts
8537 (setq fn (expand-file-name (concat filename (car chkexts))
8538 chkdir))
8539 ;;(message "Check for %s" fn)
8540 (if (verilog-dir-file-exists-p fn)
8541 (setq outlist (cons (expand-file-name
8542 fn (file-name-directory current))
8543 outlist)))
8544 (setq chkexts (cdr chkexts)))
8545 (setq chkdirs (cdr chkdirs)))
8546 (setq outlist (nreverse outlist))
8547 (setq verilog-dir-cache-lib-filenames
8548 (cons (list cache-key outlist)
8549 verilog-dir-cache-lib-filenames))
8550 outlist))))
8551
8552 (defun verilog-module-filenames (module current)
8553 "Return a search path to find the given MODULE name.
8554 Uses the CURRENT filename, `verilog-library-extensions',
8555 `verilog-library-directories' and `verilog-library-files'
8556 variables to build the path."
8557 ;; Return search locations for it
8558 (append (list current) ; first, current buffer
8559 (verilog-library-filenames module current t)
8560 verilog-library-files)) ; finally, any libraries
8561
8562 ;;
8563 ;; Module Information
8564 ;;
8565 ;; Many of these functions work on "modi" a module information structure
8566 ;; A modi is: [module-name-string file-name begin-point]
8567
8568 (defvar verilog-cache-enabled t
8569 "If true, enable caching of signals, etc. Set to nil for debugging to make things SLOW!")
8570
8571 (defvar verilog-modi-cache-list nil
8572 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
8573 For speeding up verilog-modi-get-* commands.
8574 Buffer-local.")
8575 (make-variable-buffer-local 'verilog-modi-cache-list)
8576
8577 (defvar verilog-modi-cache-preserve-tick nil
8578 "Modification tick after which the cache is still considered valid.
8579 Use `verilog-preserve-modi-cache' to set it.")
8580 (defvar verilog-modi-cache-preserve-buffer nil
8581 "Modification tick after which the cache is still considered valid.
8582 Use `verilog-preserve-modi-cache' to set it.")
8583 (defvar verilog-modi-cache-current-enable nil
8584 "If true, allow caching `verilog-modi-current', set by let().")
8585 (defvar verilog-modi-cache-current nil
8586 "Currently active `verilog-modi-current', if any, set by let().")
8587 (defvar verilog-modi-cache-current-max nil
8588 "Current endmodule point for `verilog-modi-cache-current', if any.")
8589
8590 (defun verilog-modi-current ()
8591 "Return the modi structure for the module currently at point, possibly cached."
8592 (cond ((and verilog-modi-cache-current
8593 (>= (point) (verilog-modi-get-point verilog-modi-cache-current))
8594 (<= (point) verilog-modi-cache-current-max))
8595 ;; Slow assertion, for debugging the cache:
8596 ;;(or (equal verilog-modi-cache-current (verilog-modi-current-get)) (debug))
8597 verilog-modi-cache-current)
8598 (verilog-modi-cache-current-enable
8599 (setq verilog-modi-cache-current (verilog-modi-current-get)
8600 verilog-modi-cache-current-max
8601 ;; The cache expires when we pass "endmodule" as then the
8602 ;; current modi may change to the next module
8603 ;; This relies on the AUTOs generally inserting, not deleting text
8604 (save-excursion
8605 (verilog-re-search-forward-quick verilog-end-defun-re nil nil)))
8606 verilog-modi-cache-current)
8607 (t
8608 (verilog-modi-current-get))))
8609
8610 (defun verilog-modi-current-get ()
8611 "Return the modi structure for the module currently at point."
8612 (let* (name type pt)
8613 ;; read current module's name
8614 (save-excursion
8615 (verilog-re-search-backward-quick verilog-defun-re nil nil)
8616 (setq type (match-string-no-properties 0))
8617 (verilog-re-search-forward-quick "(" nil nil)
8618 (setq name (verilog-read-module-name))
8619 (setq pt (point)))
8620 ;; return modi - note this vector built two places
8621 (verilog-modi-new name (or (buffer-file-name) (current-buffer)) pt type)))
8622
8623 (defvar verilog-modi-lookup-cache nil "Hash of (modulename modi).")
8624 (make-variable-buffer-local 'verilog-modi-lookup-cache)
8625 (defvar verilog-modi-lookup-last-current nil "Cache of `current-buffer' at last lookup.")
8626 (defvar verilog-modi-lookup-last-tick nil "Cache of `buffer-chars-modified-tick' at last lookup.")
8627
8628 (defun verilog-modi-lookup (module allow-cache &optional ignore-error)
8629 "Find the file and point at which MODULE is defined.
8630 If ALLOW-CACHE is set, check and remember cache of previous lookups.
8631 Return modi if successful, else print message unless IGNORE-ERROR is true."
8632 (let* ((current (or (buffer-file-name) (current-buffer)))
8633 modi)
8634 ;; Check cache
8635 ;;(message "verilog-modi-lookup: %s" module)
8636 (cond ((and verilog-modi-lookup-cache
8637 verilog-cache-enabled
8638 allow-cache
8639 (setq modi (gethash module verilog-modi-lookup-cache))
8640 (equal verilog-modi-lookup-last-current current)
8641 ;; Iff hit is in current buffer, then tick must match
8642 (or (equal verilog-modi-lookup-last-tick (buffer-chars-modified-tick))
8643 (not (equal current (verilog-modi-file-or-buffer modi)))))
8644 ;;(message "verilog-modi-lookup: HIT %S" modi)
8645 modi)
8646 ;; Miss
8647 (t (let* ((realmod (verilog-symbol-detick module t))
8648 (orig-filenames (verilog-module-filenames realmod current))
8649 (filenames orig-filenames)
8650 mif)
8651 (while (and filenames (not mif))
8652 (if (not (setq mif (verilog-module-inside-filename-p realmod (car filenames))))
8653 (setq filenames (cdr filenames))))
8654 ;; mif has correct form to become later elements of modi
8655 (cond (mif (setq modi mif))
8656 (t (setq modi nil)
8657 (or ignore-error
8658 (error (concat (verilog-point-text)
8659 ": Can't locate " module " module definition"
8660 (if (not (equal module realmod))
8661 (concat " (Expanded macro to " realmod ")")
8662 "")
8663 "\n Check the verilog-library-directories variable."
8664 "\n I looked in (if not listed, doesn't exist):\n\t"
8665 (mapconcat 'concat orig-filenames "\n\t"))))))
8666 (when (eval-when-compile (fboundp 'make-hash-table))
8667 (unless verilog-modi-lookup-cache
8668 (setq verilog-modi-lookup-cache
8669 (make-hash-table :test 'equal :rehash-size 4.0)))
8670 (puthash module modi verilog-modi-lookup-cache))
8671 (setq verilog-modi-lookup-last-current current
8672 verilog-modi-lookup-last-tick (buffer-chars-modified-tick)))))
8673 modi))
8674
8675 (defun verilog-modi-filename (modi)
8676 "Filename of MODI, or name of buffer if it's never been saved."
8677 (if (bufferp (verilog-modi-file-or-buffer modi))
8678 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
8679 (buffer-name (verilog-modi-file-or-buffer modi)))
8680 (verilog-modi-file-or-buffer modi)))
8681
8682 (defun verilog-modi-goto (modi)
8683 "Move point/buffer to specified MODI."
8684 (or modi (error "Passed unfound modi to goto, check earlier"))
8685 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
8686 (verilog-modi-file-or-buffer modi)
8687 (find-file-noselect (verilog-modi-file-or-buffer modi))))
8688 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
8689 (verilog-mode))
8690 (goto-char (verilog-modi-get-point modi)))
8691
8692 (defun verilog-goto-defun-file (module)
8693 "Move point to the file at which a given MODULE is defined."
8694 (interactive "sGoto File for Module: ")
8695 (let* ((modi (verilog-modi-lookup module nil)))
8696 (when modi
8697 (verilog-modi-goto modi)
8698 (switch-to-buffer (current-buffer)))))
8699
8700 (defun verilog-modi-cache-results (modi function)
8701 "Run on MODI the given FUNCTION. Locate the module in a file.
8702 Cache the output of function so next call may have faster access."
8703 (let (fass)
8704 (save-excursion ;; Cache is buffer-local so can't avoid this.
8705 (verilog-modi-goto modi)
8706 (if (and (setq fass (assoc (list modi function)
8707 verilog-modi-cache-list))
8708 ;; Destroy caching when incorrect; Modified or file changed
8709 (not (and verilog-cache-enabled
8710 (or (equal (buffer-chars-modified-tick) (nth 1 fass))
8711 (and verilog-modi-cache-preserve-tick
8712 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
8713 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
8714 (equal (visited-file-modtime) (nth 2 fass)))))
8715 (setq verilog-modi-cache-list nil
8716 fass nil))
8717 (cond (fass
8718 ;; Return data from cache hit
8719 (nth 3 fass))
8720 (t
8721 ;; Read from file
8722 ;; Clear then restore any highlighting to make emacs19 happy
8723 (let ((fontlocked (when (and (boundp 'font-lock-mode)
8724 font-lock-mode)
8725 (font-lock-mode 0)
8726 t))
8727 func-returns)
8728 (setq func-returns (funcall function))
8729 (when fontlocked (font-lock-mode t))
8730 ;; Cache for next time
8731 (setq verilog-modi-cache-list
8732 (cons (list (list modi function)
8733 (buffer-chars-modified-tick)
8734 (visited-file-modtime)
8735 func-returns)
8736 verilog-modi-cache-list))
8737 func-returns))))))
8738
8739 (defun verilog-modi-cache-add (modi function element sig-list)
8740 "Add function return results to the module cache.
8741 Update MODI's cache for given FUNCTION so that the return ELEMENT of that
8742 function now contains the additional SIG-LIST parameters."
8743 (let (fass)
8744 (save-excursion
8745 (verilog-modi-goto modi)
8746 (if (setq fass (assoc (list modi function)
8747 verilog-modi-cache-list))
8748 (let ((func-returns (nth 3 fass)))
8749 (aset func-returns element
8750 (append sig-list (aref func-returns element))))))))
8751
8752 (defmacro verilog-preserve-modi-cache (&rest body)
8753 "Execute the BODY forms, allowing cache preservation within BODY.
8754 This means that changes to the buffer will not result in the cache being
8755 flushed. If the changes affect the modsig state, they must call the
8756 modsig-cache-add-* function, else the results of later calls may be
8757 incorrect. Without this, changes are assumed to be adding/removing signals
8758 and invalidating the cache."
8759 `(let ((verilog-modi-cache-preserve-tick (buffer-chars-modified-tick))
8760 (verilog-modi-cache-preserve-buffer (current-buffer)))
8761 (progn ,@body)))
8762
8763
8764 (defun verilog-signals-matching-enum (in-list enum)
8765 "Return all signals in IN-LIST matching the given ENUM."
8766 (let (out-list)
8767 (while in-list
8768 (if (equal (verilog-sig-enum (car in-list)) enum)
8769 (setq out-list (cons (car in-list) out-list)))
8770 (setq in-list (cdr in-list)))
8771 ;; New scheme
8772 (let* ((enumvar (intern (concat "venum-" enum)))
8773 (enumlist (and (boundp enumvar) (eval enumvar))))
8774 (while enumlist
8775 (add-to-list 'out-list (list (car enumlist)))
8776 (setq enumlist (cdr enumlist))))
8777 (nreverse out-list)))
8778
8779 (defun verilog-signals-matching-regexp (in-list regexp)
8780 "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
8781 (if (or (not regexp) (equal regexp ""))
8782 in-list
8783 (let (out-list)
8784 (while in-list
8785 (if (string-match regexp (verilog-sig-name (car in-list)))
8786 (setq out-list (cons (car in-list) out-list)))
8787 (setq in-list (cdr in-list)))
8788 (nreverse out-list))))
8789
8790 (defun verilog-signals-not-matching-regexp (in-list regexp)
8791 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
8792 (if (or (not regexp) (equal regexp ""))
8793 in-list
8794 (let (out-list)
8795 (while in-list
8796 (if (not (string-match regexp (verilog-sig-name (car in-list))))
8797 (setq out-list (cons (car in-list) out-list)))
8798 (setq in-list (cdr in-list)))
8799 (nreverse out-list))))
8800
8801 (defun verilog-signals-matching-dir-re (in-list decl-type regexp)
8802 "Return all signals in IN-LIST matching the given DECL-TYPE and REGEXP,
8803 if non-nil."
8804 (if (or (not regexp) (equal regexp ""))
8805 in-list
8806 (let (out-list to-match)
8807 (while in-list
8808 ;; Note verilog-insert-one-definition matches on this order
8809 (setq to-match (concat
8810 decl-type
8811 " " (verilog-sig-signed (car in-list))
8812 " " (verilog-sig-multidim (car in-list))
8813 (verilog-sig-bits (car in-list))))
8814 (if (string-match regexp to-match)
8815 (setq out-list (cons (car in-list) out-list)))
8816 (setq in-list (cdr in-list)))
8817 (nreverse out-list))))
8818
8819 ;; Combined
8820 (defun verilog-decls-get-signals (decls)
8821 (append
8822 (verilog-decls-get-outputs decls)
8823 (verilog-decls-get-inouts decls)
8824 (verilog-decls-get-inputs decls)
8825 (verilog-decls-get-wires decls)
8826 (verilog-decls-get-regs decls)
8827 (verilog-decls-get-assigns decls)
8828 (verilog-decls-get-consts decls)
8829 (verilog-decls-get-gparams decls)))
8830
8831 (defun verilog-decls-get-ports (decls)
8832 (append
8833 (verilog-decls-get-outputs decls)
8834 (verilog-decls-get-inouts decls)
8835 (verilog-decls-get-inputs decls)))
8836
8837 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
8838 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
8839 (defsubst verilog-modi-cache-add-inouts (modi sig-list)
8840 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
8841 (defsubst verilog-modi-cache-add-inputs (modi sig-list)
8842 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
8843 (defsubst verilog-modi-cache-add-wires (modi sig-list)
8844 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
8845 (defsubst verilog-modi-cache-add-regs (modi sig-list)
8846 (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
8847
8848 (defun verilog-signals-from-signame (signame-list)
8849 "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
8850 (mapcar (function (lambda (name) (list name nil nil)))
8851 signame-list))
8852 \f
8853 ;;
8854 ;; Auto creation utilities
8855 ;;
8856
8857 (defun verilog-auto-re-search-do (search-for func)
8858 "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
8859 (goto-char (point-min))
8860 (while (verilog-re-search-forward search-for nil t)
8861 (funcall func)))
8862
8863 (defun verilog-insert-one-definition (sig type indent-pt)
8864 "Print out a definition for SIG of the given TYPE,
8865 with appropriate INDENT-PT indentation."
8866 (indent-to indent-pt)
8867 ;; Note verilog-signals-matching-dir-re matches on this order
8868 (insert type)
8869 (when (verilog-sig-modport sig)
8870 (insert "." (verilog-sig-modport sig)))
8871 (when (verilog-sig-signed sig)
8872 (insert " " (verilog-sig-signed sig)))
8873 (when (verilog-sig-multidim sig)
8874 (insert " " (verilog-sig-multidim-string sig)))
8875 (when (verilog-sig-bits sig)
8876 (insert " " (verilog-sig-bits sig)))
8877 (indent-to (max 24 (+ indent-pt 16)))
8878 (unless (= (char-syntax (preceding-char)) ?\ )
8879 (insert " ")) ; Need space between "]name" if indent-to did nothing
8880 (insert (verilog-sig-name sig))
8881 (when (verilog-sig-memory sig)
8882 (insert " " (verilog-sig-memory sig))))
8883
8884 (defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
8885 "Print out a definition for a list of SIGS of the given DIRECTION,
8886 with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
8887 format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output."
8888 (or dont-sort
8889 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
8890 (while sigs
8891 (let ((sig (car sigs)))
8892 (verilog-insert-one-definition
8893 sig
8894 ;; Want "type x" or "output type x", not "wire type x"
8895 (cond ((verilog-sig-type sig)
8896 (concat
8897 (if (not (member direction '("wire" "interface")))
8898 (concat direction " "))
8899 (verilog-sig-type sig)))
8900 (t direction))
8901 indent-pt)
8902 (insert (if v2k "," ";"))
8903 (if (or (not (verilog-sig-comment sig))
8904 (equal "" (verilog-sig-comment sig)))
8905 (insert "\n")
8906 (indent-to (max 48 (+ indent-pt 40)))
8907 (verilog-insert "// " (verilog-sig-comment sig) "\n"))
8908 (setq sigs (cdr sigs)))))
8909
8910 (eval-when-compile
8911 (if (not (boundp 'indent-pt))
8912 (defvar indent-pt nil "Local used by insert-indent")))
8913
8914 (defun verilog-insert-indent (&rest stuff)
8915 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
8916 Presumes that any newlines end a list element."
8917 (let ((need-indent t))
8918 (while stuff
8919 (if need-indent (indent-to indent-pt))
8920 (setq need-indent nil)
8921 (verilog-insert (car stuff))
8922 (setq need-indent (string-match "\n$" (car stuff))
8923 stuff (cdr stuff)))))
8924 ;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
8925
8926 (defun verilog-repair-open-comma ()
8927 "Insert comma if previous argument is other than a open parenthesis or endif."
8928 ;; We can't just search backward for ) as it might be inside another expression.
8929 ;; Also want "`ifdef X input foo `endif" to just leave things to the human to deal with
8930 (save-excursion
8931 (verilog-backward-syntactic-ws)
8932 (when (and (not (save-excursion ;; Not beginning (, or existing ,
8933 (backward-char 1)
8934 (looking-at "[(,]")))
8935 (not (save-excursion ;; Not `endif, or user define
8936 (backward-char 1)
8937 (skip-chars-backward "[a-zA-Z0-9_`]")
8938 (looking-at "`"))))
8939 (insert ","))))
8940
8941 (defun verilog-repair-close-comma ()
8942 "If point is at a comma followed by a close parenthesis, fix it.
8943 This repairs those mis-inserted by a AUTOARG."
8944 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
8945 (save-excursion
8946 (verilog-forward-close-paren)
8947 (backward-char 1)
8948 (verilog-backward-syntactic-ws)
8949 (backward-char 1)
8950 (when (looking-at ",")
8951 (delete-char 1))))
8952
8953 (defun verilog-get-list (start end)
8954 "Return the elements of a comma separated list between START and END."
8955 (interactive)
8956 (let ((my-list (list))
8957 my-string)
8958 (save-excursion
8959 (while (< (point) end)
8960 (when (re-search-forward "\\([^,{]+\\)" end t)
8961 (setq my-string (verilog-string-remove-spaces (match-string 1)))
8962 (setq my-list (nconc my-list (list my-string) ))
8963 (goto-char (match-end 0))))
8964 my-list)))
8965
8966 (defun verilog-make-width-expression (range-exp)
8967 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
8968 ;; strip off the []
8969 (cond ((not range-exp)
8970 "1")
8971 (t
8972 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
8973 (setq range-exp (match-string 1 range-exp)))
8974 (cond ((not range-exp)
8975 "1")
8976 ;; [#:#] We can compute a numeric result
8977 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
8978 range-exp)
8979 (int-to-string
8980 (1+ (abs (- (string-to-number (match-string 1 range-exp))
8981 (string-to-number (match-string 2 range-exp)))))))
8982 ;; [PARAM-1:0] can just return PARAM
8983 ((string-match "^\\s *\\([a-zA-Z_][a-zA-Z0-9_]*\\)\\s *-\\s *1\\s *:\\s *0\\s *$" range-exp)
8984 (match-string 1 range-exp))
8985 ;; [arbitrary] need math
8986 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
8987 (concat "(1+(" (match-string 1 range-exp) ")"
8988 (if (equal "0" (match-string 2 range-exp))
8989 "" ;; Don't bother with -(0)
8990 (concat "-(" (match-string 2 range-exp) ")"))
8991 ")"))
8992 (t nil)))))
8993 ;;(verilog-make-width-expression "`A:`B")
8994
8995 (defun verilog-simplify-range-expression (range-exp)
8996 "Return a simplified range expression with constants eliminated from RANGE-EXP."
8997 (let ((out range-exp)
8998 (last-pass ""))
8999 (while (not (equal last-pass out))
9000 (setq last-pass out)
9001 (while (string-match "(\\<\\([0-9A-Z-az_]+\\)\\>)" out)
9002 (setq out (replace-match "\\1" nil nil out)))
9003 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\+\\s *\\<\\([0-9]+\\)\\>" out)
9004 (setq out (replace-match
9005 (int-to-string (+ (string-to-number (match-string 1 out))
9006 (string-to-number (match-string 2 out))))
9007 nil nil out)))
9008 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\-\\s *\\<\\([0-9]+\\)\\>" out)
9009 (setq out (replace-match
9010 (int-to-string (- (string-to-number (match-string 1 out))
9011 (string-to-number (match-string 2 out))))
9012 nil nil out))))
9013 out))
9014 ;;(verilog-simplify-range-expression "1")
9015 ;;(verilog-simplify-range-expression "(((16)+1)-3)")
9016
9017 (defun verilog-typedef-name-p (variable-name)
9018 "Return true if the VARIABLE-NAME is a type definition."
9019 (when verilog-typedef-regexp
9020 (string-match verilog-typedef-regexp variable-name)))
9021 \f
9022 ;;
9023 ;; Auto deletion
9024 ;;
9025
9026 (defun verilog-delete-autos-lined ()
9027 "Delete autos that occupy multiple lines, between begin and end comments."
9028 (let ((pt (point)))
9029 (forward-line 1)
9030 (when (and
9031 (looking-at "\\s-*// Beginning")
9032 (search-forward "// End of automatic" nil t))
9033 ;; End exists
9034 (end-of-line)
9035 (delete-region pt (point))
9036 (forward-line 1))))
9037
9038 (defun verilog-delete-empty-auto-pair ()
9039 "Delete begin/end auto pair at point, if empty."
9040 (forward-line 0)
9041 (when (looking-at (concat "\\s-*// Beginning of automatic.*\n"
9042 "\\s-*// End of automatics\n"))
9043 (delete-region (point) (save-excursion (forward-line 2) (point)))))
9044
9045 (defun verilog-forward-close-paren ()
9046 "Find the close parenthesis that match the current point.
9047 Ignore other close parenthesis with matching open parens."
9048 (let ((parens 1))
9049 (while (> parens 0)
9050 (unless (verilog-re-search-forward-quick "[()]" nil t)
9051 (error "%s: Mismatching ()" (verilog-point-text)))
9052 (cond ((= (preceding-char) ?\( )
9053 (setq parens (1+ parens)))
9054 ((= (preceding-char) ?\) )
9055 (setq parens (1- parens)))))))
9056
9057 (defun verilog-backward-open-paren ()
9058 "Find the open parenthesis that match the current point.
9059 Ignore other open parenthesis with matching close parens."
9060 (let ((parens 1))
9061 (while (> parens 0)
9062 (unless (verilog-re-search-backward-quick "[()]" nil t)
9063 (error "%s: Mismatching ()" (verilog-point-text)))
9064 (cond ((= (following-char) ?\) )
9065 (setq parens (1+ parens)))
9066 ((= (following-char) ?\( )
9067 (setq parens (1- parens)))))))
9068
9069 (defun verilog-backward-open-bracket ()
9070 "Find the open bracket that match the current point.
9071 Ignore other open bracket with matching close bracket."
9072 (let ((parens 1))
9073 (while (> parens 0)
9074 (unless (verilog-re-search-backward-quick "[][]" nil t)
9075 (error "%s: Mismatching []" (verilog-point-text)))
9076 (cond ((= (following-char) ?\] )
9077 (setq parens (1+ parens)))
9078 ((= (following-char) ?\[ )
9079 (setq parens (1- parens)))))))
9080
9081 (defun verilog-delete-to-paren ()
9082 "Delete the automatic inst/sense/arg created by autos.
9083 Deletion stops at the matching end parenthesis."
9084 (delete-region (point)
9085 (save-excursion
9086 (verilog-backward-open-paren)
9087 (forward-sexp 1) ;; Moves to paren that closes argdecl's
9088 (backward-char 1)
9089 (point))))
9090
9091 (defun verilog-auto-star-safe ()
9092 "Return if a .* AUTOINST is safe to delete or expand.
9093 It was created by the AUTOS themselves, or by the user."
9094 (and verilog-auto-star-expand
9095 (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\|Interfaces\\)\\)")))
9096
9097 (defun verilog-delete-auto-star-all ()
9098 "Delete a .* AUTOINST, if it is safe."
9099 (when (verilog-auto-star-safe)
9100 (verilog-delete-to-paren)))
9101
9102 (defun verilog-delete-auto-star-implicit ()
9103 "Delete all .* implicit connections created by `verilog-auto-star'.
9104 This function will be called automatically at save unless
9105 `verilog-auto-star-save' is set, any non-templated expanded pins will be
9106 removed."
9107 (interactive)
9108 (let (paren-pt indent have-close-paren)
9109 (save-excursion
9110 (goto-char (point-min))
9111 ;; We need to match these even outside of comments.
9112 ;; For reasonable performance, we don't check if inside comments, sorry.
9113 (while (re-search-forward "// Implicit \\.\\*" nil t)
9114 (setq paren-pt (point))
9115 (beginning-of-line)
9116 (setq have-close-paren
9117 (save-excursion
9118 (when (search-forward ");" paren-pt t)
9119 (setq indent (current-indentation))
9120 t)))
9121 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
9122 (when have-close-paren
9123 ;; Delete extra commentary
9124 (save-excursion
9125 (while (progn
9126 (forward-line -1)
9127 (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\|Interfaces\\)\n"))
9128 (delete-region (match-beginning 0) (match-end 0))))
9129 ;; If it is simple, we can put the ); on the same line as the last text
9130 (let ((rtn-pt (point)))
9131 (save-excursion
9132 (while (progn (backward-char 1)
9133 (looking-at "[ \t\n\f]")))
9134 (when (looking-at ",")
9135 (delete-region (+ 1 (point)) rtn-pt))))
9136 (when (bolp)
9137 (indent-to indent))
9138 (insert ");\n")
9139 ;; Still need to kill final comma - always is one as we put one after the .*
9140 (re-search-backward ",")
9141 (delete-char 1))))))
9142
9143 (defun verilog-delete-auto ()
9144 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
9145 Use \\[verilog-auto] to re-insert the updated AUTOs.
9146
9147 The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
9148 called before and after this function, respectively."
9149 (interactive)
9150 (save-excursion
9151 (if (buffer-file-name)
9152 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
9153 (verilog-save-no-change-functions
9154 (verilog-save-scan-cache
9155 ;; Allow user to customize
9156 (run-hooks 'verilog-before-delete-auto-hook)
9157
9158 ;; Remove those that have multi-line insertions, possibly with parameters
9159 (verilog-auto-re-search-do
9160 (concat "/\\*"
9161 (eval-when-compile
9162 (verilog-regexp-words
9163 `("AUTOASCIIENUM" "AUTOCONCATCOMMENT" "AUTODEFINEVALUE"
9164 "AUTOINOUT" "AUTOINOUTCOMP" "AUTOINOUTMODULE"
9165 "AUTOINPUT" "AUTOINSERTLISP" "AUTOOUTPUT" "AUTOOUTPUTEVERY"
9166 "AUTOREG" "AUTOREGINPUT" "AUTORESET" "AUTOTIEOFF"
9167 "AUTOUNUSED" "AUTOWIRE")))
9168 ;; Optional parens or quoted parameter or .* for (((...)))
9169 "\\(\\|([^)]*)\\|(\"[^\"]*\")\\).*?"
9170 "\\*/")
9171 'verilog-delete-autos-lined)
9172 ;; Remove those that are in parenthesis
9173 (verilog-auto-re-search-do
9174 (concat "/\\*"
9175 (eval-when-compile
9176 (verilog-regexp-words
9177 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
9178 "AUTOSENSE")))
9179 "\\*/")
9180 'verilog-delete-to-paren)
9181 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
9182 (verilog-auto-re-search-do "\\.\\*"
9183 'verilog-delete-auto-star-all)
9184 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
9185 (goto-char (point-min))
9186 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
9187 (replace-match ""))
9188
9189 ;; Final customize
9190 (run-hooks 'verilog-delete-auto-hook)))))
9191 \f
9192 ;;
9193 ;; Auto inject
9194 ;;
9195
9196 (defun verilog-inject-auto ()
9197 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
9198
9199 Any always @ blocks with sensitivity lists that match computed lists will
9200 be replaced with /*AS*/ comments.
9201
9202 Any cells will get /*AUTOINST*/ added to the end of the pin list.
9203 Pins with have identical names will be deleted.
9204
9205 Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
9206 support adding new ports. You may wish to delete older ports yourself.
9207
9208 For example:
9209
9210 module ExampInject (i, o);
9211 input i;
9212 input j;
9213 output o;
9214 always @ (i or j)
9215 o = i | j;
9216 InstModule instName
9217 (.foobar(baz),
9218 j(j));
9219 endmodule
9220
9221 Typing \\[verilog-inject-auto] will make this into:
9222
9223 module ExampInject (i, o/*AUTOARG*/
9224 // Inputs
9225 j);
9226 input i;
9227 output o;
9228 always @ (/*AS*/i or j)
9229 o = i | j;
9230 InstModule instName
9231 (.foobar(baz),
9232 /*AUTOINST*/
9233 // Outputs
9234 j(j));
9235 endmodule"
9236 (interactive)
9237 (verilog-auto t))
9238
9239 (defun verilog-inject-arg ()
9240 "Inject AUTOARG into new code. See `verilog-inject-auto'."
9241 ;; Presume one module per file.
9242 (save-excursion
9243 (goto-char (point-min))
9244 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
9245 (let ((endmodp (save-excursion
9246 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
9247 (point))))
9248 ;; See if there's already a comment .. inside a comment so not verilog-re-search
9249 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
9250 (verilog-re-search-forward-quick ";" nil t)
9251 (backward-char 1)
9252 (verilog-backward-syntactic-ws)
9253 (backward-char 1) ; Moves to paren that closes argdecl's
9254 (when (looking-at ")")
9255 (verilog-insert "/*AUTOARG*/")))))))
9256
9257 (defun verilog-inject-sense ()
9258 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
9259 (save-excursion
9260 (goto-char (point-min))
9261 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
9262 (let* ((start-pt (point))
9263 (modi (verilog-modi-current))
9264 (moddecls (verilog-modi-get-decls modi))
9265 pre-sigs
9266 got-sigs)
9267 (backward-char 1)
9268 (forward-sexp 1)
9269 (backward-char 1) ;; End )
9270 (when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
9271 (setq pre-sigs (verilog-signals-from-signame
9272 (verilog-read-signals start-pt (point)))
9273 got-sigs (verilog-auto-sense-sigs moddecls nil))
9274 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
9275 (verilog-signals-not-in got-sigs pre-sigs)))
9276 (delete-region start-pt (point))
9277 (verilog-insert "/*AS*/")))))))
9278
9279 (defun verilog-inject-inst ()
9280 "Inject AUTOINST into new code. See `verilog-inject-auto'."
9281 (save-excursion
9282 (goto-char (point-min))
9283 ;; It's hard to distinguish modules; we'll instead search for pins.
9284 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
9285 (verilog-backward-open-paren) ;; Inst start
9286 (cond
9287 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
9288 (forward-char 1)
9289 (verilog-forward-close-paren)) ;; Parameters done
9290 (t
9291 (forward-char 1)
9292 (let ((indent-pt (+ (current-column)))
9293 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
9294 (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
9295 (goto-char end-pt)) ;; Already there, continue search with next instance
9296 (t
9297 ;; Delete identical interconnect
9298 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
9299 (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
9300 (delete-region (match-beginning 0) (match-end 0))
9301 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
9302 (while (or (looking-at "[ \t\n\f,]+")
9303 (looking-at "//[^\n]*"))
9304 (delete-region (match-beginning 0) (match-end 0))
9305 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
9306 (verilog-forward-close-paren)
9307 (backward-char 1)
9308 ;; Not verilog-re-search, as we don't want to strip comments
9309 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
9310 (delete-region (match-beginning 0) (match-end 0)))
9311 (verilog-insert "\n")
9312 (verilog-insert-indent "/*AUTOINST*/")))))))))
9313 \f
9314 ;;
9315 ;; Auto save
9316 ;;
9317
9318 (defun verilog-auto-save-check ()
9319 "On saving see if we need auto update."
9320 (cond ((not verilog-auto-save-policy)) ; disabled
9321 ((not (save-excursion
9322 (save-match-data
9323 (let ((case-fold-search nil))
9324 (goto-char (point-min))
9325 (re-search-forward "AUTO" nil t))))))
9326 ((eq verilog-auto-save-policy 'force)
9327 (verilog-auto))
9328 ((not (buffer-modified-p)))
9329 ((eq verilog-auto-update-tick (buffer-chars-modified-tick))) ; up-to-date
9330 ((eq verilog-auto-save-policy 'detect)
9331 (verilog-auto))
9332 (t
9333 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
9334 (verilog-auto))
9335 ;; Don't ask again if didn't update
9336 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))))
9337 (when (not verilog-auto-star-save)
9338 (verilog-delete-auto-star-implicit))
9339 nil) ;; Always return nil -- we don't write the file ourselves
9340
9341 (defun verilog-auto-read-locals ()
9342 "Return file local variable segment at bottom of file."
9343 (save-excursion
9344 (goto-char (point-max))
9345 (if (re-search-backward "Local Variables:" nil t)
9346 (buffer-substring-no-properties (point) (point-max))
9347 "")))
9348
9349 (defun verilog-auto-reeval-locals (&optional force)
9350 "Read file local variable segment at bottom of file if it has changed.
9351 If FORCE, always reread it."
9352 (make-local-variable 'verilog-auto-last-file-locals)
9353 (let ((curlocal (verilog-auto-read-locals)))
9354 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
9355 (setq verilog-auto-last-file-locals curlocal)
9356 ;; Note this may cause this function to be recursively invoked,
9357 ;; because hack-local-variables may call (verilog-mode)
9358 ;; The above when statement will prevent it from recursing forever.
9359 (hack-local-variables)
9360 t)))
9361 \f
9362 ;;
9363 ;; Auto creation
9364 ;;
9365
9366 (defun verilog-auto-arg-ports (sigs message indent-pt)
9367 "Print a list of ports for a AUTOINST.
9368 Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
9369 (when sigs
9370 (when verilog-auto-arg-sort
9371 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
9372 (insert "\n")
9373 (indent-to indent-pt)
9374 (insert message)
9375 (insert "\n")
9376 (let ((space ""))
9377 (indent-to indent-pt)
9378 (while sigs
9379 (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
9380 (insert "\n")
9381 (indent-to indent-pt))
9382 (t (insert space)))
9383 (insert (verilog-sig-name (car sigs)) ",")
9384 (setq sigs (cdr sigs)
9385 space " ")))))
9386
9387 (defun verilog-auto-arg ()
9388 "Expand AUTOARG statements.
9389 Replace the argument declarations at the beginning of the
9390 module with ones automatically derived from input and output
9391 statements. This can be dangerous if the module is instantiated
9392 using position-based connections, so use only name-based when
9393 instantiating the resulting module. Long lines are split based
9394 on the `fill-column', see \\[set-fill-column].
9395
9396 Limitations:
9397 Concatenation and outputting partial busses is not supported.
9398
9399 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9400
9401 For example:
9402
9403 module ExampArg (/*AUTOARG*/);
9404 input i;
9405 output o;
9406 endmodule
9407
9408 Typing \\[verilog-auto] will make this into:
9409
9410 module ExampArg (/*AUTOARG*/
9411 // Outputs
9412 o,
9413 // Inputs
9414 i
9415 );
9416 input i;
9417 output o;
9418 endmodule
9419
9420 The argument declarations may be printed in declaration order to best suit
9421 order based instantiations, or alphabetically, based on the
9422 `verilog-auto-arg-sort' variable.
9423
9424 Any ports declared between the ( and /*AUTOARG*/ are presumed to be
9425 predeclared and are not redeclared by AUTOARG. AUTOARG will make a
9426 conservative guess on adding a comma for the first signal, if you have
9427 any ifdefs or complicated expressions before the AUTOARG you will need
9428 to choose the comma yourself.
9429
9430 Avoid declaring ports manually, as it makes code harder to maintain."
9431 (save-excursion
9432 (let* ((modi (verilog-modi-current))
9433 (moddecls (verilog-modi-get-decls modi))
9434 (skip-pins (aref (verilog-read-arg-pins) 0)))
9435 (verilog-repair-open-comma)
9436 (verilog-auto-arg-ports (verilog-signals-not-in
9437 (verilog-decls-get-outputs moddecls)
9438 skip-pins)
9439 "// Outputs"
9440 verilog-indent-level-declaration)
9441 (verilog-auto-arg-ports (verilog-signals-not-in
9442 (verilog-decls-get-inouts moddecls)
9443 skip-pins)
9444 "// Inouts"
9445 verilog-indent-level-declaration)
9446 (verilog-auto-arg-ports (verilog-signals-not-in
9447 (verilog-decls-get-inputs moddecls)
9448 skip-pins)
9449 "// Inputs"
9450 verilog-indent-level-declaration)
9451 (verilog-repair-close-comma)
9452 (unless (eq (char-before) ?/ )
9453 (insert "\n"))
9454 (indent-to verilog-indent-level-declaration))))
9455
9456 (defun verilog-auto-inst-port-map (port-st)
9457 nil)
9458
9459 (defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
9460 (defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
9461 (defvar vl-modport nil "See `verilog-auto-inst'.") ; Prevent compile warning
9462 (defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
9463 (defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
9464 (defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
9465 (defvar vl-bits nil "See `verilog-auto-inst'.") ; Prevent compile warning
9466 (defvar vl-mbits nil "See `verilog-auto-inst'.") ; Prevent compile warning
9467
9468 (defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
9469 "Print out a instantiation connection for this PORT-ST.
9470 Insert to INDENT-PT, use template TPL-LIST.
9471 @ are instantiation numbers, replaced with TPL-NUM.
9472 @\"(expression @)\" are evaluated, with @ as a variable.
9473 If FOR-STAR add comment it is a .* expansion.
9474 If PAR-VALUES replace final strings with these parameter values."
9475 (let* ((port (verilog-sig-name port-st))
9476 (tpl-ass (or (assoc port (car tpl-list))
9477 (verilog-auto-inst-port-map port-st)))
9478 ;; vl-* are documented for user use
9479 (vl-name (verilog-sig-name port-st))
9480 (vl-width (verilog-sig-width port-st))
9481 (vl-modport (verilog-sig-modport port-st))
9482 (vl-mbits (if (verilog-sig-multidim port-st)
9483 (verilog-sig-multidim-string port-st) ""))
9484 (vl-bits (if (or verilog-auto-inst-vector
9485 (not (assoc port vector-skip-list))
9486 (not (equal (verilog-sig-bits port-st)
9487 (verilog-sig-bits (assoc port vector-skip-list)))))
9488 (or (verilog-sig-bits port-st) "")
9489 ""))
9490 (case-fold-search nil)
9491 (check-values par-values)
9492 tpl-net)
9493 ;; Replace parameters in bit-width
9494 (when (and check-values
9495 (not (equal vl-bits "")))
9496 (while check-values
9497 (setq vl-bits (verilog-string-replace-matches
9498 (concat "\\<" (nth 0 (car check-values)) "\\>")
9499 (concat "(" (nth 1 (car check-values)) ")")
9500 t t vl-bits)
9501 check-values (cdr check-values)))
9502 (setq vl-bits (verilog-simplify-range-expression vl-bits))) ; Not in the loop for speed
9503 ;; Default net value if not found
9504 (setq tpl-net (concat port
9505 (if vl-modport (concat "." vl-modport) "")
9506 (if (verilog-sig-multidim port-st)
9507 (concat "/*" (verilog-sig-multidim-string port-st)
9508 vl-bits "*/")
9509 (concat vl-bits))))
9510 ;; Find template
9511 (cond (tpl-ass ; Template of exact port name
9512 (setq tpl-net (nth 1 tpl-ass)))
9513 ((nth 1 tpl-list) ; Wildcards in template, search them
9514 (let ((wildcards (nth 1 tpl-list)))
9515 (while wildcards
9516 (when (string-match (nth 0 (car wildcards)) port)
9517 (setq tpl-ass (car wildcards) ; so allow @ parsing
9518 tpl-net (replace-match (nth 1 (car wildcards))
9519 t nil port)))
9520 (setq wildcards (cdr wildcards))))))
9521 ;; Parse Templated variable
9522 (when tpl-ass
9523 ;; Evaluate @"(lispcode)"
9524 (when (string-match "@\".*[^\\]\"" tpl-net)
9525 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
9526 (setq tpl-net
9527 (concat
9528 (substring tpl-net 0 (match-beginning 0))
9529 (save-match-data
9530 (let* ((expr (match-string 1 tpl-net))
9531 (value
9532 (progn
9533 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
9534 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
9535 (prin1 (eval (car (read-from-string expr)))
9536 (lambda (ch) ())))))
9537 (if (numberp value) (setq value (number-to-string value)))
9538 value))
9539 (substring tpl-net (match-end 0))))))
9540 ;; Replace @ and [] magic variables in final output
9541 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
9542 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
9543 ;; Insert it
9544 (indent-to indent-pt)
9545 (insert "." port)
9546 (unless (and verilog-auto-inst-dot-name
9547 (equal port tpl-net))
9548 (indent-to verilog-auto-inst-column)
9549 (insert "(" tpl-net ")"))
9550 (insert ",")
9551 (cond (tpl-ass
9552 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
9553 verilog-auto-inst-column))
9554 (if verilog-auto-inst-template-numbers
9555 (verilog-insert " // Templated"
9556 " T" (int-to-string (nth 2 tpl-ass))
9557 " L" (int-to-string (nth 3 tpl-ass)))
9558 (verilog-insert " // Templated")))
9559 (for-star
9560 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
9561 verilog-auto-inst-column))
9562 (verilog-insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
9563 (insert "\n")))
9564 ;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
9565 ;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
9566 ;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
9567
9568 (defun verilog-auto-inst-first ()
9569 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
9570 ;; Do we need a trailing comma?
9571 ;; There maybe a ifdef or something similar before us. What a mess. Thus
9572 ;; to avoid trouble we only insert on preceding ) or *.
9573 ;; Insert first port on new line
9574 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
9575 (save-excursion
9576 (verilog-re-search-backward "[^ \t\n\f]" nil nil)
9577 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
9578 (forward-char 1)
9579 (insert ","))))
9580
9581 (defun verilog-auto-star ()
9582 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
9583
9584 If `verilog-auto-star-expand' is set, .* pins are treated if they were
9585 AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
9586 will also ignore any .* that are not last in your pin list (this prevents
9587 it from deleting pins following the .* when it expands the AUTOINST.)
9588
9589 On writing your file, unless `verilog-auto-star-save' is set, any
9590 non-templated expanded pins will be removed. You may do this at any time
9591 with \\[verilog-delete-auto-star-implicit].
9592
9593 If you are converting a module to use .* for the first time, you may wish
9594 to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
9595
9596 See `verilog-auto-inst' for examples, templates, and more information."
9597 (when (verilog-auto-star-safe)
9598 (verilog-auto-inst)))
9599
9600 (defun verilog-auto-inst ()
9601 "Expand AUTOINST statements, as part of \\[verilog-auto].
9602 Replace the pin connections to an instantiation or interface
9603 declaration with ones automatically derived from the module or
9604 interface header of the instantiated item.
9605
9606 If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
9607 and delete them before saving unless `verilog-auto-star-save' is set.
9608 See `verilog-auto-star' for more information.
9609
9610 Limitations:
9611 Module names must be resolvable to filenames by adding a
9612 `verilog-library-extensions', and being found in the same directory, or
9613 by changing the variable `verilog-library-flags' or
9614 `verilog-library-directories'. Macros `modname are translated through the
9615 vh-{name} Emacs variable, if that is not found, it just ignores the `.
9616
9617 In templates you must have one signal per line, ending in a ), or ));,
9618 and have proper () nesting, including a final ); to end the template.
9619
9620 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9621
9622 SystemVerilog multidimensional input/output has only experimental support.
9623
9624 SystemVerilog .name syntax is used if `verilog-auto-inst-dot-name' is set.
9625
9626 Parameters referenced by the instantiation will remain symbolic, unless
9627 `verilog-auto-inst-param-value' is set.
9628
9629 Gate primitives (and/or) may have AUTOINST for the purpose of
9630 AUTOWIRE declarations, etc. Gates are the only case when
9631 position based connections are passed.
9632
9633 For example, first take the submodule InstModule.v:
9634
9635 module InstModule (o,i);
9636 output [31:0] o;
9637 input i;
9638 wire [31:0] o = {32{i}};
9639 endmodule
9640
9641 This is then used in a upper level module:
9642
9643 module ExampInst (o,i);
9644 output o;
9645 input i;
9646 InstModule instName
9647 (/*AUTOINST*/);
9648 endmodule
9649
9650 Typing \\[verilog-auto] will make this into:
9651
9652 module ExampInst (o,i);
9653 output o;
9654 input i;
9655 InstModule instName
9656 (/*AUTOINST*/
9657 // Outputs
9658 .ov (ov[31:0]),
9659 // Inputs
9660 .i (i));
9661 endmodule
9662
9663 Where the list of inputs and outputs came from the inst module.
9664 \f
9665 Exceptions:
9666
9667 Unless you are instantiating a module multiple times, or the module is
9668 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
9669 It just makes for unmaintainable code. To sanitize signal names, try
9670 vrename from URL `http://www.veripool.org'.
9671
9672 When you need to violate this suggestion there are two ways to list
9673 exceptions, placing them before the AUTOINST, or using templates.
9674
9675 Any ports defined before the /*AUTOINST*/ are not included in the list of
9676 automatics. This is similar to making a template as described below, but
9677 is restricted to simple connections just like you normally make. Also note
9678 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
9679 you have the appropriate // Input or // Output comment, and exactly the
9680 same line formatting as AUTOINST itself uses.
9681
9682 InstModule instName
9683 (// Inputs
9684 .i (my_i_dont_mess_with_it),
9685 /*AUTOINST*/
9686 // Outputs
9687 .ov (ov[31:0]));
9688
9689 \f
9690 Templates:
9691
9692 For multiple instantiations based upon a single template, create a
9693 commented out template:
9694
9695 /* InstModule AUTO_TEMPLATE (
9696 .sig3 (sigz[]),
9697 );
9698 */
9699
9700 Templates go ABOVE the instantiation(s). When an instantiation is
9701 expanded `verilog-mode' simply searches up for the closest template.
9702 Thus you can have multiple templates for the same module, just alternate
9703 between the template for an instantiation and the instantiation itself.
9704
9705 The module name must be the same as the name of the module in the
9706 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
9707 words and capitalized. Only signals that must be different for each
9708 instantiation need to be listed.
9709
9710 Inside a template, a [] in a connection name (with nothing else inside
9711 the brackets) will be replaced by the same bus subscript as it is being
9712 connected to, or the [] will be removed if it is a single bit signal.
9713 Generally it is a good idea to do this for all connections in a template,
9714 as then they will work for any width signal, and with AUTOWIRE. See
9715 PTL_BUS becoming PTL_BUSNEW below.
9716
9717 If you have a complicated template, set `verilog-auto-inst-template-numbers'
9718 to see which regexps are matching. Don't leave that mode set after
9719 debugging is completed though, it will result in lots of extra differences
9720 and merge conflicts.
9721
9722 For example:
9723
9724 /* InstModule AUTO_TEMPLATE (
9725 .ptl_bus (ptl_busnew[]),
9726 );
9727 */
9728 InstModule ms2m (/*AUTOINST*/);
9729
9730 Typing \\[verilog-auto] will make this into:
9731
9732 InstModule ms2m (/*AUTOINST*/
9733 // Outputs
9734 .NotInTemplate (NotInTemplate),
9735 .ptl_bus (ptl_busnew[3:0]), // Templated
9736 ....
9737 \f
9738 @ Templates:
9739
9740 It is common to instantiate a cell multiple times, so templates make it
9741 trivial to substitute part of the cell name into the connection name.
9742
9743 /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
9744 .sig1 (sigx[@]),
9745 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
9746 );
9747 */
9748
9749 If no regular expression is provided immediately after the AUTO_TEMPLATE
9750 keyword, then the @ character in any connection names will be replaced
9751 with the instantiation number; the first digits found in the cell's
9752 instantiation name.
9753
9754 If a regular expression is provided, the @ character will be replaced
9755 with the first \(\) grouping that matches against the cell name. Using a
9756 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
9757 regexp is provided. If you use multiple layers of parenthesis,
9758 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
9759 characters after test and before _, whereas
9760 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
9761 match.
9762
9763 For example:
9764
9765 /* InstModule AUTO_TEMPLATE (
9766 .ptl_mapvalidx (ptl_mapvalid[@]),
9767 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
9768 );
9769 */
9770 InstModule ms2m (/*AUTOINST*/);
9771
9772 Typing \\[verilog-auto] will make this into:
9773
9774 InstModule ms2m (/*AUTOINST*/
9775 // Outputs
9776 .ptl_mapvalidx (ptl_mapvalid[2]),
9777 .ptl_mapvalidp1x (ptl_mapvalid[3]));
9778
9779 Note the @ character was replaced with the 2 from \"ms2m\".
9780
9781 Alternatively, using a regular expression for @:
9782
9783 /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
9784 .ptl_mapvalidx (@_ptl_mapvalid),
9785 .ptl_mapvalidp1x (ptl_mapvalid_@),
9786 );
9787 */
9788 InstModule ms2_FOO (/*AUTOINST*/);
9789 InstModule ms2_BAR (/*AUTOINST*/);
9790
9791 Typing \\[verilog-auto] will make this into:
9792
9793 InstModule ms2_FOO (/*AUTOINST*/
9794 // Outputs
9795 .ptl_mapvalidx (FOO_ptl_mapvalid),
9796 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
9797 InstModule ms2_BAR (/*AUTOINST*/
9798 // Outputs
9799 .ptl_mapvalidx (BAR_ptl_mapvalid),
9800 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
9801
9802 \f
9803 Regexp Templates:
9804
9805 A template entry of the form
9806
9807 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
9808
9809 will apply an Emacs style regular expression search for any port beginning
9810 in pci_req followed by numbers and ending in _l and connecting that to
9811 the pci_req_jtag_[] net, with the bus subscript coming from what matches
9812 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
9813
9814 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
9815 does the same thing. (Note a @ in the connection/replacement text is
9816 completely different -- still use \\1 there!) Thus this is the same as
9817 the above template:
9818
9819 .pci_req@_l (pci_req_jtag_[\\1]),
9820
9821 Here's another example to remove the _l, useful when naming conventions
9822 specify _ alone to mean active low. Note the use of [] to keep the bus
9823 subscript:
9824
9825 .\\(.*\\)_l (\\1_[]),
9826 \f
9827 Lisp Templates:
9828
9829 First any regular expression template is expanded.
9830
9831 If the syntax @\"( ... )\" is found in a connection, the expression in
9832 quotes will be evaluated as a Lisp expression, with @ replaced by the
9833 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
9834 4 into the brackets. Quote all double-quotes inside the expression with
9835 a leading backslash (\\\"...\\\"); or if the Lisp template is also a
9836 regexp template backslash the backslash quote (\\\\\"...\\\\\").
9837
9838 There are special variables defined that are useful in these
9839 Lisp functions:
9840
9841 vl-name Name portion of the input/output port.
9842 vl-bits Bus bits portion of the input/output port ('[2:0]').
9843 vl-mbits Multidimensional array bits for port ('[2:0][3:0]').
9844 vl-width Width of the input/output port ('3' for [2:0]).
9845 May be a (...) expression if bits isn't a constant.
9846 vl-dir Direction of the pin input/output/inout/interface.
9847 vl-modport The modport, if an interface with a modport.
9848 vl-cell-type Module name/type of the cell ('InstModule').
9849 vl-cell-name Instance name of the cell ('instName').
9850
9851 Normal Lisp variables may be used in expressions. See
9852 `verilog-read-defines' which can set vh-{definename} variables for use
9853 here. Also, any comments of the form:
9854
9855 /*AUTO_LISP(setq foo 1)*/
9856
9857 will evaluate any Lisp expression inside the parenthesis between the
9858 beginning of the buffer and the point of the AUTOINST. This allows
9859 functions to be defined or variables to be changed between instantiations.
9860 (See also `verilog-auto-insert-lisp' if you want the output from your
9861 lisp function to be inserted.)
9862
9863 Note that when using lisp expressions errors may occur when @ is not a
9864 number; you may need to use the standard Emacs Lisp functions
9865 `number-to-string' and `string-to-number'.
9866
9867 After the evaluation is completed, @ substitution and [] substitution
9868 occur.
9869
9870 For more information see the \\[verilog-faq] and forums at URL
9871 `http://www.veripool.org'."
9872 (save-excursion
9873 ;; Find beginning
9874 (let* ((pt (point))
9875 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
9876 (indent-pt (save-excursion (verilog-backward-open-paren)
9877 (1+ (current-column))))
9878 (verilog-auto-inst-column (max verilog-auto-inst-column
9879 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
9880 (modi (verilog-modi-current))
9881 (moddecls (verilog-modi-get-decls modi))
9882 (vector-skip-list (unless verilog-auto-inst-vector
9883 (verilog-decls-get-signals moddecls)))
9884 submod submodi submoddecls
9885 inst skip-pins tpl-list tpl-num did-first par-values)
9886
9887 ;; Find module name that is instantiated
9888 (setq submod (verilog-read-inst-module)
9889 inst (verilog-read-inst-name)
9890 vl-cell-type submod
9891 vl-cell-name inst
9892 skip-pins (aref (verilog-read-inst-pins) 0))
9893
9894 ;; Parse any AUTO_LISP() before here
9895 (verilog-read-auto-lisp (point-min) pt)
9896
9897 ;; Read parameters (after AUTO_LISP)
9898 (setq par-values (and verilog-auto-inst-param-value
9899 (verilog-read-inst-param-value)))
9900
9901 ;; Lookup position, etc of submodule
9902 ;; Note this may raise an error
9903 (when (and (not (member submod verilog-gate-keywords))
9904 (setq submodi (verilog-modi-lookup submod t)))
9905 (setq submoddecls (verilog-modi-get-decls submodi))
9906 ;; If there's a number in the instantiation, it may be a argument to the
9907 ;; automatic variable instantiation program.
9908 (let* ((tpl-info (verilog-read-auto-template submod))
9909 (tpl-regexp (aref tpl-info 0)))
9910 (setq tpl-num (if (string-match tpl-regexp inst)
9911 (match-string 1 inst)
9912 "")
9913 tpl-list (aref tpl-info 1)))
9914 ;; Find submodule's signals and dump
9915 (let ((sig-list (and (equal (verilog-modi-get-type submodi) "interface")
9916 (verilog-signals-not-in
9917 (append (verilog-decls-get-wires submoddecls)
9918 (verilog-decls-get-regs submoddecls))
9919 skip-pins)))
9920 (vl-dir "interfaced"))
9921 (when sig-list
9922 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9923 ;; Note these are searched for in verilog-read-sub-decls.
9924 (verilog-insert-indent "// Interfaced\n")
9925 (mapc (lambda (port)
9926 (verilog-auto-inst-port port indent-pt
9927 tpl-list tpl-num for-star par-values))
9928 sig-list)))
9929 (let ((sig-list (verilog-signals-not-in
9930 (verilog-decls-get-interfaces submoddecls)
9931 skip-pins))
9932 (vl-dir "interface"))
9933 (when sig-list
9934 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9935 ;; Note these are searched for in verilog-read-sub-decls.
9936 (verilog-insert-indent "// Interfaces\n")
9937 (mapc (lambda (port)
9938 (verilog-auto-inst-port port indent-pt
9939 tpl-list tpl-num for-star par-values))
9940 sig-list)))
9941 (let ((sig-list (verilog-signals-not-in
9942 (verilog-decls-get-outputs submoddecls)
9943 skip-pins))
9944 (vl-dir "output"))
9945 (when sig-list
9946 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9947 (verilog-insert-indent "// Outputs\n")
9948 (mapc (lambda (port)
9949 (verilog-auto-inst-port port indent-pt
9950 tpl-list tpl-num for-star par-values))
9951 sig-list)))
9952 (let ((sig-list (verilog-signals-not-in
9953 (verilog-decls-get-inouts submoddecls)
9954 skip-pins))
9955 (vl-dir "inout"))
9956 (when sig-list
9957 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9958 (verilog-insert-indent "// Inouts\n")
9959 (mapc (lambda (port)
9960 (verilog-auto-inst-port port indent-pt
9961 tpl-list tpl-num for-star par-values))
9962 sig-list)))
9963 (let ((sig-list (verilog-signals-not-in
9964 (verilog-decls-get-inputs submoddecls)
9965 skip-pins))
9966 (vl-dir "input"))
9967 (when sig-list
9968 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9969 (verilog-insert-indent "// Inputs\n")
9970 (mapc (lambda (port)
9971 (verilog-auto-inst-port port indent-pt
9972 tpl-list tpl-num for-star par-values))
9973 sig-list)))
9974 ;; Kill extra semi
9975 (save-excursion
9976 (cond (did-first
9977 (re-search-backward "," pt t)
9978 (delete-char 1)
9979 (insert ");")
9980 (search-forward "\n") ;; Added by inst-port
9981 (delete-char -1)
9982 (if (search-forward ")" nil t) ;; From user, moved up a line
9983 (delete-char -1))
9984 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
9985 (delete-char -1)))))))))
9986
9987 (defun verilog-auto-inst-param ()
9988 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
9989 Replace the parameter connections to an instantiation with ones
9990 automatically derived from the module header of the instantiated netlist.
9991
9992 See \\[verilog-auto-inst] for limitations, and templates to customize the
9993 output.
9994
9995 For example, first take the submodule InstModule.v:
9996
9997 module InstModule (o,i);
9998 parameter PAR;
9999 endmodule
10000
10001 This is then used in a upper level module:
10002
10003 module ExampInst (o,i);
10004 parameter PAR;
10005 InstModule #(/*AUTOINSTPARAM*/)
10006 instName (/*AUTOINST*/);
10007 endmodule
10008
10009 Typing \\[verilog-auto] will make this into:
10010
10011 module ExampInst (o,i);
10012 output o;
10013 input i;
10014 InstModule #(/*AUTOINSTPARAM*/
10015 // Parameters
10016 .PAR (PAR));
10017 instName (/*AUTOINST*/);
10018 endmodule
10019
10020 Where the list of parameter connections come from the inst module.
10021 \f
10022 Templates:
10023
10024 You can customize the parameter connections using AUTO_TEMPLATEs,
10025 just as you would with \\[verilog-auto-inst]."
10026 (save-excursion
10027 ;; Find beginning
10028 (let* ((pt (point))
10029 (indent-pt (save-excursion (verilog-backward-open-paren)
10030 (1+ (current-column))))
10031 (verilog-auto-inst-column (max verilog-auto-inst-column
10032 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
10033 (modi (verilog-modi-current))
10034 (moddecls (verilog-modi-get-decls modi))
10035 (vector-skip-list (unless verilog-auto-inst-vector
10036 (verilog-decls-get-signals moddecls)))
10037 submod submodi submoddecls
10038 inst skip-pins tpl-list tpl-num did-first)
10039 ;; Find module name that is instantiated
10040 (setq submod (save-excursion
10041 ;; Get to the point where AUTOINST normally is to read the module
10042 (verilog-re-search-forward-quick "[(;]" nil nil)
10043 (verilog-read-inst-module))
10044 inst (save-excursion
10045 ;; Get to the point where AUTOINST normally is to read the module
10046 (verilog-re-search-forward-quick "[(;]" nil nil)
10047 (verilog-read-inst-name))
10048 vl-cell-type submod
10049 vl-cell-name inst
10050 skip-pins (aref (verilog-read-inst-pins) 0))
10051
10052 ;; Parse any AUTO_LISP() before here
10053 (verilog-read-auto-lisp (point-min) pt)
10054
10055 ;; Lookup position, etc of submodule
10056 ;; Note this may raise an error
10057 (when (setq submodi (verilog-modi-lookup submod t))
10058 (setq submoddecls (verilog-modi-get-decls submodi))
10059 ;; If there's a number in the instantiation, it may be a argument to the
10060 ;; automatic variable instantiation program.
10061 (let* ((tpl-info (verilog-read-auto-template submod))
10062 (tpl-regexp (aref tpl-info 0)))
10063 (setq tpl-num (if (string-match tpl-regexp inst)
10064 (match-string 1 inst)
10065 "")
10066 tpl-list (aref tpl-info 1)))
10067 ;; Find submodule's signals and dump
10068 (let ((sig-list (verilog-signals-not-in
10069 (verilog-decls-get-gparams submoddecls)
10070 skip-pins))
10071 (vl-dir "parameter"))
10072 (when sig-list
10073 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
10074 ;; Note these are searched for in verilog-read-sub-decls.
10075 (verilog-insert-indent "// Parameters\n")
10076 (mapc (lambda (port)
10077 (verilog-auto-inst-port port indent-pt
10078 tpl-list tpl-num nil nil))
10079 sig-list)))
10080 ;; Kill extra semi
10081 (save-excursion
10082 (cond (did-first
10083 (re-search-backward "," pt t)
10084 (delete-char 1)
10085 (insert ")")
10086 (search-forward "\n") ;; Added by inst-port
10087 (delete-char -1)
10088 (if (search-forward ")" nil t) ;; From user, moved up a line
10089 (delete-char -1)))))))))
10090
10091 (defun verilog-auto-reg ()
10092 "Expand AUTOREG statements, as part of \\[verilog-auto].
10093 Make reg statements for any output that isn't already declared,
10094 and isn't a wire output from a block.
10095
10096 Limitations:
10097 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10098
10099 This does NOT work on memories, declare those yourself.
10100
10101 An example:
10102
10103 module ExampReg (o,i);
10104 output o;
10105 input i;
10106 /*AUTOREG*/
10107 always o = i;
10108 endmodule
10109
10110 Typing \\[verilog-auto] will make this into:
10111
10112 module ExampReg (o,i);
10113 output o;
10114 input i;
10115 /*AUTOREG*/
10116 // Beginning of automatic regs (for this module's undeclared outputs)
10117 reg o;
10118 // End of automatics
10119 always o = i;
10120 endmodule"
10121 (save-excursion
10122 ;; Point must be at insertion point.
10123 (let* ((indent-pt (current-indentation))
10124 (modi (verilog-modi-current))
10125 (moddecls (verilog-modi-get-decls modi))
10126 (modsubdecls (verilog-modi-get-sub-decls modi))
10127 (sig-list (verilog-signals-not-in
10128 (verilog-decls-get-outputs moddecls)
10129 (append (verilog-decls-get-wires moddecls)
10130 (verilog-decls-get-regs moddecls)
10131 (verilog-decls-get-assigns moddecls)
10132 (verilog-decls-get-consts moddecls)
10133 (verilog-decls-get-gparams moddecls)
10134 (verilog-subdecls-get-interfaced modsubdecls)
10135 (verilog-subdecls-get-outputs modsubdecls)
10136 (verilog-subdecls-get-inouts modsubdecls)))))
10137 (forward-line 1)
10138 (when sig-list
10139 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
10140 (verilog-insert-definition sig-list "reg" indent-pt nil)
10141 (verilog-modi-cache-add-regs modi sig-list)
10142 (verilog-insert-indent "// End of automatics\n")))))
10143
10144 (defun verilog-auto-reg-input ()
10145 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
10146 Make reg statements instantiation inputs that aren't already declared.
10147 This is useful for making a top level shell for testing the module that is
10148 to be instantiated.
10149
10150 Limitations:
10151 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
10152
10153 This does NOT work on memories, declare those yourself.
10154
10155 An example (see `verilog-auto-inst' for what else is going on here):
10156
10157 module ExampRegInput (o,i);
10158 output o;
10159 input i;
10160 /*AUTOREGINPUT*/
10161 InstModule instName
10162 (/*AUTOINST*/);
10163 endmodule
10164
10165 Typing \\[verilog-auto] will make this into:
10166
10167 module ExampRegInput (o,i);
10168 output o;
10169 input i;
10170 /*AUTOREGINPUT*/
10171 // Beginning of automatic reg inputs (for undeclared ...
10172 reg [31:0] iv; // From inst of inst.v
10173 // End of automatics
10174 InstModule instName
10175 (/*AUTOINST*/
10176 // Outputs
10177 .o (o[31:0]),
10178 // Inputs
10179 .iv (iv));
10180 endmodule"
10181 (save-excursion
10182 ;; Point must be at insertion point.
10183 (let* ((indent-pt (current-indentation))
10184 (modi (verilog-modi-current))
10185 (moddecls (verilog-modi-get-decls modi))
10186 (modsubdecls (verilog-modi-get-sub-decls modi))
10187 (sig-list (verilog-signals-combine-bus
10188 (verilog-signals-not-in
10189 (append (verilog-subdecls-get-inputs modsubdecls)
10190 (verilog-subdecls-get-inouts modsubdecls))
10191 (verilog-decls-get-signals moddecls)))))
10192 (forward-line 1)
10193 (when sig-list
10194 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
10195 (verilog-insert-definition sig-list "reg" indent-pt nil)
10196 (verilog-modi-cache-add-regs modi sig-list)
10197 (verilog-insert-indent "// End of automatics\n")))))
10198
10199 (defun verilog-auto-wire ()
10200 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
10201 Make wire statements for instantiations outputs that aren't
10202 already declared.
10203
10204 Limitations:
10205 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
10206 and all busses must have widths, such as those from AUTOINST, or using []
10207 in AUTO_TEMPLATEs.
10208
10209 This does NOT work on memories or SystemVerilog .name connections,
10210 declare those yourself.
10211
10212 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
10213 determine how to bus together. This occurs when you have ports with
10214 non-numeric or non-sequential bus subscripts. If Verilog mode
10215 mis-guessed, you'll have to declare them yourself.
10216
10217 An example (see `verilog-auto-inst' for what else is going on here):
10218
10219 module ExampWire (o,i);
10220 output o;
10221 input i;
10222 /*AUTOWIRE*/
10223 InstModule instName
10224 (/*AUTOINST*/);
10225 endmodule
10226
10227 Typing \\[verilog-auto] will make this into:
10228
10229 module ExampWire (o,i);
10230 output o;
10231 input i;
10232 /*AUTOWIRE*/
10233 // Beginning of automatic wires
10234 wire [31:0] ov; // From inst of inst.v
10235 // End of automatics
10236 InstModule instName
10237 (/*AUTOINST*/
10238 // Outputs
10239 .ov (ov[31:0]),
10240 // Inputs
10241 .i (i));
10242 wire o = | ov;
10243 endmodule"
10244 (save-excursion
10245 ;; Point must be at insertion point.
10246 (let* ((indent-pt (current-indentation))
10247 (modi (verilog-modi-current))
10248 (moddecls (verilog-modi-get-decls modi))
10249 (modsubdecls (verilog-modi-get-sub-decls modi))
10250 (sig-list (verilog-signals-combine-bus
10251 (verilog-signals-not-in
10252 (append (verilog-subdecls-get-outputs modsubdecls)
10253 (verilog-subdecls-get-inouts modsubdecls))
10254 (verilog-decls-get-signals moddecls)))))
10255 (forward-line 1)
10256 (when sig-list
10257 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
10258 (verilog-insert-definition sig-list "wire" indent-pt nil)
10259 (verilog-modi-cache-add-wires modi sig-list)
10260 (verilog-insert-indent "// End of automatics\n")
10261 (when nil ;; Too slow on huge modules, plus makes everyone's module change
10262 (beginning-of-line)
10263 (setq pnt (point))
10264 (verilog-pretty-declarations quiet)
10265 (goto-char pnt)
10266 (verilog-pretty-expr t "//"))))))
10267
10268 (defun verilog-auto-output (&optional with-params)
10269 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
10270 Make output statements for any output signal from an /*AUTOINST*/ that
10271 isn't a input to another AUTOINST. This is useful for modules which
10272 only instantiate other modules.
10273
10274 Limitations:
10275 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10276
10277 If placed inside the parenthesis of a module declaration, it creates
10278 Verilog 2001 style, else uses Verilog 1995 style.
10279
10280 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10281 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10282
10283 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10284
10285 Signals matching `verilog-auto-output-ignore-regexp' are not included.
10286
10287 An example (see `verilog-auto-inst' for what else is going on here):
10288
10289 module ExampOutput (ov,i);
10290 input i;
10291 /*AUTOOUTPUT*/
10292 InstModule instName
10293 (/*AUTOINST*/);
10294 endmodule
10295
10296 Typing \\[verilog-auto] will make this into:
10297
10298 module ExampOutput (ov,i);
10299 input i;
10300 /*AUTOOUTPUT*/
10301 // Beginning of automatic outputs (from unused autoinst outputs)
10302 output [31:0] ov; // From inst of inst.v
10303 // End of automatics
10304 InstModule instName
10305 (/*AUTOINST*/
10306 // Outputs
10307 .ov (ov[31:0]),
10308 // Inputs
10309 .i (i));
10310 endmodule
10311
10312 You may also provide an optional regular expression, in which case only
10313 signals matching the regular expression will be included. For example the
10314 same expansion will result from only extracting outputs starting with ov:
10315
10316 /*AUTOOUTPUT(\"^ov\")*/"
10317 (save-excursion
10318 ;; Point must be at insertion point.
10319 (let* ((indent-pt (current-indentation))
10320 (regexp (and with-params
10321 (nth 0 (verilog-read-auto-params 1))))
10322 (v2k (verilog-in-paren))
10323 (modi (verilog-modi-current))
10324 (moddecls (verilog-modi-get-decls modi))
10325 (modsubdecls (verilog-modi-get-sub-decls modi))
10326 (sig-list (verilog-signals-not-in
10327 (verilog-subdecls-get-outputs modsubdecls)
10328 (append (verilog-decls-get-outputs moddecls)
10329 (verilog-decls-get-inouts moddecls)
10330 (verilog-subdecls-get-inputs modsubdecls)
10331 (verilog-subdecls-get-inouts modsubdecls)))))
10332 (when regexp
10333 (setq sig-list (verilog-signals-matching-regexp
10334 sig-list regexp)))
10335 (setq sig-list (verilog-signals-not-matching-regexp
10336 sig-list verilog-auto-output-ignore-regexp))
10337 (forward-line 1)
10338 (when v2k (verilog-repair-open-comma))
10339 (when sig-list
10340 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
10341 (verilog-insert-definition sig-list "output" indent-pt v2k)
10342 (verilog-modi-cache-add-outputs modi sig-list)
10343 (verilog-insert-indent "// End of automatics\n"))
10344 (when v2k (verilog-repair-close-comma)))))
10345
10346 (defun verilog-auto-output-every ()
10347 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
10348 Make output statements for any signals that aren't primary inputs or
10349 outputs already. This makes every signal in the design a output. This is
10350 useful to get Synopsys to preserve every signal in the design, since it
10351 won't optimize away the outputs.
10352
10353 An example:
10354
10355 module ExampOutputEvery (o,i,tempa,tempb);
10356 output o;
10357 input i;
10358 /*AUTOOUTPUTEVERY*/
10359 wire tempa = i;
10360 wire tempb = tempa;
10361 wire o = tempb;
10362 endmodule
10363
10364 Typing \\[verilog-auto] will make this into:
10365
10366 module ExampOutputEvery (o,i,tempa,tempb);
10367 output o;
10368 input i;
10369 /*AUTOOUTPUTEVERY*/
10370 // Beginning of automatic outputs (every signal)
10371 output tempb;
10372 output tempa;
10373 // End of automatics
10374 wire tempa = i;
10375 wire tempb = tempa;
10376 wire o = tempb;
10377 endmodule"
10378 (save-excursion
10379 ;;Point must be at insertion point
10380 (let* ((indent-pt (current-indentation))
10381 (v2k (verilog-in-paren))
10382 (modi (verilog-modi-current))
10383 (moddecls (verilog-modi-get-decls modi))
10384 (sig-list (verilog-signals-combine-bus
10385 (verilog-signals-not-in
10386 (verilog-decls-get-signals moddecls)
10387 (verilog-decls-get-ports moddecls)))))
10388 (forward-line 1)
10389 (when v2k (verilog-repair-open-comma))
10390 (when sig-list
10391 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
10392 (verilog-insert-definition sig-list "output" indent-pt v2k)
10393 (verilog-modi-cache-add-outputs modi sig-list)
10394 (verilog-insert-indent "// End of automatics\n"))
10395 (when v2k (verilog-repair-close-comma)))))
10396
10397 (defun verilog-auto-input (&optional with-params)
10398 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
10399 Make input statements for any input signal into an /*AUTOINST*/ that
10400 isn't declared elsewhere inside the module. This is useful for modules which
10401 only instantiate other modules.
10402
10403 Limitations:
10404 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10405
10406 If placed inside the parenthesis of a module declaration, it creates
10407 Verilog 2001 style, else uses Verilog 1995 style.
10408
10409 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10410 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10411
10412 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10413
10414 Signals matching `verilog-auto-input-ignore-regexp' are not included.
10415
10416 An example (see `verilog-auto-inst' for what else is going on here):
10417
10418 module ExampInput (ov,i);
10419 output [31:0] ov;
10420 /*AUTOINPUT*/
10421 InstModule instName
10422 (/*AUTOINST*/);
10423 endmodule
10424
10425 Typing \\[verilog-auto] will make this into:
10426
10427 module ExampInput (ov,i);
10428 output [31:0] ov;
10429 /*AUTOINPUT*/
10430 // Beginning of automatic inputs (from unused autoinst inputs)
10431 input i; // From inst of inst.v
10432 // End of automatics
10433 InstModule instName
10434 (/*AUTOINST*/
10435 // Outputs
10436 .ov (ov[31:0]),
10437 // Inputs
10438 .i (i));
10439 endmodule
10440
10441 You may also provide an optional regular expression, in which case only
10442 signals matching the regular expression will be included. For example the
10443 same expansion will result from only extracting inputs starting with i:
10444
10445 /*AUTOINPUT(\"^i\")*/"
10446 (save-excursion
10447 (let* ((indent-pt (current-indentation))
10448 (regexp (and with-params
10449 (nth 0 (verilog-read-auto-params 1))))
10450 (v2k (verilog-in-paren))
10451 (modi (verilog-modi-current))
10452 (moddecls (verilog-modi-get-decls modi))
10453 (modsubdecls (verilog-modi-get-sub-decls modi))
10454 (sig-list (verilog-signals-not-in
10455 (verilog-subdecls-get-inputs modsubdecls)
10456 (append (verilog-decls-get-inputs moddecls)
10457 (verilog-decls-get-inouts moddecls)
10458 (verilog-decls-get-wires moddecls)
10459 (verilog-decls-get-regs moddecls)
10460 (verilog-decls-get-consts moddecls)
10461 (verilog-decls-get-gparams moddecls)
10462 (verilog-subdecls-get-interfaced modsubdecls)
10463 (verilog-subdecls-get-outputs modsubdecls)
10464 (verilog-subdecls-get-inouts modsubdecls)))))
10465 (when regexp
10466 (setq sig-list (verilog-signals-matching-regexp
10467 sig-list regexp)))
10468 (setq sig-list (verilog-signals-not-matching-regexp
10469 sig-list verilog-auto-input-ignore-regexp))
10470 (forward-line 1)
10471 (when v2k (verilog-repair-open-comma))
10472 (when sig-list
10473 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
10474 (verilog-insert-definition sig-list "input" indent-pt v2k)
10475 (verilog-modi-cache-add-inputs modi sig-list)
10476 (verilog-insert-indent "// End of automatics\n"))
10477 (when v2k (verilog-repair-close-comma)))))
10478
10479 (defun verilog-auto-inout (&optional with-params)
10480 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
10481 Make inout statements for any inout signal in an /*AUTOINST*/ that
10482 isn't declared elsewhere inside the module.
10483
10484 Limitations:
10485 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10486
10487 If placed inside the parenthesis of a module declaration, it creates
10488 Verilog 2001 style, else uses Verilog 1995 style.
10489
10490 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10491 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10492
10493 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10494
10495 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
10496
10497 An example (see `verilog-auto-inst' for what else is going on here):
10498
10499 module ExampInout (ov,i);
10500 input i;
10501 /*AUTOINOUT*/
10502 InstModule instName
10503 (/*AUTOINST*/);
10504 endmodule
10505
10506 Typing \\[verilog-auto] will make this into:
10507
10508 module ExampInout (ov,i);
10509 input i;
10510 /*AUTOINOUT*/
10511 // Beginning of automatic inouts (from unused autoinst inouts)
10512 inout [31:0] ov; // From inst of inst.v
10513 // End of automatics
10514 InstModule instName
10515 (/*AUTOINST*/
10516 // Inouts
10517 .ov (ov[31:0]),
10518 // Inputs
10519 .i (i));
10520 endmodule
10521
10522 You may also provide an optional regular expression, in which case only
10523 signals matching the regular expression will be included. For example the
10524 same expansion will result from only extracting inouts starting with i:
10525
10526 /*AUTOINOUT(\"^i\")*/"
10527 (save-excursion
10528 ;; Point must be at insertion point.
10529 (let* ((indent-pt (current-indentation))
10530 (regexp (and with-params
10531 (nth 0 (verilog-read-auto-params 1))))
10532 (v2k (verilog-in-paren))
10533 (modi (verilog-modi-current))
10534 (moddecls (verilog-modi-get-decls modi))
10535 (modsubdecls (verilog-modi-get-sub-decls modi))
10536 (sig-list (verilog-signals-not-in
10537 (verilog-subdecls-get-inouts modsubdecls)
10538 (append (verilog-decls-get-outputs moddecls)
10539 (verilog-decls-get-inouts moddecls)
10540 (verilog-decls-get-inputs moddecls)
10541 (verilog-subdecls-get-inputs modsubdecls)
10542 (verilog-subdecls-get-outputs modsubdecls)))))
10543 (when regexp
10544 (setq sig-list (verilog-signals-matching-regexp
10545 sig-list regexp)))
10546 (setq sig-list (verilog-signals-not-matching-regexp
10547 sig-list verilog-auto-inout-ignore-regexp))
10548 (forward-line 1)
10549 (when v2k (verilog-repair-open-comma))
10550 (when sig-list
10551 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
10552 (verilog-insert-definition sig-list "inout" indent-pt v2k)
10553 (verilog-modi-cache-add-inouts modi sig-list)
10554 (verilog-insert-indent "// End of automatics\n"))
10555 (when v2k (verilog-repair-close-comma)))))
10556
10557 (defun verilog-auto-inout-module (&optional complement)
10558 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
10559 Take input/output/inout statements from the specified module and insert
10560 into the current module. This is useful for making null templates and
10561 shell modules which need to have identical I/O with another module.
10562 Any I/O which are already defined in this module will not be redefined.
10563 For the complement of this function, see `verilog-auto-inout-comp'.
10564
10565 Limitations:
10566 If placed inside the parenthesis of a module declaration, it creates
10567 Verilog 2001 style, else uses Verilog 1995 style.
10568
10569 Concatenation and outputting partial busses is not supported.
10570
10571 Module names must be resolvable to filenames. See `verilog-auto-inst'.
10572
10573 Signals are not inserted in the same order as in the original module,
10574 though they will appear to be in the same order to a AUTOINST
10575 instantiating either module.
10576
10577 An example:
10578
10579 module ExampShell (/*AUTOARG*/);
10580 /*AUTOINOUTMODULE(\"ExampMain\")*/
10581 endmodule
10582
10583 module ExampMain (i,o,io);
10584 input i;
10585 output o;
10586 inout io;
10587 endmodule
10588
10589 Typing \\[verilog-auto] will make this into:
10590
10591 module ExampShell (/*AUTOARG*/i,o,io);
10592 /*AUTOINOUTMODULE(\"ExampMain\")*/
10593 // Beginning of automatic in/out/inouts (from specific module)
10594 output o;
10595 inout io;
10596 input i;
10597 // End of automatics
10598 endmodule
10599
10600 You may also provide an optional regular expression, in which case only
10601 signals matching the regular expression will be included. For example the
10602 same expansion will result from only extracting signals starting with i:
10603
10604 /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/
10605
10606 You may also provide an optional second regular expression, in
10607 which case only signals which have that pin direction and data
10608 type will be included. This matches against everything before
10609 the signal name in the declaration, for example against
10610 \"input\" (single bit), \"output logic\" (direction and type) or
10611 \"output [1:0]\" (direction and implicit type). You also
10612 probably want to skip spaces in your regexp.
10613
10614 For example, the below will result in matching the output \"o\"
10615 against the previous example's module:
10616
10617 /*AUTOINOUTMODULE(\"ExampMain\",\"\",\"^output.*\")*/"
10618 (save-excursion
10619 (let* ((params (verilog-read-auto-params 1 3))
10620 (submod (nth 0 params))
10621 (regexp (nth 1 params))
10622 (direction-re (nth 2 params))
10623 submodi)
10624 ;; Lookup position, etc of co-module
10625 ;; Note this may raise an error
10626 (when (setq submodi (verilog-modi-lookup submod t))
10627 (let* ((indent-pt (current-indentation))
10628 (v2k (verilog-in-paren))
10629 (modi (verilog-modi-current))
10630 (moddecls (verilog-modi-get-decls modi))
10631 (submoddecls (verilog-modi-get-decls submodi))
10632 (sig-list-i (verilog-signals-not-in
10633 (if complement
10634 (verilog-decls-get-outputs submoddecls)
10635 (verilog-decls-get-inputs submoddecls))
10636 (append (verilog-decls-get-inputs moddecls))))
10637 (sig-list-o (verilog-signals-not-in
10638 (if complement
10639 (verilog-decls-get-inputs submoddecls)
10640 (verilog-decls-get-outputs submoddecls))
10641 (append (verilog-decls-get-outputs moddecls))))
10642 (sig-list-io (verilog-signals-not-in
10643 (verilog-decls-get-inouts submoddecls)
10644 (append (verilog-decls-get-inouts moddecls))))
10645 (sig-list-if (verilog-signals-not-in
10646 (verilog-decls-get-interfaces submoddecls)
10647 (append (verilog-decls-get-interfaces moddecls)))))
10648 (forward-line 1)
10649 (setq sig-list-i (verilog-signals-matching-dir-re
10650 (verilog-signals-matching-regexp sig-list-i regexp)
10651 "input" direction-re)
10652 sig-list-o (verilog-signals-matching-dir-re
10653 (verilog-signals-matching-regexp sig-list-o regexp)
10654 "output" direction-re)
10655 sig-list-io (verilog-signals-matching-dir-re
10656 (verilog-signals-matching-regexp sig-list-io regexp)
10657 "inout" direction-re)
10658 sig-list-if (verilog-signals-matching-dir-re
10659 (verilog-signals-matching-regexp sig-list-if regexp)
10660 "interface" direction-re))
10661 (when v2k (verilog-repair-open-comma))
10662 (when (or sig-list-i sig-list-o sig-list-io)
10663 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
10664 ;; Don't sort them so a upper AUTOINST will match the main module
10665 (verilog-insert-definition sig-list-o "output" indent-pt v2k t)
10666 (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
10667 (verilog-insert-definition sig-list-i "input" indent-pt v2k t)
10668 (verilog-insert-definition sig-list-if "interface" indent-pt v2k t)
10669 (verilog-modi-cache-add-inputs modi sig-list-i)
10670 (verilog-modi-cache-add-outputs modi sig-list-o)
10671 (verilog-modi-cache-add-inouts modi sig-list-io)
10672 (verilog-insert-indent "// End of automatics\n"))
10673 (when v2k (verilog-repair-close-comma)))))))
10674
10675 (defun verilog-auto-inout-comp ()
10676 "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
10677 Take input/output/inout statements from the specified module and
10678 insert the inverse into the current module (inputs become outputs
10679 and vice-versa.) This is useful for making test and stimulus
10680 modules which need to have complementing I/O with another module.
10681 Any I/O which are already defined in this module will not be
10682 redefined. For the complement of this function, see
10683 `verilog-auto-inout-module'.
10684
10685 Limitations:
10686 If placed inside the parenthesis of a module declaration, it creates
10687 Verilog 2001 style, else uses Verilog 1995 style.
10688
10689 Concatenation and outputting partial busses is not supported.
10690
10691 Module names must be resolvable to filenames. See `verilog-auto-inst'.
10692
10693 Signals are not inserted in the same order as in the original module,
10694 though they will appear to be in the same order to a AUTOINST
10695 instantiating either module.
10696
10697 An example:
10698
10699 module ExampShell (/*AUTOARG*/);
10700 /*AUTOINOUTCOMP(\"ExampMain\")*/
10701 endmodule
10702
10703 module ExampMain (i,o,io);
10704 input i;
10705 output o;
10706 inout io;
10707 endmodule
10708
10709 Typing \\[verilog-auto] will make this into:
10710
10711 module ExampShell (/*AUTOARG*/i,o,io);
10712 /*AUTOINOUTCOMP(\"ExampMain\")*/
10713 // Beginning of automatic in/out/inouts (from specific module)
10714 output i;
10715 inout io;
10716 input o;
10717 // End of automatics
10718 endmodule
10719
10720 You may also provide an optional regular expression, in which case only
10721 signals matching the regular expression will be included. For example the
10722 same expansion will result from only extracting signals starting with i:
10723
10724 /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/"
10725 (verilog-auto-inout-module t))
10726
10727 (defun verilog-auto-insert-lisp ()
10728 "Expand AUTOINSERTLISP statements, as part of \\[verilog-auto].
10729 The Lisp code provided is called, and the Lisp code calls
10730 `insert` to insert text into the current file beginning on the
10731 line after the AUTOINSERTLISP.
10732
10733 See also AUTO_LISP, which takes a Lisp expression and evaluates
10734 it during `verilog-auto-inst' but does not insert any text.
10735
10736 An example:
10737
10738 module ExampInsertLisp;
10739 /*AUTOINSERTLISP(my-verilog-insert-hello \"world\")*/
10740 endmodule
10741
10742 // For this example we declare the function in the
10743 // module's file itself. Often you'd define it instead
10744 // in a site-start.el or .emacs file.
10745 /*
10746 Local Variables:
10747 eval:
10748 (defun my-verilog-insert-hello (who)
10749 (insert (concat \"initial $write(\\\"hello \" who \"\\\");\\n\")))
10750 End:
10751 */
10752
10753 Typing \\[verilog-auto] will call my-verilog-insert-hello and
10754 expand the above into:
10755
10756 // Beginning of automatic insert lisp
10757 initial $write(\"hello world\");
10758 // End of automatics
10759
10760 You can also call an external program and insert the returned
10761 text:
10762
10763 /*AUTOINSERTLISP(insert (shell-command-to-string \"echo //hello\"))*/
10764 // Beginning of automatic insert lisp
10765 //hello
10766 // End of automatics"
10767 (save-excursion
10768 ;; Point is at end of /*AUTO...*/
10769 (let* ((indent-pt (current-indentation))
10770 (cmd-end-pt (save-excursion (search-backward ")")
10771 (forward-char)
10772 (point))) ;; Closing paren
10773 (cmd-beg-pt (save-excursion (goto-char cmd-end-pt)
10774 (backward-sexp 1)
10775 (point))) ;; Beginning paren
10776 (cmd (buffer-substring-no-properties cmd-beg-pt cmd-end-pt)))
10777 (forward-line 1)
10778 ;; Some commands don't move point (like insert-file) so we always
10779 ;; add the begin/end comments, then delete it if not needed
10780 (verilog-insert-indent "// Beginning of automatic insert lisp\n")
10781 (verilog-insert-indent "// End of automatics\n")
10782 (forward-line -1)
10783 (eval (read cmd))
10784 (forward-line -1)
10785 (setq verilog-scan-cache-tick nil) ;; Clear cache; inserted unknown text
10786 (verilog-delete-empty-auto-pair))))
10787
10788 (defun verilog-auto-sense-sigs (moddecls presense-sigs)
10789 "Return list of signals for current AUTOSENSE block."
10790 (let* ((sigss (verilog-read-always-signals))
10791 (sig-list (verilog-signals-not-params
10792 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
10793 (append (and (not verilog-auto-sense-include-inputs)
10794 (verilog-alw-get-outputs sigss))
10795 (verilog-alw-get-temps sigss)
10796 (verilog-decls-get-consts moddecls)
10797 (verilog-decls-get-gparams moddecls)
10798 presense-sigs)))))
10799 sig-list))
10800
10801 (defun verilog-auto-sense ()
10802 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
10803 Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
10804 with one automatically derived from all inputs declared in the always
10805 statement. Signals that are generated within the same always block are NOT
10806 placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
10807 Long lines are split based on the `fill-column', see \\[set-fill-column].
10808
10809 Limitations:
10810 Verilog does not allow memories (multidimensional arrays) in sensitivity
10811 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
10812
10813 Constant signals:
10814 AUTOSENSE cannot always determine if a `define is a constant or a signal
10815 (it could be in a include file for example). If a `define or other signal
10816 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
10817 declaration anywhere in the module (parenthesis are required):
10818
10819 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
10820
10821 Better yet, use a parameter, which will be understood to be constant
10822 automatically.
10823
10824 OOps!
10825 If AUTOSENSE makes a mistake, please report it. (First try putting
10826 a begin/end after your always!) As a workaround, if a signal that
10827 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
10828 If a signal should be in the sensitivity list wasn't, placing it before
10829 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
10830 autos are updated (or added if it occurs there already).
10831
10832 An example:
10833
10834 always @ (/*AS*/) begin
10835 /* AUTO_CONSTANT (`constant) */
10836 outin = ina | inb | `constant;
10837 out = outin;
10838 end
10839
10840 Typing \\[verilog-auto] will make this into:
10841
10842 always @ (/*AS*/ina or inb) begin
10843 /* AUTO_CONSTANT (`constant) */
10844 outin = ina | inb | `constant;
10845 out = outin;
10846 end
10847
10848 Note in Verilog 2001, you can often get the same result from the new @*
10849 operator. (This was added to the language in part due to AUTOSENSE!)
10850
10851 always @* begin
10852 outin = ina | inb | `constant;
10853 out = outin;
10854 end"
10855 (save-excursion
10856 ;; Find beginning
10857 (let* ((start-pt (save-excursion
10858 (verilog-re-search-backward "(" nil t)
10859 (point)))
10860 (indent-pt (save-excursion
10861 (or (and (goto-char start-pt) (1+ (current-column)))
10862 (current-indentation))))
10863 (modi (verilog-modi-current))
10864 (moddecls (verilog-modi-get-decls modi))
10865 (sig-memories (verilog-signals-memory
10866 (append
10867 (verilog-decls-get-regs moddecls)
10868 (verilog-decls-get-wires moddecls))))
10869 sig-list not-first presense-sigs)
10870 ;; Read signals in always, eliminate outputs from sense list
10871 (setq presense-sigs (verilog-signals-from-signame
10872 (save-excursion
10873 (verilog-read-signals start-pt (point)))))
10874 (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
10875 (when sig-memories
10876 (let ((tlen (length sig-list)))
10877 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
10878 (if (not (eq tlen (length sig-list))) (verilog-insert " /*memory or*/ "))))
10879 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
10880 (save-excursion (goto-char (point))
10881 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10882 (verilog-re-search-backward "\\s-" start-pt t)
10883 (while (looking-at "\\s-`endif")
10884 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10885 (verilog-re-search-backward "\\s-" start-pt t))
10886 (not (looking-at "\\s-or\\b"))))
10887 (setq not-first t))
10888 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10889 (while sig-list
10890 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
10891 (insert "\n")
10892 (indent-to indent-pt)
10893 (if not-first (insert "or ")))
10894 (not-first (insert " or ")))
10895 (insert (verilog-sig-name (car sig-list)))
10896 (setq sig-list (cdr sig-list)
10897 not-first t)))))
10898
10899 (defun verilog-auto-reset ()
10900 "Expand AUTORESET statements, as part of \\[verilog-auto].
10901 Replace the /*AUTORESET*/ comment with code to initialize all
10902 registers set elsewhere in the always block.
10903
10904 Limitations:
10905 AUTORESET will not clear memories.
10906
10907 AUTORESET uses <= if there are any <= assignments in the block,
10908 else it uses =.
10909
10910 /*AUTORESET*/ presumes that any signals mentioned between the previous
10911 begin/case/if statement and the AUTORESET comment are being reset manually
10912 and should not be automatically reset. This includes omitting any signals
10913 used on the right hand side of assignments.
10914
10915 By default, AUTORESET will include the width of the signal in the autos,
10916 this is a recent change. To control this behavior, see
10917 `verilog-auto-reset-widths'.
10918
10919 AUTORESET ties signals to deasserted, which is presumed to be zero.
10920 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
10921 them to a one.
10922
10923 An example:
10924
10925 always @(posedge clk or negedge reset_l) begin
10926 if (!reset_l) begin
10927 c <= 1;
10928 /*AUTORESET*/
10929 end
10930 else begin
10931 a <= in_a;
10932 b <= in_b;
10933 c <= in_c;
10934 end
10935 end
10936
10937 Typing \\[verilog-auto] will make this into:
10938
10939 always @(posedge core_clk or negedge reset_l) begin
10940 if (!reset_l) begin
10941 c <= 1;
10942 /*AUTORESET*/
10943 // Beginning of autoreset for uninitialized flops
10944 a <= 0;
10945 b <= 0;
10946 // End of automatics
10947 end
10948 else begin
10949 a <= in_a;
10950 b <= in_b;
10951 c <= in_c;
10952 end
10953 end"
10954
10955 (interactive)
10956 (save-excursion
10957 ;; Find beginning
10958 (let* ((indent-pt (current-indentation))
10959 (modi (verilog-modi-current))
10960 (moddecls (verilog-modi-get-decls modi))
10961 (all-list (verilog-decls-get-signals moddecls))
10962 sigss sig-list prereset-sigs assignment-str)
10963 ;; Read signals in always, eliminate outputs from reset list
10964 (setq prereset-sigs (verilog-signals-from-signame
10965 (save-excursion
10966 (verilog-read-signals
10967 (save-excursion
10968 (verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
10969 (point))
10970 (point)))))
10971 (save-excursion
10972 (verilog-re-search-backward "@" nil t)
10973 (setq sigss (verilog-read-always-signals)))
10974 (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
10975 (concat " <= " verilog-assignment-delay)
10976 " = "))
10977 (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
10978 (append
10979 (verilog-alw-get-temps sigss)
10980 prereset-sigs)))
10981 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10982 (when sig-list
10983 (insert "\n");
10984 (verilog-insert-indent "// Beginning of autoreset for uninitialized flops\n");
10985 (indent-to indent-pt)
10986 (while sig-list
10987 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
10988 (car sig-list))))
10989 (insert (verilog-sig-name sig)
10990 assignment-str
10991 (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
10992 ";\n")
10993 (indent-to indent-pt)
10994 (setq sig-list (cdr sig-list))))
10995 (verilog-insert "// End of automatics")))))
10996
10997 (defun verilog-auto-tieoff ()
10998 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
10999 Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
11000 signals to deasserted.
11001
11002 /*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
11003 input/output list as another module, but no internals. Specifically, it
11004 finds all outputs in the module, and if that input is not otherwise declared
11005 as a register or wire, creates a tieoff.
11006
11007 AUTORESET ties signals to deasserted, which is presumed to be zero.
11008 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
11009 them to a one.
11010
11011 You can add signals you do not want included in AUTOTIEOFF with
11012 `verilog-auto-tieoff-ignore-regexp'.
11013
11014 An example of making a stub for another module:
11015
11016 module ExampStub (/*AUTOINST*/);
11017 /*AUTOINOUTMODULE(\"Foo\")*/
11018 /*AUTOTIEOFF*/
11019 // verilator lint_off UNUSED
11020 wire _unused_ok = &{1'b0,
11021 /*AUTOUNUSED*/
11022 1'b0};
11023 // verilator lint_on UNUSED
11024 endmodule
11025
11026 Typing \\[verilog-auto] will make this into:
11027
11028 module ExampStub (/*AUTOINST*/...);
11029 /*AUTOINOUTMODULE(\"Foo\")*/
11030 // Beginning of autotieoff
11031 output [2:0] foo;
11032 // End of automatics
11033
11034 /*AUTOTIEOFF*/
11035 // Beginning of autotieoff
11036 wire [2:0] foo = 3'b0;
11037 // End of automatics
11038 ...
11039 endmodule"
11040 (interactive)
11041 (save-excursion
11042 ;; Find beginning
11043 (let* ((indent-pt (current-indentation))
11044 (modi (verilog-modi-current))
11045 (moddecls (verilog-modi-get-decls modi))
11046 (modsubdecls (verilog-modi-get-sub-decls modi))
11047 (sig-list (verilog-signals-not-in
11048 (verilog-decls-get-outputs moddecls)
11049 (append (verilog-decls-get-wires moddecls)
11050 (verilog-decls-get-regs moddecls)
11051 (verilog-decls-get-assigns moddecls)
11052 (verilog-decls-get-consts moddecls)
11053 (verilog-decls-get-gparams moddecls)
11054 (verilog-subdecls-get-interfaced modsubdecls)
11055 (verilog-subdecls-get-outputs modsubdecls)
11056 (verilog-subdecls-get-inouts modsubdecls)))))
11057 (setq sig-list (verilog-signals-not-matching-regexp
11058 sig-list verilog-auto-tieoff-ignore-regexp))
11059 (when sig-list
11060 (forward-line 1)
11061 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
11062 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
11063 (verilog-modi-cache-add-wires modi sig-list) ; Before we trash list
11064 (while sig-list
11065 (let ((sig (car sig-list)))
11066 (verilog-insert-one-definition sig "wire" indent-pt)
11067 (indent-to (max 48 (+ indent-pt 40)))
11068 (insert "= " (verilog-sig-tieoff sig)
11069 ";\n")
11070 (setq sig-list (cdr sig-list))))
11071 (verilog-insert-indent "// End of automatics\n")))))
11072
11073 (defun verilog-auto-unused ()
11074 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
11075 Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
11076 input and inout signals.
11077
11078 /*AUTOUNUSED*/ is used to make stub modules; modules that have the same
11079 input/output list as another module, but no internals. Specifically, it
11080 finds all inputs and inouts in the module, and if that input is not otherwise
11081 used, adds it to a comma separated list.
11082
11083 The comma separated list is intended to be used to create a _unused_ok
11084 signal. Using the exact name \"_unused_ok\" for name of the temporary
11085 signal is recommended as it will insure maximum forward compatibility, it
11086 also makes lint warnings easy to understand; ignore any unused warnings
11087 with \"unused\" in the signal name.
11088
11089 To reduce simulation time, the _unused_ok signal should be forced to a
11090 constant to prevent wiggling. The easiest thing to do is use a
11091 reduction-and with 1'b0 as shown.
11092
11093 This way all unused signals are in one place, making it convenient to add
11094 your tool's specific pragmas around the assignment to disable any unused
11095 warnings.
11096
11097 You can add signals you do not want included in AUTOUNUSED with
11098 `verilog-auto-unused-ignore-regexp'.
11099
11100 An example of making a stub for another module:
11101
11102 module ExampStub (/*AUTOINST*/);
11103 /*AUTOINOUTMODULE(\"Examp\")*/
11104 /*AUTOTIEOFF*/
11105 // verilator lint_off UNUSED
11106 wire _unused_ok = &{1'b0,
11107 /*AUTOUNUSED*/
11108 1'b0};
11109 // verilator lint_on UNUSED
11110 endmodule
11111
11112 Typing \\[verilog-auto] will make this into:
11113
11114 ...
11115 // verilator lint_off UNUSED
11116 wire _unused_ok = &{1'b0,
11117 /*AUTOUNUSED*/
11118 // Beginning of automatics
11119 unused_input_a,
11120 unused_input_b,
11121 unused_input_c,
11122 // End of automatics
11123 1'b0};
11124 // verilator lint_on UNUSED
11125 endmodule"
11126 (interactive)
11127 (save-excursion
11128 ;; Find beginning
11129 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
11130 (modi (verilog-modi-current))
11131 (moddecls (verilog-modi-get-decls modi))
11132 (modsubdecls (verilog-modi-get-sub-decls modi))
11133 (sig-list (verilog-signals-not-in
11134 (append (verilog-decls-get-inputs moddecls)
11135 (verilog-decls-get-inouts moddecls))
11136 (append (verilog-subdecls-get-inputs modsubdecls)
11137 (verilog-subdecls-get-inouts modsubdecls)))))
11138 (setq sig-list (verilog-signals-not-matching-regexp
11139 sig-list verilog-auto-unused-ignore-regexp))
11140 (when sig-list
11141 (forward-line 1)
11142 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
11143 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
11144 (while sig-list
11145 (let ((sig (car sig-list)))
11146 (indent-to indent-pt)
11147 (insert (verilog-sig-name sig) ",\n")
11148 (setq sig-list (cdr sig-list))))
11149 (verilog-insert-indent "// End of automatics\n")))))
11150
11151 (defun verilog-enum-ascii (signm elim-regexp)
11152 "Convert an enum name SIGNM to an ascii string for insertion.
11153 Remove user provided prefix ELIM-REGEXP."
11154 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
11155 (let ((case-fold-search t))
11156 ;; All upper becomes all lower for readability
11157 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
11158
11159 (defun verilog-auto-ascii-enum ()
11160 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
11161 Create a register to contain the ASCII decode of a enumerated signal type.
11162 This will allow trace viewers to show the ASCII name of states.
11163
11164 First, parameters are built into a enumeration using the synopsys enum
11165 comment. The comment must be between the keyword and the symbol.
11166 \(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
11167
11168 Next, registers which that enum applies to are also tagged with the same
11169 enum. Synopsys also suggests labeling state vectors, but `verilog-mode'
11170 doesn't care.
11171
11172 Finally, a AUTOASCIIENUM command is used.
11173
11174 The first parameter is the name of the signal to be decoded.
11175 If and only if the first parameter width is 2^(number of states
11176 in enum) and does NOT match the width of the enum, the signal
11177 is assumed to be a one hot decode. Otherwise, it's a normal
11178 encoded state vector.
11179
11180 The second parameter is the name to store the ASCII code into. For the
11181 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
11182 a signal that is just for simulation, and the magic characters _ascii
11183 tell viewers like Dinotrace to display in ASCII format.
11184
11185 The final optional parameter is a string which will be removed from the
11186 state names.
11187
11188 An example:
11189
11190 //== State enumeration
11191 parameter [2:0] // synopsys enum state_info
11192 SM_IDLE = 3'b000,
11193 SM_SEND = 3'b001,
11194 SM_WAIT1 = 3'b010;
11195 //== State variables
11196 reg [2:0] /* synopsys enum state_info */
11197 state_r; /* synopsys state_vector state_r */
11198 reg [2:0] /* synopsys enum state_info */
11199 state_e1;
11200
11201 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
11202
11203 Typing \\[verilog-auto] will make this into:
11204
11205 ... same front matter ...
11206
11207 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
11208 // Beginning of automatic ASCII enum decoding
11209 reg [39:0] state_ascii_r; // Decode of state_r
11210 always @(state_r) begin
11211 case ({state_r})
11212 SM_IDLE: state_ascii_r = \"idle \";
11213 SM_SEND: state_ascii_r = \"send \";
11214 SM_WAIT1: state_ascii_r = \"wait1\";
11215 default: state_ascii_r = \"%Erro\";
11216 endcase
11217 end
11218 // End of automatics"
11219 (save-excursion
11220 (let* ((params (verilog-read-auto-params 2 3))
11221 (undecode-name (nth 0 params))
11222 (ascii-name (nth 1 params))
11223 (elim-regexp (nth 2 params))
11224 ;;
11225 (indent-pt (current-indentation))
11226 (modi (verilog-modi-current))
11227 (moddecls (verilog-modi-get-decls modi))
11228 ;;
11229 (sig-list-consts (append (verilog-decls-get-consts moddecls)
11230 (verilog-decls-get-gparams moddecls)))
11231 (sig-list-all (append (verilog-decls-get-regs moddecls)
11232 (verilog-decls-get-outputs moddecls)
11233 (verilog-decls-get-inouts moddecls)
11234 (verilog-decls-get-inputs moddecls)
11235 (verilog-decls-get-wires moddecls)))
11236 ;;
11237 (undecode-sig (or (assoc undecode-name sig-list-all)
11238 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
11239 (undecode-enum (or (verilog-sig-enum undecode-sig)
11240 (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
11241 ;;
11242 (enum-sigs (verilog-signals-not-in
11243 (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
11244 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum))
11245 nil))
11246 ;;
11247 (one-hot (and ;; width(enum) != width(sig)
11248 (or (not (verilog-sig-bits (car enum-sigs)))
11249 (not (equal (verilog-sig-width (car enum-sigs))
11250 (verilog-sig-width undecode-sig))))
11251 ;; count(enums) == width(sig)
11252 (equal (number-to-string (length enum-sigs))
11253 (verilog-sig-width undecode-sig))))
11254 (enum-chars 0)
11255 (ascii-chars 0))
11256 ;;
11257 ;; Find number of ascii chars needed
11258 (let ((tmp-sigs enum-sigs))
11259 (while tmp-sigs
11260 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
11261 ascii-chars (max ascii-chars (length (verilog-enum-ascii
11262 (verilog-sig-name (car tmp-sigs))
11263 elim-regexp)))
11264 tmp-sigs (cdr tmp-sigs))))
11265 ;;
11266 (forward-line 1)
11267 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
11268 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
11269 (concat "Decode of " undecode-name) nil nil))))
11270 (verilog-insert-definition decode-sig-list "reg" indent-pt nil)
11271 (verilog-modi-cache-add-regs modi decode-sig-list))
11272 ;;
11273 (verilog-insert-indent "always @(" undecode-name ") begin\n")
11274 (setq indent-pt (+ indent-pt verilog-indent-level))
11275 (indent-to indent-pt)
11276 (insert "case ({" undecode-name "})\n")
11277 (setq indent-pt (+ indent-pt verilog-case-indent))
11278 ;;
11279 (let ((tmp-sigs enum-sigs)
11280 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n"
11281 (+ (if one-hot 9 1) (max 8 enum-chars))
11282 ascii-name ascii-chars))
11283 (errname (substring "%Error" 0 (min 6 ascii-chars))))
11284 (while tmp-sigs
11285 (verilog-insert-indent
11286 (concat
11287 (format chrfmt
11288 (concat (if one-hot "(")
11289 (if one-hot (verilog-sig-width undecode-sig))
11290 ;; We use a shift instead of var[index]
11291 ;; so that a non-one hot value will show as error.
11292 (if one-hot "'b1<<")
11293 (verilog-sig-name (car tmp-sigs))
11294 (if one-hot ")") ":")
11295 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
11296 elim-regexp))))
11297 (setq tmp-sigs (cdr tmp-sigs)))
11298 (verilog-insert-indent (format chrfmt "default:" errname)))
11299 ;;
11300 (setq indent-pt (- indent-pt verilog-case-indent))
11301 (verilog-insert-indent "endcase\n")
11302 (setq indent-pt (- indent-pt verilog-indent-level))
11303 (verilog-insert-indent "end\n"
11304 "// End of automatics\n"))))
11305
11306 (defun verilog-auto-templated-rel ()
11307 "Replace Templated relative line numbers with absolute line numbers.
11308 Internal use only. This hacks around the line numbers in AUTOINST Templates
11309 being different from the final output's line numbering."
11310 (let ((templateno 0) (template-line (list 0)) (buf-line 1))
11311 ;; Find line number each template is on
11312 ;; Count lines as we go, as otherwise it's O(n^2) to use count-lines
11313 (goto-char (point-min))
11314 (while (not (eobp))
11315 (when (looking-at ".*AUTO_TEMPLATE")
11316 (setq templateno (1+ templateno))
11317 (setq template-line (cons buf-line template-line)))
11318 (setq buf-line (1+ buf-line))
11319 (forward-line 1))
11320 (setq template-line (nreverse template-line))
11321 ;; Replace T# L# with absolute line number
11322 (goto-char (point-min))
11323 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
11324 (replace-match
11325 (concat " Templated "
11326 (int-to-string (+ (nth (string-to-number (match-string 1))
11327 template-line)
11328 (string-to-number (match-string 2)))))
11329 t t))))
11330
11331 \f
11332 ;;
11333 ;; Auto top level
11334 ;;
11335
11336 (defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing a arg
11337 "Expand AUTO statements.
11338 Look for any /*AUTO...*/ commands in the code, as used in
11339 instantiations or argument headers. Update the list of signals
11340 following the /*AUTO...*/ command.
11341
11342 Use \\[verilog-delete-auto] to remove the AUTOs.
11343
11344 Use \\[verilog-inject-auto] to insert AUTOs for the first time.
11345
11346 Use \\[verilog-faq] for a pointer to frequently asked questions.
11347
11348 The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
11349 called before and after this function, respectively.
11350
11351 For example:
11352 module ModuleName (/*AUTOARG*/);
11353 /*AUTOINPUT*/
11354 /*AUTOOUTPUT*/
11355 /*AUTOWIRE*/
11356 /*AUTOREG*/
11357 InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
11358
11359 You can also update the AUTOs from the shell using:
11360 emacs --batch <filenames.v> -f verilog-batch-auto
11361 Or fix indentation with:
11362 emacs --batch <filenames.v> -f verilog-batch-indent
11363 Likewise, you can delete or inject AUTOs with:
11364 emacs --batch <filenames.v> -f verilog-batch-delete-auto
11365 emacs --batch <filenames.v> -f verilog-batch-inject-auto
11366
11367 Using \\[describe-function], see also:
11368 `verilog-auto-arg' for AUTOARG module instantiations
11369 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
11370 `verilog-auto-inout-comp' for AUTOINOUTCOMP copy complemented i/o
11371 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
11372 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
11373 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
11374 `verilog-auto-insert-lisp' for AUTOINSERTLISP insert code from lisp function
11375 `verilog-auto-inst' for AUTOINST instantiation pins
11376 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
11377 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
11378 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
11379 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
11380 `verilog-auto-reg' for AUTOREG registers
11381 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
11382 `verilog-auto-reset' for AUTORESET flop resets
11383 `verilog-auto-sense' for AUTOSENSE always sensitivity lists
11384 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
11385 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
11386 `verilog-auto-wire' for AUTOWIRE instantiation wires
11387
11388 `verilog-read-defines' for reading `define values
11389 `verilog-read-includes' for reading `includes
11390
11391 If you have bugs with these autos, please file an issue at
11392 URL `http://www.veripool.org/verilog-mode' or contact the AUTOAUTHOR
11393 Wilson Snyder (wsnyder@wsnyder.org)."
11394 (interactive)
11395 (unless noninteractive (message "Updating AUTOs..."))
11396 (if (fboundp 'dinotrace-unannotate-all)
11397 (dinotrace-unannotate-all))
11398 (let ((oldbuf (if (not (buffer-modified-p))
11399 (buffer-string)))
11400 ;; Before version 20, match-string with font-lock returns a
11401 ;; vector that is not equal to the string. IE if on "input"
11402 ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
11403 (fontlocked (when (and (boundp 'font-lock-mode)
11404 font-lock-mode)
11405 (font-lock-mode 0)
11406 t))
11407 ;; Cache directories; we don't write new files, so can't change
11408 (verilog-dir-cache-preserving t)
11409 ;; Cache current module
11410 (verilog-modi-cache-current-enable t)
11411 (verilog-modi-cache-current-max (point-min)) ; IE it's invalid
11412 verilog-modi-cache-current)
11413 (unwind-protect
11414 ;; Disable change hooks for speed
11415 ;; This let can't be part of above let; must restore
11416 ;; after-change-functions before font-lock resumes
11417 (verilog-save-no-change-functions
11418 (verilog-save-scan-cache
11419 (save-excursion
11420 ;; If we're not in verilog-mode, change syntax table so parsing works right
11421 (unless (eq major-mode `verilog-mode) (verilog-mode))
11422 ;; Allow user to customize
11423 (run-hooks 'verilog-before-auto-hook)
11424 ;; Try to save the user from needing to revert-file to reread file local-variables
11425 (verilog-auto-reeval-locals)
11426 (verilog-read-auto-lisp-present)
11427 (verilog-read-auto-lisp (point-min) (point-max))
11428 (verilog-getopt-flags)
11429 ;; From here on out, we can cache anything we read from disk
11430 (verilog-preserve-dir-cache
11431 ;; These two may seem obvious to do always, but on large includes it can be way too slow
11432 (when verilog-auto-read-includes
11433 (verilog-read-includes)
11434 (verilog-read-defines nil nil t))
11435 ;; This particular ordering is important
11436 ;; INST: Lower modules correct, no internal dependencies, FIRST
11437 (verilog-preserve-modi-cache
11438 ;; Clear existing autos else we'll be screwed by existing ones
11439 (verilog-delete-auto)
11440 ;; Injection if appropriate
11441 (when inject
11442 (verilog-inject-inst)
11443 (verilog-inject-sense)
11444 (verilog-inject-arg))
11445 ;;
11446 ;; Do user inserts first, so their code can insert AUTOs
11447 ;; We may provide a AUTOINSERTLISPLAST if another cleanup pass is needed
11448 (verilog-auto-re-search-do "/\\*AUTOINSERTLISP(.*?)\\*/"
11449 'verilog-auto-insert-lisp)
11450 ;; Expand instances before need the signals the instances input/output
11451 (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
11452 (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
11453 (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
11454 ;; Doesn't matter when done, but combine it with a common changer
11455 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
11456 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
11457 ;; Must be done before autoin/out as creates a reg
11458 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
11459 ;;
11460 ;; first in/outs from other files
11461 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
11462 (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP([^)]*)\\*/" 'verilog-auto-inout-comp)
11463 ;; next in/outs which need previous sucked inputs first
11464 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((\"[^\"]*\")\\)\\*/"
11465 '(lambda () (verilog-auto-output t)))
11466 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\*/" 'verilog-auto-output)
11467 (verilog-auto-re-search-do "/\\*AUTOINPUT\\((\"[^\"]*\")\\)\\*/"
11468 '(lambda () (verilog-auto-input t)))
11469 (verilog-auto-re-search-do "/\\*AUTOINPUT\\*/" 'verilog-auto-input)
11470 (verilog-auto-re-search-do "/\\*AUTOINOUT\\((\"[^\"]*\")\\)\\*/"
11471 '(lambda () (verilog-auto-inout t)))
11472 (verilog-auto-re-search-do "/\\*AUTOINOUT\\*/" 'verilog-auto-inout)
11473 ;; Then tie off those in/outs
11474 (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
11475 ;; Wires/regs must be after inputs/outputs
11476 (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
11477 (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
11478 (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
11479 ;; outputevery needs AUTOOUTPUTs done first
11480 (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\*/" 'verilog-auto-output-every)
11481 ;; After we've created all new variables
11482 (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
11483 ;; Must be after all inputs outputs are generated
11484 (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
11485 ;; Fix line numbers (comments only)
11486 (when verilog-auto-inst-template-numbers
11487 (verilog-auto-templated-rel))))
11488 ;;
11489 (run-hooks 'verilog-auto-hook)
11490 ;;
11491 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))
11492 ;;
11493 ;; If end result is same as when started, clear modified flag
11494 (cond ((and oldbuf (equal oldbuf (buffer-string)))
11495 (set-buffer-modified-p nil)
11496 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
11497 (t (unless noninteractive (message "Updating AUTOs...done"))))
11498 ;; End of after-change protection
11499 )))
11500 ;; Unwind forms
11501 (progn
11502 ;; Restore font-lock
11503 (when fontlocked (font-lock-mode t))))))
11504 \f
11505
11506 ;;
11507 ;; Skeleton based code insertion
11508 ;;
11509 (defvar verilog-template-map
11510 (let ((map (make-sparse-keymap)))
11511 (define-key map "a" 'verilog-sk-always)
11512 (define-key map "b" 'verilog-sk-begin)
11513 (define-key map "c" 'verilog-sk-case)
11514 (define-key map "f" 'verilog-sk-for)
11515 (define-key map "g" 'verilog-sk-generate)
11516 (define-key map "h" 'verilog-sk-header)
11517 (define-key map "i" 'verilog-sk-initial)
11518 (define-key map "j" 'verilog-sk-fork)
11519 (define-key map "m" 'verilog-sk-module)
11520 (define-key map "p" 'verilog-sk-primitive)
11521 (define-key map "r" 'verilog-sk-repeat)
11522 (define-key map "s" 'verilog-sk-specify)
11523 (define-key map "t" 'verilog-sk-task)
11524 (define-key map "w" 'verilog-sk-while)
11525 (define-key map "x" 'verilog-sk-casex)
11526 (define-key map "z" 'verilog-sk-casez)
11527 (define-key map "?" 'verilog-sk-if)
11528 (define-key map ":" 'verilog-sk-else-if)
11529 (define-key map "/" 'verilog-sk-comment)
11530 (define-key map "A" 'verilog-sk-assign)
11531 (define-key map "F" 'verilog-sk-function)
11532 (define-key map "I" 'verilog-sk-input)
11533 (define-key map "O" 'verilog-sk-output)
11534 (define-key map "S" 'verilog-sk-state-machine)
11535 (define-key map "=" 'verilog-sk-inout)
11536 (define-key map "W" 'verilog-sk-wire)
11537 (define-key map "R" 'verilog-sk-reg)
11538 (define-key map "D" 'verilog-sk-define-signal)
11539 map)
11540 "Keymap used in Verilog mode for smart template operations.")
11541
11542
11543 ;;
11544 ;; Place the templates into Verilog Mode. They may be inserted under any key.
11545 ;; C-c C-t will be the default. If you use templates a lot, you
11546 ;; may want to consider moving the binding to another key in your .emacs
11547 ;; file.
11548 ;;
11549 ;(define-key verilog-mode-map "\C-ct" verilog-template-map)
11550 (define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
11551
11552 ;;; ---- statement skeletons ------------------------------------------
11553
11554 (define-skeleton verilog-sk-prompt-condition
11555 "Prompt for the loop condition."
11556 "[condition]: " str )
11557
11558 (define-skeleton verilog-sk-prompt-init
11559 "Prompt for the loop init statement."
11560 "[initial statement]: " str )
11561
11562 (define-skeleton verilog-sk-prompt-inc
11563 "Prompt for the loop increment statement."
11564 "[increment statement]: " str )
11565
11566 (define-skeleton verilog-sk-prompt-name
11567 "Prompt for the name of something."
11568 "[name]: " str)
11569
11570 (define-skeleton verilog-sk-prompt-clock
11571 "Prompt for the name of something."
11572 "name and edge of clock(s): " str)
11573
11574 (defvar verilog-sk-reset nil)
11575 (defun verilog-sk-prompt-reset ()
11576 "Prompt for the name of a state machine reset."
11577 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
11578
11579
11580 (define-skeleton verilog-sk-prompt-state-selector
11581 "Prompt for the name of a state machine selector."
11582 "name of selector (eg {a,b,c,d}): " str )
11583
11584 (define-skeleton verilog-sk-prompt-output
11585 "Prompt for the name of something."
11586 "output: " str)
11587
11588 (define-skeleton verilog-sk-prompt-msb
11589 "Prompt for least significant bit specification."
11590 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
11591
11592 (define-skeleton verilog-sk-prompt-lsb
11593 "Prompt for least significant bit specification."
11594 "lsb:" str )
11595
11596 (defvar verilog-sk-p nil)
11597 (define-skeleton verilog-sk-prompt-width
11598 "Prompt for a width specification."
11599 ()
11600 (progn
11601 (setq verilog-sk-p (point))
11602 (verilog-sk-prompt-msb)
11603 (if (> (point) verilog-sk-p) "] " " ")))
11604
11605 (defun verilog-sk-header ()
11606 "Insert a descriptive header at the top of the file.
11607 See also `verilog-header' for an alternative format."
11608 (interactive "*")
11609 (save-excursion
11610 (goto-char (point-min))
11611 (verilog-sk-header-tmpl)))
11612
11613 (define-skeleton verilog-sk-header-tmpl
11614 "Insert a comment block containing the module title, author, etc."
11615 "[Description]: "
11616 "// -*- Mode: Verilog -*-"
11617 "\n// Filename : " (buffer-name)
11618 "\n// Description : " str
11619 "\n// Author : " (user-full-name)
11620 "\n// Created On : " (current-time-string)
11621 "\n// Last Modified By: " (user-full-name)
11622 "\n// Last Modified On: " (current-time-string)
11623 "\n// Update Count : 0"
11624 "\n// Status : Unknown, Use with caution!"
11625 "\n")
11626
11627 (define-skeleton verilog-sk-module
11628 "Insert a module definition."
11629 ()
11630 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
11631 > _ \n
11632 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
11633
11634 (define-skeleton verilog-sk-primitive
11635 "Insert a task definition."
11636 ()
11637 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
11638 > _ \n
11639 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
11640
11641 (define-skeleton verilog-sk-task
11642 "Insert a task definition."
11643 ()
11644 > "task " '(verilog-sk-prompt-name) & ?; \n
11645 > _ \n
11646 > "begin" \n
11647 > \n
11648 > (- verilog-indent-level-behavioral) "end" \n
11649 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
11650
11651 (define-skeleton verilog-sk-function
11652 "Insert a function definition."
11653 ()
11654 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
11655 > _ \n
11656 > "begin" \n
11657 > \n
11658 > (- verilog-indent-level-behavioral) "end" \n
11659 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
11660
11661 (define-skeleton verilog-sk-always
11662 "Insert always block. Uses the minibuffer to prompt
11663 for sensitivity list."
11664 ()
11665 > "always @ ( /*AUTOSENSE*/ ) begin\n"
11666 > _ \n
11667 > (- verilog-indent-level-behavioral) "end" \n >
11668 )
11669
11670 (define-skeleton verilog-sk-initial
11671 "Insert an initial block."
11672 ()
11673 > "initial begin\n"
11674 > _ \n
11675 > (- verilog-indent-level-behavioral) "end" \n > )
11676
11677 (define-skeleton verilog-sk-specify
11678 "Insert specify block. "
11679 ()
11680 > "specify\n"
11681 > _ \n
11682 > (- verilog-indent-level-behavioral) "endspecify" \n > )
11683
11684 (define-skeleton verilog-sk-generate
11685 "Insert generate block. "
11686 ()
11687 > "generate\n"
11688 > _ \n
11689 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
11690
11691 (define-skeleton verilog-sk-begin
11692 "Insert begin end block. Uses the minibuffer to prompt for name."
11693 ()
11694 > "begin" '(verilog-sk-prompt-name) \n
11695 > _ \n
11696 > (- verilog-indent-level-behavioral) "end"
11697 )
11698
11699 (define-skeleton verilog-sk-fork
11700 "Insert a fork join block."
11701 ()
11702 > "fork\n"
11703 > "begin" \n
11704 > _ \n
11705 > (- verilog-indent-level-behavioral) "end" \n
11706 > "begin" \n
11707 > \n
11708 > (- verilog-indent-level-behavioral) "end" \n
11709 > (- verilog-indent-level-behavioral) "join" \n
11710 > )
11711
11712
11713 (define-skeleton verilog-sk-case
11714 "Build skeleton case statement, prompting for the selector expression,
11715 and the case items."
11716 "[selector expression]: "
11717 > "case (" str ") " \n
11718 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
11719 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11720
11721 (define-skeleton verilog-sk-casex
11722 "Build skeleton casex statement, prompting for the selector expression,
11723 and the case items."
11724 "[selector expression]: "
11725 > "casex (" str ") " \n
11726 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
11727 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11728
11729 (define-skeleton verilog-sk-casez
11730 "Build skeleton casez statement, prompting for the selector expression,
11731 and the case items."
11732 "[selector expression]: "
11733 > "casez (" str ") " \n
11734 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
11735 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11736
11737 (define-skeleton verilog-sk-if
11738 "Insert a skeleton if statement."
11739 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
11740 > _ \n
11741 > (- verilog-indent-level-behavioral) "end " \n )
11742
11743 (define-skeleton verilog-sk-else-if
11744 "Insert a skeleton else if statement."
11745 > (verilog-indent-line) "else if ("
11746 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
11747 > _ \n
11748 > "end" (progn (electric-verilog-terminate-line) nil))
11749
11750 (define-skeleton verilog-sk-datadef
11751 "Common routine to get data definition."
11752 ()
11753 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
11754
11755 (define-skeleton verilog-sk-input
11756 "Insert an input definition."
11757 ()
11758 > "input [" '(verilog-sk-datadef))
11759
11760 (define-skeleton verilog-sk-output
11761 "Insert an output definition."
11762 ()
11763 > "output [" '(verilog-sk-datadef))
11764
11765 (define-skeleton verilog-sk-inout
11766 "Insert an inout definition."
11767 ()
11768 > "inout [" '(verilog-sk-datadef))
11769
11770 (defvar verilog-sk-signal nil)
11771 (define-skeleton verilog-sk-def-reg
11772 "Insert a reg definition."
11773 ()
11774 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
11775
11776 (defun verilog-sk-define-signal ()
11777 "Insert a definition of signal under point at top of module."
11778 (interactive "*")
11779 (let* ((sig-re "[a-zA-Z0-9_]*")
11780 (v1 (buffer-substring
11781 (save-excursion
11782 (skip-chars-backward sig-re)
11783 (point))
11784 (save-excursion
11785 (skip-chars-forward sig-re)
11786 (point)))))
11787 (if (not (member v1 verilog-keywords))
11788 (save-excursion
11789 (setq verilog-sk-signal v1)
11790 (verilog-beg-of-defun)
11791 (verilog-end-of-statement)
11792 (verilog-forward-syntactic-ws)
11793 (verilog-sk-def-reg)
11794 (message "signal at point is %s" v1))
11795 (message "object at point (%s) is a keyword" v1))))
11796
11797 (define-skeleton verilog-sk-wire
11798 "Insert a wire definition."
11799 ()
11800 > "wire [" '(verilog-sk-datadef))
11801
11802 (define-skeleton verilog-sk-reg
11803 "Insert a reg definition."
11804 ()
11805 > "reg [" '(verilog-sk-datadef))
11806
11807 (define-skeleton verilog-sk-assign
11808 "Insert a skeleton assign statement."
11809 ()
11810 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
11811
11812 (define-skeleton verilog-sk-while
11813 "Insert a skeleton while loop statement."
11814 ()
11815 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
11816 > _ \n
11817 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11818
11819 (define-skeleton verilog-sk-repeat
11820 "Insert a skeleton repeat loop statement."
11821 ()
11822 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
11823 > _ \n
11824 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11825
11826 (define-skeleton verilog-sk-for
11827 "Insert a skeleton while loop statement."
11828 ()
11829 > "for ("
11830 '(verilog-sk-prompt-init) "; "
11831 '(verilog-sk-prompt-condition) "; "
11832 '(verilog-sk-prompt-inc)
11833 ") begin" \n
11834 > _ \n
11835 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11836
11837 (define-skeleton verilog-sk-comment
11838 "Inserts three comment lines, making a display comment."
11839 ()
11840 > "/*\n"
11841 > "* " _ \n
11842 > "*/")
11843
11844 (define-skeleton verilog-sk-state-machine
11845 "Insert a state machine definition."
11846 "Name of state variable: "
11847 '(setq input "state")
11848 > "// State registers for " str | -23 \n
11849 '(setq verilog-sk-state str)
11850 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
11851 '(setq input nil)
11852 > \n
11853 > "// State FF for " verilog-sk-state \n
11854 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
11855 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
11856 > verilog-sk-state " = next_" verilog-sk-state ?; \n
11857 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
11858 > \n
11859 > "// Next State Logic for " verilog-sk-state \n
11860 > "always @ ( /*AUTOSENSE*/ ) begin\n"
11861 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
11862 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
11863 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
11864 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
11865 \f
11866
11867 ;;
11868 ;; Include file loading with mouse/return event
11869 ;;
11870 ;; idea & first impl.: M. Rouat (eldo-mode.el)
11871 ;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
11872
11873 (if (featurep 'xemacs)
11874 (require 'overlay))
11875
11876 (defconst verilog-include-file-regexp
11877 "^`include\\s-+\"\\([^\n\"]*\\)\""
11878 "Regexp that matches the include file.")
11879
11880 (defvar verilog-mode-mouse-map
11881 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
11882 (set-keymap-parent map verilog-mode-map)
11883 ;; mouse button bindings
11884 (define-key map "\r" 'verilog-load-file-at-point)
11885 (if (featurep 'xemacs)
11886 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
11887 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
11888 (if (featurep 'xemacs)
11889 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
11890 (define-key map [S-mouse-2] 'mouse-yank-at-click))
11891 map)
11892 "Map containing mouse bindings for `verilog-mode'.")
11893
11894
11895 (defun verilog-highlight-region (beg end old-len)
11896 "Colorize included files and modules in the (changed?) region.
11897 Clicking on the middle-mouse button loads them in a buffer (as in dired)."
11898 (when (or verilog-highlight-includes
11899 verilog-highlight-modules)
11900 (save-excursion
11901 (save-match-data ;; A query-replace may call this function - do not disturb
11902 (verilog-save-buffer-state
11903 (verilog-save-scan-cache
11904 (let (end-point)
11905 (goto-char end)
11906 (setq end-point (point-at-eol))
11907 (goto-char beg)
11908 (beginning-of-line) ; scan entire line
11909 ;; delete overlays existing on this line
11910 (let ((overlays (overlays-in (point) end-point)))
11911 (while overlays
11912 (if (and
11913 (overlay-get (car overlays) 'detachable)
11914 (or (overlay-get (car overlays) 'verilog-include-file)
11915 (overlay-get (car overlays) 'verilog-inst-module)))
11916 (delete-overlay (car overlays)))
11917 (setq overlays (cdr overlays))))
11918 ;;
11919 ;; make new include overlays
11920 (when verilog-highlight-includes
11921 (while (search-forward-regexp verilog-include-file-regexp end-point t)
11922 (goto-char (match-beginning 1))
11923 (let ((ov (make-overlay (match-beginning 1) (match-end 1))))
11924 (overlay-put ov 'start-closed 't)
11925 (overlay-put ov 'end-closed 't)
11926 (overlay-put ov 'evaporate 't)
11927 (overlay-put ov 'verilog-include-file 't)
11928 (overlay-put ov 'mouse-face 'highlight)
11929 (overlay-put ov 'local-map verilog-mode-mouse-map))))
11930 ;;
11931 ;; make new module overlays
11932 (goto-char beg)
11933 ;; This scanner is syntax-fragile, so don't get bent
11934 (when verilog-highlight-modules
11935 (condition-case nil
11936 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-point t)
11937 (save-excursion
11938 (goto-char (match-beginning 0))
11939 (unless (verilog-inside-comment-p)
11940 (verilog-read-inst-module-matcher) ;; sets match 0
11941 (let* ((ov (make-overlay (match-beginning 0) (match-end 0))))
11942 (overlay-put ov 'start-closed 't)
11943 (overlay-put ov 'end-closed 't)
11944 (overlay-put ov 'evaporate 't)
11945 (overlay-put ov 'verilog-inst-module 't)
11946 (overlay-put ov 'mouse-face 'highlight)
11947 (overlay-put ov 'local-map verilog-mode-mouse-map)))))
11948 (error nil)))
11949 ;;
11950 ;; Future highlights:
11951 ;; variables - make an Occur buffer of where referenced
11952 ;; pins - make an Occur buffer of the sig in the declaration module
11953 )))))))
11954
11955 (defun verilog-highlight-buffer ()
11956 "Colorize included files and modules across the whole buffer."
11957 ;; Invoked via verilog-mode calling font-lock then `font-lock-mode-hook'
11958 (interactive)
11959 ;; delete and remake overlays
11960 (verilog-highlight-region (point-min) (point-max) nil))
11961
11962 ;; Deprecated, but was interactive, so we'll keep it around
11963 (defalias 'verilog-colorize-include-files-buffer 'verilog-highlight-buffer)
11964
11965 ;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
11966 ;; so define this function to do more or less the same as ffap-at-mouse
11967 ;; but first resolve filename...
11968 (defun verilog-load-file-at-mouse (event)
11969 "Load file under button 2 click's EVENT.
11970 Files are checked based on `verilog-library-flags'."
11971 (interactive "@e")
11972 (save-excursion ;; implement a Verilog specific ffap-at-mouse
11973 (mouse-set-point event)
11974 (verilog-load-file-at-point t)))
11975
11976 ;; ffap isn't useable for Verilog mode. It uses library paths.
11977 ;; so define this function to do more or less the same as ffap
11978 ;; but first resolve filename...
11979 (defun verilog-load-file-at-point (&optional warn)
11980 "Load file under point.
11981 If WARN, throw warning if not found.
11982 Files are checked based on `verilog-library-flags'."
11983 (interactive)
11984 (save-excursion ;; implement a Verilog specific ffap
11985 (let ((overlays (overlays-in (point) (point)))
11986 hit)
11987 (while (and overlays (not hit))
11988 (when (overlay-get (car overlays) 'verilog-inst-module)
11989 (verilog-goto-defun-file (buffer-substring
11990 (overlay-start (car overlays))
11991 (overlay-end (car overlays))))
11992 (setq hit t))
11993 (setq overlays (cdr overlays)))
11994 ;; Include?
11995 (beginning-of-line)
11996 (when (and (not hit)
11997 (looking-at verilog-include-file-regexp))
11998 (if (and (car (verilog-library-filenames
11999 (match-string 1) (buffer-file-name)))
12000 (file-readable-p (car (verilog-library-filenames
12001 (match-string 1) (buffer-file-name)))))
12002 (find-file (car (verilog-library-filenames
12003 (match-string 1) (buffer-file-name))))
12004 (when warn
12005 (message
12006 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
12007 (match-string 1))))))))
12008
12009 ;;
12010 ;; Bug reporting
12011 ;;
12012
12013 (defun verilog-faq ()
12014 "Tell the user their current version, and where to get the FAQ etc."
12015 (interactive)
12016 (with-output-to-temp-buffer "*verilog-mode help*"
12017 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
12018 (princ "\n")
12019 (princ "For new releases, see http://www.verilog.com\n")
12020 (princ "\n")
12021 (princ "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
12022 (princ "\n")
12023 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
12024 (princ "\n")))
12025
12026 (autoload 'reporter-submit-bug-report "reporter")
12027 (defvar reporter-prompt-for-summary-p)
12028
12029 (defun verilog-submit-bug-report ()
12030 "Submit via mail a bug report on verilog-mode.el."
12031 (interactive)
12032 (let ((reporter-prompt-for-summary-p t))
12033 (reporter-submit-bug-report
12034 "mac@verilog.com, wsnyder@wsnyder.org"
12035 (concat "verilog-mode v" verilog-mode-version)
12036 '(
12037 verilog-active-low-regexp
12038 verilog-align-ifelse
12039 verilog-assignment-delay
12040 verilog-auto-arg-sort
12041 verilog-auto-endcomments
12042 verilog-auto-hook
12043 verilog-auto-ignore-concat
12044 verilog-auto-indent-on-newline
12045 verilog-auto-inout-ignore-regexp
12046 verilog-auto-input-ignore-regexp
12047 verilog-auto-inst-column
12048 verilog-auto-inst-dot-name
12049 verilog-auto-inst-param-value
12050 verilog-auto-inst-template-numbers
12051 verilog-auto-inst-vector
12052 verilog-auto-lineup
12053 verilog-auto-newline
12054 verilog-auto-output-ignore-regexp
12055 verilog-auto-read-includes
12056 verilog-auto-reset-widths
12057 verilog-auto-save-policy
12058 verilog-auto-sense-defines-constant
12059 verilog-auto-sense-include-inputs
12060 verilog-auto-star-expand
12061 verilog-auto-star-save
12062 verilog-auto-unused-ignore-regexp
12063 verilog-before-auto-hook
12064 verilog-before-delete-auto-hook
12065 verilog-before-getopt-flags-hook
12066 verilog-case-indent
12067 verilog-cexp-indent
12068 verilog-compiler
12069 verilog-coverage
12070 verilog-delete-auto-hook
12071 verilog-getopt-flags-hook
12072 verilog-highlight-grouping-keywords
12073 verilog-highlight-p1800-keywords
12074 verilog-highlight-translate-off
12075 verilog-indent-begin-after-if
12076 verilog-indent-declaration-macros
12077 verilog-indent-level
12078 verilog-indent-level-behavioral
12079 verilog-indent-level-declaration
12080 verilog-indent-level-directive
12081 verilog-indent-level-module
12082 verilog-indent-lists
12083 verilog-library-directories
12084 verilog-library-extensions
12085 verilog-library-files
12086 verilog-library-flags
12087 verilog-linter
12088 verilog-minimum-comment-distance
12089 verilog-mode-hook
12090 verilog-preprocessor
12091 verilog-simulator
12092 verilog-tab-always-indent
12093 verilog-tab-to-comment
12094 verilog-typedef-regexp
12095 )
12096 nil nil
12097 (concat "Hi Mac,
12098
12099 I want to report a bug.
12100
12101 Before I go further, I want to say that Verilog mode has changed my life.
12102 I save so much time, my files are colored nicely, my co workers respect
12103 my coding ability... until now. I'd really appreciate anything you
12104 could do to help me out with this minor deficiency in the product.
12105
12106 I've taken a look at the Verilog-Mode FAQ at
12107 http://www.veripool.org/verilog-mode-faq.html.
12108
12109 And, I've considered filing the bug on the issue tracker at
12110 http://www.veripool.org/verilog-mode-bugs
12111 since I realize that public bugs are easier for you to track,
12112 and for others to search, but would prefer to email.
12113
12114 So, to reproduce the bug, start a fresh Emacs via " invocation-name "
12115 -no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
12116 the code included below.
12117
12118 Given those lines, I expected [[Fill in here]] to happen;
12119 but instead, [[Fill in here]] happens!.
12120
12121 == The code: =="))))
12122
12123 (provide 'verilog-mode)
12124
12125 ;; Local Variables:
12126 ;; checkdoc-permit-comma-termination-flag:t
12127 ;; checkdoc-force-docstrings-flag:nil
12128 ;; End:
12129
12130 ;;; verilog-mode.el ends here