]> code.delx.au - gnu-emacs/blob - lisp/progmodes/verilog-mode.el
Convert consecutive FSF copyright years to ranges.
[gnu-emacs] / lisp / progmodes / verilog-mode.el
1 ;; verilog-mode.el --- major mode for editing verilog source in Emacs
2
3 ;; Copyright (C) 1996-2011 Free Software Foundation, Inc.
4
5 ;; Author: Michael McNamara (mac@verilog.com),
6 ;; Wilson Snyder (wsnyder@wsnyder.org)
7 ;; Please see our web sites:
8 ;; http://www.verilog.com
9 ;; http://www.veripool.org
10 ;;
11 ;; Keywords: languages
12
13 ;; Yoni Rabkin <yoni@rabkins.net> contacted the maintainer of this
14 ;; file on 19/3/2008, and the maintainer agreed that when a bug is
15 ;; filed in the Emacs bug reporting system against this file, a copy
16 ;; of the bug report be sent to the maintainer's email address.
17
18 ;; This code supports Emacs 21.1 and later
19 ;; And XEmacs 21.1 and later
20 ;; Please do not make changes that break Emacs 21. Thanks!
21 ;;
22 ;;
23
24 ;; This file is part of GNU Emacs.
25
26 ;; GNU Emacs is free software: you can redistribute it and/or modify
27 ;; it under the terms of the GNU General Public License as published by
28 ;; the Free Software Foundation, either version 3 of the License, or
29 ;; (at your option) any later version.
30
31 ;; GNU Emacs is distributed in the hope that it will be useful,
32 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
33 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 ;; GNU General Public License for more details.
35
36 ;; You should have received a copy of the GNU General Public License
37 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
38
39 ;;; Commentary:
40
41 ;; This mode borrows heavily from the Pascal-mode and the cc-mode of Emacs
42
43 ;; USAGE
44 ;; =====
45
46 ;; A major mode for editing Verilog HDL source code. When you have
47 ;; entered Verilog mode, you may get more info by pressing C-h m. You
48 ;; may also get online help describing various functions by: C-h f
49 ;; <Name of function you want described>
50
51 ;; KNOWN BUGS / BUG REPORTS
52 ;; =======================
53
54 ;; Verilog is a rapidly evolving language, and hence this mode is
55 ;; under continuous development. Hence this is beta code, and likely
56 ;; has bugs. Please report any issues to the issue tracker at
57 ;; http://www.veripool.org/verilog-mode
58 ;; Please use verilog-submit-bug-report to submit a report; type C-c
59 ;; C-b to invoke this and as a result I will have a much easier time
60 ;; of reproducing the bug you find, and hence fixing it.
61
62 ;; INSTALLING THE MODE
63 ;; ===================
64
65 ;; An older version of this mode may be already installed as a part of
66 ;; your environment, and one method of updating would be to update
67 ;; your Emacs environment. Sometimes this is difficult for local
68 ;; political/control reasons, and hence you can always install a
69 ;; private copy (or even a shared copy) which overrides the system
70 ;; default.
71
72 ;; You can get step by step help in installing this file by going to
73 ;; <http://www.verilog.com/emacs_install.html>
74
75 ;; The short list of installation instructions are: To set up
76 ;; automatic Verilog mode, put this file in your load path, and put
77 ;; the following in code (please un comment it first!) in your
78 ;; .emacs, or in your site's site-load.el
79
80 ; (autoload 'verilog-mode "verilog-mode" "Verilog mode" t )
81 ; (add-to-list 'auto-mode-alist '("\\.[ds]?vh?\\'" . verilog-mode))
82
83 ;; Be sure to examine at the help for verilog-auto, and the other
84 ;; verilog-auto-* functions for some major coding time savers.
85 ;;
86 ;; If you want to customize Verilog mode to fit your needs better,
87 ;; you may add the below lines (the values of the variables presented
88 ;; here are the defaults). Note also that if you use an Emacs that
89 ;; supports custom, it's probably better to use the custom menu to
90 ;; edit these. If working as a member of a large team these settings
91 ;; should be common across all users (in a site-start file), or set
92 ;; in Local Variables in every file. Otherwise, different people's
93 ;; AUTO expansion may result different whitespace changes.
94 ;;
95 ; ;; Enable syntax highlighting of **all** languages
96 ; (global-font-lock-mode t)
97 ;
98 ; ;; User customization for Verilog mode
99 ; (setq verilog-indent-level 3
100 ; verilog-indent-level-module 3
101 ; verilog-indent-level-declaration 3
102 ; verilog-indent-level-behavioral 3
103 ; verilog-indent-level-directive 1
104 ; verilog-case-indent 2
105 ; verilog-auto-newline t
106 ; verilog-auto-indent-on-newline t
107 ; verilog-tab-always-indent t
108 ; verilog-auto-endcomments t
109 ; verilog-minimum-comment-distance 40
110 ; verilog-indent-begin-after-if t
111 ; verilog-auto-lineup 'declarations
112 ; verilog-highlight-p1800-keywords nil
113 ; verilog-linter "my_lint_shell_command"
114 ; )
115
116 ;; \f
117
118 ;;; History:
119 ;;
120 ;; See commit history at http://www.veripool.org/verilog-mode.html
121 ;; (This section is required to appease checkdoc.)
122
123 ;;; Code:
124
125 ;; This variable will always hold the version number of the mode
126 (defconst verilog-mode-version "650"
127 "Version of this Verilog mode.")
128 (defconst verilog-mode-release-date "2010-11-05-GNU"
129 "Release date of this Verilog mode.")
130 (defconst verilog-mode-release-emacs t
131 "If non-nil, this version of Verilog mode was released with Emacs itself.")
132
133 (defun verilog-version ()
134 "Inform caller of the version of this file."
135 (interactive)
136 (message "Using verilog-mode version %s" verilog-mode-version))
137
138 ;; Insure we have certain packages, and deal with it if we don't
139 ;; Be sure to note which Emacs flavor and version added each feature.
140 (eval-when-compile
141 ;; Provide stuff if we are XEmacs
142 (when (featurep 'xemacs)
143 (condition-case nil
144 (require 'easymenu)
145 (error nil))
146 (condition-case nil
147 (require 'regexp-opt)
148 (error nil))
149 ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
150 (condition-case nil
151 (load "skeleton")
152 (error nil))
153 (condition-case nil
154 (if (fboundp 'when)
155 nil ;; fab
156 (defmacro when (cond &rest body)
157 (list 'if cond (cons 'progn body))))
158 (error nil))
159 (condition-case nil
160 (if (fboundp 'unless)
161 nil ;; fab
162 (defmacro unless (cond &rest body)
163 (cons 'if (cons cond (cons nil body)))))
164 (error nil))
165 (condition-case nil
166 (if (fboundp 'store-match-data)
167 nil ;; fab
168 (defmacro store-match-data (&rest args) nil))
169 (error nil))
170 (condition-case nil
171 (if (fboundp 'char-before)
172 nil ;; great
173 (defmacro char-before (&rest body)
174 (char-after (1- (point)))))
175 (error nil))
176 (condition-case nil
177 (require 'custom)
178 (error nil))
179 (condition-case nil
180 (if (fboundp 'match-string-no-properties)
181 nil ;; great
182 (defsubst match-string-no-properties (num &optional string)
183 "Return string of text matched by last search, without text properties.
184 NUM specifies which parenthesized expression in the last regexp.
185 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
186 Zero means the entire text matched by the whole regexp or whole string.
187 STRING should be given if the last search was by `string-match' on STRING."
188 (if (match-beginning num)
189 (if string
190 (let ((result
191 (substring string
192 (match-beginning num) (match-end num))))
193 (set-text-properties 0 (length result) nil result)
194 result)
195 (buffer-substring-no-properties (match-beginning num)
196 (match-end num)
197 (current-buffer)))))
198 )
199 (error nil))
200 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
201 nil ;; We've got what we needed
202 ;; We have the old custom-library, hack around it!
203 (defmacro defgroup (&rest args) nil)
204 (defmacro customize (&rest args)
205 (message
206 "Sorry, Customize is not available with this version of Emacs"))
207 (defmacro defcustom (var value doc &rest args)
208 `(defvar ,var ,value ,doc))
209 )
210 (if (fboundp 'defface)
211 nil ; great!
212 (defmacro defface (var values doc &rest args)
213 `(make-face ,var))
214 )
215
216 (if (and (featurep 'custom) (fboundp 'customize-group))
217 nil ;; We've got what we needed
218 ;; We have an intermediate custom-library, hack around it!
219 (defmacro customize-group (var &rest args)
220 `(customize ,var))
221 )
222
223 (unless (boundp 'inhibit-point-motion-hooks)
224 (defvar inhibit-point-motion-hooks nil))
225 (unless (boundp 'deactivate-mark)
226 (defvar deactivate-mark nil))
227 )
228 ;;
229 ;; OK, do this stuff if we are NOT XEmacs:
230 (unless (featurep 'xemacs)
231 (unless (fboundp 'region-active-p)
232 (defmacro region-active-p ()
233 `(and transient-mark-mode mark-active))))
234 )
235
236 ;; Provide a regular expression optimization routine, using regexp-opt
237 ;; if provided by the user's elisp libraries
238 (eval-and-compile
239 ;; The below were disabled when GNU Emacs 22 was released;
240 ;; perhaps some still need to be there to support Emacs 21.
241 (if (featurep 'xemacs)
242 (if (fboundp 'regexp-opt)
243 ;; regexp-opt is defined, does it take 3 or 2 arguments?
244 (if (fboundp 'function-max-args)
245 (let ((args (function-max-args `regexp-opt)))
246 (cond
247 ((eq args 3) ;; It takes 3
248 (condition-case nil ; Hide this defun from emacses
249 ;with just a two input regexp
250 (defun verilog-regexp-opt (a b)
251 "Deal with differing number of required arguments for `regexp-opt'.
252 Call 'regexp-opt' on A and B."
253 (regexp-opt a b 't))
254 (error nil))
255 )
256 ((eq args 2) ;; It takes 2
257 (defun verilog-regexp-opt (a b)
258 "Call 'regexp-opt' on A and B."
259 (regexp-opt a b))
260 )
261 (t nil)))
262 ;; We can't tell; assume it takes 2
263 (defun verilog-regexp-opt (a b)
264 "Call 'regexp-opt' on A and B."
265 (regexp-opt a b))
266 )
267 ;; There is no regexp-opt, provide our own
268 (defun verilog-regexp-opt (strings &optional paren shy)
269 (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
270 (concat open (mapconcat 'regexp-quote strings "\\|") close)))
271 )
272 ;; Emacs.
273 (defalias 'verilog-regexp-opt 'regexp-opt)))
274
275 (eval-and-compile
276 ;; Both xemacs and emacs
277 (condition-case nil
278 (unless (fboundp 'buffer-chars-modified-tick) ;; Emacs 22 added
279 (defmacro buffer-chars-modified-tick () (buffer-modified-tick)))
280 (error nil)))
281
282 (eval-when-compile
283 (defun verilog-regexp-words (a)
284 "Call 'regexp-opt' with word delimiters for the words A."
285 (concat "\\<" (verilog-regexp-opt a t) "\\>")))
286 (defun verilog-regexp-words (a)
287 "Call 'regexp-opt' with word delimiters for the words A."
288 ;; The FAQ references this function, so user LISP sometimes calls it
289 (concat "\\<" (verilog-regexp-opt a t) "\\>"))
290
291 (defun verilog-easy-menu-filter (menu)
292 "Filter `easy-menu-define' MENU to support new features."
293 (cond ((not (featurep 'xemacs))
294 menu) ;; GNU Emacs - passthru
295 ;; Xemacs doesn't support :help. Strip it.
296 ;; Recursively filter the a submenu
297 ((listp menu)
298 (mapcar 'verilog-easy-menu-filter menu))
299 ;; Look for [:help "blah"] and remove
300 ((vectorp menu)
301 (let ((i 0) (out []))
302 (while (< i (length menu))
303 (if (equal `:help (aref menu i))
304 (setq i (+ 2 i))
305 (setq out (vconcat out (vector (aref menu i)))
306 i (1+ i))))
307 out))
308 (t menu))) ;; Default - ok
309 ;;(verilog-easy-menu-filter
310 ;; `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
311 ;; "----" ["MB" nil :help "Help MB"]))
312
313 (defun verilog-customize ()
314 "Customize variables and other settings used by Verilog-Mode."
315 (interactive)
316 (customize-group 'verilog-mode))
317
318 (defun verilog-font-customize ()
319 "Customize fonts used by Verilog-Mode."
320 (interactive)
321 (if (fboundp 'customize-apropos)
322 (customize-apropos "font-lock-*" 'faces)))
323
324 (defun verilog-booleanp (value)
325 "Return t if VALUE is boolean.
326 This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
327 This function may be removed when Emacs 21 is no longer supported."
328 (or (equal value t) (equal value nil)))
329
330 (defun verilog-insert-last-command-event ()
331 "Insert the `last-command-event'."
332 (insert (if (featurep 'xemacs)
333 ;; XEmacs 21.5 doesn't like last-command-event
334 last-command-char
335 ;; And GNU Emacs 22 has obsoleted last-command-char
336 last-command-event)))
337
338 (defalias 'verilog-syntax-ppss
339 (if (fboundp 'syntax-ppss) 'syntax-ppss
340 (lambda (&optional pos) (parse-partial-sexp (point-min) (or pos (point))))))
341
342 (defgroup verilog-mode nil
343 "Facilitates easy editing of Verilog source text."
344 :version "22.2"
345 :group 'languages)
346
347 ; (defgroup verilog-mode-fonts nil
348 ; "Facilitates easy customization fonts used in Verilog source text"
349 ; :link '(customize-apropos "font-lock-*" 'faces)
350 ; :group 'verilog-mode)
351
352 (defgroup verilog-mode-indent nil
353 "Customize indentation and highlighting of Verilog source text."
354 :group 'verilog-mode)
355
356 (defgroup verilog-mode-actions nil
357 "Customize actions on Verilog source text."
358 :group 'verilog-mode)
359
360 (defgroup verilog-mode-auto nil
361 "Customize AUTO actions when expanding Verilog source text."
362 :group 'verilog-mode)
363
364 (defvar verilog-debug nil
365 "If set, enable debug messages for `verilog-mode' internals.")
366
367 (defcustom verilog-linter
368 "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
369 "*Unix program and arguments to call to run a lint checker on Verilog source.
370 Depending on the `verilog-set-compile-command', this may be invoked when
371 you type \\[compile]. When the compile completes, \\[next-error] will take
372 you to the next lint error."
373 :type 'string
374 :group 'verilog-mode-actions)
375 ;; We don't mark it safe, as it's used as a shell command
376
377 (defcustom verilog-coverage
378 "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
379 "*Program and arguments to use to annotate for coverage Verilog source.
380 Depending on the `verilog-set-compile-command', this may be invoked when
381 you type \\[compile]. When the compile completes, \\[next-error] will take
382 you to the next lint error."
383 :type 'string
384 :group 'verilog-mode-actions)
385 ;; We don't mark it safe, as it's used as a shell command
386
387 (defcustom verilog-simulator
388 "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
389 "*Program and arguments to use to interpret Verilog source.
390 Depending on the `verilog-set-compile-command', this may be invoked when
391 you type \\[compile]. When the compile completes, \\[next-error] will take
392 you to the next lint error."
393 :type 'string
394 :group 'verilog-mode-actions)
395 ;; We don't mark it safe, as it's used as a shell command
396
397 (defcustom verilog-compiler
398 "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
399 "*Program and arguments to use to compile Verilog source.
400 Depending on the `verilog-set-compile-command', this may be invoked when
401 you type \\[compile]. When the compile completes, \\[next-error] will take
402 you to the next lint error."
403 :type 'string
404 :group 'verilog-mode-actions)
405 ;; We don't mark it safe, as it's used as a shell command
406
407 (defcustom verilog-preprocessor
408 ;; Very few tools give preprocessed output, so we'll default to Verilog-Perl
409 "vppreproc __FLAGS__ __FILE__"
410 "*Program and arguments to use to preprocess Verilog source.
411 This is invoked with `verilog-preprocess', and depending on the
412 `verilog-set-compile-command', may also be invoked when you type
413 \\[compile]. When the compile completes, \\[next-error] will
414 take you to the next lint error."
415 :type 'string
416 :group 'verilog-mode-actions)
417 ;; We don't mark it safe, as it's used as a shell command
418
419 (defvar verilog-preprocess-history nil
420 "History for `verilog-preprocess'.")
421
422 (defvar verilog-tool 'verilog-linter
423 "Which tool to use for building compiler-command.
424 Either nil, `verilog-linter, `verilog-compiler,
425 `verilog-coverage, `verilog-preprocessor, or `verilog-simulator.
426 Alternatively use the \"Choose Compilation Action\" menu. See
427 `verilog-set-compile-command' for more information.")
428
429 (defcustom verilog-highlight-translate-off nil
430 "*Non-nil means background-highlight code excluded from translation.
431 That is, all code between \"// synopsys translate_off\" and
432 \"// synopsys translate_on\" is highlighted using a different background color
433 \(face `verilog-font-lock-translate-off-face').
434
435 Note: This will slow down on-the-fly fontification (and thus editing).
436
437 Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
438 entry \"Fontify Buffer\"). XEmacs: turn off and on font locking."
439 :type 'boolean
440 :group 'verilog-mode-indent)
441 ;; Note we don't use :safe, as that would break on Emacsen before 22.0.
442 (put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
443
444 (defcustom verilog-auto-lineup 'declarations
445 "*Type of statements to lineup across multiple lines.
446 If 'all' is selected, then all line ups described below are done.
447
448 If 'declaration', then just declarations are lined up with any
449 preceding declarations, taking into account widths and the like,
450 so or example the code:
451 reg [31:0] a;
452 reg b;
453 would become
454 reg [31:0] a;
455 reg b;
456
457 If 'assignment', then assignments are lined up with any preceding
458 assignments, so for example the code
459 a_long_variable <= b + c;
460 d = e + f;
461 would become
462 a_long_variable <= b + c;
463 d = e + f;
464
465 In order to speed up editing, large blocks of statements are lined up
466 only when a \\[verilog-pretty-expr] is typed; and large blocks of declarations
467 are lineup only when \\[verilog-pretty-declarations] is typed."
468
469 :type '(radio (const :tag "Line up Assignments and Declarations" all)
470 (const :tag "Line up Assignment statements" assignments )
471 (const :tag "Line up Declarations" declarations)
472 (function :tag "Other"))
473 :group 'verilog-mode-indent )
474
475 (defcustom verilog-indent-level 3
476 "*Indentation of Verilog statements with respect to containing block."
477 :group 'verilog-mode-indent
478 :type 'integer)
479 (put 'verilog-indent-level 'safe-local-variable 'integerp)
480
481 (defcustom verilog-indent-level-module 3
482 "*Indentation of Module level Verilog statements (eg always, initial).
483 Set to 0 to get initial and always statements lined up on the left side of
484 your screen."
485 :group 'verilog-mode-indent
486 :type 'integer)
487 (put 'verilog-indent-level-module 'safe-local-variable 'integerp)
488
489 (defcustom verilog-indent-level-declaration 3
490 "*Indentation of declarations with respect to containing block.
491 Set to 0 to get them list right under containing block."
492 :group 'verilog-mode-indent
493 :type 'integer)
494 (put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
495
496 (defcustom verilog-indent-declaration-macros nil
497 "*How to treat macro expansions in a declaration.
498 If nil, indent as:
499 input [31:0] a;
500 input `CP;
501 output c;
502 If non nil, treat as:
503 input [31:0] a;
504 input `CP ;
505 output c;"
506 :group 'verilog-mode-indent
507 :type 'boolean)
508 (put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
509
510 (defcustom verilog-indent-lists t
511 "*How to treat indenting items in a list.
512 If t (the default), indent as:
513 always @( posedge a or
514 reset ) begin
515
516 If nil, treat as:
517 always @( posedge a or
518 reset ) begin"
519 :group 'verilog-mode-indent
520 :type 'boolean)
521 (put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
522
523 (defcustom verilog-indent-level-behavioral 3
524 "*Absolute indentation of first begin in a task or function block.
525 Set to 0 to get such code to start at the left side of the screen."
526 :group 'verilog-mode-indent
527 :type 'integer)
528 (put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
529
530 (defcustom verilog-indent-level-directive 1
531 "*Indentation to add to each level of `ifdef declarations.
532 Set to 0 to have all directives start at the left side of the screen."
533 :group 'verilog-mode-indent
534 :type 'integer)
535 (put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
536
537 (defcustom verilog-cexp-indent 2
538 "*Indentation of Verilog statements split across lines."
539 :group 'verilog-mode-indent
540 :type 'integer)
541 (put 'verilog-cexp-indent 'safe-local-variable 'integerp)
542
543 (defcustom verilog-case-indent 2
544 "*Indentation for case statements."
545 :group 'verilog-mode-indent
546 :type 'integer)
547 (put 'verilog-case-indent 'safe-local-variable 'integerp)
548
549 (defcustom verilog-auto-newline t
550 "*True means automatically newline after semicolons."
551 :group 'verilog-mode-indent
552 :type 'boolean)
553 (put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
554
555 (defcustom verilog-auto-indent-on-newline t
556 "*True means automatically indent line after newline."
557 :group 'verilog-mode-indent
558 :type 'boolean)
559 (put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
560
561 (defcustom verilog-tab-always-indent t
562 "*True means TAB should always re-indent the current line.
563 A nil value means TAB will only reindent when at the beginning of the line."
564 :group 'verilog-mode-indent
565 :type 'boolean)
566 (put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
567
568 (defcustom verilog-tab-to-comment nil
569 "*True means TAB moves to the right hand column in preparation for a comment."
570 :group 'verilog-mode-actions
571 :type 'boolean)
572 (put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
573
574 (defcustom verilog-indent-begin-after-if t
575 "*If true, indent begin statements following if, else, while, for and repeat.
576 Otherwise, line them up."
577 :group 'verilog-mode-indent
578 :type 'boolean)
579 (put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
580
581
582 (defcustom verilog-align-ifelse nil
583 "*If true, align `else' under matching `if'.
584 Otherwise else is lined up with first character on line holding matching if."
585 :group 'verilog-mode-indent
586 :type 'boolean)
587 (put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
588
589 (defcustom verilog-minimum-comment-distance 10
590 "*Minimum distance (in lines) between begin and end required before a comment.
591 Setting this variable to zero results in every end acquiring a comment; the
592 default avoids too many redundant comments in tight quarters."
593 :group 'verilog-mode-indent
594 :type 'integer)
595 (put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
596
597 (defcustom verilog-highlight-p1800-keywords nil
598 "*True means highlight words newly reserved by IEEE-1800.
599 These will appear in `verilog-font-lock-p1800-face' in order to gently
600 suggest changing where these words are used as variables to something else.
601 A nil value means highlight these words as appropriate for the SystemVerilog
602 IEEE-1800 standard. Note that changing this will require restarting Emacs
603 to see the effect as font color choices are cached by Emacs."
604 :group 'verilog-mode-indent
605 :type 'boolean)
606 (put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
607
608 (defcustom verilog-highlight-grouping-keywords nil
609 "*True means highlight grouping keywords 'begin' and 'end' more dramatically.
610 If false, these words are in the `font-lock-type-face'; if True then they are in
611 `verilog-font-lock-ams-face'. Some find that special highlighting on these
612 grouping constructs allow the structure of the code to be understood at a glance."
613 :group 'verilog-mode-indent
614 :type 'boolean)
615 (put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
616
617 (defcustom verilog-highlight-modules nil
618 "*True means highlight module statements for `verilog-load-file-at-point'.
619 When true, mousing over module names will allow jumping to the
620 module definition. If false, this is not supported. Setting
621 this is experimental, and may lead to bad performance."
622 :group 'verilog-mode-indent
623 :type 'boolean)
624 (put 'verilog-highlight-modules 'safe-local-variable 'verilog-booleanp)
625
626 (defcustom verilog-highlight-includes t
627 "*True means highlight module statements for `verilog-load-file-at-point'.
628 When true, mousing over include file names will allow jumping to the
629 file referenced. If false, this is not supported."
630 :group 'verilog-mode-indent
631 :type 'boolean)
632 (put 'verilog-highlight-includes 'safe-local-variable 'verilog-booleanp)
633
634 (defcustom verilog-auto-endcomments t
635 "*True means insert a comment /* ... */ after 'end's.
636 The name of the function or case will be set between the braces."
637 :group 'verilog-mode-actions
638 :type 'boolean)
639 (put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
640
641 (defcustom verilog-auto-ignore-concat nil
642 "*True means ignore signals in {...} concatenations for AUTOWIRE etc.
643 This will exclude signals referenced as pin connections in {...}
644 from AUTOWIRE, AUTOOUTPUT and friends. This flag should be set
645 for backward compatibility only and not set in new designs; it
646 may be removed in future versions."
647 :group 'verilog-mode-actions
648 :type 'boolean)
649 (put 'verilog-auto-ignore-concat 'safe-local-variable 'verilog-booleanp)
650
651 (defcustom verilog-auto-read-includes nil
652 "*True means to automatically read includes before AUTOs.
653 This will do a `verilog-read-defines' and `verilog-read-includes' before
654 each AUTO expansion. This makes it easier to embed defines and includes,
655 but can result in very slow reading times if there are many or large
656 include files."
657 :group 'verilog-mode-actions
658 :type 'boolean)
659 (put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
660
661 (defcustom verilog-auto-save-policy nil
662 "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
663 A value of `force' will always do a \\[verilog-auto] automatically if
664 needed on every save. A value of `detect' will do \\[verilog-auto]
665 automatically when it thinks necessary. A value of `ask' will query the
666 user when it thinks updating is needed.
667
668 You should not rely on the 'ask or 'detect policies, they are safeguards
669 only. They do not detect when AUTOINSTs need to be updated because a
670 sub-module's port list has changed."
671 :group 'verilog-mode-actions
672 :type '(choice (const nil) (const ask) (const detect) (const force)))
673
674 (defcustom verilog-auto-star-expand t
675 "*Non-nil indicates to expand a SystemVerilog .* instance ports.
676 They will be expanded in the same way as if there was a AUTOINST in the
677 instantiation. See also `verilog-auto-star' and `verilog-auto-star-save'."
678 :group 'verilog-mode-actions
679 :type 'boolean)
680 (put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
681
682 (defcustom verilog-auto-star-save nil
683 "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
684 A nil value indicates direct connections will be removed before saving.
685 Only meaningful to those created due to `verilog-auto-star-expand' being set.
686
687 Instead of setting this, you may want to use /*AUTOINST*/, which will
688 always be saved."
689 :group 'verilog-mode-actions
690 :type 'boolean)
691 (put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
692
693 (defvar verilog-auto-update-tick nil
694 "Modification tick at which autos were last performed.")
695
696 (defvar verilog-auto-last-file-locals nil
697 "Text from file-local-variables during last evaluation.")
698
699 ;;; Compile support
700 (require 'compile)
701 (defvar verilog-error-regexp-added nil)
702
703 (defvar verilog-error-regexp-emacs-alist
704 '(
705 (verilog-xl-1
706 "\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
707 (verilog-xl-2
708 "([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 3)
709 (verilog-IES
710 ".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)" 2 3)
711 (verilog-surefire-1
712 "[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
713 (verilog-surefire-2
714 "\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\),\\s-+\\(line \\)?\\([0-9]+\\):" 2 4 )
715 (verilog-verbose
716 "\
717 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
718 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
719 (verilog-xsim
720 "\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
721 (verilog-vcs-1
722 "\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
723 (verilog-vcs-2
724 "Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
725 (verilog-vcs-3
726 "\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
727 (verilog-vcs-4
728 "syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
729 (verilog-verilator
730 "%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
731 (verilog-leda
732 "^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 2)
733 )
734 "List of regexps for Verilog compilers.
735 See `compilation-error-regexp-alist' for the formatting. For Emacs 22+.")
736
737 (defvar verilog-error-regexp-xemacs-alist
738 ;; Emacs form is '((v-tool "re" 1 2) ...)
739 ;; XEmacs form is '(verilog ("re" 1 2) ...)
740 ;; So we can just map from Emacs to Xemacs
741 (cons 'verilog (mapcar 'cdr verilog-error-regexp-emacs-alist))
742 "List of regexps for Verilog compilers.
743 See `compilation-error-regexp-alist-alist' for the formatting. For XEmacs.")
744
745 (defvar verilog-error-font-lock-keywords
746 '(
747 ;; verilog-xl-1
748 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
749 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
750 ;; verilog-xl-2
751 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 1 bold t)
752 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\(line[ \t]+\\)?\\([0-9]+\\):.*$" 3 bold t)
753 ;; verilog-IES (nc-verilog)
754 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
755 (".*\\*[WE],[0-9A-Z]+\\(\[[0-9A-Z_,]+\]\\)? (\\([^ \t,]+\\),\\([0-9]+\\)|" 3 bold t)
756 ;; verilog-surefire-1
757 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
758 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
759 ;; verilog-surefire-2
760 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
761 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
762 ;; verilog-verbose
763 ("\
764 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
765 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
766 ("\
767 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
768 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
769 ;; verilog-vcs-1
770 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
771 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
772 ;; verilog-vcs-2
773 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
774 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
775 ;; verilog-vcs-3
776 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
777 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
778 ;; verilog-vcs-4
779 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
780 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
781 ;; verilog-verilator
782 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
783 (".*%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
784 ;; verilog-leda
785 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 1 bold t)
786 ("^In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\(Warning\\|Error\\|Failure\\)[^\n]*" 2 bold t)
787 )
788 "*Keywords to also highlight in Verilog *compilation* buffers.
789 Only used in XEmacs; GNU Emacs uses `verilog-error-regexp-emacs-alist'.")
790
791 (defcustom verilog-library-flags '("")
792 "*List of standard Verilog arguments to use for /*AUTOINST*/.
793 These arguments are used to find files for `verilog-auto', and match
794 the flags accepted by a standard Verilog-XL simulator.
795
796 -f filename Reads more `verilog-library-flags' from the filename.
797 +incdir+dir Adds the directory to `verilog-library-directories'.
798 -Idir Adds the directory to `verilog-library-directories'.
799 -y dir Adds the directory to `verilog-library-directories'.
800 +libext+.v Adds the extensions to `verilog-library-extensions'.
801 -v filename Adds the filename to `verilog-library-files'.
802
803 filename Adds the filename to `verilog-library-files'.
804 This is not recommended, -v is a better choice.
805
806 You might want these defined in each file; put at the *END* of your file
807 something like:
808
809 // Local Variables:
810 // verilog-library-flags:(\"-y dir -y otherdir\")
811 // End:
812
813 Verilog-mode attempts to detect changes to this local variable, but they
814 are only insured to be correct when the file is first visited. Thus if you
815 have problems, use \\[find-alternate-file] RET to have these take effect.
816
817 See also the variables mentioned above."
818 :group 'verilog-mode-auto
819 :type '(repeat string))
820 (put 'verilog-library-flags 'safe-local-variable 'listp)
821
822 (defcustom verilog-library-directories '(".")
823 "*List of directories when looking for files for /*AUTOINST*/.
824 The directory may be relative to the current file, or absolute.
825 Environment variables are also expanded in the directory names.
826 Having at least the current directory is a good idea.
827
828 You might want these defined in each file; put at the *END* of your file
829 something like:
830
831 // Local Variables:
832 // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
833 // End:
834
835 Verilog-mode attempts to detect changes to this local variable, but they
836 are only insured to be correct when the file is first visited. Thus if you
837 have problems, use \\[find-alternate-file] RET to have these take effect.
838
839 See also `verilog-library-flags', `verilog-library-files'
840 and `verilog-library-extensions'."
841 :group 'verilog-mode-auto
842 :type '(repeat file))
843 (put 'verilog-library-directories 'safe-local-variable 'listp)
844
845 (defcustom verilog-library-files '()
846 "*List of files to search for modules.
847 AUTOINST will use this when it needs to resolve a module name.
848 This is a complete path, usually to a technology file with many standard
849 cells defined in it.
850
851 You might want these defined in each file; put at the *END* of your file
852 something like:
853
854 // Local Variables:
855 // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
856 // End:
857
858 Verilog-mode attempts to detect changes to this local variable, but they
859 are only insured to be correct when the file is first visited. Thus if you
860 have problems, use \\[find-alternate-file] RET to have these take effect.
861
862 See also `verilog-library-flags', `verilog-library-directories'."
863 :group 'verilog-mode-auto
864 :type '(repeat directory))
865 (put 'verilog-library-files 'safe-local-variable 'listp)
866
867 (defcustom verilog-library-extensions '(".v" ".sv")
868 "*List of extensions to use when looking for files for /*AUTOINST*/.
869 See also `verilog-library-flags', `verilog-library-directories'."
870 :type '(repeat string)
871 :group 'verilog-mode-auto)
872 (put 'verilog-library-extensions 'safe-local-variable 'listp)
873
874 (defcustom verilog-active-low-regexp nil
875 "*If set, treat signals matching this regexp as active low.
876 This is used for AUTORESET and AUTOTIEOFF. For proper behavior,
877 you will probably also need `verilog-auto-reset-widths' set."
878 :group 'verilog-mode-auto
879 :type 'string)
880 (put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
881
882 (defcustom verilog-auto-sense-include-inputs nil
883 "*If true, AUTOSENSE should include all inputs.
884 If nil, only inputs that are NOT output signals in the same block are
885 included."
886 :group 'verilog-mode-auto
887 :type 'boolean)
888 (put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
889
890 (defcustom verilog-auto-sense-defines-constant nil
891 "*If true, AUTOSENSE should assume all defines represent constants.
892 When true, the defines will not be included in sensitivity lists. To
893 maintain compatibility with other sites, this should be set at the bottom
894 of each Verilog file that requires it, rather than being set globally."
895 :group 'verilog-mode-auto
896 :type 'boolean)
897 (put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
898
899 (defcustom verilog-auto-reset-widths t
900 "*If true, AUTORESET should determine the width of signals.
901 This is then used to set the width of the zero (32'h0 for example). This
902 is required by some lint tools that aren't smart enough to ignore widths of
903 the constant zero. This may result in ugly code when parameters determine
904 the MSB or LSB of a signal inside an AUTORESET."
905 :type 'boolean
906 :group 'verilog-mode-auto)
907 (put 'verilog-auto-reset-widths 'safe-local-variable 'verilog-booleanp)
908
909 (defcustom verilog-assignment-delay ""
910 "*Text used for delays in delayed assignments. Add a trailing space if set."
911 :group 'verilog-mode-auto
912 :type 'string)
913 (put 'verilog-assignment-delay 'safe-local-variable 'stringp)
914
915 (defcustom verilog-auto-arg-sort nil
916 "*If set, AUTOARG signal names will be sorted, not in delaration order.
917 Declaration order is advantageous with order based instantiations
918 and is the default for backward compatibility. Sorted order
919 reduces changes when declarations are moved around in a file, and
920 it's bad practice to rely on order based instantiations anyhow."
921 :group 'verilog-mode-auto
922 :type 'boolean)
923 (put 'verilog-auto-arg-sort 'safe-local-variable 'verilog-booleanp)
924
925 (defcustom verilog-auto-inst-dot-name nil
926 "*If true, when creating ports with AUTOINST, use .name syntax.
927 This will use \".port\" instead of \".port(port)\" when possible.
928 This is only legal in SystemVerilog files, and will confuse older
929 simulators. Setting `verilog-auto-inst-vector' to nil may also
930 be desirable to increase how often .name will be used."
931 :group 'verilog-mode-auto
932 :type 'boolean)
933 (put 'verilog-auto-inst-dot-name 'safe-local-variable 'verilog-booleanp)
934
935 (defcustom verilog-auto-inst-param-value nil
936 "*If set, AUTOINST will replace parameters with the parameter value.
937 If nil, leave parameters as symbolic names.
938
939 Parameters must be in Verilog 2001 format #(...), and if a parameter is not
940 listed as such there (as when the default value is acceptable), it will not
941 be replaced, and will remain symbolic.
942
943 For example, imagine a submodule uses parameters to declare the size of its
944 inputs. This is then used by a upper module:
945
946 module InstModule (o,i);
947 parameter WIDTH;
948 input [WIDTH-1:0] i;
949 endmodule
950
951 module ExampInst;
952 InstModule
953 #(PARAM(10))
954 instName
955 (/*AUTOINST*/
956 .i (i[PARAM-1:0]));
957
958 Note even though PARAM=10, the AUTOINST has left the parameter as a
959 symbolic name. If `verilog-auto-inst-param-value' is set, this will
960 instead expand to:
961
962 module ExampInst;
963 InstModule
964 #(PARAM(10))
965 instName
966 (/*AUTOINST*/
967 .i (i[9:0]));"
968 :group 'verilog-mode-auto
969 :type 'boolean)
970 (put 'verilog-auto-inst-param-value 'safe-local-variable 'verilog-booleanp)
971
972 (defcustom verilog-auto-inst-vector t
973 "*If true, when creating default ports with AUTOINST, use bus subscripts.
974 If nil, skip the subscript when it matches the entire bus as declared in
975 the module (AUTOWIRE signals always are subscripted, you must manually
976 declare the wire to have the subscripts removed.) Setting this to nil may
977 speed up some simulators, but is less general and harder to read, so avoid."
978 :group 'verilog-mode-auto
979 :type 'boolean)
980 (put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
981
982 (defcustom verilog-auto-inst-template-numbers nil
983 "*If true, when creating templated ports with AUTOINST, add a comment.
984 The comment will add the line number of the template that was used for that
985 port declaration. Setting this aids in debugging, but nil is suggested for
986 regular use to prevent large numbers of merge conflicts."
987 :group 'verilog-mode-auto
988 :type 'boolean)
989 (put 'verilog-auto-inst-template-numbers 'safe-local-variable 'verilog-booleanp)
990
991 (defcustom verilog-auto-inst-column 40
992 "*Indent-to column number for net name part of AUTOINST created pin."
993 :group 'verilog-mode-indent
994 :type 'integer)
995 (put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
996
997 (defcustom verilog-auto-input-ignore-regexp nil
998 "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
999 See the \\[verilog-faq] for examples on using this."
1000 :group 'verilog-mode-auto
1001 :type 'string)
1002 (put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
1003
1004 (defcustom verilog-auto-inout-ignore-regexp nil
1005 "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
1006 See the \\[verilog-faq] for examples on using this."
1007 :group 'verilog-mode-auto
1008 :type 'string)
1009 (put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
1010
1011 (defcustom verilog-auto-output-ignore-regexp nil
1012 "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
1013 See the \\[verilog-faq] for examples on using this."
1014 :group 'verilog-mode-auto
1015 :type 'string)
1016 (put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
1017
1018 (defcustom verilog-auto-tieoff-ignore-regexp nil
1019 "*If set, when creating AUTOTIEOFF list, ignore signals matching this regexp.
1020 See the \\[verilog-faq] for examples on using this."
1021 :group 'verilog-mode-auto
1022 :type 'string)
1023 (put 'verilog-auto-tieoff-ignore-regexp 'safe-local-variable 'stringp)
1024
1025 (defcustom verilog-auto-unused-ignore-regexp nil
1026 "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
1027 See the \\[verilog-faq] for examples on using this."
1028 :group 'verilog-mode-auto
1029 :type 'string)
1030 (put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
1031
1032 (defcustom verilog-typedef-regexp nil
1033 "*If non-nil, regular expression that matches Verilog-2001 typedef names.
1034 For example, \"_t$\" matches typedefs named with _t, as in the C language."
1035 :group 'verilog-mode-auto
1036 :type 'string)
1037 (put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
1038
1039 (defcustom verilog-mode-hook 'verilog-set-compile-command
1040 "*Hook run after Verilog mode is loaded."
1041 :type 'hook
1042 :group 'verilog-mode)
1043
1044 (defcustom verilog-auto-hook nil
1045 "*Hook run after `verilog-mode' updates AUTOs."
1046 :group 'verilog-mode-auto
1047 :type 'hook)
1048
1049 (defcustom verilog-before-auto-hook nil
1050 "*Hook run before `verilog-mode' updates AUTOs."
1051 :group 'verilog-mode-auto
1052 :type 'hook)
1053
1054 (defcustom verilog-delete-auto-hook nil
1055 "*Hook run after `verilog-mode' deletes AUTOs."
1056 :group 'verilog-mode-auto
1057 :type 'hook)
1058
1059 (defcustom verilog-before-delete-auto-hook nil
1060 "*Hook run before `verilog-mode' deletes AUTOs."
1061 :group 'verilog-mode-auto
1062 :type 'hook)
1063
1064 (defcustom verilog-getopt-flags-hook nil
1065 "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
1066 :group 'verilog-mode-auto
1067 :type 'hook)
1068
1069 (defcustom verilog-before-getopt-flags-hook nil
1070 "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
1071 :group 'verilog-mode-auto
1072 :type 'hook)
1073
1074 (defvar verilog-imenu-generic-expression
1075 '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
1076 ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
1077 "Imenu expression for Verilog mode. See `imenu-generic-expression'.")
1078
1079 ;;
1080 ;; provide a verilog-header function.
1081 ;; Customization variables:
1082 ;;
1083 (defvar verilog-date-scientific-format nil
1084 "*If non-nil, dates are written in scientific format (e.g. 1997/09/17).
1085 If nil, in European format (e.g. 17.09.1997). The brain-dead American
1086 format (e.g. 09/17/1997) is not supported.")
1087
1088 (defvar verilog-company nil
1089 "*Default name of Company for Verilog header.
1090 If set will become buffer local.")
1091 (make-variable-buffer-local 'verilog-company)
1092
1093 (defvar verilog-project nil
1094 "*Default name of Project for Verilog header.
1095 If set will become buffer local.")
1096 (make-variable-buffer-local 'verilog-project)
1097
1098 (defvar verilog-mode-map
1099 (let ((map (make-sparse-keymap)))
1100 (define-key map ";" 'electric-verilog-semi)
1101 (define-key map [(control 59)] 'electric-verilog-semi-with-comment)
1102 (define-key map ":" 'electric-verilog-colon)
1103 ;;(define-key map "=" 'electric-verilog-equal)
1104 (define-key map "\`" 'electric-verilog-tick)
1105 (define-key map "\t" 'electric-verilog-tab)
1106 (define-key map "\r" 'electric-verilog-terminate-line)
1107 ;; backspace/delete key bindings
1108 (define-key map [backspace] 'backward-delete-char-untabify)
1109 (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
1110 (define-key map [delete] 'delete-char)
1111 (define-key map [(meta delete)] 'kill-word))
1112 (define-key map "\M-\C-b" 'electric-verilog-backward-sexp)
1113 (define-key map "\M-\C-f" 'electric-verilog-forward-sexp)
1114 (define-key map "\M-\r" `electric-verilog-terminate-and-indent)
1115 (define-key map "\M-\t" 'verilog-complete-word)
1116 (define-key map "\M-?" 'verilog-show-completions)
1117 (define-key map "\C-c\`" 'verilog-lint-off)
1118 (define-key map "\C-c\*" 'verilog-delete-auto-star-implicit)
1119 (define-key map "\C-c\C-r" 'verilog-label-be)
1120 (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
1121 (define-key map "\C-c=" 'verilog-pretty-expr)
1122 (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
1123 (define-key map "\M-*" 'verilog-star-comment)
1124 (define-key map "\C-c\C-c" 'verilog-comment-region)
1125 (define-key map "\C-c\C-u" 'verilog-uncomment-region)
1126 (when (featurep 'xemacs)
1127 (define-key map [(meta control h)] 'verilog-mark-defun)
1128 (define-key map "\M-\C-a" 'verilog-beg-of-defun)
1129 (define-key map "\M-\C-e" 'verilog-end-of-defun))
1130 (define-key map "\C-c\C-d" 'verilog-goto-defun)
1131 (define-key map "\C-c\C-k" 'verilog-delete-auto)
1132 (define-key map "\C-c\C-a" 'verilog-auto)
1133 (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
1134 (define-key map "\C-c\C-p" 'verilog-preprocess)
1135 (define-key map "\C-c\C-z" 'verilog-inject-auto)
1136 (define-key map "\C-c\C-e" 'verilog-expand-vector)
1137 (define-key map "\C-c\C-h" 'verilog-header)
1138 map)
1139 "Keymap used in Verilog mode.")
1140
1141 ;; menus
1142 (easy-menu-define
1143 verilog-menu verilog-mode-map "Menu for Verilog mode"
1144 (verilog-easy-menu-filter
1145 '("Verilog"
1146 ("Choose Compilation Action"
1147 ["None"
1148 (progn
1149 (setq verilog-tool nil)
1150 (verilog-set-compile-command))
1151 :style radio
1152 :selected (equal verilog-tool nil)
1153 :help "When invoking compilation, use compile-command"]
1154 ["Lint"
1155 (progn
1156 (setq verilog-tool 'verilog-linter)
1157 (verilog-set-compile-command))
1158 :style radio
1159 :selected (equal verilog-tool `verilog-linter)
1160 :help "When invoking compilation, use lint checker"]
1161 ["Coverage"
1162 (progn
1163 (setq verilog-tool 'verilog-coverage)
1164 (verilog-set-compile-command))
1165 :style radio
1166 :selected (equal verilog-tool `verilog-coverage)
1167 :help "When invoking compilation, annotate for coverage"]
1168 ["Simulator"
1169 (progn
1170 (setq verilog-tool 'verilog-simulator)
1171 (verilog-set-compile-command))
1172 :style radio
1173 :selected (equal verilog-tool `verilog-simulator)
1174 :help "When invoking compilation, interpret Verilog source"]
1175 ["Compiler"
1176 (progn
1177 (setq verilog-tool 'verilog-compiler)
1178 (verilog-set-compile-command))
1179 :style radio
1180 :selected (equal verilog-tool `verilog-compiler)
1181 :help "When invoking compilation, compile Verilog source"]
1182 ["Preprocessor"
1183 (progn
1184 (setq verilog-tool 'verilog-preprocessor)
1185 (verilog-set-compile-command))
1186 :style radio
1187 :selected (equal verilog-tool `verilog-preprocessor)
1188 :help "When invoking compilation, preprocess Verilog source, see also `verilog-preprocess'"]
1189 )
1190 ("Move"
1191 ["Beginning of function" verilog-beg-of-defun
1192 :keys "C-M-a"
1193 :help "Move backward to the beginning of the current function or procedure"]
1194 ["End of function" verilog-end-of-defun
1195 :keys "C-M-e"
1196 :help "Move forward to the end of the current function or procedure"]
1197 ["Mark function" verilog-mark-defun
1198 :keys "C-M-h"
1199 :help "Mark the current Verilog function or procedure"]
1200 ["Goto function/module" verilog-goto-defun
1201 :help "Move to specified Verilog module/task/function"]
1202 ["Move to beginning of block" electric-verilog-backward-sexp
1203 :help "Move backward over one balanced expression"]
1204 ["Move to end of block" electric-verilog-forward-sexp
1205 :help "Move forward over one balanced expression"]
1206 )
1207 ("Comments"
1208 ["Comment Region" verilog-comment-region
1209 :help "Put marked area into a comment"]
1210 ["UnComment Region" verilog-uncomment-region
1211 :help "Uncomment an area commented with Comment Region"]
1212 ["Multi-line comment insert" verilog-star-comment
1213 :help "Insert Verilog /* */ comment at point"]
1214 ["Lint error to comment" verilog-lint-off
1215 :help "Convert a Verilog linter warning line into a disable statement"]
1216 )
1217 "----"
1218 ["Compile" compile
1219 :help "Perform compilation-action (above) on the current buffer"]
1220 ["AUTO, Save, Compile" verilog-auto-save-compile
1221 :help "Recompute AUTOs, save buffer, and compile"]
1222 ["Next Compile Error" next-error
1223 :help "Visit next compilation error message and corresponding source code"]
1224 ["Ignore Lint Warning at point" verilog-lint-off
1225 :help "Convert a Verilog linter warning line into a disable statement"]
1226 "----"
1227 ["Line up declarations around point" verilog-pretty-declarations
1228 :help "Line up declarations around point"]
1229 ["Line up equations around point" verilog-pretty-expr
1230 :help "Line up expressions around point"]
1231 ["Redo/insert comments on every end" verilog-label-be
1232 :help "Label matching begin ... end statements"]
1233 ["Expand [x:y] vector line" verilog-expand-vector
1234 :help "Take a signal vector on the current line and expand it to multiple lines"]
1235 ["Insert begin-end block" verilog-insert-block
1236 :help "Insert begin ... end"]
1237 ["Complete word" verilog-complete-word
1238 :help "Complete word at point"]
1239 "----"
1240 ["Recompute AUTOs" verilog-auto
1241 :help "Expand AUTO meta-comment statements"]
1242 ["Kill AUTOs" verilog-delete-auto
1243 :help "Remove AUTO expansions"]
1244 ["Inject AUTOs" verilog-inject-auto
1245 :help "Inject AUTOs into legacy non-AUTO buffer"]
1246 ("AUTO Help..."
1247 ["AUTO General" (describe-function 'verilog-auto)
1248 :help "Help introduction on AUTOs"]
1249 ["AUTO Library Flags" (describe-variable 'verilog-library-flags)
1250 :help "Help on verilog-library-flags"]
1251 ["AUTO Library Path" (describe-variable 'verilog-library-directories)
1252 :help "Help on verilog-library-directories"]
1253 ["AUTO Library Files" (describe-variable 'verilog-library-files)
1254 :help "Help on verilog-library-files"]
1255 ["AUTO Library Extensions" (describe-variable 'verilog-library-extensions)
1256 :help "Help on verilog-library-extensions"]
1257 ["AUTO `define Reading" (describe-function 'verilog-read-defines)
1258 :help "Help on reading `defines"]
1259 ["AUTO `include Reading" (describe-function 'verilog-read-includes)
1260 :help "Help on parsing `includes"]
1261 ["AUTOARG" (describe-function 'verilog-auto-arg)
1262 :help "Help on AUTOARG - declaring module port list"]
1263 ["AUTOASCIIENUM" (describe-function 'verilog-auto-ascii-enum)
1264 :help "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
1265 ["AUTOINOUTCOMP" (describe-function 'verilog-auto-inout-comp)
1266 :help "Help on AUTOINOUTCOMP - copying complemented i/o from another file"]
1267 ["AUTOINOUTMODULE" (describe-function 'verilog-auto-inout-module)
1268 :help "Help on AUTOINOUTMODULE - copying i/o from another file"]
1269 ["AUTOINSERTLISP" (describe-function 'verilog-auto-insert-lisp)
1270 :help "Help on AUTOINSERTLISP - insert text from a lisp function"]
1271 ["AUTOINOUT" (describe-function 'verilog-auto-inout)
1272 :help "Help on AUTOINOUT - adding inouts from cells"]
1273 ["AUTOINPUT" (describe-function 'verilog-auto-input)
1274 :help "Help on AUTOINPUT - adding inputs from cells"]
1275 ["AUTOINST" (describe-function 'verilog-auto-inst)
1276 :help "Help on AUTOINST - adding pins for cells"]
1277 ["AUTOINST (.*)" (describe-function 'verilog-auto-star)
1278 :help "Help on expanding Verilog-2001 .* pins"]
1279 ["AUTOINSTPARAM" (describe-function 'verilog-auto-inst-param)
1280 :help "Help on AUTOINSTPARAM - adding parameter pins to cells"]
1281 ["AUTOOUTPUT" (describe-function 'verilog-auto-output)
1282 :help "Help on AUTOOUTPUT - adding outputs from cells"]
1283 ["AUTOOUTPUTEVERY" (describe-function 'verilog-auto-output-every)
1284 :help "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
1285 ["AUTOREG" (describe-function 'verilog-auto-reg)
1286 :help "Help on AUTOREG - declaring registers for non-wires"]
1287 ["AUTOREGINPUT" (describe-function 'verilog-auto-reg-input)
1288 :help "Help on AUTOREGINPUT - declaring inputs for non-wires"]
1289 ["AUTORESET" (describe-function 'verilog-auto-reset)
1290 :help "Help on AUTORESET - resetting always blocks"]
1291 ["AUTOSENSE" (describe-function 'verilog-auto-sense)
1292 :help "Help on AUTOSENSE - sensitivity lists for always blocks"]
1293 ["AUTOTIEOFF" (describe-function 'verilog-auto-tieoff)
1294 :help "Help on AUTOTIEOFF - tieing off unused outputs"]
1295 ["AUTOUNUSED" (describe-function 'verilog-auto-unused)
1296 :help "Help on AUTOUNUSED - terminating unused inputs"]
1297 ["AUTOWIRE" (describe-function 'verilog-auto-wire)
1298 :help "Help on AUTOWIRE - declaring wires for cells"]
1299 )
1300 "----"
1301 ["Submit bug report" verilog-submit-bug-report
1302 :help "Submit via mail a bug report on verilog-mode.el"]
1303 ["Version and FAQ" verilog-faq
1304 :help "Show the current version, and where to get the FAQ etc"]
1305 ["Customize Verilog Mode..." verilog-customize
1306 :help "Customize variables and other settings used by Verilog-Mode"]
1307 ["Customize Verilog Fonts & Colors" verilog-font-customize
1308 :help "Customize fonts used by Verilog-Mode."])))
1309
1310 (easy-menu-define
1311 verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
1312 (verilog-easy-menu-filter
1313 '("Statements"
1314 ["Header" verilog-sk-header
1315 :help "Insert a header block at the top of file"]
1316 ["Comment" verilog-sk-comment
1317 :help "Insert a comment block"]
1318 "----"
1319 ["Module" verilog-sk-module
1320 :help "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
1321 ["Primitive" verilog-sk-primitive
1322 :help "Insert a primitive .. (.. );.. endprimitive block"]
1323 "----"
1324 ["Input" verilog-sk-input
1325 :help "Insert an input declaration"]
1326 ["Output" verilog-sk-output
1327 :help "Insert an output declaration"]
1328 ["Inout" verilog-sk-inout
1329 :help "Insert an inout declaration"]
1330 ["Wire" verilog-sk-wire
1331 :help "Insert a wire declaration"]
1332 ["Reg" verilog-sk-reg
1333 :help "Insert a register declaration"]
1334 ["Define thing under point as a register" verilog-sk-define-signal
1335 :help "Define signal under point as a register at the top of the module"]
1336 "----"
1337 ["Initial" verilog-sk-initial
1338 :help "Insert an initial begin .. end block"]
1339 ["Always" verilog-sk-always
1340 :help "Insert an always @(AS) begin .. end block"]
1341 ["Function" verilog-sk-function
1342 :help "Insert a function .. begin .. end endfunction block"]
1343 ["Task" verilog-sk-task
1344 :help "Insert a task .. begin .. end endtask block"]
1345 ["Specify" verilog-sk-specify
1346 :help "Insert a specify .. endspecify block"]
1347 ["Generate" verilog-sk-generate
1348 :help "Insert a generate .. endgenerate block"]
1349 "----"
1350 ["Begin" verilog-sk-begin
1351 :help "Insert a begin .. end block"]
1352 ["If" verilog-sk-if
1353 :help "Insert an if (..) begin .. end block"]
1354 ["(if) else" verilog-sk-else-if
1355 :help "Insert an else if (..) begin .. end block"]
1356 ["For" verilog-sk-for
1357 :help "Insert a for (...) begin .. end block"]
1358 ["While" verilog-sk-while
1359 :help "Insert a while (...) begin .. end block"]
1360 ["Fork" verilog-sk-fork
1361 :help "Insert a fork begin .. end .. join block"]
1362 ["Repeat" verilog-sk-repeat
1363 :help "Insert a repeat (..) begin .. end block"]
1364 ["Case" verilog-sk-case
1365 :help "Insert a case block, prompting for details"]
1366 ["Casex" verilog-sk-casex
1367 :help "Insert a casex (...) item: begin.. end endcase block"]
1368 ["Casez" verilog-sk-casez
1369 :help "Insert a casez (...) item: begin.. end endcase block"])))
1370
1371 (defvar verilog-mode-abbrev-table nil
1372 "Abbrev table in use in Verilog-mode buffers.")
1373
1374 (define-abbrev-table 'verilog-mode-abbrev-table ())
1375
1376 ;;
1377 ;; Macros
1378 ;;
1379
1380 (defsubst verilog-within-string ()
1381 (nth 3 (parse-partial-sexp (point-at-bol) (point))))
1382
1383 (defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1384 "Replace occurrences of FROM-STRING with TO-STRING.
1385 FIXEDCASE and LITERAL as in `replace-match`. STRING is what to replace.
1386 The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1387 will break, as the o's continuously replace. xa -> x works ok though."
1388 ;; Hopefully soon to a emacs built-in
1389 (let ((start 0))
1390 (while (string-match from-string string start)
1391 (setq string (replace-match to-string fixedcase literal string)
1392 start (min (length string) (+ (match-beginning 0) (length to-string)))))
1393 string))
1394
1395 (defsubst verilog-string-remove-spaces (string)
1396 "Remove spaces surrounding STRING."
1397 (save-match-data
1398 (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1399 (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1400 string))
1401
1402 (defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1403 ; checkdoc-params: (REGEXP BOUND NOERROR)
1404 "Like `re-search-forward', but skips over match in comments or strings."
1405 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1406 (while (and
1407 (re-search-forward REGEXP BOUND NOERROR)
1408 (setq mdata (match-data))
1409 (and (verilog-skip-forward-comment-or-string)
1410 (progn
1411 (setq mdata '(nil nil))
1412 (if BOUND
1413 (< (point) BOUND)
1414 t)))))
1415 (store-match-data mdata)
1416 (match-end 0)))
1417
1418 (defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1419 ; checkdoc-params: (REGEXP BOUND NOERROR)
1420 "Like `re-search-backward', but skips over match in comments or strings."
1421 (let ((mdata '(nil nil))) ;; So match-end will return nil if no matches found
1422 (while (and
1423 (re-search-backward REGEXP BOUND NOERROR)
1424 (setq mdata (match-data))
1425 (and (verilog-skip-backward-comment-or-string)
1426 (progn
1427 (setq mdata '(nil nil))
1428 (if BOUND
1429 (> (point) BOUND)
1430 t)))))
1431 (store-match-data mdata)
1432 (match-end 0)))
1433
1434 (defsubst verilog-re-search-forward-quick (regexp bound noerror)
1435 "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1436 but trashes match data and is faster for REGEXP that doesn't match often.
1437 This may at some point use text properties to ignore comments,
1438 so there may be a large up front penalty for the first search."
1439 (let (pt)
1440 (while (and (not pt)
1441 (re-search-forward regexp bound noerror))
1442 (if (not (verilog-inside-comment-p))
1443 (setq pt (match-end 0))))
1444 pt))
1445
1446 (defsubst verilog-re-search-backward-quick (regexp bound noerror)
1447 ; checkdoc-params: (REGEXP BOUND NOERROR)
1448 "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1449 but trashes match data and is faster for REGEXP that doesn't match often.
1450 This may at some point use text properties to ignore comments,
1451 so there may be a large up front penalty for the first search."
1452 (let (pt)
1453 (while (and (not pt)
1454 (re-search-backward regexp bound noerror))
1455 (if (not (verilog-inside-comment-p))
1456 (setq pt (match-end 0))))
1457 pt))
1458
1459 (defsubst verilog-re-search-forward-substr (substr regexp bound noerror)
1460 "Like `re-search-forward', but first search for SUBSTR constant.
1461 Then searched for the normal REGEXP (which contains SUBSTR), with given
1462 BOUND and NOERROR. The REGEXP must fit within a single line.
1463 This speeds up complicated regexp matches."
1464 ;; Problem with overlap: search-forward BAR then FOOBARBAZ won't match.
1465 ;; thus require matches to be on one line, and use beginning-of-line.
1466 (let (done)
1467 (while (and (not done)
1468 (search-forward substr bound noerror))
1469 (save-excursion
1470 (beginning-of-line)
1471 (setq done (re-search-forward regexp (point-at-eol) noerror)))
1472 (unless (and (<= (match-beginning 0) (point))
1473 (>= (match-end 0) (point)))
1474 (setq done nil)))
1475 (when done (goto-char done))
1476 done))
1477 ;;(verilog-re-search-forward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1478
1479 (defsubst verilog-re-search-backward-substr (substr regexp bound noerror)
1480 "Like `re-search-backward', but first search for SUBSTR constant.
1481 Then searched for the normal REGEXP (which contains SUBSTR), with given
1482 BOUND and NOERROR. The REGEXP must fit within a single line.
1483 This speeds up complicated regexp matches."
1484 ;; Problem with overlap: search-backward BAR then FOOBARBAZ won't match.
1485 ;; thus require matches to be on one line, and use beginning-of-line.
1486 (let (done)
1487 (while (and (not done)
1488 (search-backward substr bound noerror))
1489 (save-excursion
1490 (end-of-line)
1491 (setq done (re-search-backward regexp (point-at-bol) noerror)))
1492 (unless (and (<= (match-beginning 0) (point))
1493 (>= (match-end 0) (point)))
1494 (setq done nil)))
1495 (when done (goto-char done))
1496 done))
1497 ;;(verilog-re-search-backward-substr "-end" "get-end-of" nil t) ;;-end (test bait)
1498
1499 (defvar compile-command)
1500
1501 ;; compilation program
1502 (defun verilog-set-compile-command ()
1503 "Function to compute shell command to compile Verilog.
1504
1505 This reads `verilog-tool' and sets `compile-command'. This specifies the
1506 program that executes when you type \\[compile] or
1507 \\[verilog-auto-save-compile].
1508
1509 By default `verilog-tool' uses a Makefile if one exists in the
1510 current directory. If not, it is set to the `verilog-linter',
1511 `verilog-compiler', `verilog-coverage', `verilog-preprocessor',
1512 or `verilog-simulator' variables, as selected with the Verilog ->
1513 \"Choose Compilation Action\" menu.
1514
1515 You should set `verilog-tool' or the other variables to the path and
1516 arguments for your Verilog simulator. For example:
1517 \"vcs -p123 -O\"
1518 or a string like:
1519 \"(cd /tmp; surecov %s)\".
1520
1521 In the former case, the path to the current buffer is concat'ed to the
1522 value of `verilog-tool'; in the later, the path to the current buffer is
1523 substituted for the %s.
1524
1525 Where __FLAGS__ appears in the string `verilog-current-flags'
1526 will be substituted.
1527
1528 Where __FILE__ appears in the string, the variable
1529 `buffer-file-name' of the current buffer, without the directory
1530 portion, will be substituted."
1531 (interactive)
1532 (cond
1533 ((or (file-exists-p "makefile") ;If there is a makefile, use it
1534 (file-exists-p "Makefile"))
1535 (set (make-local-variable 'compile-command) "make "))
1536 (t
1537 (set (make-local-variable 'compile-command)
1538 (if verilog-tool
1539 (if (string-match "%s" (eval verilog-tool))
1540 (format (eval verilog-tool) (or buffer-file-name ""))
1541 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1542 ""))))
1543 (verilog-modify-compile-command))
1544
1545 (defun verilog-expand-command (command)
1546 "Replace meta-information in COMMAND and return it.
1547 Where __FLAGS__ appears in the string `verilog-current-flags'
1548 will be substituted. Where __FILE__ appears in the string, the
1549 current buffer's file-name, without the directory portion, will
1550 be substituted."
1551 (setq command (verilog-string-replace-matches
1552 ;; Note \\b only works if under verilog syntax table
1553 "\\b__FLAGS__\\b" (verilog-current-flags)
1554 t t command))
1555 (setq command (verilog-string-replace-matches
1556 "\\b__FILE__\\b" (file-name-nondirectory
1557 (or (buffer-file-name) ""))
1558 t t command))
1559 command)
1560
1561 (defun verilog-modify-compile-command ()
1562 "Update `compile-command' using `verilog-expand-command'."
1563 (when (and
1564 (stringp compile-command)
1565 (string-match "\\b\\(__FLAGS__\\|__FILE__\\)\\b" compile-command))
1566 (set (make-local-variable 'compile-command)
1567 (verilog-expand-command compile-command))))
1568
1569 (if (featurep 'xemacs)
1570 ;; Following code only gets called from compilation-mode-hook on XEmacs to add error handling.
1571 (defun verilog-error-regexp-add-xemacs ()
1572 "Teach XEmacs about verilog errors.
1573 Called by `compilation-mode-hook'. This allows \\[next-error] to
1574 find the errors."
1575 (interactive)
1576 (if (boundp 'compilation-error-regexp-systems-alist)
1577 (if (and
1578 (not (equal compilation-error-regexp-systems-list 'all))
1579 (not (member compilation-error-regexp-systems-list 'verilog)))
1580 (push 'verilog compilation-error-regexp-systems-list)))
1581 (if (boundp 'compilation-error-regexp-alist-alist)
1582 (if (not (assoc 'verilog compilation-error-regexp-alist-alist))
1583 (setcdr compilation-error-regexp-alist-alist
1584 (cons verilog-error-regexp-xemacs-alist
1585 (cdr compilation-error-regexp-alist-alist)))))
1586 (if (boundp 'compilation-font-lock-keywords)
1587 (progn
1588 (set (make-local-variable 'compilation-font-lock-keywords)
1589 verilog-error-font-lock-keywords)
1590 (font-lock-set-defaults)))
1591 ;; Need to re-run compilation-error-regexp builder
1592 (if (fboundp 'compilation-build-compilation-error-regexp-alist)
1593 (compilation-build-compilation-error-regexp-alist))
1594 ))
1595
1596 ;; Following code only gets called from compilation-mode-hook on Emacs to add error handling.
1597 (defun verilog-error-regexp-add-emacs ()
1598 "Tell Emacs compile that we are Verilog.
1599 Called by `compilation-mode-hook'. This allows \\[next-error] to
1600 find the errors."
1601 (interactive)
1602 (if (boundp 'compilation-error-regexp-alist-alist)
1603 (progn
1604 (if (not (assoc 'verilog-xl-1 compilation-error-regexp-alist-alist))
1605 (mapcar
1606 (lambda (item)
1607 (push (car item) compilation-error-regexp-alist)
1608 (push item compilation-error-regexp-alist-alist)
1609 )
1610 verilog-error-regexp-emacs-alist)))))
1611
1612 (if (featurep 'xemacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-xemacs))
1613 (if (featurep 'emacs) (add-hook 'compilation-mode-hook 'verilog-error-regexp-add-emacs))
1614
1615 (defconst verilog-directive-re
1616 (eval-when-compile
1617 (verilog-regexp-words
1618 '(
1619 "`case" "`default" "`define" "`else" "`elsif" "`endfor" "`endif"
1620 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1621 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1622 "`time_scale" "`undef" "`while" ))))
1623
1624 (defconst verilog-directive-re-1
1625 (concat "[ \t]*" verilog-directive-re))
1626
1627 (defconst verilog-directive-begin
1628 "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1629
1630 (defconst verilog-directive-middle
1631 "\\<`\\(else\\|elsif\\|default\\|case\\)\\>")
1632
1633 (defconst verilog-directive-end
1634 "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1635
1636 (defconst verilog-ovm-begin-re
1637 (eval-when-compile
1638 (verilog-regexp-opt
1639 '(
1640 "`ovm_component_utils_begin"
1641 "`ovm_component_param_utils_begin"
1642 "`ovm_field_utils_begin"
1643 "`ovm_object_utils_begin"
1644 "`ovm_object_param_utils_begin"
1645 "`ovm_sequence_utils_begin"
1646 "`ovm_sequencer_utils_begin"
1647 ) nil )))
1648
1649 (defconst verilog-ovm-end-re
1650 (eval-when-compile
1651 (verilog-regexp-opt
1652 '(
1653 "`ovm_component_utils_end"
1654 "`ovm_field_utils_end"
1655 "`ovm_object_utils_end"
1656 "`ovm_sequence_utils_end"
1657 "`ovm_sequencer_utils_end"
1658 ) nil )))
1659
1660 (defconst verilog-vmm-begin-re
1661 (eval-when-compile
1662 (verilog-regexp-opt
1663 '(
1664 "`vmm_data_member_begin"
1665 "`vmm_env_member_begin"
1666 "`vmm_scenario_member_begin"
1667 "`vmm_subenv_member_begin"
1668 "`vmm_xactor_member_begin"
1669 ) nil ) ) )
1670
1671 (defconst verilog-vmm-end-re
1672 (eval-when-compile
1673 (verilog-regexp-opt
1674 '(
1675 "`vmm_data_member_end"
1676 "`vmm_env_member_end"
1677 "`vmm_scenario_member_end"
1678 "`vmm_subenv_member_end"
1679 "`vmm_xactor_member_end"
1680 ) nil ) ) )
1681
1682 (defconst verilog-vmm-statement-re
1683 (eval-when-compile
1684 (verilog-regexp-opt
1685 '(
1686 ;; "`vmm_xactor_member_enum_array"
1687 "`vmm_\\(data\\|env\\|scenario\\|subenv\\|xactor\\)_member_\\(scalar\\|string\\|enum\\|vmm_data\\|channel\\|xactor\\|subenv\\|user_defined\\)\\(_array\\)?"
1688 ;; "`vmm_xactor_member_scalar_array"
1689 ;; "`vmm_xactor_member_scalar"
1690 ) nil )))
1691
1692 (defconst verilog-ovm-statement-re
1693 (eval-when-compile
1694 (verilog-regexp-opt
1695 '(
1696 ;; Statements
1697 "`DUT_ERROR"
1698 "`MESSAGE"
1699 "`dut_error"
1700 "`message"
1701 "`ovm_analysis_imp_decl"
1702 "`ovm_blocking_get_imp_decl"
1703 "`ovm_blocking_get_peek_imp_decl"
1704 "`ovm_blocking_master_imp_decl"
1705 "`ovm_blocking_peek_imp_decl"
1706 "`ovm_blocking_put_imp_decl"
1707 "`ovm_blocking_slave_imp_decl"
1708 "`ovm_blocking_transport_imp_decl"
1709 "`ovm_component_registry"
1710 "`ovm_component_registry_param"
1711 "`ovm_component_utils"
1712 "`ovm_create"
1713 "`ovm_create_seq"
1714 "`ovm_declare_sequence_lib"
1715 "`ovm_do"
1716 "`ovm_do_seq"
1717 "`ovm_do_seq_with"
1718 "`ovm_do_with"
1719 "`ovm_error"
1720 "`ovm_fatal"
1721 "`ovm_field_aa_int_byte"
1722 "`ovm_field_aa_int_byte_unsigned"
1723 "`ovm_field_aa_int_int"
1724 "`ovm_field_aa_int_int_unsigned"
1725 "`ovm_field_aa_int_integer"
1726 "`ovm_field_aa_int_integer_unsigned"
1727 "`ovm_field_aa_int_key"
1728 "`ovm_field_aa_int_longint"
1729 "`ovm_field_aa_int_longint_unsigned"
1730 "`ovm_field_aa_int_shortint"
1731 "`ovm_field_aa_int_shortint_unsigned"
1732 "`ovm_field_aa_int_string"
1733 "`ovm_field_aa_object_int"
1734 "`ovm_field_aa_object_string"
1735 "`ovm_field_aa_string_int"
1736 "`ovm_field_aa_string_string"
1737 "`ovm_field_array_int"
1738 "`ovm_field_array_object"
1739 "`ovm_field_array_string"
1740 "`ovm_field_enum"
1741 "`ovm_field_event"
1742 "`ovm_field_int"
1743 "`ovm_field_object"
1744 "`ovm_field_queue_int"
1745 "`ovm_field_queue_object"
1746 "`ovm_field_queue_string"
1747 "`ovm_field_sarray_int"
1748 "`ovm_field_string"
1749 "`ovm_field_utils"
1750 "`ovm_file"
1751 "`ovm_get_imp_decl"
1752 "`ovm_get_peek_imp_decl"
1753 "`ovm_info"
1754 "`ovm_info1"
1755 "`ovm_info2"
1756 "`ovm_info3"
1757 "`ovm_info4"
1758 "`ovm_line"
1759 "`ovm_master_imp_decl"
1760 "`ovm_msg_detail"
1761 "`ovm_non_blocking_transport_imp_decl"
1762 "`ovm_nonblocking_get_imp_decl"
1763 "`ovm_nonblocking_get_peek_imp_decl"
1764 "`ovm_nonblocking_master_imp_decl"
1765 "`ovm_nonblocking_peek_imp_decl"
1766 "`ovm_nonblocking_put_imp_decl"
1767 "`ovm_nonblocking_slave_imp_decl"
1768 "`ovm_object_registry"
1769 "`ovm_object_registry_param"
1770 "`ovm_object_utils"
1771 "`ovm_peek_imp_decl"
1772 "`ovm_phase_func_decl"
1773 "`ovm_phase_task_decl"
1774 "`ovm_print_aa_int_object"
1775 "`ovm_print_aa_string_int"
1776 "`ovm_print_aa_string_object"
1777 "`ovm_print_aa_string_string"
1778 "`ovm_print_array_int"
1779 "`ovm_print_array_object"
1780 "`ovm_print_array_string"
1781 "`ovm_print_object_queue"
1782 "`ovm_print_queue_int"
1783 "`ovm_print_string_queue"
1784 "`ovm_put_imp_decl"
1785 "`ovm_rand_send"
1786 "`ovm_rand_send_with"
1787 "`ovm_send"
1788 "`ovm_sequence_utils"
1789 "`ovm_slave_imp_decl"
1790 "`ovm_transport_imp_decl"
1791 "`ovm_update_sequence_lib"
1792 "`ovm_update_sequence_lib_and_item"
1793 "`ovm_warning"
1794 "`static_dut_error"
1795 "`static_message") nil )))
1796
1797
1798 ;;
1799 ;; Regular expressions used to calculate indent, etc.
1800 ;;
1801 (defconst verilog-symbol-re "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
1802 ;; Want to match
1803 ;; aa :
1804 ;; aa,bb :
1805 ;; a[34:32] :
1806 ;; a,
1807 ;; b :
1808
1809 (defconst verilog-label-re (concat verilog-symbol-re "\\s-*:\\s-*"))
1810 (defconst verilog-property-re
1811 (concat "\\(" verilog-label-re "\\)?"
1812 "\\(\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(assert\\)"))
1813 ;; "\\(assert\\|assume\\|cover\\)\\s-+property\\>"
1814
1815 (defconst verilog-no-indent-begin-re
1816 "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
1817
1818 (defconst verilog-ends-re
1819 ;; Parenthesis indicate type of keyword found
1820 (concat
1821 "\\(\\<else\\>\\)\\|" ; 1
1822 "\\(\\<if\\>\\)\\|" ; 2
1823 "\\(\\<assert\\>\\)\\|" ; 3
1824 "\\(\\<end\\>\\)\\|" ; 3.1
1825 "\\(\\<endcase\\>\\)\\|" ; 4
1826 "\\(\\<endfunction\\>\\)\\|" ; 5
1827 "\\(\\<endtask\\>\\)\\|" ; 6
1828 "\\(\\<endspecify\\>\\)\\|" ; 7
1829 "\\(\\<endtable\\>\\)\\|" ; 8
1830 "\\(\\<endgenerate\\>\\)\\|" ; 9
1831 "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
1832 "\\(\\<endclass\\>\\)\\|" ; 11
1833 "\\(\\<endgroup\\>\\)\\|" ; 12
1834 ;; VMM
1835 "\\(\\<`vmm_data_member_end\\>\\)\\|"
1836 "\\(\\<`vmm_env_member_end\\>\\)\\|"
1837 "\\(\\<`vmm_scenario_member_end\\>\\)\\|"
1838 "\\(\\<`vmm_subenv_member_end\\>\\)\\|"
1839 "\\(\\<`vmm_xactor_member_end\\>\\)\\|"
1840 ;; OVM
1841 "\\(\\<`ovm_component_utils_end\\>\\)\\|"
1842 "\\(\\<`ovm_field_utils_end\\>\\)\\|"
1843 "\\(\\<`ovm_object_utils_end\\>\\)\\|"
1844 "\\(\\<`ovm_sequence_utils_end\\>\\)\\|"
1845 "\\(\\<`ovm_sequencer_utils_end\\>\\)"
1846
1847 ))
1848
1849 (defconst verilog-auto-end-comment-lines-re
1850 ;; Matches to names in this list cause auto-end-commentation
1851 (concat "\\("
1852 verilog-directive-re "\\)\\|\\("
1853 (eval-when-compile
1854 (verilog-regexp-words
1855 `( "begin"
1856 "else"
1857 "end"
1858 "endcase"
1859 "endclass"
1860 "endclocking"
1861 "endgroup"
1862 "endfunction"
1863 "endmodule"
1864 "endprogram"
1865 "endprimitive"
1866 "endinterface"
1867 "endpackage"
1868 "endsequence"
1869 "endspecify"
1870 "endtable"
1871 "endtask"
1872 "join"
1873 "join_any"
1874 "join_none"
1875 "module"
1876 "macromodule"
1877 "primitive"
1878 "interface"
1879 "package")))
1880 "\\)"))
1881
1882 ;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
1883 ;;; verilog-end-block-ordered-re matches exactly the same strings.
1884 (defconst verilog-end-block-ordered-re
1885 ;; Parenthesis indicate type of keyword found
1886 (concat "\\(\\<endcase\\>\\)\\|" ; 1
1887 "\\(\\<end\\>\\)\\|" ; 2
1888 "\\(\\<end" ; 3, but not used
1889 "\\(" ; 4, but not used
1890 "\\(function\\)\\|" ; 5
1891 "\\(task\\)\\|" ; 6
1892 "\\(module\\)\\|" ; 7
1893 "\\(primitive\\)\\|" ; 8
1894 "\\(interface\\)\\|" ; 9
1895 "\\(package\\)\\|" ; 10
1896 "\\(class\\)\\|" ; 11
1897 "\\(group\\)\\|" ; 12
1898 "\\(program\\)\\|" ; 13
1899 "\\(sequence\\)\\|" ; 14
1900 "\\(clocking\\)\\|" ; 15
1901 "\\)\\>\\)"))
1902 (defconst verilog-end-block-re
1903 (eval-when-compile
1904 (verilog-regexp-words
1905
1906 `("end" ;; closes begin
1907 "endcase" ;; closes any of case, casex casez or randcase
1908 "join" "join_any" "join_none" ;; closes fork
1909 "endclass"
1910 "endtable"
1911 "endspecify"
1912 "endfunction"
1913 "endgenerate"
1914 "endtask"
1915 "endgroup"
1916 "endproperty"
1917 "endinterface"
1918 "endpackage"
1919 "endprogram"
1920 "endsequence"
1921 "endclocking"
1922 ;; OVM
1923 "`ovm_component_utils_end"
1924 "`ovm_field_utils_end"
1925 "`ovm_object_utils_end"
1926 "`ovm_sequence_utils_end"
1927 "`ovm_sequencer_utils_end"
1928 ;; VMM
1929 "`vmm_data_member_end"
1930 "`vmm_env_member_end"
1931 "`vmm_scenario_member_end"
1932 "`vmm_subenv_member_end"
1933 "`vmm_xactor_member_end"
1934 ))))
1935
1936
1937 (defconst verilog-endcomment-reason-re
1938 ;; Parenthesis indicate type of keyword found
1939 (concat
1940 "\\(\\<begin\\>\\)\\|" ; 1
1941 "\\(\\<else\\>\\)\\|" ; 2
1942 "\\(\\<end\\>\\s-+\\<else\\>\\)\\|" ; 3
1943 "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|" ; 4
1944 "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|" ; 5
1945 "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|" ; 6
1946 "\\(\\<fork\\>\\)\\|" ; 7
1947 "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
1948 "\\(\\<if\\>\\)\\|"
1949 verilog-property-re "\\|"
1950 "\\(\\(" verilog-label-re "\\)?\\<assert\\>\\)\\|"
1951 "\\(\\<clocking\\>\\)\\|"
1952 "\\(\\<task\\>\\)\\|"
1953 "\\(\\<function\\>\\)\\|"
1954 "\\(\\<initial\\>\\)\\|"
1955 "\\(\\<interface\\>\\)\\|"
1956 "\\(\\<package\\>\\)\\|"
1957 "\\(\\<final\\>\\)\\|"
1958 "\\(@\\)\\|"
1959 "\\(\\<while\\>\\)\\|"
1960 "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
1961 "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
1962 "#"))
1963
1964 (defconst verilog-named-block-re "begin[ \t]*:")
1965
1966 ;; These words begin a block which can occur inside a module which should be indented,
1967 ;; and closed with the respective word from the end-block list
1968
1969 (defconst verilog-beg-block-re
1970 (eval-when-compile
1971 (verilog-regexp-words
1972 `("begin"
1973 "case" "casex" "casez" "randcase"
1974 "clocking"
1975 "generate"
1976 "fork"
1977 "function"
1978 "property"
1979 "specify"
1980 "table"
1981 "task"
1982 ;;; OVM
1983 "`ovm_component_utils_begin"
1984 "`ovm_component_param_utils_begin"
1985 "`ovm_field_utils_begin"
1986 "`ovm_object_utils_begin"
1987 "`ovm_object_param_utils_begin"
1988 "`ovm_sequence_utils_begin"
1989 "`ovm_sequencer_utils_begin"
1990 ;; VMM
1991 "`vmm_data_member_begin"
1992 "`vmm_env_member_begin"
1993 "`vmm_scenario_member_begin"
1994 "`vmm_subenv_member_begin"
1995 "`vmm_xactor_member_begin"
1996 ))))
1997 ;; These are the same words, in a specific order in the regular
1998 ;; expression so that matching will work nicely for
1999 ;; verilog-forward-sexp and verilog-calc-indent
2000 (defconst verilog-beg-block-re-ordered
2001 ( concat "\\(\\<begin\\>\\)" ;1
2002 "\\|\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
2003 "\\|\\(\\(\\<disable\\>\\s-+\\)?fork\\>\\)" ;4,5
2004 "\\|\\(\\<class\\>\\)" ;6
2005 "\\|\\(\\<table\\>\\)" ;7
2006 "\\|\\(\\<specify\\>\\)" ;8
2007 "\\|\\(\\<function\\>\\)" ;9
2008 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<function\\>\\)" ;10
2009 "\\|\\(\\<task\\>\\)" ;14
2010 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)" ;15
2011 "\\|\\(\\<generate\\>\\)" ;18
2012 "\\|\\(\\<covergroup\\>\\)" ;16 20
2013 "\\|\\(\\(\\(\\<cover\\>\\s-+\\)\\|\\(\\<assert\\>\\s-+\\)\\)*\\<property\\>\\)" ;17 21
2014 "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;21 25
2015 "\\|\\(\\<clocking\\>\\)" ;22 27
2016 "\\|\\(\\<`ovm_[a-z_]+_begin\\>\\)" ;28
2017 "\\|\\(\\<`vmm_[a-z_]+_member_begin\\>\\)"
2018 ;;
2019
2020 ))
2021
2022 (defconst verilog-end-block-ordered-rry
2023 [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2024 "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
2025 "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
2026 "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
2027 "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
2028 "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
2029 "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
2030 "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
2031 "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
2032 "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
2033 "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
2034 "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
2035 "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
2036 ] )
2037
2038 (defconst verilog-nameable-item-re
2039 (eval-when-compile
2040 (verilog-regexp-words
2041 `("begin"
2042 "fork"
2043 "join" "join_any" "join_none"
2044 "end"
2045 "endcase"
2046 "endconfig"
2047 "endclass"
2048 "endclocking"
2049 "endfunction"
2050 "endgenerate"
2051 "endmodule"
2052 "endprimitive"
2053 "endinterface"
2054 "endpackage"
2055 "endspecify"
2056 "endtable"
2057 "endtask" )
2058 )))
2059
2060 (defconst verilog-declaration-opener
2061 (eval-when-compile
2062 (verilog-regexp-words
2063 `("module" "begin" "task" "function"))))
2064
2065 (defconst verilog-declaration-prefix-re
2066 (eval-when-compile
2067 (verilog-regexp-words
2068 `(
2069 ;; port direction
2070 "inout" "input" "output" "ref"
2071 ;; changeableness
2072 "const" "static" "protected" "local"
2073 ;; parameters
2074 "localparam" "parameter" "var"
2075 ;; type creation
2076 "typedef"
2077 ))))
2078 (defconst verilog-declaration-core-re
2079 (eval-when-compile
2080 (verilog-regexp-words
2081 `(
2082 ;; port direction (by themselves)
2083 "inout" "input" "output"
2084 ;; integer_atom_type
2085 "byte" "shortint" "int" "longint" "integer" "time"
2086 ;; integer_vector_type
2087 "bit" "logic" "reg"
2088 ;; non_integer_type
2089 "shortreal" "real" "realtime"
2090 ;; net_type
2091 "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
2092 ;; misc
2093 "string" "event" "chandle" "virtual" "enum" "genvar"
2094 "struct" "union"
2095 ;; builtin classes
2096 "mailbox" "semaphore"
2097 ))))
2098 (defconst verilog-declaration-re
2099 (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
2100 (defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
2101 (defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
2102 (defconst verilog-optional-signed-range-re
2103 (concat
2104 "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
2105 (defconst verilog-macroexp-re "`\\sw+")
2106
2107 (defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
2108 (defconst verilog-declaration-re-2-no-macro
2109 (concat "\\s-*" verilog-declaration-re
2110 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2111 "\\)?"))
2112 (defconst verilog-declaration-re-2-macro
2113 (concat "\\s-*" verilog-declaration-re
2114 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
2115 "\\|\\(" verilog-macroexp-re "\\)"
2116 "\\)?"))
2117 (defconst verilog-declaration-re-1-macro
2118 (concat "^" verilog-declaration-re-2-macro))
2119
2120 (defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
2121
2122 (defconst verilog-defun-re
2123 (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
2124 (defconst verilog-end-defun-re
2125 (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
2126 (defconst verilog-zero-indent-re
2127 (concat verilog-defun-re "\\|" verilog-end-defun-re))
2128
2129 (defconst verilog-behavioral-block-beg-re
2130 (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
2131 "function" "task"))))
2132 (defconst verilog-coverpoint-re "\\w+\\s*:\\s*\\(coverpoint\\|cross\\constraint\\)" )
2133 (defconst verilog-indent-re
2134 (eval-when-compile
2135 (verilog-regexp-words
2136 `(
2137 "{"
2138 "always" "always_latch" "always_ff" "always_comb"
2139 "begin" "end"
2140 ; "unique" "priority"
2141 "case" "casex" "casez" "randcase" "endcase"
2142 "class" "endclass"
2143 "clocking" "endclocking"
2144 "config" "endconfig"
2145 "covergroup" "endgroup"
2146 "fork" "join" "join_any" "join_none"
2147 "function" "endfunction"
2148 "final"
2149 "generate" "endgenerate"
2150 "initial"
2151 "interface" "endinterface"
2152 "module" "macromodule" "endmodule"
2153 "package" "endpackage"
2154 "primitive" "endprimative"
2155 "program" "endprogram"
2156 "property" "endproperty"
2157 "sequence" "randsequence" "endsequence"
2158 "specify" "endspecify"
2159 "table" "endtable"
2160 "task" "endtask"
2161 "virtual"
2162 "`case"
2163 "`default"
2164 "`define" "`undef"
2165 "`if" "`ifdef" "`ifndef" "`else" "`elsif" "`endif"
2166 "`while" "`endwhile"
2167 "`for" "`endfor"
2168 "`format"
2169 "`include"
2170 "`let"
2171 "`protect" "`endprotect"
2172 "`switch" "`endswitch"
2173 "`timescale"
2174 "`time_scale"
2175 ;; OVM Begin tokens
2176 "`ovm_component_utils_begin"
2177 "`ovm_component_param_utils_begin"
2178 "`ovm_field_utils_begin"
2179 "`ovm_object_utils_begin"
2180 "`ovm_object_param_utils_begin"
2181 "`ovm_sequence_utils_begin"
2182 "`ovm_sequencer_utils_begin"
2183 ;; OVM End tokens
2184 "`ovm_component_utils_end"
2185 "`ovm_field_utils_end"
2186 "`ovm_object_utils_end"
2187 "`ovm_sequence_utils_end"
2188 "`ovm_sequencer_utils_end"
2189 ;; VMM Begin tokens
2190 "`vmm_data_member_begin"
2191 "`vmm_env_member_begin"
2192 "`vmm_scenario_member_begin"
2193 "`vmm_subenv_member_begin"
2194 "`vmm_xactor_member_begin"
2195 ;; VMM End tokens
2196 "`vmm_data_member_end"
2197 "`vmm_env_member_end"
2198 "`vmm_scenario_member_end"
2199 "`vmm_subenv_member_end"
2200 "`vmm_xactor_member_end"
2201 ))))
2202
2203 (defconst verilog-defun-level-not-generate-re
2204 (eval-when-compile
2205 (verilog-regexp-words
2206 `( "module" "macromodule" "primitive" "class" "program"
2207 "interface" "package" "config"))))
2208
2209 (defconst verilog-defun-level-re
2210 (eval-when-compile
2211 (verilog-regexp-words
2212 (append
2213 `( "module" "macromodule" "primitive" "class" "program"
2214 "interface" "package" "config")
2215 `( "initial" "final" "always" "always_comb" "always_ff"
2216 "always_latch" "endtask" "endfunction" )))))
2217
2218 (defconst verilog-defun-level-generate-only-re
2219 (eval-when-compile
2220 (verilog-regexp-words
2221 `( "initial" "final" "always" "always_comb" "always_ff"
2222 "always_latch" "endtask" "endfunction" ))))
2223
2224 (defconst verilog-cpp-level-re
2225 (eval-when-compile
2226 (verilog-regexp-words
2227 `(
2228 "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
2229 ))))
2230 (defconst verilog-disable-fork-re "disable\\s-+fork\\>")
2231 (defconst verilog-fork-wait-re "fork\\s-+wait\\>")
2232 (defconst verilog-extended-case-re "\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?")
2233 (defconst verilog-extended-complete-re
2234 (concat "\\(\\<extern\\s-+\\|\\<\\(\\<pure\\>\\s-+\\)?virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)"
2235 "\\|\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)"
2236 "\\|\\(\\<import\\>\\s-+\\)?\"DPI-C\"\\s-+\\(function\\>\\|task\\>\\)"
2237 "\\|" verilog-extended-case-re ))
2238 (defconst verilog-basic-complete-re
2239 (eval-when-compile
2240 (verilog-regexp-words
2241 `(
2242 "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
2243 "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
2244 "if" "for" "forever" "foreach" "else" "parameter" "do" "localparam" "assert"
2245 ))))
2246 (defconst verilog-complete-reg
2247 (concat
2248 verilog-extended-complete-re
2249 "\\|"
2250 verilog-basic-complete-re))
2251
2252 (defconst verilog-end-statement-re
2253 (concat "\\(" verilog-beg-block-re "\\)\\|\\("
2254 verilog-end-block-re "\\)"))
2255
2256 (defconst verilog-endcase-re
2257 (concat verilog-extended-case-re "\\|"
2258 "\\(endcase\\)\\|"
2259 verilog-defun-re
2260 ))
2261
2262 (defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
2263 "String used to mark beginning of excluded text.")
2264 (defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
2265 "String used to mark end of excluded text.")
2266 (defconst verilog-preprocessor-re
2267 (eval-when-compile
2268 (verilog-regexp-words
2269 `(
2270 "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
2271 ))))
2272
2273 (defconst verilog-keywords
2274 '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
2275 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
2276 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
2277 "`time_scale" "`undef" "`while"
2278
2279 "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
2280 "assert" "assign" "assume" "automatic" "before" "begin" "bind"
2281 "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
2282 "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
2283 "config" "const" "constraint" "context" "continue" "cover"
2284 "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
2285 "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
2286 "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
2287 "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
2288 "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
2289 "endtask" "enum" "event" "expect" "export" "extends" "extern"
2290 "final" "first_match" "for" "force" "foreach" "forever" "fork"
2291 "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
2292 "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
2293 "include" "initial" "inout" "input" "inside" "instance" "int"
2294 "integer" "interface" "intersect" "join" "join_any" "join_none"
2295 "large" "liblist" "library" "local" "localparam" "logic"
2296 "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
2297 "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
2298 "notif0" "notif1" "null" "or" "output" "package" "packed"
2299 "parameter" "pmos" "posedge" "primitive" "priority" "program"
2300 "property" "protected" "pull0" "pull1" "pulldown" "pullup"
2301 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2302 "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
2303 "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
2304 "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
2305 "showcancelled" "signed" "small" "solve" "specify" "specparam"
2306 "static" "string" "strong0" "strong1" "struct" "super" "supply0"
2307 "supply1" "table" "tagged" "task" "this" "throughout" "time"
2308 "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
2309 "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
2310 "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
2311 "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
2312 "wire" "with" "within" "wor" "xnor" "xor"
2313 ;; 1800-2009
2314 "accept_on" "checker" "endchecker" "eventually" "global" "implies"
2315 "let" "nexttime" "reject_on" "restrict" "s_always" "s_eventually"
2316 "s_nexttime" "s_until" "s_until_with" "strong" "sync_accept_on"
2317 "sync_reject_on" "unique0" "until" "until_with" "untyped" "weak"
2318 )
2319 "List of Verilog keywords.")
2320
2321 (defconst verilog-comment-start-regexp "//\\|/\\*"
2322 "Dual comment value for `comment-start-regexp'.")
2323
2324 (defvar verilog-mode-syntax-table
2325 (let ((table (make-syntax-table)))
2326 ;; Populate the syntax TABLE.
2327 (modify-syntax-entry ?\\ "\\" table)
2328 (modify-syntax-entry ?+ "." table)
2329 (modify-syntax-entry ?- "." table)
2330 (modify-syntax-entry ?= "." table)
2331 (modify-syntax-entry ?% "." table)
2332 (modify-syntax-entry ?< "." table)
2333 (modify-syntax-entry ?> "." table)
2334 (modify-syntax-entry ?& "." table)
2335 (modify-syntax-entry ?| "." table)
2336 (modify-syntax-entry ?` "w" table)
2337 (modify-syntax-entry ?_ "w" table)
2338 (modify-syntax-entry ?\' "." table)
2339
2340 ;; Set up TABLE to handle block and line style comments.
2341 (if (featurep 'xemacs)
2342 (progn
2343 ;; XEmacs (formerly Lucid) has the best implementation
2344 (modify-syntax-entry ?/ ". 1456" table)
2345 (modify-syntax-entry ?* ". 23" table)
2346 (modify-syntax-entry ?\n "> b" table))
2347 ;; Emacs does things differently, but we can work with it
2348 (modify-syntax-entry ?/ ". 124b" table)
2349 (modify-syntax-entry ?* ". 23" table)
2350 (modify-syntax-entry ?\n "> b" table))
2351 table)
2352 "Syntax table used in Verilog mode buffers.")
2353
2354 (defvar verilog-font-lock-keywords nil
2355 "Default highlighting for Verilog mode.")
2356
2357 (defvar verilog-font-lock-keywords-1 nil
2358 "Subdued level highlighting for Verilog mode.")
2359
2360 (defvar verilog-font-lock-keywords-2 nil
2361 "Medium level highlighting for Verilog mode.
2362 See also `verilog-font-lock-extra-types'.")
2363
2364 (defvar verilog-font-lock-keywords-3 nil
2365 "Gaudy level highlighting for Verilog mode.
2366 See also `verilog-font-lock-extra-types'.")
2367 (defvar verilog-font-lock-translate-off-face
2368 'verilog-font-lock-translate-off-face
2369 "Font to use for translated off regions.")
2370 (defface verilog-font-lock-translate-off-face
2371 '((((class color)
2372 (background light))
2373 (:background "gray90" :italic t ))
2374 (((class color)
2375 (background dark))
2376 (:background "gray10" :italic t ))
2377 (((class grayscale) (background light))
2378 (:foreground "DimGray" :italic t))
2379 (((class grayscale) (background dark))
2380 (:foreground "LightGray" :italic t))
2381 (t (:italis t)))
2382 "Font lock mode face used to background highlight translate-off regions."
2383 :group 'font-lock-highlighting-faces)
2384
2385 (defvar verilog-font-lock-p1800-face
2386 'verilog-font-lock-p1800-face
2387 "Font to use for p1800 keywords.")
2388 (defface verilog-font-lock-p1800-face
2389 '((((class color)
2390 (background light))
2391 (:foreground "DarkOrange3" :bold t ))
2392 (((class color)
2393 (background dark))
2394 (:foreground "orange1" :bold t ))
2395 (t (:italic t)))
2396 "Font lock mode face used to highlight P1800 keywords."
2397 :group 'font-lock-highlighting-faces)
2398
2399 (defvar verilog-font-lock-ams-face
2400 'verilog-font-lock-ams-face
2401 "Font to use for Analog/Mixed Signal keywords.")
2402 (defface verilog-font-lock-ams-face
2403 '((((class color)
2404 (background light))
2405 (:foreground "Purple" :bold t ))
2406 (((class color)
2407 (background dark))
2408 (:foreground "orange1" :bold t ))
2409 (t (:italic t)))
2410 "Font lock mode face used to highlight AMS keywords."
2411 :group 'font-lock-highlighting-faces)
2412
2413 (defvar verilog-font-grouping-keywords-face
2414 'verilog-font-lock-grouping-keywords-face
2415 "Font to use for Verilog Grouping Keywords (such as begin..end).")
2416 (defface verilog-font-lock-grouping-keywords-face
2417 '((((class color)
2418 (background light))
2419 (:foreground "red4" :bold t ))
2420 (((class color)
2421 (background dark))
2422 (:foreground "red4" :bold t ))
2423 (t (:italic t)))
2424 "Font lock mode face used to highlight verilog grouping keywords."
2425 :group 'font-lock-highlighting-faces)
2426
2427 (let* ((verilog-type-font-keywords
2428 (eval-when-compile
2429 (verilog-regexp-opt
2430 '(
2431 "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
2432 "event" "genvar" "inout" "input" "integer" "localparam"
2433 "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
2434 "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
2435 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
2436 "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
2437 "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
2438 "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
2439 "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
2440 ) nil )))
2441
2442 (verilog-pragma-keywords
2443 (eval-when-compile
2444 (verilog-regexp-opt
2445 '("surefire" "synopsys" "rtl_synthesis" "verilint" "leda" "0in") nil
2446 )))
2447
2448 (verilog-1800-2005-keywords
2449 (eval-when-compile
2450 (verilog-regexp-opt
2451 '("alias" "assert" "assume" "automatic" "before" "bind"
2452 "bins" "binsof" "break" "byte" "cell" "chandle" "class"
2453 "clocking" "config" "const" "constraint" "context" "continue"
2454 "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
2455 "dist" "do" "edge" "endclass" "endclocking" "endconfig"
2456 "endgroup" "endprogram" "endproperty" "endsequence" "enum"
2457 "expect" "export" "extends" "extern" "first_match" "foreach"
2458 "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
2459 "illegal_bins" "import" "incdir" "include" "inside" "instance"
2460 "int" "intersect" "large" "liblist" "library" "local" "longint"
2461 "matches" "medium" "modport" "new" "noshowcancelled" "null"
2462 "packed" "program" "property" "protected" "pull0" "pull1"
2463 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2464 "randcase" "randsequence" "ref" "release" "return" "scalared"
2465 "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
2466 "specparam" "static" "string" "strong0" "strong1" "struct"
2467 "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
2468 "type" "union" "unsigned" "use" "var" "virtual" "void"
2469 "wait_order" "weak0" "weak1" "wildcard" "with" "within"
2470 ) nil )))
2471
2472 (verilog-1800-2009-keywords
2473 (eval-when-compile
2474 (verilog-regexp-opt
2475 '("accept_on" "checker" "endchecker" "eventually" "global"
2476 "implies" "let" "nexttime" "reject_on" "restrict" "s_always"
2477 "s_eventually" "s_nexttime" "s_until" "s_until_with" "strong"
2478 "sync_accept_on" "sync_reject_on" "unique0" "until"
2479 "until_with" "untyped" "weak" ) nil )))
2480
2481 (verilog-ams-keywords
2482 (eval-when-compile
2483 (verilog-regexp-opt
2484 '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
2485 "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
2486 "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
2487 "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
2488 "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
2489 "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
2490 "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
2491 "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
2492 "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
2493 "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
2494 "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
2495
2496 (verilog-font-keywords
2497 (eval-when-compile
2498 (verilog-regexp-opt
2499 '(
2500 "assign" "case" "casex" "casez" "randcase" "deassign"
2501 "default" "disable" "else" "endcase" "endfunction"
2502 "endgenerate" "endinterface" "endmodule" "endprimitive"
2503 "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
2504 "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
2505 "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
2506 "package" "endpackage" "always" "always_comb" "always_ff"
2507 "always_latch" "posedge" "primitive" "priority" "release"
2508 "repeat" "specify" "table" "task" "unique" "wait" "while"
2509 "class" "program" "endclass" "endprogram"
2510 ) nil )))
2511
2512 (verilog-font-grouping-keywords
2513 (eval-when-compile
2514 (verilog-regexp-opt
2515 '( "begin" "end" ) nil ))))
2516
2517 (setq verilog-font-lock-keywords
2518 (list
2519 ;; Fontify all builtin keywords
2520 (concat "\\<\\(" verilog-font-keywords "\\|"
2521 ;; And user/system tasks and functions
2522 "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
2523 "\\)\\>")
2524 ;; Fontify all types
2525 (if verilog-highlight-grouping-keywords
2526 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2527 'verilog-font-lock-ams-face)
2528 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2529 'font-lock-type-face))
2530 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
2531 'font-lock-type-face)
2532 ;; Fontify IEEE-1800-2005 keywords appropriately
2533 (if verilog-highlight-p1800-keywords
2534 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
2535 'verilog-font-lock-p1800-face)
2536 (cons (concat "\\<\\(" verilog-1800-2005-keywords "\\)\\>")
2537 'font-lock-type-face))
2538 ;; Fontify IEEE-1800-2009 keywords appropriately
2539 (if verilog-highlight-p1800-keywords
2540 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
2541 'verilog-font-lock-p1800-face)
2542 (cons (concat "\\<\\(" verilog-1800-2009-keywords "\\)\\>")
2543 'font-lock-type-face))
2544 ;; Fontify Verilog-AMS keywords
2545 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
2546 'verilog-font-lock-ams-face)))
2547
2548 (setq verilog-font-lock-keywords-1
2549 (append verilog-font-lock-keywords
2550 (list
2551 ;; Fontify module definitions
2552 (list
2553 "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
2554 '(1 font-lock-keyword-face)
2555 '(3 font-lock-function-name-face 'prepend))
2556 ;; Fontify function definitions
2557 (list
2558 (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
2559 '(1 font-lock-keyword-face)
2560 '(3 font-lock-constant-face prepend))
2561 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
2562 (1 font-lock-keyword-face)
2563 (2 font-lock-constant-face append))
2564 '("\\<function\\>\\s-+\\(\\sw+\\)"
2565 1 'font-lock-constant-face append))))
2566
2567 (setq verilog-font-lock-keywords-2
2568 (append verilog-font-lock-keywords-1
2569 (list
2570 ;; Fontify pragmas
2571 (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
2572 ;; Fontify escaped names
2573 '("\\(\\\\\\S-*\\s-\\)" 0 font-lock-function-name-face)
2574 ;; Fontify macro definitions/ uses
2575 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
2576 'font-lock-preprocessor-face
2577 'font-lock-type-face))
2578 ;; Fontify delays/numbers
2579 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
2580 0 font-lock-type-face append)
2581 ;; Fontify instantiation names
2582 '("\\([A-Za-z][A-Za-z0-9_]*\\)\\s-*(" 1 font-lock-function-name-face)
2583 )))
2584
2585 (setq verilog-font-lock-keywords-3
2586 (append verilog-font-lock-keywords-2
2587 (when verilog-highlight-translate-off
2588 (list
2589 ;; Fontify things in translate off regions
2590 '(verilog-match-translate-off
2591 (0 'verilog-font-lock-translate-off-face prepend))
2592 )))))
2593
2594 ;;
2595 ;; Buffer state preservation
2596
2597 (defmacro verilog-save-buffer-state (&rest body)
2598 "Execute BODY forms, saving state around insignificant change.
2599 Changes in text properties like `face' or `syntax-table' are
2600 considered insignificant. This macro allows text properties to
2601 be changed, even in a read-only buffer.
2602
2603 A change is considered significant if it affects the buffer text
2604 in any way that isn't completely restored again. Any
2605 user-visible changes to the buffer must not be within a
2606 `verilog-save-buffer-state'."
2607 ;; From c-save-buffer-state
2608 `(let* ((modified (buffer-modified-p))
2609 (buffer-undo-list t)
2610 (inhibit-read-only t)
2611 (inhibit-point-motion-hooks t)
2612 before-change-functions
2613 after-change-functions
2614 deactivate-mark
2615 buffer-file-name ; Prevent primitives checking
2616 buffer-file-truename) ; for file modification
2617 (unwind-protect
2618 (progn ,@body)
2619 (and (not modified)
2620 (buffer-modified-p)
2621 (set-buffer-modified-p nil)))))
2622
2623 (defmacro verilog-save-no-change-functions (&rest body)
2624 "Execute BODY forms, disabling all change hooks in BODY.
2625 For insigificant changes, see instead `verilog-save-buffer-state'."
2626 `(let* ((inhibit-point-motion-hooks t)
2627 before-change-functions
2628 after-change-functions)
2629 (progn ,@body)))
2630
2631 ;;
2632 ;; Comment detection and caching
2633
2634 (defvar verilog-scan-cache-preserving nil
2635 "If set, the specified buffer's comment properties are static.
2636 Buffer changes will be ignored. See `verilog-inside-comment-p'
2637 and `verilog-scan'.")
2638
2639 (defvar verilog-scan-cache-tick nil
2640 "Modification tick at which `verilog-scan' was last completed.")
2641 (make-variable-buffer-local 'verilog-scan-cache-tick)
2642
2643 (defun verilog-scan-cache-ok-p ()
2644 "Return t iff the scan cache is up to date."
2645 (or (and verilog-scan-cache-preserving
2646 (eq verilog-scan-cache-preserving (current-buffer))
2647 verilog-scan-cache-tick)
2648 (equal verilog-scan-cache-tick (buffer-chars-modified-tick))))
2649
2650 (defmacro verilog-save-scan-cache (&rest body)
2651 "Execute the BODY forms, allowing scan cache preservation within BODY.
2652 This requires that insertions must use `verilog-insert'."
2653 ;; If the buffer is out of date, trash it, as we'll not check later the tick
2654 ;; Note this must work properly if there's multiple layers of calls
2655 ;; to verilog-save-scan-cache even with differing ticks.
2656 `(progn
2657 (unless (verilog-scan-cache-ok-p) ;; Must be before let
2658 (setq verilog-scan-cache-tick nil))
2659 (let* ((verilog-scan-cache-preserving (current-buffer)))
2660 (progn ,@body))))
2661
2662 (defun verilog-scan-region (beg end)
2663 "Parse comments between BEG and END for `verilog-inside-comment-p'.
2664 This creates v-cmt properties where comments are in force."
2665 ;; Why properties and not overlays? Overlays have much slower non O(1)
2666 ;; lookup times.
2667 ;; This function is warm - called on every verilog-insert
2668 (save-excursion
2669 (save-match-data
2670 (verilog-save-buffer-state
2671 (let (pt)
2672 (goto-char beg)
2673 (while (< (point) end)
2674 (cond ((looking-at "//")
2675 (setq pt (point))
2676 (or (search-forward "\n" end t)
2677 (goto-char end))
2678 ;; "1+": The leading // or /* itself isn't considered as
2679 ;; being "inside" the comment, so that a (search-backward)
2680 ;; that lands at the start of the // won't mis-indicate
2681 ;; it's inside a comment
2682 (put-text-property (1+ pt) (point) 'v-cmt t))
2683 ((looking-at "/\\*")
2684 (setq pt (point))
2685 (or (search-forward "*/" end t)
2686 ;; No error - let later code indicate it so we can
2687 ;; use inside functions on-the-fly
2688 ;;(error "%s: Unmatched /* */, at char %d"
2689 ;; (verilog-point-text) (point))
2690 (goto-char end))
2691 (put-text-property (1+ pt) (point) 'v-cmt t))
2692 (t
2693 (forward-char 1)
2694 (if (re-search-forward "/[/*]" end t)
2695 (backward-char 2)
2696 (goto-char end))))))))))
2697
2698 (defun verilog-scan ()
2699 "Parse the buffer, marking all comments with properties.
2700 Also assumes any text inserted since `verilog-scan-cache-tick'
2701 either is ok to parse as a non-comment, or `verilog-insert' was used."
2702 (unless (verilog-scan-cache-ok-p)
2703 (save-excursion
2704 (verilog-save-buffer-state
2705 (when verilog-debug
2706 (message "Scanning %s cache=%s cachetick=%S tick=%S" (current-buffer)
2707 verilog-scan-cache-preserving verilog-scan-cache-tick
2708 (buffer-chars-modified-tick)))
2709 (remove-text-properties (point-min) (point-max) '(v-cmt nil))
2710 (verilog-scan-region (point-min) (point-max))
2711 (setq verilog-scan-cache-tick (buffer-chars-modified-tick))
2712 (when verilog-debug (message "Scaning... done"))))))
2713
2714 (defun verilog-inside-comment-p ()
2715 "Check if point inside a comment.
2716 This may require a slow pre-parse of the buffer with `verilog-scan'
2717 to establish comment properties on all text."
2718 ;; This function is very hot
2719 (verilog-scan)
2720 (get-text-property (point) 'v-cmt))
2721
2722 (defun verilog-insert (&rest stuff)
2723 "Insert STUFF arguments, tracking comments for `verilog-inside-comment-p'.
2724 Any insert that includes a comment must have the entire commente
2725 inserted using a single call to `verilog-insert'."
2726 (let ((pt (point)))
2727 (while stuff
2728 (insert (car stuff))
2729 (setq stuff (cdr stuff)))
2730 (verilog-scan-region pt (point))))
2731
2732 ;; More searching
2733
2734 (defun verilog-declaration-end ()
2735 (search-forward ";"))
2736
2737 (defun verilog-point-text (&optional pointnum)
2738 "Return text describing where POINTNUM or current point is (for errors).
2739 Use filename, if current buffer being edited shorten to just buffer name."
2740 (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
2741 (buffer-name))
2742 buffer-file-name
2743 (buffer-name))
2744 ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
2745
2746 (defun electric-verilog-backward-sexp ()
2747 "Move backward over one balanced expression."
2748 (interactive)
2749 ;; before that see if we are in a comment
2750 (verilog-backward-sexp))
2751
2752 (defun electric-verilog-forward-sexp ()
2753 "Move forward over one balanced expression."
2754 (interactive)
2755 ;; before that see if we are in a comment
2756 (verilog-forward-sexp))
2757
2758 ;;;used by hs-minor-mode
2759 (defun verilog-forward-sexp-function (arg)
2760 (if (< arg 0)
2761 (verilog-backward-sexp)
2762 (verilog-forward-sexp)))
2763
2764
2765 (defun verilog-backward-sexp ()
2766 (let ((reg)
2767 (elsec 1)
2768 (found nil)
2769 (st (point)))
2770 (if (not (looking-at "\\<"))
2771 (forward-word -1))
2772 (cond
2773 ((verilog-skip-backward-comment-or-string))
2774 ((looking-at "\\<else\\>")
2775 (setq reg (concat
2776 verilog-end-block-re
2777 "\\|\\(\\<else\\>\\)"
2778 "\\|\\(\\<if\\>\\)"))
2779 (while (and (not found)
2780 (verilog-re-search-backward reg nil 'move))
2781 (cond
2782 ((match-end 1) ; matched verilog-end-block-re
2783 ; try to leap back to matching outward block by striding across
2784 ; indent level changing tokens then immediately
2785 ; previous line governs indentation.
2786 (verilog-leap-to-head))
2787 ((match-end 2) ; else, we're in deep
2788 (setq elsec (1+ elsec)))
2789 ((match-end 3) ; found it
2790 (setq elsec (1- elsec))
2791 (if (= 0 elsec)
2792 ;; Now previous line describes syntax
2793 (setq found 't))))))
2794 ((looking-at verilog-end-block-re)
2795 (verilog-leap-to-head))
2796 ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
2797 (cond
2798 ((match-end 1)
2799 (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
2800 ((match-end 2)
2801 (verilog-re-search-backward "\\<primitive\\>" nil 'move))
2802 ((match-end 3)
2803 (verilog-re-search-backward "\\<class\\>" nil 'move))
2804 ((match-end 4)
2805 (verilog-re-search-backward "\\<program\\>" nil 'move))
2806 ((match-end 5)
2807 (verilog-re-search-backward "\\<interface\\>" nil 'move))
2808 ((match-end 6)
2809 (verilog-re-search-backward "\\<package\\>" nil 'move))
2810 (t
2811 (goto-char st)
2812 (backward-sexp 1))))
2813 (t
2814 (goto-char st)
2815 (backward-sexp)))))
2816
2817 (defun verilog-forward-sexp ()
2818 (let ((reg)
2819 (md 2)
2820 (st (point))
2821 (nest 'yes))
2822 (if (not (looking-at "\\<"))
2823 (forward-word -1))
2824 (cond
2825 ((verilog-skip-forward-comment-or-string)
2826 (verilog-forward-syntactic-ws))
2827 ((looking-at verilog-beg-block-re-ordered)
2828 (cond
2829 ((match-end 1);
2830 ;; Search forward for matching end
2831 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
2832 ((match-end 2)
2833 ;; Search forward for matching endcase
2834 (setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2835 (setq md 3) ;; ender is third item in regexp
2836 )
2837 ((match-end 4)
2838 ;; might be "disable fork" or "fork wait"
2839 (let
2840 (here)
2841 (if (looking-at verilog-fork-wait-re)
2842 (progn ;; it is a fork wait; ignore it
2843 (goto-char (match-end 0))
2844 (setq reg nil))
2845 (if (or
2846 (looking-at verilog-disable-fork-re)
2847 (and (looking-at "fork")
2848 (progn
2849 (setq here (point)) ;; sometimes a fork is just a fork
2850 (forward-word -1)
2851 (looking-at verilog-disable-fork-re))))
2852 (progn ;; it is a disable fork; ignore it
2853 (goto-char (match-end 0))
2854 (forward-word 1)
2855 (setq reg nil))
2856 (progn ;; it is a nice simple fork
2857 (goto-char here) ;; return from looking for "disable fork"
2858 ;; Search forward for matching join
2859 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))))))
2860 ((match-end 6)
2861 ;; Search forward for matching endclass
2862 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
2863
2864 ((match-end 7)
2865 ;; Search forward for matching endtable
2866 (setq reg "\\<endtable\\>" )
2867 (setq nest 'no))
2868 ((match-end 8)
2869 ;; Search forward for matching endspecify
2870 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
2871 ((match-end 9)
2872 ;; Search forward for matching endfunction
2873 (setq reg "\\<endfunction\\>" )
2874 (setq nest 'no))
2875 ((match-end 10)
2876 ;; Search forward for matching endfunction
2877 (setq reg "\\<endfunction\\>" )
2878 (setq nest 'no))
2879 ((match-end 14)
2880 ;; Search forward for matching endtask
2881 (setq reg "\\<endtask\\>" )
2882 (setq nest 'no))
2883 ((match-end 15)
2884 ;; Search forward for matching endtask
2885 (setq reg "\\<endtask\\>" )
2886 (setq nest 'no))
2887 ((match-end 19)
2888 ;; Search forward for matching endgenerate
2889 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
2890 ((match-end 20)
2891 ;; Search forward for matching endgroup
2892 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
2893 ((match-end 21)
2894 ;; Search forward for matching endproperty
2895 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
2896 ((match-end 25)
2897 ;; Search forward for matching endsequence
2898 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
2899 (setq md 3)) ; 3 to get to endsequence in the reg above
2900 ((match-end 27)
2901 ;; Search forward for matching endclocking
2902 (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
2903 (if (and reg
2904 (forward-word 1))
2905 (catch 'skip
2906 (if (eq nest 'yes)
2907 (let ((depth 1)
2908 here)
2909 (while (verilog-re-search-forward reg nil 'move)
2910 (cond
2911 ((match-end md) ; a closer in regular expression, so we are climbing out
2912 (setq depth (1- depth))
2913 (if (= 0 depth) ; we are out!
2914 (throw 'skip 1)))
2915 ((match-end 1) ; an opener in the r-e, so we are in deeper now
2916 (setq here (point)) ; remember where we started
2917 (goto-char (match-beginning 1))
2918 (cond
2919 ((looking-at verilog-fork-wait-re)
2920 (goto-char (match-end 0))) ; false alarm
2921 ((if (or
2922 (looking-at verilog-disable-fork-re)
2923 (and (looking-at "fork")
2924 (progn
2925 (forward-word -1)
2926 (looking-at verilog-disable-fork-re))))
2927 (progn ;; it is a disable fork; another false alarm
2928 (goto-char (match-end 0)))
2929 (progn ;; it is a simple fork (or has nothing to do with fork)
2930 (goto-char here)
2931 (setq depth (1+ depth))))))))))
2932 (if (verilog-re-search-forward reg nil 'move)
2933 (throw 'skip 1))))))
2934
2935 ((looking-at (concat
2936 "\\(\\<\\(macro\\)?module\\>\\)\\|"
2937 "\\(\\<primitive\\>\\)\\|"
2938 "\\(\\<class\\>\\)\\|"
2939 "\\(\\<program\\>\\)\\|"
2940 "\\(\\<interface\\>\\)\\|"
2941 "\\(\\<package\\>\\)"))
2942 (cond
2943 ((match-end 1)
2944 (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
2945 ((match-end 2)
2946 (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
2947 ((match-end 3)
2948 (verilog-re-search-forward "\\<endclass\\>" nil 'move))
2949 ((match-end 4)
2950 (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
2951 ((match-end 5)
2952 (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
2953 ((match-end 6)
2954 (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
2955 (t
2956 (goto-char st)
2957 (if (= (following-char) ?\) )
2958 (forward-char 1)
2959 (forward-sexp 1)))))
2960 (t
2961 (goto-char st)
2962 (if (= (following-char) ?\) )
2963 (forward-char 1)
2964 (forward-sexp 1))))))
2965
2966 (defun verilog-declaration-beg ()
2967 (verilog-re-search-backward verilog-declaration-re (bobp) t))
2968
2969 ;;
2970 ;;
2971 ;; Mode
2972 ;;
2973 (defvar verilog-which-tool 1)
2974 ;;;###autoload
2975 (define-derived-mode verilog-mode prog-mode "Verilog"
2976 "Major mode for editing Verilog code.
2977 \\<verilog-mode-map>
2978 See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
2979 AUTOs can improve coding efficiency.
2980
2981 Use \\[verilog-faq] for a pointer to frequently asked questions.
2982
2983 NEWLINE, TAB indents for Verilog code.
2984 Delete converts tabs to spaces as it moves back.
2985
2986 Supports highlighting.
2987
2988 Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
2989 with no args, if that value is non-nil.
2990
2991 Variables controlling indentation/edit style:
2992
2993 variable `verilog-indent-level' (default 3)
2994 Indentation of Verilog statements with respect to containing block.
2995 `verilog-indent-level-module' (default 3)
2996 Absolute indentation of Module level Verilog statements.
2997 Set to 0 to get initial and always statements lined up
2998 on the left side of your screen.
2999 `verilog-indent-level-declaration' (default 3)
3000 Indentation of declarations with respect to containing block.
3001 Set to 0 to get them list right under containing block.
3002 `verilog-indent-level-behavioral' (default 3)
3003 Indentation of first begin in a task or function block
3004 Set to 0 to get such code to lined up underneath the task or
3005 function keyword.
3006 `verilog-indent-level-directive' (default 1)
3007 Indentation of `ifdef/`endif blocks.
3008 `verilog-cexp-indent' (default 1)
3009 Indentation of Verilog statements broken across lines i.e.:
3010 if (a)
3011 begin
3012 `verilog-case-indent' (default 2)
3013 Indentation for case statements.
3014 `verilog-auto-newline' (default nil)
3015 Non-nil means automatically newline after semicolons and the punctuation
3016 mark after an end.
3017 `verilog-auto-indent-on-newline' (default t)
3018 Non-nil means automatically indent line after newline.
3019 `verilog-tab-always-indent' (default t)
3020 Non-nil means TAB in Verilog mode should always reindent the current line,
3021 regardless of where in the line point is when the TAB command is used.
3022 `verilog-indent-begin-after-if' (default t)
3023 Non-nil means to indent begin statements following a preceding
3024 if, else, while, for and repeat statements, if any. Otherwise,
3025 the begin is lined up with the preceding token. If t, you get:
3026 if (a)
3027 begin // amount of indent based on `verilog-cexp-indent'
3028 otherwise you get:
3029 if (a)
3030 begin
3031 `verilog-auto-endcomments' (default t)
3032 Non-nil means a comment /* ... */ is set after the ends which ends
3033 cases, tasks, functions and modules.
3034 The type and name of the object will be set between the braces.
3035 `verilog-minimum-comment-distance' (default 10)
3036 Minimum distance (in lines) between begin and end required before a comment
3037 will be inserted. Setting this variable to zero results in every
3038 end acquiring a comment; the default avoids too many redundant
3039 comments in tight quarters.
3040 `verilog-auto-lineup' (default 'declarations)
3041 List of contexts where auto lineup of code should be done.
3042
3043 Variables controlling other actions:
3044
3045 `verilog-linter' (default surelint)
3046 Unix program to call to run the lint checker. This is the default
3047 command for \\[compile-command] and \\[verilog-auto-save-compile].
3048
3049 See \\[customize] for the complete list of variables.
3050
3051 AUTO expansion functions are, in part:
3052
3053 \\[verilog-auto] Expand AUTO statements.
3054 \\[verilog-delete-auto] Remove the AUTOs.
3055 \\[verilog-inject-auto] Insert AUTOs for the first time.
3056
3057 Some other functions are:
3058
3059 \\[verilog-complete-word] Complete word with appropriate possibilities.
3060 \\[verilog-mark-defun] Mark function.
3061 \\[verilog-beg-of-defun] Move to beginning of current function.
3062 \\[verilog-end-of-defun] Move to end of current function.
3063 \\[verilog-label-be] Label matching begin ... end, fork ... join, etc statements.
3064
3065 \\[verilog-comment-region] Put marked area in a comment.
3066 \\[verilog-uncomment-region] Uncomment an area commented with \\[verilog-comment-region].
3067 \\[verilog-insert-block] Insert begin ... end.
3068 \\[verilog-star-comment] Insert /* ... */.
3069
3070 \\[verilog-sk-always] Insert an always @(AS) begin .. end block.
3071 \\[verilog-sk-begin] Insert a begin .. end block.
3072 \\[verilog-sk-case] Insert a case block, prompting for details.
3073 \\[verilog-sk-for] Insert a for (...) begin .. end block, prompting for details.
3074 \\[verilog-sk-generate] Insert a generate .. endgenerate block.
3075 \\[verilog-sk-header] Insert a header block at the top of file.
3076 \\[verilog-sk-initial] Insert an initial begin .. end block.
3077 \\[verilog-sk-fork] Insert a fork begin .. end .. join block.
3078 \\[verilog-sk-module] Insert a module .. (/*AUTOARG*/);.. endmodule block.
3079 \\[verilog-sk-primitive] Insert a primitive .. (.. );.. endprimitive block.
3080 \\[verilog-sk-repeat] Insert a repeat (..) begin .. end block.
3081 \\[verilog-sk-specify] Insert a specify .. endspecify block.
3082 \\[verilog-sk-task] Insert a task .. begin .. end endtask block.
3083 \\[verilog-sk-while] Insert a while (...) begin .. end block, prompting for details.
3084 \\[verilog-sk-casex] Insert a casex (...) item: begin.. end endcase block, prompting for details.
3085 \\[verilog-sk-casez] Insert a casez (...) item: begin.. end endcase block, prompting for details.
3086 \\[verilog-sk-if] Insert an if (..) begin .. end block.
3087 \\[verilog-sk-else-if] Insert an else if (..) begin .. end block.
3088 \\[verilog-sk-comment] Insert a comment block.
3089 \\[verilog-sk-assign] Insert an assign .. = ..; statement.
3090 \\[verilog-sk-function] Insert a function .. begin .. end endfunction block.
3091 \\[verilog-sk-input] Insert an input declaration, prompting for details.
3092 \\[verilog-sk-output] Insert an output declaration, prompting for details.
3093 \\[verilog-sk-state-machine] Insert a state machine definition, prompting for details.
3094 \\[verilog-sk-inout] Insert an inout declaration, prompting for details.
3095 \\[verilog-sk-wire] Insert a wire declaration, prompting for details.
3096 \\[verilog-sk-reg] Insert a register declaration, prompting for details.
3097 \\[verilog-sk-define-signal] Define signal under point as a register at the top of the module.
3098
3099 All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
3100 Key bindings specific to `verilog-mode-map' are:
3101
3102 \\{verilog-mode-map}"
3103 :abbrev-table verilog-mode-abbrev-table
3104 (set (make-local-variable 'beginning-of-defun-function)
3105 'verilog-beg-of-defun)
3106 (set (make-local-variable 'end-of-defun-function)
3107 'verilog-end-of-defun)
3108 (set-syntax-table verilog-mode-syntax-table)
3109 (set (make-local-variable 'indent-line-function)
3110 #'verilog-indent-line-relative)
3111 (setq comment-indent-function 'verilog-comment-indent)
3112 (set (make-local-variable 'parse-sexp-ignore-comments) nil)
3113
3114 (set (make-local-variable 'comment-start) "// ")
3115 (set (make-local-variable 'comment-end) "")
3116 (set (make-local-variable 'comment-start-skip) "/\\*+ *\\|// *")
3117 (set (make-local-variable 'comment-multi-line) nil)
3118 ;; Set up for compilation
3119 (setq verilog-which-tool 1)
3120 (setq verilog-tool 'verilog-linter)
3121 (verilog-set-compile-command)
3122 (when (boundp 'hack-local-variables-hook) ;; Also modify any file-local-variables
3123 (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
3124
3125 ;; Setting up menus
3126 (when (featurep 'xemacs)
3127 (easy-menu-add verilog-stmt-menu)
3128 (easy-menu-add verilog-menu)
3129 (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
3130
3131 ;; Stuff for GNU Emacs
3132 (set (make-local-variable 'font-lock-defaults)
3133 `((verilog-font-lock-keywords verilog-font-lock-keywords-1
3134 verilog-font-lock-keywords-2
3135 verilog-font-lock-keywords-3)
3136 nil nil nil
3137 ,(if (functionp 'syntax-ppss)
3138 ;; verilog-beg-of-defun uses syntax-ppss, and syntax-ppss uses
3139 ;; font-lock-beginning-of-syntax-function, so
3140 ;; font-lock-beginning-of-syntax-function, can't use
3141 ;; verilog-beg-of-defun.
3142 nil
3143 'verilog-beg-of-defun)))
3144 ;;------------------------------------------------------------
3145 ;; now hook in 'verilog-highlight-include-files (eldo-mode.el&spice-mode.el)
3146 ;; all buffer local:
3147 (unless noninteractive ;; Else can't see the result, and change hooks are slow
3148 (when (featurep 'xemacs)
3149 (make-local-hook 'font-lock-mode-hook)
3150 (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
3151 (make-local-hook 'after-change-functions))
3152 (add-hook 'font-lock-mode-hook 'verilog-highlight-buffer t t)
3153 (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-highlight-buffer t t) ; not in Emacs
3154 (add-hook 'after-change-functions 'verilog-highlight-region t t))
3155
3156 ;; Tell imenu how to handle Verilog.
3157 (set (make-local-variable 'imenu-generic-expression)
3158 verilog-imenu-generic-expression)
3159 ;; Tell which-func-modes that imenu knows about verilog
3160 (when (boundp 'which-function-modes)
3161 (add-to-list 'which-func-modes 'verilog-mode))
3162 ;; hideshow support
3163 (when (boundp 'hs-special-modes-alist)
3164 (unless (assq 'verilog-mode hs-special-modes-alist)
3165 (setq hs-special-modes-alist
3166 (cons '(verilog-mode-mode "\\<begin\\>" "\\<end\\>" nil
3167 verilog-forward-sexp-function)
3168 hs-special-modes-alist))))
3169
3170 ;; Stuff for autos
3171 (add-hook 'write-contents-hooks 'verilog-auto-save-check nil 'local))
3172 \f
3173
3174 ;;
3175 ;; Electric functions
3176 ;;
3177 (defun electric-verilog-terminate-line (&optional arg)
3178 "Terminate line and indent next line.
3179 With optional ARG, remove existing end of line comments."
3180 (interactive)
3181 ;; before that see if we are in a comment
3182 (let ((state (save-excursion (verilog-syntax-ppss))))
3183 (cond
3184 ((nth 7 state) ; Inside // comment
3185 (if (eolp)
3186 (progn
3187 (delete-horizontal-space)
3188 (newline))
3189 (progn
3190 (newline)
3191 (insert "// ")
3192 (beginning-of-line)))
3193 (verilog-indent-line))
3194 ((nth 4 state) ; Inside any comment (hence /**/)
3195 (newline)
3196 (verilog-more-comment))
3197 ((eolp)
3198 ;; First, check if current line should be indented
3199 (if (save-excursion
3200 (delete-horizontal-space)
3201 (beginning-of-line)
3202 (skip-chars-forward " \t")
3203 (if (looking-at verilog-auto-end-comment-lines-re)
3204 (let ((indent-str (verilog-indent-line)))
3205 ;; Maybe we should set some endcomments
3206 (if verilog-auto-endcomments
3207 (verilog-set-auto-endcomments indent-str arg))
3208 (end-of-line)
3209 (delete-horizontal-space)
3210 (if arg
3211 ()
3212 (newline))
3213 nil)
3214 (progn
3215 (end-of-line)
3216 (delete-horizontal-space)
3217 't)))
3218 ;; see if we should line up assignments
3219 (progn
3220 (if (or (eq 'all verilog-auto-lineup)
3221 (eq 'assignments verilog-auto-lineup))
3222 (verilog-pretty-expr t "\\(<\\|:\\)?=" ))
3223 (newline))
3224 (forward-line 1))
3225 ;; Indent next line
3226 (if verilog-auto-indent-on-newline
3227 (verilog-indent-line)))
3228 (t
3229 (newline)))))
3230
3231 (defun electric-verilog-terminate-and-indent ()
3232 "Insert a newline and indent for the next statement."
3233 (interactive)
3234 (electric-verilog-terminate-line 1))
3235
3236 (defun electric-verilog-semi ()
3237 "Insert `;' character and reindent the line."
3238 (interactive)
3239 (verilog-insert-last-command-event)
3240
3241 (if (or (verilog-in-comment-or-string-p)
3242 (verilog-in-escaped-name-p))
3243 ()
3244 (save-excursion
3245 (beginning-of-line)
3246 (verilog-forward-ws&directives)
3247 (verilog-indent-line))
3248 (if (and verilog-auto-newline
3249 (not (verilog-parenthesis-depth)))
3250 (electric-verilog-terminate-line))))
3251
3252 (defun electric-verilog-semi-with-comment ()
3253 "Insert `;' character, reindent the line and indent for comment."
3254 (interactive)
3255 (insert "\;")
3256 (save-excursion
3257 (beginning-of-line)
3258 (verilog-indent-line))
3259 (indent-for-comment))
3260
3261 (defun electric-verilog-colon ()
3262 "Insert `:' and do all indentations except line indent on this line."
3263 (interactive)
3264 (verilog-insert-last-command-event)
3265 ;; Do nothing if within string.
3266 (if (or
3267 (verilog-within-string)
3268 (not (verilog-in-case-region-p)))
3269 ()
3270 (save-excursion
3271 (let ((p (point))
3272 (lim (progn (verilog-beg-of-statement) (point))))
3273 (goto-char p)
3274 (verilog-backward-case-item lim)
3275 (verilog-indent-line)))
3276 ;; (let ((verilog-tab-always-indent nil))
3277 ;; (verilog-indent-line))
3278 ))
3279
3280 ;;(defun electric-verilog-equal ()
3281 ;; "Insert `=', and do indentation if within block."
3282 ;; (interactive)
3283 ;; (verilog-insert-last-command-event)
3284 ;; Could auto line up expressions, but not yet
3285 ;; (if (eq (car (verilog-calculate-indent)) 'block)
3286 ;; (let ((verilog-tab-always-indent nil))
3287 ;; (verilog-indent-command)))
3288 ;; )
3289
3290 (defun electric-verilog-tick ()
3291 "Insert back-tick, and indent to column 0 if this is a CPP directive."
3292 (interactive)
3293 (verilog-insert-last-command-event)
3294 (save-excursion
3295 (if (verilog-in-directive-p)
3296 (verilog-indent-line))))
3297
3298 (defun electric-verilog-tab ()
3299 "Function called when TAB is pressed in Verilog mode."
3300 (interactive)
3301 ;; If verilog-tab-always-indent, indent the beginning of the line.
3302 (cond
3303 ;; The region is active, indent it.
3304 ((and (region-active-p)
3305 (not (eq (region-beginning) (region-end))))
3306 (indent-region (region-beginning) (region-end) nil))
3307 ((or verilog-tab-always-indent
3308 (save-excursion
3309 (skip-chars-backward " \t")
3310 (bolp)))
3311 (let* ((oldpnt (point))
3312 (boi-point
3313 (save-excursion
3314 (beginning-of-line)
3315 (skip-chars-forward " \t")
3316 (verilog-indent-line)
3317 (back-to-indentation)
3318 (point))))
3319 (if (< (point) boi-point)
3320 (back-to-indentation)
3321 (cond ((not verilog-tab-to-comment))
3322 ((not (eolp))
3323 (end-of-line))
3324 (t
3325 (indent-for-comment)
3326 (when (and (eolp) (= oldpnt (point)))
3327 ; kill existing comment
3328 (beginning-of-line)
3329 (re-search-forward comment-start-skip oldpnt 'move)
3330 (goto-char (match-beginning 0))
3331 (skip-chars-backward " \t")
3332 (kill-region (point) oldpnt)))))))
3333 (t (progn (insert "\t")))))
3334
3335 \f
3336
3337 ;;
3338 ;; Interactive functions
3339 ;;
3340
3341 (defun verilog-indent-buffer ()
3342 "Indent-region the entire buffer as Verilog code.
3343 To call this from the command line, see \\[verilog-batch-indent]."
3344 (interactive)
3345 (verilog-mode)
3346 (indent-region (point-min) (point-max) nil))
3347
3348 (defun verilog-insert-block ()
3349 "Insert Verilog begin ... end; block in the code with right indentation."
3350 (interactive)
3351 (verilog-indent-line)
3352 (insert "begin")
3353 (electric-verilog-terminate-line)
3354 (save-excursion
3355 (electric-verilog-terminate-line)
3356 (insert "end")
3357 (beginning-of-line)
3358 (verilog-indent-line)))
3359
3360 (defun verilog-star-comment ()
3361 "Insert Verilog star comment at point."
3362 (interactive)
3363 (verilog-indent-line)
3364 (insert "/*")
3365 (save-excursion
3366 (newline)
3367 (insert " */"))
3368 (newline)
3369 (insert " * "))
3370
3371 (defun verilog-insert-1 (fmt max)
3372 "Use format string FMT to insert integers 0 to MAX - 1.
3373 Inserts one integer per line, at the current column. Stops early
3374 if it reaches the end of the buffer."
3375 (let ((col (current-column))
3376 (n 0))
3377 (save-excursion
3378 (while (< n max)
3379 (insert (format fmt n))
3380 (forward-line 1)
3381 ;; Note that this function does not bother to check for lines
3382 ;; shorter than col.
3383 (if (eobp)
3384 (setq n max)
3385 (setq n (1+ n))
3386 (move-to-column col))))))
3387
3388 (defun verilog-insert-indices (max)
3389 "Insert a set of indices into a rectangle.
3390 The upper left corner is defined by point. Indices begin with 0
3391 and extend to the MAX - 1. If no prefix arg is given, the user
3392 is prompted for a value. The indices are surrounded by square
3393 brackets \[]. For example, the following code with the point
3394 located after the first 'a' gives:
3395
3396 a = b a[ 0] = b
3397 a = b a[ 1] = b
3398 a = b a[ 2] = b
3399 a = b a[ 3] = b
3400 a = b ==> insert-indices ==> a[ 4] = b
3401 a = b a[ 5] = b
3402 a = b a[ 6] = b
3403 a = b a[ 7] = b
3404 a = b a[ 8] = b"
3405
3406 (interactive "NMAX: ")
3407 (verilog-insert-1 "[%3d]" max))
3408
3409 (defun verilog-generate-numbers (max)
3410 "Insert a set of generated numbers into a rectangle.
3411 The upper left corner is defined by point. The numbers are padded to three
3412 digits, starting with 000 and extending to (MAX - 1). If no prefix argument
3413 is supplied, then the user is prompted for the MAX number. Consider the
3414 following code fragment:
3415
3416 buf buf buf buf000
3417 buf buf buf buf001
3418 buf buf buf buf002
3419 buf buf buf buf003
3420 buf buf ==> generate-numbers ==> buf buf004
3421 buf buf buf buf005
3422 buf buf buf buf006
3423 buf buf buf buf007
3424 buf buf buf buf008"
3425
3426 (interactive "NMAX: ")
3427 (verilog-insert-1 "%3.3d" max))
3428
3429 (defun verilog-mark-defun ()
3430 "Mark the current Verilog function (or procedure).
3431 This puts the mark at the end, and point at the beginning."
3432 (interactive)
3433 (if (featurep 'xemacs)
3434 (progn
3435 (push-mark (point))
3436 (verilog-end-of-defun)
3437 (push-mark (point))
3438 (verilog-beg-of-defun)
3439 (if (fboundp 'zmacs-activate-region)
3440 (zmacs-activate-region)))
3441 (mark-defun)))
3442
3443 (defun verilog-comment-region (start end)
3444 ; checkdoc-params: (start end)
3445 "Put the region into a Verilog comment.
3446 The comments that are in this area are \"deformed\":
3447 `*)' becomes `!(*' and `}' becomes `!{'.
3448 These deformed comments are returned to normal if you use
3449 \\[verilog-uncomment-region] to undo the commenting.
3450
3451 The commented area starts with `verilog-exclude-str-start', and ends with
3452 `verilog-exclude-str-end'. But if you change these variables,
3453 \\[verilog-uncomment-region] won't recognize the comments."
3454 (interactive "r")
3455 (save-excursion
3456 ;; Insert start and endcomments
3457 (goto-char end)
3458 (if (and (save-excursion (skip-chars-forward " \t") (eolp))
3459 (not (save-excursion (skip-chars-backward " \t") (bolp))))
3460 (forward-line 1)
3461 (beginning-of-line))
3462 (insert verilog-exclude-str-end)
3463 (setq end (point))
3464 (newline)
3465 (goto-char start)
3466 (beginning-of-line)
3467 (insert verilog-exclude-str-start)
3468 (newline)
3469 ;; Replace end-comments within commented area
3470 (goto-char end)
3471 (save-excursion
3472 (while (re-search-backward "\\*/" start t)
3473 (replace-match "*-/" t t)))
3474 (save-excursion
3475 (let ((s+1 (1+ start)))
3476 (while (re-search-backward "/\\*" s+1 t)
3477 (replace-match "/-*" t t))))))
3478
3479 (defun verilog-uncomment-region ()
3480 "Uncomment a commented area; change deformed comments back to normal.
3481 This command does nothing if the pointer is not in a commented
3482 area. See also `verilog-comment-region'."
3483 (interactive)
3484 (save-excursion
3485 (let ((start (point))
3486 (end (point)))
3487 ;; Find the boundaries of the comment
3488 (save-excursion
3489 (setq start (progn (search-backward verilog-exclude-str-start nil t)
3490 (point)))
3491 (setq end (progn (search-forward verilog-exclude-str-end nil t)
3492 (point))))
3493 ;; Check if we're really inside a comment
3494 (if (or (equal start (point)) (<= end (point)))
3495 (message "Not standing within commented area.")
3496 (progn
3497 ;; Remove endcomment
3498 (goto-char end)
3499 (beginning-of-line)
3500 (let ((pos (point)))
3501 (end-of-line)
3502 (delete-region pos (1+ (point))))
3503 ;; Change comments back to normal
3504 (save-excursion
3505 (while (re-search-backward "\\*-/" start t)
3506 (replace-match "*/" t t)))
3507 (save-excursion
3508 (while (re-search-backward "/-\\*" start t)
3509 (replace-match "/*" t t)))
3510 ;; Remove start comment
3511 (goto-char start)
3512 (beginning-of-line)
3513 (let ((pos (point)))
3514 (end-of-line)
3515 (delete-region pos (1+ (point)))))))))
3516
3517 (defun verilog-beg-of-defun ()
3518 "Move backward to the beginning of the current function or procedure."
3519 (interactive)
3520 (verilog-re-search-backward verilog-defun-re nil 'move))
3521
3522 (defun verilog-end-of-defun ()
3523 "Move forward to the end of the current function or procedure."
3524 (interactive)
3525 (verilog-re-search-forward verilog-end-defun-re nil 'move))
3526
3527 (defun verilog-get-beg-of-defun (&optional warn)
3528 (save-excursion
3529 (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
3530 (point))
3531 (t
3532 (error "%s: Can't find module beginning" (verilog-point-text))
3533 (point-max)))))
3534 (defun verilog-get-end-of-defun (&optional warn)
3535 (save-excursion
3536 (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
3537 (point))
3538 (t
3539 (error "%s: Can't find endmodule" (verilog-point-text))
3540 (point-max)))))
3541
3542 (defun verilog-label-be (&optional arg)
3543 "Label matching begin ... end, fork ... join and case ... endcase statements.
3544 With ARG, first kill any existing labels."
3545 (interactive)
3546 (let ((cnt 0)
3547 (oldpos (point))
3548 (b (progn
3549 (verilog-beg-of-defun)
3550 (point-marker)))
3551 (e (progn
3552 (verilog-end-of-defun)
3553 (point-marker))))
3554 (goto-char (marker-position b))
3555 (if (> (- e b) 200)
3556 (message "Relabeling module..."))
3557 (while (and
3558 (> (marker-position e) (point))
3559 (verilog-re-search-forward
3560 (concat
3561 "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
3562 "\\|\\(`endif\\)\\|\\(`else\\)")
3563 nil 'move))
3564 (goto-char (match-beginning 0))
3565 (let ((indent-str (verilog-indent-line)))
3566 (verilog-set-auto-endcomments indent-str 't)
3567 (end-of-line)
3568 (delete-horizontal-space))
3569 (setq cnt (1+ cnt))
3570 (if (= 9 (% cnt 10))
3571 (message "%d..." cnt)))
3572 (goto-char oldpos)
3573 (if (or
3574 (> (- e b) 200)
3575 (> cnt 20))
3576 (message "%d lines auto commented" cnt))))
3577
3578 (defun verilog-beg-of-statement ()
3579 "Move backward to beginning of statement."
3580 (interactive)
3581 ;; Move back token by token until we see the end
3582 ;; of some ealier line.
3583 (let (h)
3584 (while
3585 ;; If the current point does not begin a new
3586 ;; statement, as in the character ahead of us is a ';', or SOF
3587 ;; or the string after us unambiguously starts a statement,
3588 ;; or the token before us unambiguously ends a statement,
3589 ;; then move back a token and test again.
3590 (not (or
3591 ;; stop if beginning of buffer
3592 (bolp)
3593 ;; stop if we find a ;
3594 (= (preceding-char) ?\;)
3595 ;; stop if we see a named coverpoint
3596 (looking-at "\\w+\\W*:\\W*\\(coverpoint\\|cross\\|constraint\\)")
3597 ;; keep going if we are in the middle of a word
3598 (not (or (looking-at "\\<") (forward-word -1)))
3599 ;; stop if we see an assertion (perhaps labled)
3600 (and
3601 (looking-at "\\(\\<\\(assert\\|assume\\|cover\\)\\>\\s-+\\<property\\>\\)\\|\\(\\<assert\\>\\)")
3602 (progn
3603 (setq h (point))
3604 (save-excursion
3605 (verilog-backward-token)
3606 (if (looking-at verilog-label-re)
3607 (setq h (point))))
3608 (goto-char h)))
3609 ;; stop if we see a complete reg, perhaps an extended one
3610 (and
3611 (looking-at verilog-complete-reg)
3612 (let* ((p (point)))
3613 (while (and (looking-at verilog-extended-complete-re)
3614 (progn (setq p (point))
3615 (verilog-backward-token)
3616 (/= p (point)))))
3617 (goto-char p)))
3618 ;; stop if we see a complete reg (previous found extended ones)
3619 (looking-at verilog-basic-complete-re)
3620 ;; stop if previous token is an ender
3621 (save-excursion
3622 (verilog-backward-token)
3623 (or
3624 (looking-at verilog-end-block-re)
3625 (looking-at verilog-preprocessor-re))))) ;; end of test
3626 (verilog-backward-syntactic-ws)
3627 (verilog-backward-token))
3628 ;; Now point is where the previous line ended.
3629 (verilog-forward-syntactic-ws)))
3630
3631 (defun verilog-beg-of-statement-1 ()
3632 "Move backward to beginning of statement."
3633 (interactive)
3634 (if (verilog-in-comment-p)
3635 (verilog-backward-syntactic-ws))
3636 (let ((pt (point)))
3637 (catch 'done
3638 (while (not (looking-at verilog-complete-reg))
3639 (setq pt (point))
3640 (verilog-backward-syntactic-ws)
3641 (if (or (bolp)
3642 (= (preceding-char) ?\;)
3643 (save-excursion
3644 (verilog-backward-token)
3645 (looking-at verilog-ends-re)))
3646 (progn
3647 (goto-char pt)
3648 (throw 'done t))
3649 (verilog-backward-token))))
3650 (verilog-forward-syntactic-ws)))
3651 ;
3652 ; (while (and
3653 ; (not (looking-at verilog-complete-reg))
3654 ; (not (bolp))
3655 ; (not (= (preceding-char) ?\;)))
3656 ; (verilog-backward-token)
3657 ; (verilog-backward-syntactic-ws)
3658 ; (setq pt (point)))
3659 ; (goto-char pt)
3660 ; ;(verilog-forward-syntactic-ws)
3661
3662 (defun verilog-end-of-statement ()
3663 "Move forward to end of current statement."
3664 (interactive)
3665 (let ((nest 0) pos)
3666 (cond
3667 ((verilog-in-directive-p)
3668 (forward-line 1)
3669 (backward-char 1))
3670
3671 ((looking-at verilog-beg-block-re)
3672 (verilog-forward-sexp))
3673
3674 ((equal (char-after) ?\})
3675 (forward-char))
3676
3677 ;; Skip to end of statement
3678 ((condition-case nil
3679 (setq pos
3680 (catch 'found
3681 (while t
3682 (forward-sexp 1)
3683 (verilog-skip-forward-comment-or-string)
3684 (if (eolp)
3685 (forward-line 1))
3686 (cond ((looking-at "[ \t]*;")
3687 (skip-chars-forward "^;")
3688 (forward-char 1)
3689 (throw 'found (point)))
3690 ((save-excursion
3691 (forward-sexp -1)
3692 (looking-at verilog-beg-block-re))
3693 (goto-char (match-beginning 0))
3694 (throw 'found nil))
3695 ((looking-at "[ \t]*)")
3696 (throw 'found (point)))
3697 ((eobp)
3698 (throw 'found (point)))
3699 )))
3700
3701 )
3702 (error nil))
3703 (if (not pos)
3704 ;; Skip a whole block
3705 (catch 'found
3706 (while t
3707 (verilog-re-search-forward verilog-end-statement-re nil 'move)
3708 (setq nest (if (match-end 1)
3709 (1+ nest)
3710 (1- nest)))
3711 (cond ((eobp)
3712 (throw 'found (point)))
3713 ((= 0 nest)
3714 (throw 'found (verilog-end-of-statement))))))
3715 pos)))))
3716
3717 (defun verilog-in-case-region-p ()
3718 "Return true if in a case region.
3719 More specifically, point @ in the line foo : @ begin"
3720 (interactive)
3721 (save-excursion
3722 (if (and
3723 (progn (verilog-forward-syntactic-ws)
3724 (looking-at "\\<begin\\>"))
3725 (progn (verilog-backward-syntactic-ws)
3726 (= (preceding-char) ?\:)))
3727 (catch 'found
3728 (let ((nest 1))
3729 (while t
3730 (verilog-re-search-backward
3731 (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
3732 "\\(\\<endcase\\>\\)\\>")
3733 nil 'move)
3734 (cond
3735 ((match-end 3)
3736 (setq nest (1+ nest)))
3737 ((match-end 2)
3738 (if (= nest 1)
3739 (throw 'found 1))
3740 (setq nest (1- nest)))
3741 (t
3742 (throw 'found (= nest 0)))))))
3743 nil)))
3744 (defun verilog-backward-up-list (arg)
3745 "Like backward-up-list, but deal with comments."
3746 (let (saved-psic parse-sexp-ignore-comments)
3747 (setq parse-sexp-ignore-comments 1)
3748 (backward-up-list arg)
3749 (setq parse-sexp-ignore-comments saved-psic)
3750 ))
3751
3752 (defun verilog-in-struct-region-p ()
3753 "Return true if in a struct region.
3754 More specifically, in a list after a struct|union keyword."
3755 (interactive)
3756 (save-excursion
3757 (let* ((state (verilog-syntax-ppss))
3758 (depth (nth 0 state)))
3759 (if depth
3760 (progn (verilog-backward-up-list depth)
3761 (verilog-beg-of-statement)
3762 (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>"))))))
3763
3764 (defun verilog-in-generate-region-p ()
3765 "Return true if in a generate region.
3766 More specifically, after a generate and before an endgenerate."
3767 (interactive)
3768 (let ((nest 1))
3769 (save-excursion
3770 (catch 'done
3771 (while (and
3772 (/= nest 0)
3773 (verilog-re-search-backward
3774 "\\<\\(module\\)\\|\\(generate\\)\\|\\(endgenerate\\)\\>" nil 'move)
3775 (cond
3776 ((match-end 1) ; module - we have crawled out
3777 (throw 'done 1))
3778 ((match-end 2) ; generate
3779 (setq nest (1- nest)))
3780 ((match-end 3) ; endgenerate
3781 (setq nest (1+ nest))))))))
3782 (= nest 0) )) ; return nest
3783
3784 (defun verilog-in-fork-region-p ()
3785 "Return true if between a fork and join."
3786 (interactive)
3787 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
3788 (nest 1))
3789 (save-excursion
3790 (while (and
3791 (/= nest 0)
3792 (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
3793 (cond
3794 ((match-end 1) ; fork
3795 (setq nest (1- nest)))
3796 ((match-end 2) ; join
3797 (setq nest (1+ nest)))))))
3798 (= nest 0) )) ; return nest
3799
3800 (defun verilog-backward-case-item (lim)
3801 "Skip backward to nearest enclosing case item.
3802 Limit search to point LIM."
3803 (interactive)
3804 (let ((str 'nil)
3805 (lim1
3806 (progn
3807 (save-excursion
3808 (verilog-re-search-backward verilog-endcomment-reason-re
3809 lim 'move)
3810 (point)))))
3811 ;; Try to find the real :
3812 (if (save-excursion (search-backward ":" lim1 t))
3813 (let ((colon 0)
3814 b e )
3815 (while
3816 (and
3817 (< colon 1)
3818 (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
3819 lim1 'move))
3820 (cond
3821 ((match-end 1) ;; [
3822 (setq colon (1+ colon))
3823 (if (>= colon 0)
3824 (error "%s: unbalanced [" (verilog-point-text))))
3825 ((match-end 2) ;; ]
3826 (setq colon (1- colon)))
3827
3828 ((match-end 3) ;; :
3829 (setq colon (1+ colon)))))
3830 ;; Skip back to beginning of case item
3831 (skip-chars-backward "\t ")
3832 (verilog-skip-backward-comment-or-string)
3833 (setq e (point))
3834 (setq b
3835 (progn
3836 (if
3837 (verilog-re-search-backward
3838 "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
3839 (progn
3840 (cond
3841 ((match-end 1)
3842 (goto-char (match-end 1))
3843 (verilog-forward-ws&directives)
3844 (if (looking-at "(")
3845 (progn
3846 (forward-sexp)
3847 (verilog-forward-ws&directives)))
3848 (point))
3849 (t
3850 (goto-char (match-end 0))
3851 (verilog-forward-ws&directives)
3852 (point))))
3853 (error "Malformed case item"))))
3854 (setq str (buffer-substring b e))
3855 (if
3856 (setq e
3857 (string-match
3858 "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3859 (setq str (concat (substring str 0 e) "...")))
3860 str)
3861 'nil)))
3862 \f
3863
3864 ;;
3865 ;; Other functions
3866 ;;
3867
3868 (defun verilog-kill-existing-comment ()
3869 "Kill auto comment on this line."
3870 (save-excursion
3871 (let* (
3872 (e (progn
3873 (end-of-line)
3874 (point)))
3875 (b (progn
3876 (beginning-of-line)
3877 (search-forward "//" e t))))
3878 (if b
3879 (delete-region (- b 2) e)))))
3880
3881 (defconst verilog-directive-nest-re
3882 (concat "\\(`else\\>\\)\\|"
3883 "\\(`endif\\>\\)\\|"
3884 "\\(`if\\>\\)\\|"
3885 "\\(`ifdef\\>\\)\\|"
3886 "\\(`ifndef\\>\\)\\|"
3887 "\\(`elsif\\>\\)"))
3888 (defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
3889 "Add ending comment with given INDENT-STR.
3890 With KILL-EXISTING-COMMENT, remove what was there before.
3891 Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
3892 Insert `// case expr ' if this line ends a case block.
3893 Insert `// ifdef FOO ' if this line ends code conditional on FOO.
3894 Insert `// NAME ' if this line ends a function, task, module,
3895 primitive or interface named NAME."
3896 (save-excursion
3897 (cond
3898 (; Comment close preprocessor directives
3899 (and
3900 (looking-at "\\(`endif\\)\\|\\(`else\\)")
3901 (or kill-existing-comment
3902 (not (save-excursion
3903 (end-of-line)
3904 (search-backward "//" (point-at-bol) t)))))
3905 (let ((nest 1) b e
3906 m
3907 (else (if (match-end 2) "!" " ")))
3908 (end-of-line)
3909 (if kill-existing-comment
3910 (verilog-kill-existing-comment))
3911 (delete-horizontal-space)
3912 (save-excursion
3913 (backward-sexp 1)
3914 (while (and (/= nest 0)
3915 (verilog-re-search-backward verilog-directive-nest-re nil 'move))
3916 (cond
3917 ((match-end 1) ; `else
3918 (if (= nest 1)
3919 (setq else "!")))
3920 ((match-end 2) ; `endif
3921 (setq nest (1+ nest)))
3922 ((match-end 3) ; `if
3923 (setq nest (1- nest)))
3924 ((match-end 4) ; `ifdef
3925 (setq nest (1- nest)))
3926 ((match-end 5) ; `ifndef
3927 (setq nest (1- nest)))
3928 ((match-end 6) ; `elsif
3929 (if (= nest 1)
3930 (progn
3931 (setq else "!")
3932 (setq nest 0))))))
3933 (if (match-end 0)
3934 (setq
3935 m (buffer-substring
3936 (match-beginning 0)
3937 (match-end 0))
3938 b (progn
3939 (skip-chars-forward "^ \t")
3940 (verilog-forward-syntactic-ws)
3941 (point))
3942 e (progn
3943 (skip-chars-forward "a-zA-Z0-9_")
3944 (point)))))
3945 (if b
3946 (if (> (count-lines (point) b) verilog-minimum-comment-distance)
3947 (insert (concat " // " else m " " (buffer-substring b e))))
3948 (progn
3949 (insert " // unmatched `else, `elsif or `endif")
3950 (ding 't)))))
3951
3952 (; Comment close case/class/function/task/module and named block
3953 (and (looking-at "\\<end")
3954 (or kill-existing-comment
3955 (not (save-excursion
3956 (end-of-line)
3957 (search-backward "//" (point-at-bol) t)))))
3958 (let ((type (car indent-str)))
3959 (unless (eq type 'declaration)
3960 (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
3961 (if (looking-at verilog-end-block-ordered-re)
3962 (cond
3963 (;- This is a case block; search back for the start of this case
3964 (match-end 1) ;; of verilog-end-block-ordered-re
3965
3966 (let ((err 't)
3967 (str "UNMATCHED!!"))
3968 (save-excursion
3969 (verilog-leap-to-head)
3970 (cond
3971 ((looking-at "\\<randcase\\>")
3972 (setq str "randcase")
3973 (setq err nil))
3974 ((looking-at "\\(\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?\\)")
3975 (goto-char (match-end 0))
3976 (setq str (concat (match-string 0) " " (verilog-get-expr)))
3977 (setq err nil))
3978 ))
3979 (end-of-line)
3980 (if kill-existing-comment
3981 (verilog-kill-existing-comment))
3982 (delete-horizontal-space)
3983 (insert (concat " // " str ))
3984 (if err (ding 't))))
3985
3986 (;- This is a begin..end block
3987 (match-end 2) ;; of verilog-end-block-ordered-re
3988 (let ((str " // UNMATCHED !!")
3989 (err 't)
3990 (here (point))
3991 there
3992 cntx)
3993 (save-excursion
3994 (verilog-leap-to-head)
3995 (setq there (point))
3996 (if (not (match-end 0))
3997 (progn
3998 (goto-char here)
3999 (end-of-line)
4000 (if kill-existing-comment
4001 (verilog-kill-existing-comment))
4002 (delete-horizontal-space)
4003 (insert str)
4004 (ding 't))
4005 (let ((lim
4006 (save-excursion (verilog-beg-of-defun) (point)))
4007 (here (point)))
4008 (cond
4009 (;-- handle named block differently
4010 (looking-at verilog-named-block-re)
4011 (search-forward ":")
4012 (setq there (point))
4013 (setq str (verilog-get-expr))
4014 (setq err nil)
4015 (setq str (concat " // block: " str )))
4016
4017 ((verilog-in-case-region-p) ;-- handle case item differently
4018 (goto-char here)
4019 (setq str (verilog-backward-case-item lim))
4020 (setq there (point))
4021 (setq err nil)
4022 (setq str (concat " // case: " str )))
4023
4024 (;- try to find "reason" for this begin
4025 (cond
4026 (;
4027 (eq here (progn
4028 ;; (verilog-backward-token)
4029 (verilog-beg-of-statement)
4030 (point)))
4031 (setq err nil)
4032 (setq str ""))
4033 ((looking-at verilog-endcomment-reason-re)
4034 (setq there (match-end 0))
4035 (setq cntx (concat (match-string 0) " "))
4036 (cond
4037 (;- begin
4038 (match-end 1)
4039 (setq err nil)
4040 (save-excursion
4041 (if (and (verilog-continued-line)
4042 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
4043 (progn
4044 (goto-char (match-end 0))
4045 (setq there (point))
4046 (setq str
4047 (concat " // " (match-string 0) " " (verilog-get-expr))))
4048 (setq str ""))))
4049
4050 (;- else
4051 (match-end 2)
4052 (let ((nest 0)
4053 ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
4054 (catch 'skip
4055 (while (verilog-re-search-backward reg nil 'move)
4056 (cond
4057 ((match-end 1) ; begin
4058 (setq nest (1- nest)))
4059 ((match-end 2) ; end
4060 (setq nest (1+ nest)))
4061 ((match-end 3)
4062 (if (= 0 nest)
4063 (progn
4064 (goto-char (match-end 0))
4065 (setq there (point))
4066 (setq err nil)
4067 (setq str (verilog-get-expr))
4068 (setq str (concat " // else: !if" str ))
4069 (throw 'skip 1))))
4070 ((match-end 4)
4071 (if (= 0 nest)
4072 (progn
4073 (goto-char (match-end 0))
4074 (setq there (point))
4075 (setq err nil)
4076 (setq str (verilog-get-expr))
4077 (setq str (concat " // else: !assert " str ))
4078 (throw 'skip 1)))))))))
4079 (;- end else
4080 (match-end 3)
4081 (goto-char there)
4082 (let ((nest 0)
4083 (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)\\|\\(assert\\)"))
4084 (catch 'skip
4085 (while (verilog-re-search-backward reg nil 'move)
4086 (cond
4087 ((match-end 1) ; begin
4088 (setq nest (1- nest)))
4089 ((match-end 2) ; end
4090 (setq nest (1+ nest)))
4091 ((match-end 3)
4092 (if (= 0 nest)
4093 (progn
4094 (goto-char (match-end 0))
4095 (setq there (point))
4096 (setq err nil)
4097 (setq str (verilog-get-expr))
4098 (setq str (concat " // else: !if" str ))
4099 (throw 'skip 1))))
4100 ((match-end 4)
4101 (if (= 0 nest)
4102 (progn
4103 (goto-char (match-end 0))
4104 (setq there (point))
4105 (setq err nil)
4106 (setq str (verilog-get-expr))
4107 (setq str (concat " // else: !assert " str ))
4108 (throw 'skip 1)))))))))
4109
4110 (; always_comb, always_ff, always_latch
4111 (or (match-end 4) (match-end 5) (match-end 6))
4112 (goto-char (match-end 0))
4113 (setq there (point))
4114 (setq err nil)
4115 (setq str (concat " // " cntx )))
4116
4117 (;- task/function/initial et cetera
4118 t
4119 (match-end 0)
4120 (goto-char (match-end 0))
4121 (setq there (point))
4122 (setq err nil)
4123 (setq str (concat " // " cntx (verilog-get-expr))))
4124
4125 (;-- otherwise...
4126 (setq str " // auto-endcomment confused "))))
4127
4128 ((and
4129 (verilog-in-case-region-p) ;-- handle case item differently
4130 (progn
4131 (setq there (point))
4132 (goto-char here)
4133 (setq str (verilog-backward-case-item lim))))
4134 (setq err nil)
4135 (setq str (concat " // case: " str )))
4136
4137 ((verilog-in-fork-region-p)
4138 (setq err nil)
4139 (setq str " // fork branch" ))
4140
4141 ((looking-at "\\<end\\>")
4142 ;; HERE
4143 (forward-word 1)
4144 (verilog-forward-syntactic-ws)
4145 (setq err nil)
4146 (setq str (verilog-get-expr))
4147 (setq str (concat " // " cntx str )))
4148
4149 ))))
4150 (goto-char here)
4151 (end-of-line)
4152 (if kill-existing-comment
4153 (verilog-kill-existing-comment))
4154 (delete-horizontal-space)
4155 (if (or err
4156 (> (count-lines here there) verilog-minimum-comment-distance))
4157 (insert str))
4158 (if err (ding 't))
4159 ))))
4160 (;- this is endclass, which can be nested
4161 (match-end 11) ;; of verilog-end-block-ordered-re
4162 ;;(goto-char there)
4163 (let ((nest 0)
4164 (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
4165 string)
4166 (save-excursion
4167 (catch 'skip
4168 (while (verilog-re-search-backward reg nil 'move)
4169 (cond
4170 ((match-end 3) ; endclass
4171 (ding 't)
4172 (setq string "unmatched endclass")
4173 (throw 'skip 1))
4174
4175 ((match-end 2) ; endclass
4176 (setq nest (1+ nest)))
4177
4178 ((match-end 1) ; class
4179 (setq nest (1- nest))
4180 (if (< nest 0)
4181 (progn
4182 (goto-char (match-end 0))
4183 (let (b e)
4184 (setq b (progn
4185 (skip-chars-forward "^ \t")
4186 (verilog-forward-ws&directives)
4187 (point))
4188 e (progn
4189 (skip-chars-forward "a-zA-Z0-9_")
4190 (point)))
4191 (setq string (buffer-substring b e)))
4192 (throw 'skip 1))))
4193 ))))
4194 (end-of-line)
4195 (insert (concat " // " string ))))
4196
4197 (;- this is end{function,generate,task,module,primitive,table,generate}
4198 ;- which can not be nested.
4199 t
4200 (let (string reg (name-re nil))
4201 (end-of-line)
4202 (if kill-existing-comment
4203 (save-match-data
4204 (verilog-kill-existing-comment)))
4205 (delete-horizontal-space)
4206 (backward-sexp)
4207 (cond
4208 ((match-end 5) ;; of verilog-end-block-ordered-re
4209 (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
4210 (setq name-re "\\w+\\s-*(")
4211 )
4212 ((match-end 6) ;; of verilog-end-block-ordered-re
4213 (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
4214 ((match-end 7) ;; of verilog-end-block-ordered-re
4215 (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
4216 ((match-end 8) ;; of verilog-end-block-ordered-re
4217 (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4218 ((match-end 9) ;; of verilog-end-block-ordered-re
4219 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
4220 ((match-end 10) ;; of verilog-end-block-ordered-re
4221 (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4222 ((match-end 11) ;; of verilog-end-block-ordered-re
4223 (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4224 ((match-end 12) ;; of verilog-end-block-ordered-re
4225 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4226 ((match-end 13) ;; of verilog-end-block-ordered-re
4227 (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4228 ((match-end 14) ;; of verilog-end-block-ordered-re
4229 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
4230 ((match-end 15) ;; of verilog-end-block-ordered-re
4231 (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
4232
4233 (t (error "Problem in verilog-set-auto-endcomments")))
4234 (let (b e)
4235 (save-excursion
4236 (verilog-re-search-backward reg nil 'move)
4237 (cond
4238 ((match-end 1)
4239 (setq b (progn
4240 (skip-chars-forward "^ \t")
4241 (verilog-forward-ws&directives)
4242 (if (looking-at "static\\|automatic")
4243 (progn
4244 (goto-char (match-end 0))
4245 (verilog-forward-ws&directives)))
4246 (if (and name-re (verilog-re-search-forward name-re nil 'move))
4247 (progn
4248 (goto-char (match-beginning 0))
4249 (verilog-forward-ws&directives)))
4250 (point))
4251 e (progn
4252 (skip-chars-forward "a-zA-Z0-9_")
4253 (point)))
4254 (setq string (buffer-substring b e)))
4255 (t
4256 (ding 't)
4257 (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
4258 (end-of-line)
4259 (insert (concat " // " string )))
4260 ))))))))))
4261
4262 (defun verilog-get-expr()
4263 "Grab expression at point, e.g, case ( a | b & (c ^d))."
4264 (let* ((b (progn
4265 (verilog-forward-syntactic-ws)
4266 (skip-chars-forward " \t")
4267 (point)))
4268 (e (let ((par 1))
4269 (cond
4270 ((looking-at "@")
4271 (forward-char 1)
4272 (verilog-forward-syntactic-ws)
4273 (if (looking-at "(")
4274 (progn
4275 (forward-char 1)
4276 (while (and (/= par 0)
4277 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4278 (cond
4279 ((match-end 1)
4280 (setq par (1+ par)))
4281 ((match-end 2)
4282 (setq par (1- par)))))))
4283 (point))
4284 ((looking-at "(")
4285 (forward-char 1)
4286 (while (and (/= par 0)
4287 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
4288 (cond
4289 ((match-end 1)
4290 (setq par (1+ par)))
4291 ((match-end 2)
4292 (setq par (1- par)))))
4293 (point))
4294 ((looking-at "\\[")
4295 (forward-char 1)
4296 (while (and (/= par 0)
4297 (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
4298 (cond
4299 ((match-end 1)
4300 (setq par (1+ par)))
4301 ((match-end 2)
4302 (setq par (1- par)))))
4303 (verilog-forward-syntactic-ws)
4304 (skip-chars-forward "^ \t\n\f")
4305 (point))
4306 ((looking-at "/[/\\*]")
4307 b)
4308 ('t
4309 (skip-chars-forward "^: \t\n\f")
4310 (point)))))
4311 (str (buffer-substring b e)))
4312 (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
4313 (setq str (concat (substring str 0 e) "...")))
4314 str))
4315
4316 (defun verilog-expand-vector ()
4317 "Take a signal vector on the current line and expand it to multiple lines.
4318 Useful for creating tri's and other expanded fields."
4319 (interactive)
4320 (verilog-expand-vector-internal "[" "]"))
4321
4322 (defun verilog-expand-vector-internal (bra ket)
4323 "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
4324 (save-excursion
4325 (forward-line 0)
4326 (let ((signal-string (buffer-substring (point)
4327 (progn
4328 (end-of-line) (point)))))
4329 (if (string-match
4330 (concat "\\(.*\\)"
4331 (regexp-quote bra)
4332 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
4333 (regexp-quote ket)
4334 "\\(.*\\)$") signal-string)
4335 (let* ((sig-head (match-string 1 signal-string))
4336 (vec-start (string-to-number (match-string 2 signal-string)))
4337 (vec-end (if (= (match-beginning 3) (match-end 3))
4338 vec-start
4339 (string-to-number
4340 (substring signal-string (1+ (match-beginning 3))
4341 (match-end 3)))))
4342 (vec-range
4343 (if (= (match-beginning 4) (match-end 4))
4344 1
4345 (string-to-number
4346 (substring signal-string (+ 2 (match-beginning 4))
4347 (match-end 4)))))
4348 (sig-tail (match-string 5 signal-string))
4349 vec)
4350 ;; Decode vectors
4351 (setq vec nil)
4352 (if (< vec-range 0)
4353 (let ((tmp vec-start))
4354 (setq vec-start vec-end
4355 vec-end tmp
4356 vec-range (- vec-range))))
4357 (if (< vec-end vec-start)
4358 (while (<= vec-end vec-start)
4359 (setq vec (append vec (list vec-start)))
4360 (setq vec-start (- vec-start vec-range)))
4361 (while (<= vec-start vec-end)
4362 (setq vec (append vec (list vec-start)))
4363 (setq vec-start (+ vec-start vec-range))))
4364 ;;
4365 ;; Delete current line
4366 (delete-region (point) (progn (forward-line 0) (point)))
4367 ;;
4368 ;; Expand vector
4369 (while vec
4370 (insert (concat sig-head bra
4371 (int-to-string (car vec)) ket sig-tail "\n"))
4372 (setq vec (cdr vec)))
4373 (delete-char -1)
4374 ;;
4375 )))))
4376
4377 (defun verilog-strip-comments ()
4378 "Strip all comments from the Verilog code."
4379 (interactive)
4380 (goto-char (point-min))
4381 (while (re-search-forward "//" nil t)
4382 (if (verilog-within-string)
4383 (re-search-forward "\"" nil t)
4384 (if (verilog-in-star-comment-p)
4385 (re-search-forward "\*/" nil t)
4386 (let ((bpt (- (point) 2)))
4387 (end-of-line)
4388 (delete-region bpt (point))))))
4389 ;;
4390 (goto-char (point-min))
4391 (while (re-search-forward "/\\*" nil t)
4392 (if (verilog-within-string)
4393 (re-search-forward "\"" nil t)
4394 (let ((bpt (- (point) 2)))
4395 (re-search-forward "\\*/")
4396 (delete-region bpt (point))))))
4397
4398 (defun verilog-one-line ()
4399 "Convert structural Verilog instances to occupy one line."
4400 (interactive)
4401 (goto-char (point-min))
4402 (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
4403 (replace-match "\\1 " nil nil)))
4404
4405 (defun verilog-linter-name ()
4406 "Return name of linter, either surelint or verilint."
4407 (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4408 compile-command))
4409 (lint-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
4410 verilog-linter)))
4411 (cond ((equal compile-word1 "surelint") `surelint)
4412 ((equal compile-word1 "verilint") `verilint)
4413 ((equal lint-word1 "surelint") `surelint)
4414 ((equal lint-word1 "verilint") `verilint)
4415 (t `surelint)))) ;; back compatibility
4416
4417 (defun verilog-lint-off ()
4418 "Convert a Verilog linter warning line into a disable statement.
4419 For example:
4420 pci_bfm_null.v, line 46: Unused input: pci_rst_
4421 becomes a comment for the appropriate tool.
4422
4423 The first word of the `compile-command' or `verilog-linter'
4424 variables is used to determine which product is being used.
4425
4426 See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
4427 (interactive)
4428 (let ((linter (verilog-linter-name)))
4429 (cond ((equal linter `surelint)
4430 (verilog-surelint-off))
4431 ((equal linter `verilint)
4432 (verilog-verilint-off))
4433 (t (error "Linter name not set")))))
4434
4435 (defvar compilation-last-buffer)
4436 (defvar next-error-last-buffer)
4437
4438 (defun verilog-surelint-off ()
4439 "Convert a SureLint warning line into a disable statement.
4440 Run from Verilog source window; assumes there is a *compile* buffer
4441 with point set appropriately.
4442
4443 For example:
4444 WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
4445 becomes:
4446 // surefire lint_line_off UDDONX"
4447 (interactive)
4448 (let ((buff (if (boundp 'next-error-last-buffer)
4449 next-error-last-buffer
4450 compilation-last-buffer)))
4451 (when (buffer-live-p buff)
4452 ;; FIXME with-current-buffer?
4453 (save-excursion
4454 (switch-to-buffer buff)
4455 (beginning-of-line)
4456 (when
4457 (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
4458 (let* ((code (match-string 2))
4459 (file (match-string 3))
4460 (line (match-string 4))
4461 (buffer (get-file-buffer file))
4462 dir filename)
4463 (unless buffer
4464 (progn
4465 (setq buffer
4466 (and (file-exists-p file)
4467 (find-file-noselect file)))
4468 (or buffer
4469 (let* ((pop-up-windows t))
4470 (let ((name (expand-file-name
4471 (read-file-name
4472 (format "Find this error in: (default %s) "
4473 file)
4474 dir file t))))
4475 (if (file-directory-p name)
4476 (setq name (expand-file-name filename name)))
4477 (setq buffer
4478 (and (file-exists-p name)
4479 (find-file-noselect name))))))))
4480 (switch-to-buffer buffer)
4481 (goto-char (point-min))
4482 (forward-line (- (string-to-number line)))
4483 (end-of-line)
4484 (catch 'already
4485 (cond
4486 ((verilog-in-slash-comment-p)
4487 (re-search-backward "//")
4488 (cond
4489 ((looking-at "// surefire lint_off_line ")
4490 (goto-char (match-end 0))
4491 (let ((lim (point-at-eol)))
4492 (if (re-search-forward code lim 'move)
4493 (throw 'already t)
4494 (insert (concat " " code)))))
4495 (t
4496 )))
4497 ((verilog-in-star-comment-p)
4498 (re-search-backward "/\*")
4499 (insert (format " // surefire lint_off_line %6s" code )))
4500 (t
4501 (insert (format " // surefire lint_off_line %6s" code ))
4502 )))))))))
4503
4504 (defun verilog-verilint-off ()
4505 "Convert a Verilint warning line into a disable statement.
4506
4507 For example:
4508 (W240) pci_bfm_null.v, line 46: Unused input: pci_rst_
4509 becomes:
4510 //Verilint 240 off // WARNING: Unused input"
4511 (interactive)
4512 (save-excursion
4513 (beginning-of-line)
4514 (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
4515 (replace-match (format
4516 ;; %3s makes numbers 1-999 line up nicely
4517 "\\1//Verilint %3s off // WARNING: \\3"
4518 (match-string 2)))
4519 (beginning-of-line)
4520 (verilog-indent-line))))
4521
4522 (defun verilog-auto-save-compile ()
4523 "Update automatics with \\[verilog-auto], save the buffer, and compile."
4524 (interactive)
4525 (verilog-auto) ; Always do it for safety
4526 (save-buffer)
4527 (compile compile-command))
4528
4529 (defun verilog-preprocess (&optional command filename)
4530 "Preprocess the buffer, similar to `compile', but leave output in Verilog-Mode.
4531 Takes optional COMMAND or defaults to `verilog-preprocessor', and
4532 FILENAME or defaults to `buffer-file-name`."
4533 (interactive
4534 (list
4535 (let ((default (verilog-expand-command verilog-preprocessor)))
4536 (set (make-local-variable `verilog-preprocessor)
4537 (read-from-minibuffer "Run Preprocessor (like this): "
4538 default nil nil
4539 'verilog-preprocess-history default)))))
4540 (unless command (setq command (verilog-expand-command verilog-preprocessor)))
4541 (let* ((fontlocked (and (boundp 'font-lock-mode) font-lock-mode))
4542 (dir (file-name-directory (or filename buffer-file-name)))
4543 (file (file-name-nondirectory (or filename buffer-file-name)))
4544 (cmd (concat "cd " dir "; " command " " file)))
4545 (with-output-to-temp-buffer "*Verilog-Preprocessed*"
4546 (with-current-buffer (get-buffer "*Verilog-Preprocessed*")
4547 (insert (concat "// " cmd "\n"))
4548 (shell-command cmd "*Verilog-Preprocessed*")
4549 (verilog-mode)
4550 ;; Without this force, it takes a few idle seconds
4551 ;; to get the color, which is very jarring
4552 (when fontlocked (font-lock-fontify-buffer))))))
4553 \f
4554
4555 ;;
4556 ;; Batch
4557 ;;
4558
4559 (defmacro verilog-batch-error-wrapper (&rest body)
4560 "Execute BODY and add error prefix to any errors found.
4561 This lets programs calling batch mode to easily extract error messages."
4562 `(condition-case err
4563 (progn ,@body)
4564 (error
4565 (error "%%Error: %s%s" (error-message-string err)
4566 (if (featurep 'xemacs) "\n" ""))))) ;; XEmacs forgets to add a newline
4567
4568 (defun verilog-batch-execute-func (funref)
4569 "Internal processing of a batch command, running FUNREF on all command arguments."
4570 (verilog-batch-error-wrapper
4571 ;; Setting global variables like that is *VERY NASTY* !!! --Stef
4572 ;; However, this function is called only when Emacs is being used as
4573 ;; a standalone language instead of as an editor, so we'll live.
4574 ;;
4575 ;; General globals needed
4576 (setq make-backup-files nil)
4577 (setq-default make-backup-files nil)
4578 (setq enable-local-variables t)
4579 (setq enable-local-eval t)
4580 ;; Make sure any sub-files we read get proper mode
4581 (setq-default major-mode 'verilog-mode)
4582 ;; Ditto files already read in
4583 (mapc (lambda (buf)
4584 (when (buffer-file-name buf)
4585 (with-current-buffer buf
4586 (verilog-mode))))
4587 (buffer-list))
4588 ;; Process the files
4589 (mapcar '(lambda (buf)
4590 (when (buffer-file-name buf)
4591 (save-excursion
4592 (if (not (file-exists-p (buffer-file-name buf)))
4593 (error
4594 (concat "File not found: " (buffer-file-name buf))))
4595 (message (concat "Processing " (buffer-file-name buf)))
4596 (set-buffer buf)
4597 (funcall funref)
4598 (save-buffer))))
4599 (buffer-list))))
4600
4601 (defun verilog-batch-auto ()
4602 "For use with --batch, perform automatic expansions as a stand-alone tool.
4603 This sets up the appropriate Verilog mode environment, updates automatics
4604 with \\[verilog-auto] on all command-line files, and saves the buffers.
4605 For proper results, multiple filenames need to be passed on the command
4606 line in bottom-up order."
4607 (unless noninteractive
4608 (error "Use verilog-batch-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4609 (verilog-batch-execute-func `verilog-auto))
4610
4611 (defun verilog-batch-delete-auto ()
4612 "For use with --batch, perform automatic deletion as a stand-alone tool.
4613 This sets up the appropriate Verilog mode environment, deletes automatics
4614 with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
4615 (unless noninteractive
4616 (error "Use verilog-batch-delete-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4617 (verilog-batch-execute-func `verilog-delete-auto))
4618
4619 (defun verilog-batch-inject-auto ()
4620 "For use with --batch, perform automatic injection as a stand-alone tool.
4621 This sets up the appropriate Verilog mode environment, injects new automatics
4622 with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
4623 For proper results, multiple filenames need to be passed on the command
4624 line in bottom-up order."
4625 (unless noninteractive
4626 (error "Use verilog-batch-inject-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
4627 (verilog-batch-execute-func `verilog-inject-auto))
4628
4629 (defun verilog-batch-indent ()
4630 "For use with --batch, reindent an a entire file as a stand-alone tool.
4631 This sets up the appropriate Verilog mode environment, calls
4632 \\[verilog-indent-buffer] on all command-line files, and saves the buffers."
4633 (unless noninteractive
4634 (error "Use verilog-batch-indent only with --batch")) ;; Otherwise we'd mess up buffer modes
4635 (verilog-batch-execute-func `verilog-indent-buffer))
4636 \f
4637
4638 ;;
4639 ;; Indentation
4640 ;;
4641 (defconst verilog-indent-alist
4642 '((block . (+ ind verilog-indent-level))
4643 (case . (+ ind verilog-case-indent))
4644 (cparenexp . (+ ind verilog-indent-level))
4645 (cexp . (+ ind verilog-cexp-indent))
4646 (defun . verilog-indent-level-module)
4647 (declaration . verilog-indent-level-declaration)
4648 (directive . (verilog-calculate-indent-directive))
4649 (tf . verilog-indent-level)
4650 (behavioral . (+ verilog-indent-level-behavioral verilog-indent-level-module))
4651 (statement . ind)
4652 (cpp . 0)
4653 (comment . (verilog-comment-indent))
4654 (unknown . 3)
4655 (string . 0)))
4656
4657 (defun verilog-continued-line-1 (lim)
4658 "Return true if this is a continued line.
4659 Set point to where line starts. Limit search to point LIM."
4660 (let ((continued 't))
4661 (if (eq 0 (forward-line -1))
4662 (progn
4663 (end-of-line)
4664 (verilog-backward-ws&directives lim)
4665 (if (bobp)
4666 (setq continued nil)
4667 (setq continued (verilog-backward-token))))
4668 (setq continued nil))
4669 continued))
4670
4671 (defun verilog-calculate-indent ()
4672 "Calculate the indent of the current Verilog line.
4673 Examine previous lines. Once a line is found that is definitive as to the
4674 type of the current line, return that lines' indent level and its type.
4675 Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
4676 (save-excursion
4677 (let* ((starting_position (point))
4678 (par 0)
4679 (begin (looking-at "[ \t]*begin\\>"))
4680 (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
4681 (type (catch 'nesting
4682 ;; Keep working backwards until we can figure out
4683 ;; what type of statement this is.
4684 ;; Basically we need to figure out
4685 ;; 1) if this is a continuation of the previous line;
4686 ;; 2) are we in a block scope (begin..end)
4687
4688 ;; if we are in a comment, done.
4689 (if (verilog-in-star-comment-p)
4690 (throw 'nesting 'comment))
4691
4692 ;; if we have a directive, done.
4693 (if (save-excursion (beginning-of-line)
4694 (and (looking-at verilog-directive-re-1)
4695 (not (or (looking-at "[ \t]*`ovm_")
4696 (looking-at "[ \t]*`vmm_")))))
4697 (throw 'nesting 'directive))
4698 ;; indent structs as if there were module level
4699 (if (verilog-in-struct-p)
4700 (throw 'nesting 'block))
4701
4702 ;; unless we are in the newfangled coverpoint or constraint blocks
4703 ;; if we are in a parenthesized list, and the user likes to indent these, return.
4704 (if (and
4705 verilog-indent-lists
4706 (verilog-in-paren)
4707 (not (verilog-in-coverage-p))
4708 )
4709 (progn (setq par 1)
4710 (throw 'nesting 'block)))
4711
4712 ;; See if we are continuing a previous line
4713 (while t
4714 ;; trap out if we crawl off the top of the buffer
4715 (if (bobp) (throw 'nesting 'cpp))
4716
4717 (if (verilog-continued-line-1 lim)
4718 (let ((sp (point)))
4719 (if (and
4720 (not (looking-at verilog-complete-reg))
4721 (verilog-continued-line-1 lim))
4722 (progn (goto-char sp)
4723 (throw 'nesting 'cexp))
4724
4725 (goto-char sp))
4726
4727 (if (and begin
4728 (not verilog-indent-begin-after-if)
4729 (looking-at verilog-no-indent-begin-re))
4730 (progn
4731 (beginning-of-line)
4732 (skip-chars-forward " \t")
4733 (throw 'nesting 'statement))
4734 (progn
4735 (throw 'nesting 'cexp))))
4736 ;; not a continued line
4737 (goto-char starting_position))
4738
4739 (if (looking-at "\\<else\\>")
4740 ;; search back for governing if, striding across begin..end pairs
4741 ;; appropriately
4742 (let ((elsec 1))
4743 (while (verilog-re-search-backward verilog-ends-re nil 'move)
4744 (cond
4745 ((match-end 1) ; else, we're in deep
4746 (setq elsec (1+ elsec)))
4747 ((match-end 2) ; if
4748 (setq elsec (1- elsec))
4749 (if (= 0 elsec)
4750 (if verilog-align-ifelse
4751 (throw 'nesting 'statement)
4752 (progn ;; back up to first word on this line
4753 (beginning-of-line)
4754 (verilog-forward-syntactic-ws)
4755 (throw 'nesting 'statement)))))
4756 ((match-end 3) ; assert block
4757 (setq elsec (1- elsec))
4758 (verilog-beg-of-statement) ;; doesn't get to beginning
4759 (if (looking-at verilog-property-re)
4760 (throw 'nesting 'statement) ; We don't need an endproperty for these
4761 (throw 'nesting 'block) ;We still need a endproperty
4762 ))
4763 (t ; endblock
4764 ; try to leap back to matching outward block by striding across
4765 ; indent level changing tokens then immediately
4766 ; previous line governs indentation.
4767 (let (( reg) (nest 1))
4768 ;; verilog-ends => else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
4769 (cond
4770 ((match-end 4) ; end
4771 ;; Search back for matching begin
4772 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
4773 ((match-end 5) ; endcase
4774 ;; Search back for matching case
4775 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4776 ((match-end 6) ; endfunction
4777 ;; Search back for matching function
4778 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4779 ((match-end 7) ; endtask
4780 ;; Search back for matching task
4781 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
4782 ((match-end 8) ; endspecify
4783 ;; Search back for matching specify
4784 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4785 ((match-end 9) ; endtable
4786 ;; Search back for matching table
4787 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4788 ((match-end 10) ; endgenerate
4789 ;; Search back for matching generate
4790 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4791 ((match-end 11) ; joins
4792 ;; Search back for matching fork
4793 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
4794 ((match-end 12) ; class
4795 ;; Search back for matching class
4796 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4797 ((match-end 13) ; covergroup
4798 ;; Search back for matching covergroup
4799 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
4800 (catch 'skip
4801 (while (verilog-re-search-backward reg nil 'move)
4802 (cond
4803 ((match-end 1) ; begin
4804 (setq nest (1- nest))
4805 (if (= 0 nest)
4806 (throw 'skip 1)))
4807 ((match-end 2) ; end
4808 (setq nest (1+ nest)))))
4809 )))))))
4810 (throw 'nesting (verilog-calc-1)))
4811 );; catch nesting
4812 );; type
4813 )
4814 ;; Return type of block and indent level.
4815 (if (not type)
4816 (setq type 'cpp))
4817 (if (> par 0) ; Unclosed Parenthesis
4818 (list 'cparenexp par)
4819 (cond
4820 ((eq type 'case)
4821 (list type (verilog-case-indent-level)))
4822 ((eq type 'statement)
4823 (list type (current-column)))
4824 ((eq type 'defun)
4825 (list type 0))
4826 (t
4827 (list type (verilog-current-indent-level))))))))
4828
4829 (defun verilog-wai ()
4830 "Show matching nesting block for debugging."
4831 (interactive)
4832 (save-excursion
4833 (let* ((type (verilog-calc-1))
4834 depth)
4835 ;; Return type of block and indent level.
4836 (if (not type)
4837 (setq type 'cpp))
4838 (if (and
4839 verilog-indent-lists
4840 (not(or (verilog-in-coverage-p)
4841 (verilog-in-struct-p)))
4842 (verilog-in-paren))
4843 (setq depth 1)
4844 (cond
4845 ((eq type 'case)
4846 (setq depth (verilog-case-indent-level)))
4847 ((eq type 'statement)
4848 (setq depth (current-column)))
4849 ((eq type 'defun)
4850 (setq depth 0))
4851 (t
4852 (setq depth (verilog-current-indent-level)))))
4853 (message "You are at nesting %s depth %d" type depth))))
4854
4855 (defun verilog-calc-1 ()
4856 (catch 'nesting
4857 (let ((re (concat "\\({\\|}\\|" verilog-indent-re "\\)")))
4858 (while (verilog-re-search-backward re nil 'move)
4859 (catch 'continue
4860 (cond
4861 ((equal (char-after) ?\{)
4862 (if (verilog-at-constraint-p)
4863 (throw 'nesting 'block)))
4864
4865 ((equal (char-after) ?\})
4866 (let ((there (verilog-at-close-constraint-p)))
4867 (if there ;; we are at the } that closes a constraint. Find the { that opens it
4868 (progn
4869 (forward-char 1)
4870 (backward-list 1)
4871 (verilog-beg-of-statement)))))
4872
4873 ((looking-at verilog-beg-block-re-ordered)
4874 (cond
4875 ((match-end 2) ; *sigh* could be "unique case" or "priority casex"
4876 (let ((here (point)))
4877 (verilog-beg-of-statement)
4878 (if (looking-at verilog-extended-case-re)
4879 (throw 'nesting 'case)
4880 (goto-char here)))
4881 (throw 'nesting 'case))
4882
4883 ((match-end 4) ; *sigh* could be "disable fork"
4884 (let ((here (point)))
4885 (verilog-beg-of-statement)
4886 (if (or (looking-at verilog-disable-fork-re)
4887 (looking-at verilog-fork-wait-re))
4888 t ; this is a normal statement
4889 (progn ; or is fork, starts a new block
4890 (goto-char here)
4891 (throw 'nesting 'block)))))
4892
4893 ((match-end 27) ; *sigh* might be a clocking declaration
4894 (let ((here (point)))
4895 (if (verilog-in-paren)
4896 t ; this is a normal statement
4897 (progn ; or is fork, starts a new block
4898 (goto-char here)
4899 (throw 'nesting 'block)))))
4900
4901 ;; need to consider typedef struct here...
4902 ((looking-at "\\<class\\|struct\\|function\\|task\\>")
4903 ; *sigh* These words have an optional prefix:
4904 ; extern {virtual|protected}? function a();
4905 ; typedef class foo;
4906 ; and we don't want to confuse this with
4907 ; function a();
4908 ; property
4909 ; ...
4910 ; endfunction
4911 (verilog-beg-of-statement)
4912 (if (looking-at verilog-beg-block-re-ordered)
4913 (throw 'nesting 'block)
4914 (throw 'nesting 'defun)))
4915
4916 ((looking-at "\\<property\\>")
4917 ; *sigh*
4918 ; {assert|assume|cover} property (); are complete
4919 ; and could also be labeled: - foo: assert property
4920 ; but
4921 ; property ID () ... needs end_property
4922 (verilog-beg-of-statement)
4923 (if (looking-at verilog-property-re)
4924 (throw 'continue 'statement) ; We don't need an endproperty for these
4925 (throw 'nesting 'block) ;We still need a endproperty
4926 ))
4927
4928 (t (throw 'nesting 'block))))
4929
4930 ((looking-at verilog-end-block-re)
4931 (verilog-leap-to-head)
4932 (if (verilog-in-case-region-p)
4933 (progn
4934 (verilog-leap-to-case-head)
4935 (if (looking-at verilog-extended-case-re)
4936 (throw 'nesting 'case)))))
4937
4938 ((looking-at verilog-defun-level-re)
4939 (if (looking-at verilog-defun-level-generate-only-re)
4940 (if (verilog-in-generate-region-p)
4941 (throw 'continue 'foo) ; always block in a generate - keep looking
4942 (throw 'nesting 'defun))
4943 (throw 'nesting 'defun)))
4944
4945 ((looking-at verilog-cpp-level-re)
4946 (throw 'nesting 'cpp))
4947
4948 ((bobp)
4949 (throw 'nesting 'cpp)))))
4950
4951 (throw 'nesting 'cpp))))
4952
4953 (defun verilog-calculate-indent-directive ()
4954 "Return indentation level for directive.
4955 For speed, the searcher looks at the last directive, not the indent
4956 of the appropriate enclosing block."
4957 (let ((base -1) ;; Indent of the line that determines our indentation
4958 (ind 0)) ;; Relative offset caused by other directives (like `endif on same line as `else)
4959 ;; Start at current location, scan back for another directive
4960
4961 (save-excursion
4962 (beginning-of-line)
4963 (while (and (< base 0)
4964 (verilog-re-search-backward verilog-directive-re nil t))
4965 (cond ((save-excursion (skip-chars-backward " \t") (bolp))
4966 (setq base (current-indentation))))
4967 (cond ((and (looking-at verilog-directive-end) (< base 0)) ;; Only matters when not at BOL
4968 (setq ind (- ind verilog-indent-level-directive)))
4969 ((and (looking-at verilog-directive-middle) (>= base 0)) ;; Only matters when at BOL
4970 (setq ind (+ ind verilog-indent-level-directive)))
4971 ((looking-at verilog-directive-begin)
4972 (setq ind (+ ind verilog-indent-level-directive)))))
4973 ;; Adjust indent to starting indent of critical line
4974 (setq ind (max 0 (+ ind base))))
4975
4976 (save-excursion
4977 (beginning-of-line)
4978 (skip-chars-forward " \t")
4979 (cond ((or (looking-at verilog-directive-middle)
4980 (looking-at verilog-directive-end))
4981 (setq ind (max 0 (- ind verilog-indent-level-directive))))))
4982 ind))
4983
4984 (defun verilog-leap-to-case-head ()
4985 (let ((nest 1))
4986 (while (/= 0 nest)
4987 (verilog-re-search-backward
4988 (concat
4989 "\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?\\<case[xz]?\\>\\)"
4990 "\\|\\(\\<endcase\\>\\)" )
4991 nil 'move)
4992 (cond
4993 ((match-end 1)
4994 (let ((here (point)))
4995 (verilog-beg-of-statement)
4996 (unless (looking-at verilog-extended-case-re)
4997 (goto-char here)))
4998 (setq nest (1- nest)))
4999 ((match-end 3)
5000 (setq nest (1+ nest)))
5001 ((bobp)
5002 (ding 't)
5003 (setq nest 0))))))
5004
5005 (defun verilog-leap-to-head ()
5006 "Move point to the head of this block.
5007 Jump from end to matching begin, from endcase to matching case, and so on."
5008 (let ((reg nil)
5009 snest
5010 (nesting 'yes)
5011 (nest 1))
5012 (cond
5013 ((looking-at "\\<end\\>")
5014 ;; 1: Search back for matching begin
5015 (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
5016 "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
5017 ((looking-at "\\<endtask\\>")
5018 ;; 2: Search back for matching task
5019 (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
5020 (setq nesting 'no))
5021 ((looking-at "\\<endcase\\>")
5022 (catch 'nesting
5023 (verilog-leap-to-case-head) )
5024 (setq reg nil) ; to force skip
5025 )
5026
5027 ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
5028 ;; 4: Search back for matching fork
5029 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5030 ((looking-at "\\<endclass\\>")
5031 ;; 5: Search back for matching class
5032 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
5033 ((looking-at "\\<endtable\\>")
5034 ;; 6: Search back for matching table
5035 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
5036 ((looking-at "\\<endspecify\\>")
5037 ;; 7: Search back for matching specify
5038 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
5039 ((looking-at "\\<endfunction\\>")
5040 ;; 8: Search back for matching function
5041 (setq reg "\\(\\<function\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<function\\>\\)")
5042 (setq nesting 'no))
5043 ;;(setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
5044 ((looking-at "\\<endgenerate\\>")
5045 ;; 8: Search back for matching generate
5046 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
5047 ((looking-at "\\<endgroup\\>")
5048 ;; 10: Search back for matching covergroup
5049 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
5050 ((looking-at "\\<endproperty\\>")
5051 ;; 11: Search back for matching property
5052 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
5053 ((looking-at verilog-ovm-end-re)
5054 ;; 12: Search back for matching sequence
5055 (setq reg (concat "\\(" verilog-ovm-begin-re "\\|" verilog-ovm-end-re "\\)")))
5056 ((looking-at verilog-vmm-end-re)
5057 ;; 12: Search back for matching sequence
5058 (setq reg (concat "\\(" verilog-vmm-begin-re "\\|" verilog-vmm-end-re "\\)")))
5059 ((looking-at "\\<endinterface\\>")
5060 ;; 12: Search back for matching interface
5061 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
5062 ((looking-at "\\<endsequence\\>")
5063 ;; 12: Search back for matching sequence
5064 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
5065 ((looking-at "\\<endclocking\\>")
5066 ;; 12: Search back for matching clocking
5067 (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
5068 (if reg
5069 (catch 'skip
5070 (if (eq nesting 'yes)
5071 (let (sreg)
5072 (while (verilog-re-search-backward reg nil 'move)
5073 (cond
5074 ((match-end 1) ; begin
5075 (if (looking-at "fork")
5076 (let ((here (point)))
5077 (verilog-beg-of-statement)
5078 (unless (looking-at verilog-disable-fork-re)
5079 (goto-char here)
5080 (setq nest (1- nest))))
5081 (setq nest (1- nest)))
5082 (if (= 0 nest)
5083 ;; Now previous line describes syntax
5084 (throw 'skip 1))
5085 (if (and snest
5086 (= snest nest))
5087 (setq reg sreg)))
5088 ((match-end 2) ; end
5089 (setq nest (1+ nest)))
5090 ((match-end 3)
5091 ;; endcase, jump to case
5092 (setq snest nest)
5093 (setq nest (1+ nest))
5094 (setq sreg reg)
5095 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
5096 ((match-end 4)
5097 ;; join, jump to fork
5098 (setq snest nest)
5099 (setq nest (1+ nest))
5100 (setq sreg reg)
5101 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
5102 )))
5103 ;no nesting
5104 (if (and
5105 (verilog-re-search-backward reg nil 'move)
5106 (match-end 1)) ; task -> could be virtual and/or protected
5107 (progn
5108 (verilog-beg-of-statement)
5109 (throw 'skip 1))
5110 (throw 'skip 1)))))))
5111
5112 (defun verilog-continued-line ()
5113 "Return true if this is a continued line.
5114 Set point to where line starts."
5115 (let ((continued 't))
5116 (if (eq 0 (forward-line -1))
5117 (progn
5118 (end-of-line)
5119 (verilog-backward-ws&directives)
5120 (if (bobp)
5121 (setq continued nil)
5122 (while (and continued
5123 (save-excursion
5124 (skip-chars-backward " \t")
5125 (not (bolp))))
5126 (setq continued (verilog-backward-token)))))
5127 (setq continued nil))
5128 continued))
5129
5130 (defun verilog-backward-token ()
5131 "Step backward token, returing true if this is a continued line."
5132 (interactive)
5133 (verilog-backward-syntactic-ws)
5134 (cond
5135 ((bolp)
5136 nil)
5137 (;-- Anything ending in a ; is complete
5138 (= (preceding-char) ?\;)
5139 nil)
5140 (; If a "}" is prefixed by a ";", then this is a complete statement
5141 ; i.e.: constraint foo { a = b; }
5142 (= (preceding-char) ?\})
5143 (progn
5144 (backward-char)
5145 (not(verilog-at-close-constraint-p))))
5146 (;-- constraint foo { a = b }
5147 ; is a complete statement. *sigh*
5148 (= (preceding-char) ?\{)
5149 (progn
5150 (backward-char)
5151 (not (verilog-at-constraint-p))))
5152 (;" string "
5153 (= (preceding-char) ?\")
5154 (backward-char)
5155 (verilog-skip-backward-comment-or-string)
5156 nil)
5157
5158 (; [3:4]
5159 (= (preceding-char) ?\])
5160 (backward-char)
5161 (verilog-backward-open-bracket)
5162 t)
5163
5164 (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
5165 ; also could be simply '@(foo)'
5166 ; or foo u1 #(a=8)
5167 ; (b, ... which ISN'T complete
5168 ;;;; Do we need this???
5169 (= (preceding-char) ?\))
5170 (progn
5171 (backward-char)
5172 (verilog-backward-up-list 1)
5173 (verilog-backward-syntactic-ws)
5174 (let ((back (point)))
5175 (forward-word -1)
5176 (cond
5177 ;;XX
5178 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
5179 (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
5180 ((looking-at verilog-ovm-statement-re)
5181 nil)
5182 ((looking-at verilog-ovm-begin-re)
5183 t)
5184 ((looking-at verilog-ovm-end-re)
5185 t)
5186 ;; JBA find VMM macros
5187 ((looking-at verilog-vmm-statement-re)
5188 nil )
5189 ((looking-at verilog-vmm-begin-re)
5190 t)
5191 ((looking-at verilog-vmm-end-re)
5192 nil)
5193 ;; JBA trying to catch macro lines with no ; at end
5194 ((looking-at "\\<`")
5195 nil)
5196 (t
5197 (goto-char back)
5198 (cond
5199 ((= (preceding-char) ?\@)
5200 (backward-char)
5201 (save-excursion
5202 (verilog-backward-token)
5203 (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
5204 ((= (preceding-char) ?\#)
5205 (backward-char))
5206 (t t)))))))
5207
5208 (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
5209 t
5210 (forward-word -1)
5211 (while (= (preceding-char) ?\_)
5212 (forward-word -1))
5213 (cond
5214 ((looking-at "\\<else\\>")
5215 t)
5216 ((looking-at verilog-behavioral-block-beg-re)
5217 t)
5218 ((looking-at verilog-indent-re)
5219 nil)
5220 (t
5221 (let
5222 ((back (point)))
5223 (verilog-backward-syntactic-ws)
5224 (cond
5225 ((= (preceding-char) ?\:)
5226 (backward-char)
5227 (verilog-backward-syntactic-ws)
5228 (backward-sexp)
5229 (if (looking-at verilog-nameable-item-re )
5230 nil
5231 t))
5232 ((= (preceding-char) ?\#)
5233 (backward-char)
5234 t)
5235 ((= (preceding-char) ?\`)
5236 (backward-char)
5237 t)
5238
5239 (t
5240 (goto-char back)
5241 t))))))))
5242
5243 (defun verilog-backward-syntactic-ws ()
5244 (verilog-skip-backward-comments)
5245 (forward-comment (- (buffer-size))))
5246
5247 (defun verilog-forward-syntactic-ws ()
5248 (verilog-skip-forward-comment-p)
5249 (forward-comment (buffer-size)))
5250
5251 (defun verilog-backward-ws&directives (&optional bound)
5252 "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
5253 Optional BOUND limits search."
5254 (save-restriction
5255 (let* ((bound (or bound (point-min)))
5256 (here bound)
5257 (p nil) )
5258 (if (< bound (point))
5259 (progn
5260 (let ((state (save-excursion (verilog-syntax-ppss))))
5261 (cond
5262 ((nth 7 state) ;; in // comment
5263 (verilog-re-search-backward "//" nil 'move)
5264 (skip-chars-backward "/"))
5265 ((nth 4 state) ;; in /* */ comment
5266 (verilog-re-search-backward "/\*" nil 'move))))
5267 (narrow-to-region bound (point))
5268 (while (/= here (point))
5269 (setq here (point))
5270 (verilog-skip-backward-comments)
5271 (setq p
5272 (save-excursion
5273 (beginning-of-line)
5274 (cond
5275 ((and verilog-highlight-translate-off
5276 (verilog-within-translate-off))
5277 (verilog-back-to-start-translate-off (point-min)))
5278 ((looking-at verilog-directive-re-1)
5279 (point))
5280 (t
5281 nil))))
5282 (if p (goto-char p))))))))
5283
5284 (defun verilog-forward-ws&directives (&optional bound)
5285 "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
5286 Optional BOUND limits search."
5287 (save-restriction
5288 (let* ((bound (or bound (point-max)))
5289 (here bound)
5290 jump)
5291 (if (> bound (point))
5292 (progn
5293 (let ((state (save-excursion (verilog-syntax-ppss))))
5294 (cond
5295 ((nth 7 state) ;; in // comment
5296 (end-of-line)
5297 (forward-char 1)
5298 (skip-chars-forward " \t\n\f")
5299 )
5300 ((nth 4 state) ;; in /* */ comment
5301 (verilog-re-search-forward "\*\/\\s-*" nil 'move))))
5302 (narrow-to-region (point) bound)
5303 (while (/= here (point))
5304 (setq here (point)
5305 jump nil)
5306 (forward-comment (buffer-size))
5307 (and (looking-at "\\s-*(\\*.*\\*)\\s-*") ;; Attribute
5308 (goto-char (match-end 0)))
5309 (save-excursion
5310 (beginning-of-line)
5311 (if (looking-at verilog-directive-re-1)
5312 (setq jump t)))
5313 (if jump
5314 (beginning-of-line 2))))))))
5315
5316 (defun verilog-in-comment-p ()
5317 "Return true if in a star or // comment."
5318 (let ((state (save-excursion (verilog-syntax-ppss))))
5319 (or (nth 4 state) (nth 7 state))))
5320
5321 (defun verilog-in-star-comment-p ()
5322 "Return true if in a star comment."
5323 (let ((state (save-excursion (verilog-syntax-ppss))))
5324 (and
5325 (nth 4 state) ; t if in a comment of style a // or b /**/
5326 (not
5327 (nth 7 state) ; t if in a comment of style b /**/
5328 ))))
5329
5330 (defun verilog-in-slash-comment-p ()
5331 "Return true if in a slash comment."
5332 (let ((state (save-excursion (verilog-syntax-ppss))))
5333 (nth 7 state)))
5334
5335 (defun verilog-in-comment-or-string-p ()
5336 "Return true if in a string or comment."
5337 (let ((state (save-excursion (verilog-syntax-ppss))))
5338 (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
5339
5340 (defun verilog-in-attribute-p ()
5341 "Return true if point is in an attribute (* [] attribute *)."
5342 (save-excursion
5343 (verilog-re-search-backward "\\((\\*\\)\\|\\(\\*)\\)" nil 'move)
5344 (numberp (match-beginning 1))))
5345
5346 (defun verilog-in-escaped-name-p ()
5347 "Return true if in an escaped name."
5348 (save-excursion
5349 (backward-char)
5350 (skip-chars-backward "^ \t\n\f")
5351 (if (equal (char-after (point) ) ?\\ )
5352 t
5353 nil)))
5354 (defun verilog-in-directive-p ()
5355 "Return true if in a directive."
5356 (save-excursion
5357 (beginning-of-line)
5358 (looking-at verilog-directive-re-1)))
5359
5360 (defun verilog-in-paren ()
5361 "Return true if in a parenthetical expression."
5362 (let ((state (save-excursion (verilog-syntax-ppss))))
5363 (> (nth 0 state) 0 )))
5364
5365 (defun verilog-in-struct-p ()
5366 "Return true if in a struct declaration."
5367 (interactive)
5368 (save-excursion
5369 (if (verilog-in-paren)
5370 (progn
5371 (verilog-backward-up-list 1)
5372 (verilog-at-struct-p)
5373 )
5374 nil)))
5375
5376 (defun verilog-in-coverage-p ()
5377 "Return true if in a constraint or coverpoint expression."
5378 (interactive)
5379 (save-excursion
5380 (if (verilog-in-paren)
5381 (progn
5382 (verilog-backward-up-list 1)
5383 (verilog-at-constraint-p)
5384 )
5385 nil)))
5386 (defun verilog-at-close-constraint-p ()
5387 "If at the } that closes a constraint or covergroup, return true."
5388 (if (and
5389 (equal (char-after) ?\})
5390 (verilog-in-paren))
5391
5392 (save-excursion
5393 (verilog-backward-ws&directives)
5394 (if (equal (char-before) ?\;)
5395 (point)
5396 nil))))
5397
5398 (defun verilog-at-constraint-p ()
5399 "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
5400 (if (save-excursion
5401 (and
5402 (equal (char-after) ?\{)
5403 (forward-list)
5404 (progn (backward-char 1)
5405 (verilog-backward-ws&directives)
5406 (equal (char-before) ?\;))))
5407 ;; maybe
5408 (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
5409 ;; not
5410 nil))
5411
5412 (defun verilog-at-struct-p ()
5413 "If at the { of a struct, return true, moving point to struct."
5414 (save-excursion
5415 (if (and (equal (char-after) ?\{)
5416 (verilog-backward-token))
5417 (looking-at "\\<struct\\|union\\|packed\\|\\(un\\)?signed\\>")
5418 nil)))
5419
5420 (defun verilog-parenthesis-depth ()
5421 "Return non zero if in parenthetical-expression."
5422 (save-excursion (nth 1 (verilog-syntax-ppss))))
5423
5424
5425 (defun verilog-skip-forward-comment-or-string ()
5426 "Return true if in a string or comment."
5427 (let ((state (save-excursion (verilog-syntax-ppss))))
5428 (cond
5429 ((nth 3 state) ;Inside string
5430 (search-forward "\"")
5431 t)
5432 ((nth 7 state) ;Inside // comment
5433 (forward-line 1)
5434 t)
5435 ((nth 4 state) ;Inside any comment (hence /**/)
5436 (search-forward "*/"))
5437 (t
5438 nil))))
5439
5440 (defun verilog-skip-backward-comment-or-string ()
5441 "Return true if in a string or comment."
5442 (let ((state (save-excursion (verilog-syntax-ppss))))
5443 (cond
5444 ((nth 3 state) ;Inside string
5445 (search-backward "\"")
5446 t)
5447 ((nth 7 state) ;Inside // comment
5448 (search-backward "//")
5449 (skip-chars-backward "/")
5450 t)
5451 ((nth 4 state) ;Inside /* */ comment
5452 (search-backward "/*")
5453 t)
5454 (t
5455 nil))))
5456
5457 (defun verilog-skip-backward-comments ()
5458 "Return true if a comment was skipped."
5459 (let ((more t))
5460 (while more
5461 (setq more
5462 (let ((state (save-excursion (verilog-syntax-ppss))))
5463 (cond
5464 ((nth 7 state) ;Inside // comment
5465 (search-backward "//")
5466 (skip-chars-backward "/")
5467 (skip-chars-backward " \t\n\f")
5468 t)
5469 ((nth 4 state) ;Inside /* */ comment
5470 (search-backward "/*")
5471 (skip-chars-backward " \t\n\f")
5472 t)
5473 ((and (not (bobp))
5474 (= (char-before) ?\/)
5475 (= (char-before (1- (point))) ?\*))
5476 (goto-char (- (point) 2))
5477 t) ;; Let nth 4 state handle the rest
5478 ((and (not (bobp))
5479 (= (char-before) ?\))
5480 (= (char-before (1- (point))) ?\*))
5481 (goto-char (- (point) 2))
5482 (if (search-backward "(*" nil t)
5483 (progn
5484 (skip-chars-backward " \t\n\f")
5485 t)
5486 (progn
5487 (goto-char (+ (point) 2))
5488 nil)))
5489 (t
5490 (/= (skip-chars-backward " \t\n\f") 0))))))))
5491
5492 (defun verilog-skip-forward-comment-p ()
5493 "If in comment, move to end and return true."
5494 (let* (h
5495 (state (save-excursion (verilog-syntax-ppss)))
5496 (skip (cond
5497 ((nth 3 state) ;Inside string
5498 t)
5499 ((nth 7 state) ;Inside // comment
5500 (end-of-line)
5501 (forward-char 1)
5502 t)
5503 ((nth 4 state) ;Inside /* comment
5504 (search-forward "*/")
5505 t)
5506 ((verilog-in-attribute-p) ;Inside (* attribute
5507 (search-forward "*)" nil t)
5508 t)
5509 (t nil))))
5510 (skip-chars-forward " \t\n\f")
5511 (while
5512 (cond
5513 ((looking-at "\\/\\*")
5514 (progn
5515 (setq h (point))
5516 (goto-char (match-end 0))
5517 (if (search-forward "*/" nil t)
5518 (progn
5519 (skip-chars-forward " \t\n\f")
5520 (setq skip 't))
5521 (progn
5522 (goto-char h)
5523 nil))))
5524 ((looking-at "(\\*")
5525 (progn
5526 (setq h (point))
5527 (goto-char (match-end 0))
5528 (if (search-forward "*)" nil t)
5529 (progn
5530 (skip-chars-forward " \t\n\f")
5531 (setq skip 't))
5532 (progn
5533 (goto-char h)
5534 nil))))
5535 (t nil)))
5536 skip))
5537
5538 (defun verilog-indent-line-relative ()
5539 "Cheap version of indent line.
5540 Only look at a few lines to determine indent level."
5541 (interactive)
5542 (let ((indent-str)
5543 (sp (point)))
5544 (if (looking-at "^[ \t]*$")
5545 (cond ;- A blank line; No need to be too smart.
5546 ((bobp)
5547 (setq indent-str (list 'cpp 0)))
5548 ((verilog-continued-line)
5549 (let ((sp1 (point)))
5550 (if (verilog-continued-line)
5551 (progn
5552 (goto-char sp)
5553 (setq indent-str
5554 (list 'statement (verilog-current-indent-level))))
5555 (goto-char sp1)
5556 (setq indent-str (list 'block (verilog-current-indent-level)))))
5557 (goto-char sp))
5558 ((goto-char sp)
5559 (setq indent-str (verilog-calculate-indent))))
5560 (progn (skip-chars-forward " \t")
5561 (setq indent-str (verilog-calculate-indent))))
5562 (verilog-do-indent indent-str)))
5563
5564 (defun verilog-indent-line ()
5565 "Indent for special part of code."
5566 (verilog-do-indent (verilog-calculate-indent)))
5567
5568 (defun verilog-do-indent (indent-str)
5569 (let ((type (car indent-str))
5570 (ind (car (cdr indent-str))))
5571 (cond
5572 (; handle continued exp
5573 (eq type 'cexp)
5574 (let ((here (point)))
5575 (verilog-backward-syntactic-ws)
5576 (cond
5577 ((or
5578 (= (preceding-char) ?\,)
5579 (= (preceding-char) ?\])
5580 (save-excursion
5581 (verilog-beg-of-statement-1)
5582 (looking-at verilog-declaration-re)))
5583 (let* ( fst
5584 (val
5585 (save-excursion
5586 (backward-char 1)
5587 (verilog-beg-of-statement-1)
5588 (setq fst (point))
5589 (if (looking-at verilog-declaration-re)
5590 (progn ;; we have multiple words
5591 (goto-char (match-end 0))
5592 (skip-chars-forward " \t")
5593 (cond
5594 ((and verilog-indent-declaration-macros
5595 (= (following-char) ?\`))
5596 (progn
5597 (forward-char 1)
5598 (forward-word 1)
5599 (skip-chars-forward " \t")))
5600 ((= (following-char) ?\[)
5601 (progn
5602 (forward-char 1)
5603 (verilog-backward-up-list -1)
5604 (skip-chars-forward " \t"))))
5605 (current-column))
5606 (progn
5607 (goto-char fst)
5608 (+ (current-column) verilog-cexp-indent))))))
5609 (goto-char here)
5610 (indent-line-to val)))
5611 ((= (preceding-char) ?\) )
5612 (goto-char here)
5613 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5614 (indent-line-to val)))
5615 (t
5616 (goto-char here)
5617 (let ((val))
5618 (verilog-beg-of-statement-1)
5619 (if (and (< (point) here)
5620 (verilog-re-search-forward "=[ \\t]*" here 'move))
5621 (setq val (current-column))
5622 (setq val (eval (cdr (assoc type verilog-indent-alist)))))
5623 (goto-char here)
5624 (indent-line-to val))))))
5625
5626 (; handle inside parenthetical expressions
5627 (eq type 'cparenexp)
5628 (let* ( here
5629 (val (save-excursion
5630 (verilog-backward-up-list 1)
5631 (forward-char 1)
5632 (if verilog-indent-lists
5633 (skip-chars-forward " \t")
5634 (verilog-forward-syntactic-ws))
5635 (setq here (point))
5636 (current-column)))
5637
5638 (decl (save-excursion
5639 (goto-char here)
5640 (verilog-forward-syntactic-ws)
5641 (setq here (point))
5642 (looking-at verilog-declaration-re))))
5643 (indent-line-to val)
5644 (if decl
5645 (verilog-pretty-declarations))))
5646
5647 (;-- Handle the ends
5648 (or
5649 (looking-at verilog-end-block-re )
5650 (verilog-at-close-constraint-p))
5651 (let ((val (if (eq type 'statement)
5652 (- ind verilog-indent-level)
5653 ind)))
5654 (indent-line-to val)))
5655
5656 (;-- Case -- maybe line 'em up
5657 (and (eq type 'case) (not (looking-at "^[ \t]*$")))
5658 (progn
5659 (cond
5660 ((looking-at "\\<endcase\\>")
5661 (indent-line-to ind))
5662 (t
5663 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5664 (indent-line-to val))))))
5665
5666 (;-- defun
5667 (and (eq type 'defun)
5668 (looking-at verilog-zero-indent-re))
5669 (indent-line-to 0))
5670
5671 (;-- declaration
5672 (and (or
5673 (eq type 'defun)
5674 (eq type 'block))
5675 (looking-at verilog-declaration-re))
5676 (verilog-indent-declaration ind))
5677
5678 (;-- Everything else
5679 t
5680 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
5681 (indent-line-to val))))
5682
5683 (if (looking-at "[ \t]+$")
5684 (skip-chars-forward " \t"))
5685 indent-str ; Return indent data
5686 ))
5687
5688 (defun verilog-current-indent-level ()
5689 "Return the indent-level of the current statement."
5690 (save-excursion
5691 (let (par-pos)
5692 (beginning-of-line)
5693 (setq par-pos (verilog-parenthesis-depth))
5694 (while par-pos
5695 (goto-char par-pos)
5696 (beginning-of-line)
5697 (setq par-pos (verilog-parenthesis-depth)))
5698 (skip-chars-forward " \t")
5699 (current-column))))
5700
5701 (defun verilog-case-indent-level ()
5702 "Return the indent-level of the current statement.
5703 Do not count named blocks or case-statements."
5704 (save-excursion
5705 (skip-chars-forward " \t")
5706 (cond
5707 ((looking-at verilog-named-block-re)
5708 (current-column))
5709 ((and (not (looking-at verilog-extended-case-re))
5710 (looking-at "^[^:;]+[ \t]*:"))
5711 (verilog-re-search-forward ":" nil t)
5712 (skip-chars-forward " \t")
5713 (current-column))
5714 (t
5715 (current-column)))))
5716
5717 (defun verilog-indent-comment ()
5718 "Indent current line as comment."
5719 (let* ((stcol
5720 (cond
5721 ((verilog-in-star-comment-p)
5722 (save-excursion
5723 (re-search-backward "/\\*" nil t)
5724 (1+(current-column))))
5725 (comment-column
5726 comment-column )
5727 (t
5728 (save-excursion
5729 (re-search-backward "//" nil t)
5730 (current-column))))))
5731 (indent-line-to stcol)
5732 stcol))
5733
5734 (defun verilog-more-comment ()
5735 "Make more comment lines like the previous."
5736 (let* ((star 0)
5737 (stcol
5738 (cond
5739 ((verilog-in-star-comment-p)
5740 (save-excursion
5741 (setq star 1)
5742 (re-search-backward "/\\*" nil t)
5743 (1+(current-column))))
5744 (comment-column
5745 comment-column )
5746 (t
5747 (save-excursion
5748 (re-search-backward "//" nil t)
5749 (current-column))))))
5750 (progn
5751 (indent-to stcol)
5752 (if (and star
5753 (save-excursion
5754 (forward-line -1)
5755 (skip-chars-forward " \t")
5756 (looking-at "\*")))
5757 (insert "* ")))))
5758
5759 (defun verilog-comment-indent (&optional arg)
5760 "Return the column number the line should be indented to.
5761 ARG is ignored, for `comment-indent-function' compatibility."
5762 (cond
5763 ((verilog-in-star-comment-p)
5764 (save-excursion
5765 (re-search-backward "/\\*" nil t)
5766 (1+(current-column))))
5767 ( comment-column
5768 comment-column )
5769 (t
5770 (save-excursion
5771 (re-search-backward "//" nil t)
5772 (current-column)))))
5773
5774 ;;
5775
5776 (defun verilog-pretty-declarations (&optional quiet)
5777 "Line up declarations around point.
5778 Be verbose about progress unless optional QUIET set."
5779 (interactive)
5780 (let* ((m1 (make-marker))
5781 (e (point))
5782 el
5783 r
5784 (here (point))
5785 ind
5786 start
5787 startpos
5788 end
5789 endpos
5790 base-ind
5791 )
5792 (save-excursion
5793 (if (progn
5794 ; (verilog-beg-of-statement-1)
5795 (beginning-of-line)
5796 (verilog-forward-syntactic-ws)
5797 (and (not (verilog-in-directive-p)) ;; could have `define input foo
5798 (looking-at verilog-declaration-re)))
5799 (progn
5800 (if (verilog-parenthesis-depth)
5801 ;; in an argument list or parameter block
5802 (setq el (verilog-backward-up-list -1)
5803 start (progn
5804 (goto-char e)
5805 (verilog-backward-up-list 1)
5806 (forward-line) ;; ignore ( input foo,
5807 (verilog-re-search-forward verilog-declaration-re el 'move)
5808 (goto-char (match-beginning 0))
5809 (skip-chars-backward " \t")
5810 (point))
5811 startpos (set-marker (make-marker) start)
5812 end (progn
5813 (goto-char start)
5814 (verilog-backward-up-list -1)
5815 (forward-char -1)
5816 (verilog-backward-syntactic-ws)
5817 (point))
5818 endpos (set-marker (make-marker) end)
5819 base-ind (progn
5820 (goto-char start)
5821 (forward-char 1)
5822 (skip-chars-forward " \t")
5823 (current-column))
5824 )
5825 ;; in a declaration block (not in argument list)
5826 (setq
5827 start (progn
5828 (verilog-beg-of-statement-1)
5829 (while (and (looking-at verilog-declaration-re)
5830 (not (bobp)))
5831 (skip-chars-backward " \t")
5832 (setq e (point))
5833 (beginning-of-line)
5834 (verilog-backward-syntactic-ws)
5835 (backward-char)
5836 (verilog-beg-of-statement-1))
5837 e)
5838 startpos (set-marker (make-marker) start)
5839 end (progn
5840 (goto-char here)
5841 (verilog-end-of-statement)
5842 (setq e (point)) ;Might be on last line
5843 (verilog-forward-syntactic-ws)
5844 (while (looking-at verilog-declaration-re)
5845 (verilog-end-of-statement)
5846 (setq e (point))
5847 (verilog-forward-syntactic-ws))
5848 e)
5849 endpos (set-marker (make-marker) end)
5850 base-ind (progn
5851 (goto-char start)
5852 (verilog-do-indent (verilog-calculate-indent))
5853 (verilog-forward-ws&directives)
5854 (current-column))))
5855 ;; OK, start and end are set
5856 (goto-char (marker-position startpos))
5857 (if (and (not quiet)
5858 (> (- end start) 100))
5859 (message "Lining up declarations..(please stand by)"))
5860 ;; Get the beginning of line indent first
5861 (while (progn (setq e (marker-position endpos))
5862 (< (point) e))
5863 (cond
5864 ((save-excursion (skip-chars-backward " \t")
5865 (bolp))
5866 (verilog-forward-ws&directives)
5867 (indent-line-to base-ind)
5868 (verilog-forward-ws&directives)
5869 (if (< (point) e)
5870 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5871 (t
5872 (just-one-space)
5873 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
5874 ;;(forward-line)
5875 )
5876 ;; Now find biggest prefix
5877 (setq ind (verilog-get-lineup-indent (marker-position startpos) endpos))
5878 ;; Now indent each line.
5879 (goto-char (marker-position startpos))
5880 (while (progn (setq e (marker-position endpos))
5881 (setq r (- e (point)))
5882 (> r 0))
5883 (setq e (point))
5884 (unless quiet (message "%d" r))
5885 ;;(verilog-do-indent (verilog-calculate-indent)))
5886 (verilog-forward-ws&directives)
5887 (cond
5888 ((or (and verilog-indent-declaration-macros
5889 (looking-at verilog-declaration-re-2-macro))
5890 (looking-at verilog-declaration-re-2-no-macro))
5891 (let ((p (match-end 0)))
5892 (set-marker m1 p)
5893 (if (verilog-re-search-forward "[[#`]" p 'move)
5894 (progn
5895 (forward-char -1)
5896 (just-one-space)
5897 (goto-char (marker-position m1))
5898 (just-one-space)
5899 (indent-to ind))
5900 (progn
5901 (just-one-space)
5902 (indent-to ind)))))
5903 ((verilog-continued-line-1 (marker-position startpos))
5904 (goto-char e)
5905 (indent-line-to ind))
5906 ((verilog-in-struct-p)
5907 ;; could have a declaration of a user defined item
5908 (goto-char e)
5909 (verilog-end-of-statement))
5910 (t ; Must be comment or white space
5911 (goto-char e)
5912 (verilog-forward-ws&directives)
5913 (forward-line -1)))
5914 (forward-line 1))
5915 (unless quiet (message "")))))))
5916
5917 (defun verilog-pretty-expr (&optional quiet myre)
5918 "Line up expressions around point, optionally QUIET with regexp MYRE."
5919 (interactive "i\nsRegular Expression: ((<|:)?=) ")
5920 (save-excursion
5921 (if (or (eq myre nil)
5922 (string-equal myre ""))
5923 (setq myre "\\(<\\|:\\)?="))
5924 ;; want to match the first <= | := | =
5925 (setq myre (concat "\\(^.*?\\)\\(" myre "\\)"))
5926 (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
5927 (beginning-of-line)
5928 (if (and (not (looking-at rexp ))
5929 (looking-at myre)
5930 (save-excursion
5931 (goto-char (match-beginning 2))
5932 (not (verilog-in-comment-or-string-p))))
5933 (let* ((here (point))
5934 (e) (r)
5935 (start
5936 (progn
5937 (beginning-of-line)
5938 (setq e (point))
5939 (verilog-backward-syntactic-ws)
5940 (beginning-of-line)
5941 (while (and (not (looking-at rexp ))
5942 (looking-at myre)
5943 (not (bobp))
5944 )
5945 (setq e (point))
5946 (verilog-backward-syntactic-ws)
5947 (beginning-of-line)
5948 ) ;Ack, need to grok `define
5949 e))
5950 (end
5951 (progn
5952 (goto-char here)
5953 (end-of-line)
5954 (setq e (point)) ;Might be on last line
5955 (verilog-forward-syntactic-ws)
5956 (beginning-of-line)
5957 (while (and
5958 (not (looking-at rexp ))
5959 (looking-at myre)
5960 (progn
5961 (end-of-line)
5962 (not (eq e (point)))))
5963 (setq e (point))
5964 (verilog-forward-syntactic-ws)
5965 (beginning-of-line)
5966 )
5967 e))
5968 (endpos (set-marker (make-marker) end))
5969 (ind)
5970 )
5971 (goto-char start)
5972 (verilog-do-indent (verilog-calculate-indent))
5973 (if (and (not quiet)
5974 (> (- end start) 100))
5975 (message "Lining up expressions..(please stand by)"))
5976
5977 ;; Set indent to minimum throughout region
5978 (while (< (point) (marker-position endpos))
5979 (beginning-of-line)
5980 (verilog-just-one-space myre)
5981 (end-of-line)
5982 (verilog-forward-syntactic-ws)
5983 )
5984
5985 ;; Now find biggest prefix
5986 (setq ind (verilog-get-lineup-indent-2 myre start endpos))
5987
5988 ;; Now indent each line.
5989 (goto-char start)
5990 (while (progn (setq e (marker-position endpos))
5991 (setq r (- e (point)))
5992 (> r 0))
5993 (setq e (point))
5994 (if (not quiet) (message "%d" r))
5995 (cond
5996 ((looking-at myre)
5997 (goto-char (match-beginning 2))
5998 (if (not (verilog-parenthesis-depth)) ;; ignore parenthesized exprs
5999 (if (eq (char-after) ?=)
6000 (indent-to (1+ ind)) ; line up the = of the <= with surrounding =
6001 (indent-to ind)
6002 )))
6003 ((verilog-continued-line-1 start)
6004 (goto-char e)
6005 (indent-line-to ind))
6006 (t ; Must be comment or white space
6007 (goto-char e)
6008 (verilog-forward-ws&directives)
6009 (forward-line -1))
6010 )
6011 (forward-line 1))
6012 (unless quiet (message ""))
6013 )))))
6014
6015 (defun verilog-just-one-space (myre)
6016 "Remove extra spaces around regular expression MYRE."
6017 (interactive)
6018 (if (and (not(looking-at verilog-complete-reg))
6019 (looking-at myre))
6020 (let ((p1 (match-end 1))
6021 (p2 (match-end 2)))
6022 (progn
6023 (goto-char p2)
6024 (if (looking-at "\\s-") (just-one-space))
6025 (goto-char p1)
6026 (forward-char -1)
6027 (if (looking-at "\\s-") (just-one-space))
6028 ))))
6029
6030 (defun verilog-indent-declaration (baseind)
6031 "Indent current lines as declaration.
6032 Line up the variable names based on previous declaration's indentation.
6033 BASEIND is the base indent to offset everything."
6034 (interactive)
6035 (let ((pos (point-marker))
6036 (lim (save-excursion
6037 ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
6038 (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
6039 (point)))
6040 (ind)
6041 (val)
6042 (m1 (make-marker)))
6043 (setq val
6044 (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6045 (indent-line-to val)
6046
6047 ;; Use previous declaration (in this module) as template.
6048 (if (or (eq 'all verilog-auto-lineup)
6049 (eq 'declarations verilog-auto-lineup))
6050 (if (verilog-re-search-backward
6051 (or (and verilog-indent-declaration-macros
6052 verilog-declaration-re-1-macro)
6053 verilog-declaration-re-1-no-macro) lim t)
6054 (progn
6055 (goto-char (match-end 0))
6056 (skip-chars-forward " \t")
6057 (setq ind (current-column))
6058 (goto-char pos)
6059 (setq val
6060 (+ baseind
6061 (eval (cdr (assoc 'declaration verilog-indent-alist)))))
6062 (indent-line-to val)
6063 (if (and verilog-indent-declaration-macros
6064 (looking-at verilog-declaration-re-2-macro))
6065 (let ((p (match-end 0)))
6066 (set-marker m1 p)
6067 (if (verilog-re-search-forward "[[#`]" p 'move)
6068 (progn
6069 (forward-char -1)
6070 (just-one-space)
6071 (goto-char (marker-position m1))
6072 (just-one-space)
6073 (indent-to ind))
6074 (if (/= (current-column) ind)
6075 (progn
6076 (just-one-space)
6077 (indent-to ind)))))
6078 (if (looking-at verilog-declaration-re-2-no-macro)
6079 (let ((p (match-end 0)))
6080 (set-marker m1 p)
6081 (if (verilog-re-search-forward "[[`#]" p 'move)
6082 (progn
6083 (forward-char -1)
6084 (just-one-space)
6085 (goto-char (marker-position m1))
6086 (just-one-space)
6087 (indent-to ind))
6088 (if (/= (current-column) ind)
6089 (progn
6090 (just-one-space)
6091 (indent-to ind))))))))))
6092 (goto-char pos)))
6093
6094 (defun verilog-get-lineup-indent (b edpos)
6095 "Return the indent level that will line up several lines within the region.
6096 Region is defined by B and EDPOS."
6097 (save-excursion
6098 (let ((ind 0) e)
6099 (goto-char b)
6100 ;; Get rightmost position
6101 (while (progn (setq e (marker-position edpos))
6102 (< (point) e))
6103 (if (verilog-re-search-forward
6104 (or (and verilog-indent-declaration-macros
6105 verilog-declaration-re-1-macro)
6106 verilog-declaration-re-1-no-macro) e 'move)
6107 (progn
6108 (goto-char (match-end 0))
6109 (verilog-backward-syntactic-ws)
6110 (if (> (current-column) ind)
6111 (setq ind (current-column)))
6112 (goto-char (match-end 0)))))
6113 (if (> ind 0)
6114 (1+ ind)
6115 ;; No lineup-string found
6116 (goto-char b)
6117 (end-of-line)
6118 (verilog-backward-syntactic-ws)
6119 ;;(skip-chars-backward " \t")
6120 (1+ (current-column))))))
6121
6122 (defun verilog-get-lineup-indent-2 (myre b edpos)
6123 "Return the indent level that will line up several lines within the region."
6124 (save-excursion
6125 (let ((ind 0) e)
6126 (goto-char b)
6127 ;; Get rightmost position
6128 (while (progn (setq e (marker-position edpos))
6129 (< (point) e))
6130 (if (and (verilog-re-search-forward myre e 'move)
6131 (not (verilog-parenthesis-depth))) ;; skip parenthesized exprs
6132 (progn
6133 (goto-char (match-beginning 2))
6134 (verilog-backward-syntactic-ws)
6135 (if (> (current-column) ind)
6136 (setq ind (current-column)))
6137 (goto-char (match-end 0)))
6138 ))
6139 (if (> ind 0)
6140 (1+ ind)
6141 ;; No lineup-string found
6142 (goto-char b)
6143 (end-of-line)
6144 (skip-chars-backward " \t")
6145 (1+ (current-column))))))
6146
6147 (defun verilog-comment-depth (type val)
6148 "A useful mode debugging aide. TYPE and VAL are comments for insertion."
6149 (save-excursion
6150 (let
6151 ((b (prog2
6152 (beginning-of-line)
6153 (point-marker)
6154 (end-of-line)))
6155 (e (point-marker)))
6156 (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
6157 (progn
6158 (replace-match " /* -# ## */")
6159 (end-of-line))
6160 (progn
6161 (end-of-line)
6162 (insert " /* ## ## */"))))
6163 (backward-char 6)
6164 (insert
6165 (format "%s %d" type val))))
6166
6167 ;; \f
6168 ;;
6169 ;; Completion
6170 ;;
6171 (defvar verilog-str nil)
6172 (defvar verilog-all nil)
6173 (defvar verilog-pred nil)
6174 (defvar verilog-buffer-to-use nil)
6175 (defvar verilog-flag nil)
6176 (defvar verilog-toggle-completions nil
6177 "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
6178 Repeated use of \\[verilog-complete-word] will show you all of them.
6179 Normally, when there is more than one possible completion,
6180 it displays a list of all possible completions.")
6181
6182
6183 (defvar verilog-type-keywords
6184 '(
6185 "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
6186 "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
6187 "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pulldown" "pullup"
6188 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
6189 "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
6190 "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
6191 )
6192 "*Keywords for types used when completing a word in a declaration or parmlist.
6193 \(integer, real, reg...)")
6194
6195 (defvar verilog-cpp-keywords
6196 '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
6197 "endif")
6198 "*Keywords to complete when at first word of a line in declarative scope.
6199 \(initial, always, begin, assign...)
6200 The procedures and variables defined within the Verilog program
6201 will be completed at runtime and should not be added to this list.")
6202
6203 (defvar verilog-defun-keywords
6204 (append
6205 '(
6206 "always" "always_comb" "always_ff" "always_latch" "assign"
6207 "begin" "end" "generate" "endgenerate" "module" "endmodule"
6208 "specify" "endspecify" "function" "endfunction" "initial" "final"
6209 "task" "endtask" "primitive" "endprimitive"
6210 )
6211 verilog-type-keywords)
6212 "*Keywords to complete when at first word of a line in declarative scope.
6213 \(initial, always, begin, assign...)
6214 The procedures and variables defined within the Verilog program
6215 will be completed at runtime and should not be added to this list.")
6216
6217 (defvar verilog-block-keywords
6218 '(
6219 "begin" "break" "case" "continue" "else" "end" "endfunction"
6220 "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
6221 "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
6222 "while")
6223 "*Keywords to complete when at first word of a line in behavioral scope.
6224 \(begin, if, then, else, for, fork...)
6225 The procedures and variables defined within the Verilog program
6226 will be completed at runtime and should not be added to this list.")
6227
6228 (defvar verilog-tf-keywords
6229 '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
6230 "*Keywords to complete when at first word of a line in a task or function.
6231 \(begin, if, then, else, for, fork.)
6232 The procedures and variables defined within the Verilog program
6233 will be completed at runtime and should not be added to this list.")
6234
6235 (defvar verilog-case-keywords
6236 '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
6237 "*Keywords to complete when at first word of a line in case scope.
6238 \(begin, if, then, else, for, fork...)
6239 The procedures and variables defined within the Verilog program
6240 will be completed at runtime and should not be added to this list.")
6241
6242 (defvar verilog-separator-keywords
6243 '("else" "then" "begin")
6244 "*Keywords to complete when NOT standing at the first word of a statement.
6245 \(else, then, begin...)
6246 Variables and function names defined within the Verilog program
6247 will be completed at runtime and should not be added to this list.")
6248
6249 (defvar verilog-gate-ios
6250 ;; All these have an implied {"input"...} at the end
6251 '(("and" "output")
6252 ("buf" "output")
6253 ("bufif0" "output")
6254 ("bufif1" "output")
6255 ("cmos" "output")
6256 ("nand" "output")
6257 ("nmos" "output")
6258 ("nor" "output")
6259 ("not" "output")
6260 ("notif0" "output")
6261 ("notif1" "output")
6262 ("or" "output")
6263 ("pmos" "output")
6264 ("pulldown" "output")
6265 ("pullup" "output")
6266 ("rcmos" "output")
6267 ("rnmos" "output")
6268 ("rpmos" "output")
6269 ("rtran" "inout" "inout")
6270 ("rtranif0" "inout" "inout")
6271 ("rtranif1" "inout" "inout")
6272 ("tran" "inout" "inout")
6273 ("tranif0" "inout" "inout")
6274 ("tranif1" "inout" "inout")
6275 ("xnor" "output")
6276 ("xor" "output"))
6277 "*Map of direction for each positional argument to each gate primitive.")
6278
6279 (defvar verilog-gate-keywords (mapcar `car verilog-gate-ios)
6280 "*Keywords for gate primitives.")
6281
6282 (defun verilog-string-diff (str1 str2)
6283 "Return index of first letter where STR1 and STR2 differs."
6284 (catch 'done
6285 (let ((diff 0))
6286 (while t
6287 (if (or (> (1+ diff) (length str1))
6288 (> (1+ diff) (length str2)))
6289 (throw 'done diff))
6290 (or (equal (aref str1 diff) (aref str2 diff))
6291 (throw 'done diff))
6292 (setq diff (1+ diff))))))
6293
6294 ;; Calculate all possible completions for functions if argument is `function',
6295 ;; completions for procedures if argument is `procedure' or both functions and
6296 ;; procedures otherwise.
6297
6298 (defun verilog-func-completion (type)
6299 "Build regular expression for module/task/function names.
6300 TYPE is 'module, 'tf for task or function, or t if unknown."
6301 (if (string= verilog-str "")
6302 (setq verilog-str "[a-zA-Z_]"))
6303 (let ((verilog-str (concat (cond
6304 ((eq type 'module) "\\<\\(module\\)\\s +")
6305 ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
6306 (t "\\<\\(task\\|function\\|module\\)\\s +"))
6307 "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
6308 match)
6309
6310 (if (not (looking-at verilog-defun-re))
6311 (verilog-re-search-backward verilog-defun-re nil t))
6312 (forward-char 1)
6313
6314 ;; Search through all reachable functions
6315 (goto-char (point-min))
6316 (while (verilog-re-search-forward verilog-str (point-max) t)
6317 (progn (setq match (buffer-substring (match-beginning 2)
6318 (match-end 2)))
6319 (if (or (null verilog-pred)
6320 (funcall verilog-pred match))
6321 (setq verilog-all (cons match verilog-all)))))
6322 (if (match-beginning 0)
6323 (goto-char (match-beginning 0)))))
6324
6325 (defun verilog-get-completion-decl (end)
6326 "Macro for searching through current declaration (var, type or const)
6327 for matches of `str' and adding the occurrence tp `all' through point END."
6328 (let ((re (or (and verilog-indent-declaration-macros
6329 verilog-declaration-re-2-macro)
6330 verilog-declaration-re-2-no-macro))
6331 decl-end match)
6332 ;; Traverse lines
6333 (while (and (< (point) end)
6334 (verilog-re-search-forward re end t))
6335 ;; Traverse current line
6336 (setq decl-end (save-excursion (verilog-declaration-end)))
6337 (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
6338 (not (match-end 1)))
6339 (setq match (buffer-substring (match-beginning 0) (match-end 0)))
6340 (if (string-match (concat "\\<" verilog-str) match)
6341 (if (or (null verilog-pred)
6342 (funcall verilog-pred match))
6343 (setq verilog-all (cons match verilog-all)))))
6344 (forward-line 1)))
6345 verilog-all)
6346
6347 (defun verilog-type-completion ()
6348 "Calculate all possible completions for types."
6349 (let ((start (point))
6350 goon)
6351 ;; Search for all reachable type declarations
6352 (while (or (verilog-beg-of-defun)
6353 (setq goon (not goon)))
6354 (save-excursion
6355 (if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
6356 (point))
6357 (forward-char 1)))
6358 (verilog-re-search-forward
6359 "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
6360 start t)
6361 (not (match-end 1)))
6362 ;; Check current type declaration
6363 (verilog-get-completion-decl start))))))
6364
6365 (defun verilog-var-completion ()
6366 "Calculate all possible completions for variables (or constants)."
6367 (let ((start (point)))
6368 ;; Search for all reachable var declarations
6369 (verilog-beg-of-defun)
6370 (save-excursion
6371 ;; Check var declarations
6372 (verilog-get-completion-decl start))))
6373
6374 (defun verilog-keyword-completion (keyword-list)
6375 "Give list of all possible completions of keywords in KEYWORD-LIST."
6376 (mapcar '(lambda (s)
6377 (if (string-match (concat "\\<" verilog-str) s)
6378 (if (or (null verilog-pred)
6379 (funcall verilog-pred s))
6380 (setq verilog-all (cons s verilog-all)))))
6381 keyword-list))
6382
6383
6384 (defun verilog-completion (verilog-str verilog-pred verilog-flag)
6385 "Function passed to `completing-read', `try-completion' or `all-completions'.
6386 Called to get completion on VERILOG-STR. If VERILOG-PRED is non-nil, it
6387 must be a function to be called for every match to check if this should
6388 really be a match. If VERILOG-FLAG is t, the function returns a list of
6389 all possible completions. If VERILOG-FLAG is nil it returns a string,
6390 the longest possible completion, or t if VERILOG-STR is an exact match.
6391 If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
6392 exact match, nil otherwise."
6393 (save-excursion
6394 (let ((verilog-all nil))
6395 ;; Set buffer to use for searching labels. This should be set
6396 ;; within functions which use verilog-completions
6397 (set-buffer verilog-buffer-to-use)
6398
6399 ;; Determine what should be completed
6400 (let ((state (car (verilog-calculate-indent))))
6401 (cond ((eq state 'defun)
6402 (save-excursion (verilog-var-completion))
6403 (verilog-func-completion 'module)
6404 (verilog-keyword-completion verilog-defun-keywords))
6405
6406 ((eq state 'behavioral)
6407 (save-excursion (verilog-var-completion))
6408 (verilog-func-completion 'module)
6409 (verilog-keyword-completion verilog-defun-keywords))
6410
6411 ((eq state 'block)
6412 (save-excursion (verilog-var-completion))
6413 (verilog-func-completion 'tf)
6414 (verilog-keyword-completion verilog-block-keywords))
6415
6416 ((eq state 'case)
6417 (save-excursion (verilog-var-completion))
6418 (verilog-func-completion 'tf)
6419 (verilog-keyword-completion verilog-case-keywords))
6420
6421 ((eq state 'tf)
6422 (save-excursion (verilog-var-completion))
6423 (verilog-func-completion 'tf)
6424 (verilog-keyword-completion verilog-tf-keywords))
6425
6426 ((eq state 'cpp)
6427 (save-excursion (verilog-var-completion))
6428 (verilog-keyword-completion verilog-cpp-keywords))
6429
6430 ((eq state 'cparenexp)
6431 (save-excursion (verilog-var-completion)))
6432
6433 (t;--Anywhere else
6434 (save-excursion (verilog-var-completion))
6435 (verilog-func-completion 'both)
6436 (verilog-keyword-completion verilog-separator-keywords))))
6437
6438 ;; Now we have built a list of all matches. Give response to caller
6439 (verilog-completion-response))))
6440
6441 (defun verilog-completion-response ()
6442 (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
6443 ;; This was not called by all-completions
6444 (if (null verilog-all)
6445 ;; Return nil if there was no matching label
6446 nil
6447 ;; Get longest string common in the labels
6448 (let* ((elm (cdr verilog-all))
6449 (match (car verilog-all))
6450 (min (length match))
6451 tmp)
6452 (if (string= match verilog-str)
6453 ;; Return t if first match was an exact match
6454 (setq match t)
6455 (while (not (null elm))
6456 ;; Find longest common string
6457 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
6458 (progn
6459 (setq min tmp)
6460 (setq match (substring match 0 min))))
6461 ;; Terminate with match=t if this is an exact match
6462 (if (string= (car elm) verilog-str)
6463 (progn
6464 (setq match t)
6465 (setq elm nil))
6466 (setq elm (cdr elm)))))
6467 ;; If this is a test just for exact match, return nil ot t
6468 (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
6469 nil
6470 match))))
6471 ;; If flag is t, this was called by all-completions. Return
6472 ;; list of all possible completions
6473 (verilog-flag
6474 verilog-all)))
6475
6476 (defvar verilog-last-word-numb 0)
6477 (defvar verilog-last-word-shown nil)
6478 (defvar verilog-last-completions nil)
6479
6480 (defun verilog-complete-word ()
6481 "Complete word at current point.
6482 \(See also `verilog-toggle-completions', `verilog-type-keywords',
6483 and `verilog-separator-keywords'.)"
6484 (interactive)
6485 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
6486 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
6487 (verilog-str (buffer-substring b e))
6488 ;; The following variable is used in verilog-completion
6489 (verilog-buffer-to-use (current-buffer))
6490 (allcomp (if (and verilog-toggle-completions
6491 (string= verilog-last-word-shown verilog-str))
6492 verilog-last-completions
6493 (all-completions verilog-str 'verilog-completion)))
6494 (match (if verilog-toggle-completions
6495 "" (try-completion
6496 verilog-str (mapcar '(lambda (elm)
6497 (cons elm 0)) allcomp)))))
6498 ;; Delete old string
6499 (delete-region b e)
6500
6501 ;; Toggle-completions inserts whole labels
6502 (if verilog-toggle-completions
6503 (progn
6504 ;; Update entry number in list
6505 (setq verilog-last-completions allcomp
6506 verilog-last-word-numb
6507 (if (>= verilog-last-word-numb (1- (length allcomp)))
6508 0
6509 (1+ verilog-last-word-numb)))
6510 (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
6511 ;; Display next match or same string if no match was found
6512 (if (not (null allcomp))
6513 (insert "" verilog-last-word-shown)
6514 (insert "" verilog-str)
6515 (message "(No match)")))
6516 ;; The other form of completion does not necessarily do that.
6517
6518 ;; Insert match if found, or the original string if no match
6519 (if (or (null match) (equal match 't))
6520 (progn (insert "" verilog-str)
6521 (message "(No match)"))
6522 (insert "" match))
6523 ;; Give message about current status of completion
6524 (cond ((equal match 't)
6525 (if (not (null (cdr allcomp)))
6526 (message "(Complete but not unique)")
6527 (message "(Sole completion)")))
6528 ;; Display buffer if the current completion didn't help
6529 ;; on completing the label.
6530 ((and (not (null (cdr allcomp))) (= (length verilog-str)
6531 (length match)))
6532 (with-output-to-temp-buffer "*Completions*"
6533 (display-completion-list allcomp))
6534 ;; Wait for a key press. Then delete *Completion* window
6535 (momentary-string-display "" (point))
6536 (delete-window (get-buffer-window (get-buffer "*Completions*")))
6537 )))))
6538
6539 (defun verilog-show-completions ()
6540 "Show all possible completions at current point."
6541 (interactive)
6542 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
6543 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
6544 (verilog-str (buffer-substring b e))
6545 ;; The following variable is used in verilog-completion
6546 (verilog-buffer-to-use (current-buffer))
6547 (allcomp (if (and verilog-toggle-completions
6548 (string= verilog-last-word-shown verilog-str))
6549 verilog-last-completions
6550 (all-completions verilog-str 'verilog-completion))))
6551 ;; Show possible completions in a temporary buffer.
6552 (with-output-to-temp-buffer "*Completions*"
6553 (display-completion-list allcomp))
6554 ;; Wait for a key press. Then delete *Completion* window
6555 (momentary-string-display "" (point))
6556 (delete-window (get-buffer-window (get-buffer "*Completions*")))))
6557
6558
6559 (defun verilog-get-default-symbol ()
6560 "Return symbol around current point as a string."
6561 (save-excursion
6562 (buffer-substring (progn
6563 (skip-chars-backward " \t")
6564 (skip-chars-backward "a-zA-Z0-9_")
6565 (point))
6566 (progn
6567 (skip-chars-forward "a-zA-Z0-9_")
6568 (point)))))
6569
6570 (defun verilog-build-defun-re (str &optional arg)
6571 "Return function/task/module starting with STR as regular expression.
6572 With optional second ARG non-nil, STR is the complete name of the instruction."
6573 (if arg
6574 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
6575 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
6576
6577 (defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
6578 "Function passed to `completing-read', `try-completion' or `all-completions'.
6579 Returns a completion on any function name based on VERILOG-STR prefix. If
6580 VERILOG-PRED is non-nil, it must be a function to be called for every match
6581 to check if this should really be a match. If VERILOG-FLAG is t, the
6582 function returns a list of all possible completions. If it is nil it
6583 returns a string, the longest possible completion, or t if VERILOG-STR is
6584 an exact match. If VERILOG-FLAG is 'lambda, the function returns t if
6585 VERILOG-STR is an exact match, nil otherwise."
6586 (save-excursion
6587 (let ((verilog-all nil)
6588 match)
6589
6590 ;; Set buffer to use for searching labels. This should be set
6591 ;; within functions which use verilog-completions
6592 (set-buffer verilog-buffer-to-use)
6593
6594 (let ((verilog-str verilog-str))
6595 ;; Build regular expression for functions
6596 (if (string= verilog-str "")
6597 (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
6598 (setq verilog-str (verilog-build-defun-re verilog-str)))
6599 (goto-char (point-min))
6600
6601 ;; Build a list of all possible completions
6602 (while (verilog-re-search-forward verilog-str nil t)
6603 (setq match (buffer-substring (match-beginning 2) (match-end 2)))
6604 (if (or (null verilog-pred)
6605 (funcall verilog-pred match))
6606 (setq verilog-all (cons match verilog-all)))))
6607
6608 ;; Now we have built a list of all matches. Give response to caller
6609 (verilog-completion-response))))
6610
6611 (defun verilog-goto-defun ()
6612 "Move to specified Verilog module/interface/task/function.
6613 The default is a name found in the buffer around point.
6614 If search fails, other files are checked based on
6615 `verilog-library-flags'."
6616 (interactive)
6617 (let* ((default (verilog-get-default-symbol))
6618 ;; The following variable is used in verilog-comp-function
6619 (verilog-buffer-to-use (current-buffer))
6620 (label (if (not (string= default ""))
6621 ;; Do completion with default
6622 (completing-read (concat "Goto-Label: (default "
6623 default ") ")
6624 'verilog-comp-defun nil nil "")
6625 ;; There is no default value. Complete without it
6626 (completing-read "Goto-Label: "
6627 'verilog-comp-defun nil nil "")))
6628 pt)
6629 ;; Make sure library paths are correct, in case need to resolve module
6630 (verilog-auto-reeval-locals)
6631 (verilog-getopt-flags)
6632 ;; If there was no response on prompt, use default value
6633 (if (string= label "")
6634 (setq label default))
6635 ;; Goto right place in buffer if label is not an empty string
6636 (or (string= label "")
6637 (progn
6638 (save-excursion
6639 (goto-char (point-min))
6640 (setq pt
6641 (re-search-forward (verilog-build-defun-re label t) nil t)))
6642 (when pt
6643 (goto-char pt)
6644 (beginning-of-line))
6645 pt)
6646 (verilog-goto-defun-file label))))
6647
6648 ;; Eliminate compile warning
6649 (defvar occur-pos-list)
6650
6651 (defun verilog-showscopes ()
6652 "List all scopes in this module."
6653 (interactive)
6654 (let ((buffer (current-buffer))
6655 (linenum 1)
6656 (nlines 0)
6657 (first 1)
6658 (prevpos (point-min))
6659 (final-context-start (make-marker))
6660 (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
6661 (with-output-to-temp-buffer "*Occur*"
6662 (save-excursion
6663 (message (format "Searching for %s ..." regexp))
6664 ;; Find next match, but give up if prev match was at end of buffer.
6665 (while (and (not (= prevpos (point-max)))
6666 (verilog-re-search-forward regexp nil t))
6667 (goto-char (match-beginning 0))
6668 (beginning-of-line)
6669 (save-match-data
6670 (setq linenum (+ linenum (count-lines prevpos (point)))))
6671 (setq prevpos (point))
6672 (goto-char (match-end 0))
6673 (let* ((start (save-excursion
6674 (goto-char (match-beginning 0))
6675 (forward-line (if (< nlines 0) nlines (- nlines)))
6676 (point)))
6677 (end (save-excursion
6678 (goto-char (match-end 0))
6679 (if (> nlines 0)
6680 (forward-line (1+ nlines))
6681 (forward-line 1))
6682 (point)))
6683 (tag (format "%3d" linenum))
6684 (empty (make-string (length tag) ?\ ))
6685 tem)
6686 (save-excursion
6687 (setq tem (make-marker))
6688 (set-marker tem (point))
6689 (set-buffer standard-output)
6690 (setq occur-pos-list (cons tem occur-pos-list))
6691 (or first (zerop nlines)
6692 (insert "--------\n"))
6693 (setq first nil)
6694 (insert-buffer-substring buffer start end)
6695 (backward-char (- end start))
6696 (setq tem (if (< nlines 0) (- nlines) nlines))
6697 (while (> tem 0)
6698 (insert empty ?:)
6699 (forward-line 1)
6700 (setq tem (1- tem)))
6701 (let ((this-linenum linenum))
6702 (set-marker final-context-start
6703 (+ (point) (- (match-end 0) (match-beginning 0))))
6704 (while (< (point) final-context-start)
6705 (if (null tag)
6706 (setq tag (format "%3d" this-linenum)))
6707 (insert tag ?:)))))))
6708 (set-buffer-modified-p nil))))
6709
6710
6711 ;; Highlight helper functions
6712 (defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
6713 (defun verilog-within-translate-off ()
6714 "Return point if within translate-off region, else nil."
6715 (and (save-excursion
6716 (re-search-backward
6717 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
6718 nil t))
6719 (equal "off" (match-string 2))
6720 (point)))
6721
6722 (defun verilog-start-translate-off (limit)
6723 "Return point before translate-off directive if before LIMIT, else nil."
6724 (when (re-search-forward
6725 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6726 limit t)
6727 (match-beginning 0)))
6728
6729 (defun verilog-back-to-start-translate-off (limit)
6730 "Return point before translate-off directive if before LIMIT, else nil."
6731 (when (re-search-backward
6732 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
6733 limit t)
6734 (match-beginning 0)))
6735
6736 (defun verilog-end-translate-off (limit)
6737 "Return point after translate-on directive if before LIMIT, else nil."
6738
6739 (re-search-forward (concat
6740 "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
6741
6742 (defun verilog-match-translate-off (limit)
6743 "Match a translate-off block, setting `match-data' and returning t, else nil.
6744 Bound search by LIMIT."
6745 (when (< (point) limit)
6746 (let ((start (or (verilog-within-translate-off)
6747 (verilog-start-translate-off limit)))
6748 (case-fold-search t))
6749 (when start
6750 (let ((end (or (verilog-end-translate-off limit) limit)))
6751 (set-match-data (list start end))
6752 (goto-char end))))))
6753
6754 (defun verilog-font-lock-match-item (limit)
6755 "Match, and move over, any declaration item after point.
6756 Bound search by LIMIT. Adapted from
6757 `font-lock-match-c-style-declaration-item-and-skip-to-next'."
6758 (condition-case nil
6759 (save-restriction
6760 (narrow-to-region (point-min) limit)
6761 ;; match item
6762 (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
6763 (save-match-data
6764 (goto-char (match-end 1))
6765 ;; move to next item
6766 (if (looking-at "\\(\\s-*,\\)")
6767 (goto-char (match-end 1))
6768 (end-of-line) t))))
6769 (error nil)))
6770
6771
6772 ;; Added by Subbu Meiyappan for Header
6773
6774 (defun verilog-header ()
6775 "Insert a standard Verilog file header.
6776 See also `verilog-sk-header' for an alternative format."
6777 (interactive)
6778 (let ((start (point)))
6779 (insert "\
6780 //-----------------------------------------------------------------------------
6781 // Title : <title>
6782 // Project : <project>
6783 //-----------------------------------------------------------------------------
6784 // File : <filename>
6785 // Author : <author>
6786 // Created : <credate>
6787 // Last modified : <moddate>
6788 //-----------------------------------------------------------------------------
6789 // Description :
6790 // <description>
6791 //-----------------------------------------------------------------------------
6792 // Copyright (c) <copydate> by <company> This model is the confidential and
6793 // proprietary property of <company> and the possession or use of this
6794 // file requires a written license from <company>.
6795 //------------------------------------------------------------------------------
6796 // Modification history :
6797 // <modhist>
6798 //-----------------------------------------------------------------------------
6799
6800 ")
6801 (goto-char start)
6802 (search-forward "<filename>")
6803 (replace-match (buffer-name) t t)
6804 (search-forward "<author>") (replace-match "" t t)
6805 (insert (user-full-name))
6806 (insert " <" (user-login-name) "@" (system-name) ">")
6807 (search-forward "<credate>") (replace-match "" t t)
6808 (verilog-insert-date)
6809 (search-forward "<moddate>") (replace-match "" t t)
6810 (verilog-insert-date)
6811 (search-forward "<copydate>") (replace-match "" t t)
6812 (verilog-insert-year)
6813 (search-forward "<modhist>") (replace-match "" t t)
6814 (verilog-insert-date)
6815 (insert " : created")
6816 (goto-char start)
6817 (let (string)
6818 (setq string (read-string "title: "))
6819 (search-forward "<title>")
6820 (replace-match string t t)
6821 (setq string (read-string "project: " verilog-project))
6822 (setq verilog-project string)
6823 (search-forward "<project>")
6824 (replace-match string t t)
6825 (setq string (read-string "Company: " verilog-company))
6826 (setq verilog-company string)
6827 (search-forward "<company>")
6828 (replace-match string t t)
6829 (search-forward "<company>")
6830 (replace-match string t t)
6831 (search-forward "<company>")
6832 (replace-match string t t)
6833 (search-backward "<description>")
6834 (replace-match "" t t))))
6835
6836 ;; verilog-header Uses the verilog-insert-date function
6837
6838 (defun verilog-insert-date ()
6839 "Insert date from the system."
6840 (interactive)
6841 (if verilog-date-scientific-format
6842 (insert (format-time-string "%Y/%m/%d"))
6843 (insert (format-time-string "%d.%m.%Y"))))
6844
6845 (defun verilog-insert-year ()
6846 "Insert year from the system."
6847 (interactive)
6848 (insert (format-time-string "%Y")))
6849
6850 \f
6851 ;;
6852 ;; Signal list parsing
6853 ;;
6854
6855 ;; Elements of a signal list
6856 (defsubst verilog-sig-new (name bits comment mem enum signed type multidim modport)
6857 (list name bits comment mem enum signed type multidim modport))
6858 (defsubst verilog-sig-name (sig)
6859 (car sig))
6860 (defsubst verilog-sig-bits (sig)
6861 (nth 1 sig))
6862 (defsubst verilog-sig-comment (sig)
6863 (nth 2 sig))
6864 (defsubst verilog-sig-memory (sig)
6865 (nth 3 sig))
6866 (defsubst verilog-sig-enum (sig)
6867 (nth 4 sig))
6868 (defsubst verilog-sig-signed (sig)
6869 (nth 5 sig))
6870 (defsubst verilog-sig-type (sig)
6871 (nth 6 sig))
6872 (defsubst verilog-sig-multidim (sig)
6873 (nth 7 sig))
6874 (defsubst verilog-sig-multidim-string (sig)
6875 (if (verilog-sig-multidim sig)
6876 (let ((str "") (args (verilog-sig-multidim sig)))
6877 (while args
6878 (setq str (concat str (car args)))
6879 (setq args (cdr args)))
6880 str)))
6881 (defsubst verilog-sig-modport (sig)
6882 (nth 8 sig))
6883 (defsubst verilog-sig-width (sig)
6884 (verilog-make-width-expression (verilog-sig-bits sig)))
6885
6886 (defsubst verilog-alw-new (outputs temps inputs delayed)
6887 (list outputs temps inputs delayed))
6888 (defsubst verilog-alw-get-outputs (sigs)
6889 (nth 0 sigs))
6890 (defsubst verilog-alw-get-temps (sigs)
6891 (nth 1 sigs))
6892 (defsubst verilog-alw-get-inputs (sigs)
6893 (nth 2 sigs))
6894 (defsubst verilog-alw-get-uses-delayed (sigs)
6895 (nth 3 sigs))
6896
6897 (defsubst verilog-modi-new (name fob pt type)
6898 (vector name fob pt type))
6899 (defsubst verilog-modi-name (modi)
6900 (aref modi 0))
6901 (defsubst verilog-modi-file-or-buffer (modi)
6902 (aref modi 1))
6903 (defsubst verilog-modi-get-point (modi)
6904 (aref modi 2))
6905 (defsubst verilog-modi-get-type (modi) ;; "module" or "interface"
6906 (aref modi 3))
6907 (defsubst verilog-modi-get-decls (modi)
6908 (verilog-modi-cache-results modi 'verilog-read-decls))
6909 (defsubst verilog-modi-get-sub-decls (modi)
6910 (verilog-modi-cache-results modi 'verilog-read-sub-decls))
6911
6912 ;; Signal reading for given module
6913 ;; Note these all take modi's - as returned from verilog-modi-current
6914 (defsubst verilog-decls-new (out inout in wires regs assigns consts gparams interfaces)
6915 (vector out inout in wires regs assigns consts gparams interfaces))
6916 (defsubst verilog-decls-get-outputs (decls)
6917 (aref decls 0))
6918 (defsubst verilog-decls-get-inouts (decls)
6919 (aref decls 1))
6920 (defsubst verilog-decls-get-inputs (decls)
6921 (aref decls 2))
6922 (defsubst verilog-decls-get-wires (decls)
6923 (aref decls 3))
6924 (defsubst verilog-decls-get-regs (decls)
6925 (aref decls 4))
6926 (defsubst verilog-decls-get-assigns (decls)
6927 (aref decls 5))
6928 (defsubst verilog-decls-get-consts (decls)
6929 (aref decls 6))
6930 (defsubst verilog-decls-get-gparams (decls)
6931 (aref decls 7))
6932 (defsubst verilog-decls-get-interfaces (decls)
6933 (aref decls 8))
6934
6935 (defsubst verilog-subdecls-new (out inout in intf intfd)
6936 (vector out inout in intf intfd))
6937 (defsubst verilog-subdecls-get-outputs (subdecls)
6938 (aref subdecls 0))
6939 (defsubst verilog-subdecls-get-inouts (subdecls)
6940 (aref subdecls 1))
6941 (defsubst verilog-subdecls-get-inputs (subdecls)
6942 (aref subdecls 2))
6943 (defsubst verilog-subdecls-get-interfaces (subdecls)
6944 (aref subdecls 3))
6945 (defsubst verilog-subdecls-get-interfaced (subdecls)
6946 (aref subdecls 4))
6947
6948 (defun verilog-signals-not-in (in-list not-list)
6949 "Return list of signals in IN-LIST that aren't also in NOT-LIST.
6950 Also remove any duplicates in IN-LIST.
6951 Signals must be in standard (base vector) form."
6952 ;; This function is hot, so implemented as O(1)
6953 (cond ((eval-when-compile (fboundp 'make-hash-table))
6954 (let ((ht (make-hash-table :test 'equal :rehash-size 4.0))
6955 out-list)
6956 (while not-list
6957 (puthash (car (car not-list)) t ht)
6958 (setq not-list (cdr not-list)))
6959 (while in-list
6960 (when (not (gethash (car (car in-list)) ht))
6961 (setq out-list (cons (car in-list) out-list))
6962 (puthash (car (car in-list)) t ht))
6963 (setq in-list (cdr in-list)))
6964 (nreverse out-list)))
6965 ;; Slower Fallback if no hash tables (pre Emacs 21.1/XEmacs 21.4)
6966 (t
6967 (let (out-list)
6968 (while in-list
6969 (if (not (or (assoc (car (car in-list)) not-list)
6970 (assoc (car (car in-list)) out-list)))
6971 (setq out-list (cons (car in-list) out-list)))
6972 (setq in-list (cdr in-list)))
6973 (nreverse out-list)))))
6974 ;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
6975
6976 (defun verilog-signals-memory (in-list)
6977 "Return list of signals in IN-LIST that are memoried (multidimensional)."
6978 (let (out-list)
6979 (while in-list
6980 (if (nth 3 (car in-list))
6981 (setq out-list (cons (car in-list) out-list)))
6982 (setq in-list (cdr in-list)))
6983 out-list))
6984 ;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
6985
6986 (defun verilog-signals-sort-compare (a b)
6987 "Compare signal A and B for sorting."
6988 (string< (car a) (car b)))
6989
6990 (defun verilog-signals-not-params (in-list)
6991 "Return list of signals in IN-LIST that aren't parameters or numeric constants."
6992 (let (out-list)
6993 (while in-list
6994 (unless (boundp (intern (concat "vh-" (car (car in-list)))))
6995 (setq out-list (cons (car in-list) out-list)))
6996 (setq in-list (cdr in-list)))
6997 (nreverse out-list)))
6998
6999 (defun verilog-signals-combine-bus (in-list)
7000 "Return a list of signals in IN-LIST, with busses combined.
7001 Duplicate signals are also removed. For example A[2] and A[1] become A[2:1]."
7002 (let (combo buswarn
7003 out-list
7004 sig highbit lowbit ; Temp information about current signal
7005 sv-name sv-highbit sv-lowbit ; Details about signal we are forming
7006 sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
7007 sv-modport
7008 bus)
7009 ;; Shove signals so duplicated signals will be adjacent
7010 (setq in-list (sort in-list `verilog-signals-sort-compare))
7011 (while in-list
7012 (setq sig (car in-list))
7013 ;; No current signal; form from existing details
7014 (unless sv-name
7015 (setq sv-name (verilog-sig-name sig)
7016 sv-highbit nil
7017 sv-busstring nil
7018 sv-comment (verilog-sig-comment sig)
7019 sv-memory (verilog-sig-memory sig)
7020 sv-enum (verilog-sig-enum sig)
7021 sv-signed (verilog-sig-signed sig)
7022 sv-type (verilog-sig-type sig)
7023 sv-multidim (verilog-sig-multidim sig)
7024 sv-modport (verilog-sig-modport sig)
7025 combo ""
7026 buswarn ""))
7027 ;; Extract bus details
7028 (setq bus (verilog-sig-bits sig))
7029 (cond ((and bus
7030 (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
7031 (setq highbit (string-to-number (match-string 1 bus))
7032 lowbit (string-to-number
7033 (match-string 2 bus))))
7034 (and (string-match "\\[\\([0-9]+\\)\\]" bus)
7035 (setq highbit (string-to-number (match-string 1 bus))
7036 lowbit highbit))))
7037 ;; Combine bits in bus
7038 (if sv-highbit
7039 (setq sv-highbit (max highbit sv-highbit)
7040 sv-lowbit (min lowbit sv-lowbit))
7041 (setq sv-highbit highbit
7042 sv-lowbit lowbit)))
7043 (bus
7044 ;; String, probably something like `preproc:0
7045 (setq sv-busstring bus)))
7046 ;; Peek ahead to next signal
7047 (setq in-list (cdr in-list))
7048 (setq sig (car in-list))
7049 (cond ((and sig (equal sv-name (verilog-sig-name sig)))
7050 ;; Combine with this signal
7051 (when (and sv-busstring
7052 (not (equal sv-busstring (verilog-sig-bits sig))))
7053 (when nil ;; Debugging
7054 (message (concat "Warning, can't merge into single bus "
7055 sv-name bus
7056 ", the AUTOs may be wrong")))
7057 (setq buswarn ", Couldn't Merge"))
7058 (if (verilog-sig-comment sig) (setq combo ", ..."))
7059 (setq sv-memory (or sv-memory (verilog-sig-memory sig))
7060 sv-enum (or sv-enum (verilog-sig-enum sig))
7061 sv-signed (or sv-signed (verilog-sig-signed sig))
7062 sv-type (or sv-type (verilog-sig-type sig))
7063 sv-multidim (or sv-multidim (verilog-sig-multidim sig))
7064 sv-modport (or sv-modport (verilog-sig-modport sig))))
7065 ;; Doesn't match next signal, add to queue, zero in prep for next
7066 ;; Note sig may also be nil for the last signal in the list
7067 (t
7068 (setq out-list
7069 (cons (verilog-sig-new
7070 sv-name
7071 (or sv-busstring
7072 (if sv-highbit
7073 (concat "[" (int-to-string sv-highbit) ":"
7074 (int-to-string sv-lowbit) "]")))
7075 (concat sv-comment combo buswarn)
7076 sv-memory sv-enum sv-signed sv-type sv-multidim sv-modport)
7077 out-list)
7078 sv-name nil))))
7079 ;;
7080 out-list))
7081
7082 (defun verilog-sig-tieoff (sig &optional no-width)
7083 "Return tieoff expression for given SIG, with appropriate width.
7084 Ignore width if optional NO-WIDTH is set."
7085 (let* ((width (if no-width nil (verilog-sig-width sig))))
7086 (concat
7087 (if (and verilog-active-low-regexp
7088 (string-match verilog-active-low-regexp (verilog-sig-name sig)))
7089 "~" "")
7090 (cond ((not width)
7091 "0")
7092 ((string-match "^[0-9]+$" width)
7093 (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
7094 (t
7095 (concat "{" width "{1'b0}}"))))))
7096
7097 ;;
7098 ;; Port/Wire/Etc Reading
7099 ;;
7100
7101 (defun verilog-read-inst-backward-name ()
7102 "Internal. Move point back to beginning of inst-name."
7103 (verilog-backward-open-paren)
7104 (let (done)
7105 (while (not done)
7106 (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil) ; ] isn't word boundary
7107 (cond ((looking-at ")")
7108 (verilog-backward-open-paren))
7109 (t (setq done t)))))
7110 (while (looking-at "\\]")
7111 (verilog-backward-open-bracket)
7112 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
7113 (skip-chars-backward "a-zA-Z0-9`_$"))
7114
7115 (defun verilog-read-inst-module-matcher ()
7116 "Set match data 0 with module_name when point is inside instantiation."
7117 (verilog-read-inst-backward-name)
7118 ;; Skip over instantiation name
7119 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
7120 ;; Check for parameterized instantiations
7121 (when (looking-at ")")
7122 (verilog-backward-open-paren)
7123 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
7124 (skip-chars-backward "a-zA-Z0-9'_$")
7125 (looking-at "[a-zA-Z0-9`_\$]+")
7126 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7127 (buffer-substring-no-properties (match-beginning 0) (match-end 0))
7128 ;; Caller assumes match-beginning/match-end is still set
7129 )
7130
7131 (defun verilog-read-inst-module ()
7132 "Return module_name when point is inside instantiation."
7133 (save-excursion
7134 (verilog-read-inst-module-matcher)))
7135
7136 (defun verilog-read-inst-name ()
7137 "Return instance_name when point is inside instantiation."
7138 (save-excursion
7139 (verilog-read-inst-backward-name)
7140 (looking-at "[a-zA-Z0-9`_\$]+")
7141 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7142 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
7143
7144 (defun verilog-read-module-name ()
7145 "Return module name when after its ( or ;."
7146 (save-excursion
7147 (re-search-backward "[(;]")
7148 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
7149 (skip-chars-backward "a-zA-Z0-9`_$")
7150 (looking-at "[a-zA-Z0-9`_\$]+")
7151 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
7152 (verilog-symbol-detick
7153 (buffer-substring-no-properties (match-beginning 0) (match-end 0)) t)))
7154
7155 (defun verilog-read-inst-param-value ()
7156 "Return list of parameters and values when point is inside instantiation."
7157 (save-excursion
7158 (verilog-read-inst-backward-name)
7159 ;; Skip over instantiation name
7160 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
7161 ;; If there are parameterized instantiations
7162 (when (looking-at ")")
7163 (let ((end-pt (point))
7164 params
7165 param-name paren-beg-pt param-value)
7166 (verilog-backward-open-paren)
7167 (while (verilog-re-search-forward-quick "\\." end-pt t)
7168 (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
7169 (skip-chars-backward "a-zA-Z0-9'_$")
7170 (looking-at "[a-zA-Z0-9`_\$]+")
7171 (setq param-name (buffer-substring-no-properties
7172 (match-beginning 0) (match-end 0)))
7173 (verilog-re-search-forward-quick "(" nil nil)
7174 (setq paren-beg-pt (point))
7175 (verilog-forward-close-paren)
7176 (setq param-value (verilog-string-remove-spaces
7177 (buffer-substring-no-properties
7178 paren-beg-pt (1- (point)))))
7179 (setq params (cons (list param-name param-value) params)))
7180 params))))
7181
7182 (defun verilog-read-auto-params (num-param &optional max-param)
7183 "Return parameter list inside auto.
7184 Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
7185 (let ((olist))
7186 (save-excursion
7187 ;; /*AUTOPUNT("parameter", "parameter")*/
7188 (search-backward "(")
7189 (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
7190 (setq olist (cons (match-string 1) olist))
7191 (goto-char (match-end 0))))
7192 (or (eq nil num-param)
7193 (<= num-param (length olist))
7194 (error "%s: Expected %d parameters" (verilog-point-text) num-param))
7195 (if (eq max-param nil) (setq max-param num-param))
7196 (or (eq nil max-param)
7197 (>= max-param (length olist))
7198 (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
7199 (nreverse olist)))
7200
7201 (defun verilog-read-decls ()
7202 "Compute signal declaration information for the current module at point.
7203 Return a array of [outputs inouts inputs wire reg assign const]."
7204 (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
7205 (functask 0) (paren 0) (sig-paren 0) (v2kargs-ok t)
7206 in-modport
7207 sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const
7208 sigs-gparam sigs-intf
7209 vec expect-signal keywd newsig rvalue enum io signed typedefed multidim
7210 modport)
7211 (save-excursion
7212 (verilog-beg-of-defun)
7213 (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
7214 (while (< (point) end-mod-point)
7215 ;;(if dbg (setq dbg (concat dbg (format "Pt %s Vec %s C%c Kwd'%s'\n" (point) vec (following-char) keywd))))
7216 (cond
7217 ((looking-at "//")
7218 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
7219 (setq enum (match-string 1)))
7220 (search-forward "\n"))
7221 ((looking-at "/\\*")
7222 (forward-char 2)
7223 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
7224 (setq enum (match-string 1)))
7225 (or (search-forward "*/")
7226 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7227 ((looking-at "(\\*")
7228 (forward-char 2)
7229 (or (looking-at "\\s-*)") ; It's an "always @ (*)"
7230 (search-forward "*)")
7231 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7232 ((eq ?\" (following-char))
7233 (or (re-search-forward "[^\\]\"" nil t) ;; don't forward-char first, since we look for a non backslash first
7234 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
7235 ((eq ?\; (following-char))
7236 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil
7237 v2kargs-ok nil in-modport nil)
7238 (forward-char 1))
7239 ((eq ?= (following-char))
7240 (setq rvalue t newsig nil)
7241 (forward-char 1))
7242 ((and (eq ?, (following-char))
7243 (eq paren sig-paren))
7244 (setq rvalue nil)
7245 (forward-char 1))
7246 ;; ,'s can occur inside {} & funcs
7247 ((looking-at "[{(]")
7248 (setq paren (1+ paren))
7249 (forward-char 1))
7250 ((looking-at "[})]")
7251 (setq paren (1- paren))
7252 (forward-char 1)
7253 (when (< paren sig-paren)
7254 (setq expect-signal nil))) ; ) that ends variables inside v2k arg list
7255 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
7256 (goto-char (match-end 0))
7257 (cond (newsig ; Memory, not just width. Patch last signal added's memory (nth 3)
7258 (setcar (cdr (cdr (cdr newsig)))
7259 (if (verilog-sig-memory newsig)
7260 (concat (verilog-sig-memory newsig) (match-string 1))
7261 (match-string 1))))
7262 (vec ;; Multidimensional
7263 (setq multidim (cons vec multidim))
7264 (setq vec (verilog-string-replace-matches
7265 "\\s-+" "" nil nil (match-string 1))))
7266 (t ;; Bit width
7267 (setq vec (verilog-string-replace-matches
7268 "\\s-+" "" nil nil (match-string 1))))))
7269 ;; Normal or escaped identifier -- note we remember the \ if escaped
7270 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
7271 (goto-char (match-end 0))
7272 (setq keywd (match-string 1))
7273 (when (string-match "^\\\\" (match-string 1))
7274 (setq keywd (concat keywd " "))) ;; Escaped ID needs space at end
7275 ;; Add any :: package names to same identifier
7276 (while (looking-at "\\s-*::\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
7277 (goto-char (match-end 0))
7278 (setq keywd (concat keywd "::" (match-string 1)))
7279 (when (string-match "^\\\\" (match-string 1))
7280 (setq keywd (concat keywd " ")))) ;; Escaped ID needs space at end
7281 (cond ((equal keywd "input")
7282 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
7283 expect-signal 'sigs-in io t modport nil))
7284 ((equal keywd "output")
7285 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
7286 expect-signal 'sigs-out io t modport nil))
7287 ((equal keywd "inout")
7288 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
7289 expect-signal 'sigs-inout io t modport nil))
7290 ((equal keywd "parameter")
7291 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7292 expect-signal 'sigs-gparam io t modport nil))
7293 ((member keywd '("wire" "tri" "tri0" "tri1" "triand" "trior" "wand" "wor"))
7294 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7295 expect-signal 'sigs-wire modport nil)))
7296 ((member keywd '("reg" "trireg"
7297 "byte" "shortint" "int" "longint" "integer" "time"
7298 "bit" "logic"
7299 "shortreal" "real" "realtime"
7300 "string" "event" "chandle"))
7301 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7302 expect-signal 'sigs-reg modport nil)))
7303 ((equal keywd "assign")
7304 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7305 expect-signal 'sigs-assign modport nil))
7306 ((member keywd '("supply0" "supply1" "supply"
7307 "localparam" "genvar"))
7308 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
7309 expect-signal 'sigs-const modport nil)))
7310 ((equal keywd "signed")
7311 (setq signed "signed"))
7312 ((member keywd '("class" "clocking" "covergroup" "function"
7313 "property" "randsequence" "sequence" "task"))
7314 (setq functask (1+ functask)))
7315 ((member keywd '("endclass" "endclocking" "endgroup" "endfunction"
7316 "endproperty" "endsequence" "endtask"))
7317 (setq functask (1- functask)))
7318 ((equal keywd "modport")
7319 (setq in-modport t))
7320 ;; Ifdef? Ignore name of define
7321 ((member keywd '("`ifdef" "`ifndef" "`elsif"))
7322 (setq rvalue t))
7323 ;; Type?
7324 ((verilog-typedef-name-p keywd)
7325 (setq typedefed keywd))
7326 ;; Interface with optional modport in v2k arglist?
7327 ;; Skip over parsing modport, and take the interface name as the type
7328 ((and v2kargs-ok
7329 (eq paren 1)
7330 (not rvalue)
7331 (looking-at "\\s-*\\(\\.\\(\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*\\)\\|\\)\\s-*[a-zA-Z`_$][a-zA-Z0-9`_$]*"))
7332 (when (match-end 2) (goto-char (match-end 2)))
7333 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed keywd multidim nil sig-paren paren
7334 expect-signal 'sigs-intf io t modport (match-string 2)))
7335 ;; Ignore dotted LHS assignments: "assign foo.bar = z;"
7336 ((looking-at "\\s-*\\.")
7337 (goto-char (match-end 0))
7338 (when (not rvalue)
7339 (setq expect-signal nil)))
7340 ;; New signal, maybe?
7341 ((and expect-signal
7342 (not rvalue)
7343 (eq functask 0)
7344 (not in-modport)
7345 (not (member keywd verilog-keywords)))
7346 ;; Add new signal to expect-signal's variable
7347 (setq newsig (verilog-sig-new keywd vec nil nil enum signed typedefed multidim modport))
7348 (set expect-signal (cons newsig
7349 (symbol-value expect-signal))))))
7350 (t
7351 (forward-char 1)))
7352 (skip-syntax-forward " "))
7353 ;; Return arguments
7354 (verilog-decls-new (nreverse sigs-out)
7355 (nreverse sigs-inout)
7356 (nreverse sigs-in)
7357 (nreverse sigs-wire)
7358 (nreverse sigs-reg)
7359 (nreverse sigs-assign)
7360 (nreverse sigs-const)
7361 (nreverse sigs-gparam)
7362 (nreverse sigs-intf)))))
7363
7364 (defvar verilog-read-sub-decls-in-interfaced nil
7365 "For `verilog-read-sub-decls', process next signal as under interfaced block.")
7366
7367 (defvar verilog-read-sub-decls-gate-ios nil
7368 "For `verilog-read-sub-decls', gate IO pins remaining, nil if non-primitive.")
7369
7370 (eval-when-compile
7371 ;; Prevent compile warnings; these are let's, not globals
7372 ;; Do not remove the eval-when-compile
7373 ;; - we want a error when we are debugging this code if they are refed.
7374 (defvar sigs-in)
7375 (defvar sigs-inout)
7376 (defvar sigs-out)
7377 (defvar sigs-intf)
7378 (defvar sigs-intfd))
7379
7380 (defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
7381 "For `verilog-read-sub-decls-line', add a signal."
7382 ;; sig eq t to indicate .name syntax
7383 ;;(message "vrsds: %s(%S)" port sig)
7384 (let ((dotname (eq sig t))
7385 portdata)
7386 (when sig
7387 (setq port (verilog-symbol-detick-denumber port))
7388 (setq sig (if dotname port (verilog-symbol-detick-denumber sig)))
7389 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
7390 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
7391 (unless (or (not sig)
7392 (equal sig "")) ;; Ignore .foo(1'b1) assignments
7393 (cond ((or (setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
7394 (equal "inout" verilog-read-sub-decls-gate-ios))
7395 (setq sigs-inout
7396 (cons (verilog-sig-new
7397 sig
7398 (if dotname (verilog-sig-bits portdata) vec)
7399 (concat "To/From " comment)
7400 (verilog-sig-memory portdata)
7401 nil
7402 (verilog-sig-signed portdata)
7403 (verilog-sig-type portdata)
7404 multidim nil)
7405 sigs-inout)))
7406 ((or (setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
7407 (equal "output" verilog-read-sub-decls-gate-ios))
7408 (setq sigs-out
7409 (cons (verilog-sig-new
7410 sig
7411 (if dotname (verilog-sig-bits portdata) vec)
7412 (concat "From " comment)
7413 (verilog-sig-memory portdata)
7414 nil
7415 (verilog-sig-signed portdata)
7416 (verilog-sig-type portdata)
7417 multidim nil)
7418 sigs-out)))
7419 ((or (setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
7420 (equal "input" verilog-read-sub-decls-gate-ios))
7421 (setq sigs-in
7422 (cons (verilog-sig-new
7423 sig
7424 (if dotname (verilog-sig-bits portdata) vec)
7425 (concat "To " comment)
7426 (verilog-sig-memory portdata)
7427 nil
7428 (verilog-sig-signed portdata)
7429 (verilog-sig-type portdata)
7430 multidim nil)
7431 sigs-in)))
7432 ((setq portdata (assoc port (verilog-decls-get-interfaces submoddecls)))
7433 (setq sigs-intf
7434 (cons (verilog-sig-new
7435 sig
7436 (if dotname (verilog-sig-bits portdata) vec)
7437 (concat "To/From " comment)
7438 (verilog-sig-memory portdata)
7439 nil
7440 (verilog-sig-signed portdata)
7441 (verilog-sig-type portdata)
7442 multidim nil)
7443 sigs-intf)))
7444 ((setq portdata (and verilog-read-sub-decls-in-interfaced
7445 (or (assoc port (verilog-decls-get-regs submoddecls))
7446 (assoc port (verilog-decls-get-wires submoddecls)))))
7447 (setq sigs-intfd
7448 (cons (verilog-sig-new
7449 sig
7450 (if dotname (verilog-sig-bits portdata) vec)
7451 (concat "To/From " comment)
7452 (verilog-sig-memory portdata)
7453 nil
7454 (verilog-sig-signed portdata)
7455 (verilog-sig-type portdata)
7456 multidim nil)
7457 sigs-intf)))
7458 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
7459 )))))
7460
7461 (defun verilog-read-sub-decls-expr (submoddecls comment port expr)
7462 "For `verilog-read-sub-decls-line', parse a subexpression and add signals."
7463 ;;(message "vrsde: '%s'" expr)
7464 ;; Replace special /*[....]*/ comments inserted by verilog-auto-inst-port
7465 (setq expr (verilog-string-replace-matches "/\\*\\(\\[[^*]+\\]\\)\\*/" "\\1" nil nil expr))
7466 ;; Remove front operators
7467 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
7468 ;;
7469 (cond
7470 ;; {..., a, b} requires us to recurse on a,b
7471 ;; To support {#{},{#{a,b}} we'll just split everything on [{},]
7472 ((string-match "^\\s-*{\\(.*\\)}\\s-*$" expr)
7473 (unless verilog-auto-ignore-concat
7474 (let ((mlst (split-string (match-string 1 expr) "[{},]"))
7475 mstr)
7476 (while (setq mstr (pop mlst))
7477 (verilog-read-sub-decls-expr submoddecls comment port mstr)))))
7478 (t
7479 (let (sig vec multidim)
7480 ;; Remove leading reduction operators, etc
7481 (setq expr (verilog-string-replace-matches "^\\s-*[---+~!|&]+\\s-*" "" nil nil expr))
7482 ;;(message "vrsde-ptop: '%s'" expr)
7483 (cond ;; Find \signal. Final space is part of escaped signal name
7484 ((string-match "^\\s-*\\(\\\\[^ \t\n\f]+\\s-\\)" expr)
7485 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
7486 (setq sig (match-string 1 expr)
7487 expr (substring expr (match-end 0))))
7488 ;; Find signal
7489 ((string-match "^\\s-*\\([a-zA-Z_][a-zA-Z_0-9]*\\)" expr)
7490 ;;(message "vrsde-s: '%s'" (match-string 1 expr))
7491 (setq sig (verilog-string-remove-spaces (match-string 1 expr))
7492 expr (substring expr (match-end 0)))))
7493 ;; Find [vector] or [multi][multi][multi][vector]
7494 (while (string-match "^\\s-*\\(\\[[^]]+\\]\\)" expr)
7495 ;;(message "vrsde-v: '%s'" (match-string 1 expr))
7496 (when vec (setq multidim (cons vec multidim)))
7497 (setq vec (match-string 1 expr)
7498 expr (substring expr (match-end 0))))
7499 ;; If found signal, and nothing unrecognized, add the signal
7500 ;;(message "vrsde-rem: '%s'" expr)
7501 (when (and sig (string-match "^\\s-*$" expr))
7502 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))))
7503
7504 (defun verilog-read-sub-decls-line (submoddecls comment)
7505 "For `verilog-read-sub-decls', read lines of port defs until none match.
7506 Inserts the list of signals found, using submodi to look up each port."
7507 (let (done port)
7508 (save-excursion
7509 (forward-line 1)
7510 (while (not done)
7511 ;; Get port name
7512 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
7513 (setq port (match-string 1))
7514 (goto-char (match-end 0)))
7515 ;; .\escaped (
7516 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
7517 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
7518 (goto-char (match-end 0)))
7519 ;; .name
7520 ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*[,)/]")
7521 (verilog-read-sub-decls-sig
7522 submoddecls comment (match-string 1) t ; sig==t for .name
7523 nil nil) ; vec multidim
7524 (setq port nil))
7525 ;; .\escaped_name
7526 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*[,)/]")
7527 (verilog-read-sub-decls-sig
7528 submoddecls comment (concat (match-string 1) " ") t ; sig==t for .name
7529 nil nil) ; vec multidim
7530 (setq port nil))
7531 ;; random
7532 ((looking-at "\\s-*\\.[^(]*(")
7533 (setq port nil) ;; skip this line
7534 (goto-char (match-end 0)))
7535 (t
7536 (setq port nil done t))) ;; Unknown, ignore rest of line
7537 ;; Get signal name. Point is at the first-non-space after (
7538 ;; We intentionally ignore (non-escaped) signals with .s in them
7539 ;; this prevents AUTOWIRE etc from noticing hierarchical sigs.
7540 (when port
7541 (cond ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*)")
7542 (verilog-read-sub-decls-sig
7543 submoddecls comment port
7544 (verilog-string-remove-spaces (match-string 1)) ; sig
7545 nil nil)) ; vec multidim
7546 ;;
7547 ((looking-at "\\([a-zA-Z_][a-zA-Z_0-9]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
7548 (verilog-read-sub-decls-sig
7549 submoddecls comment port
7550 (verilog-string-remove-spaces (match-string 1)) ; sig
7551 (match-string 2) nil)) ; vec multidim
7552 ;; Fastpath was above looking-at's.
7553 ;; For something more complicated invoke a parser
7554 ((looking-at "[^)]+")
7555 (verilog-read-sub-decls-expr
7556 submoddecls comment port
7557 (buffer-substring
7558 (point) (1- (progn (search-backward "(") ; start at (
7559 (forward-sexp 1) (point)))))))) ; expr
7560 ;;
7561 (forward-line 1)))))
7562
7563 (defun verilog-read-sub-decls-gate (submoddecls comment submod end-inst-point)
7564 "For `verilog-read-sub-decls', read lines of UDP gate decl until none match.
7565 Inserts the list of signals found."
7566 (save-excursion
7567 (let ((iolist (cdr (assoc submod verilog-gate-ios))))
7568 (while (< (point) end-inst-point)
7569 ;; Get primitive's signal name, as will never have port, and no trailing )
7570 (cond ((looking-at "//")
7571 (search-forward "\n"))
7572 ((looking-at "/\\*")
7573 (or (search-forward "*/")
7574 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7575 ((looking-at "(\\*")
7576 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7577 (search-forward "*)")
7578 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7579 ;; On pins, parse and advance to next pin
7580 ;; Looking at pin, but *not* an // Output comment, or ) to end the inst
7581 ((looking-at "\\s-*[a-zA-Z0-9`_$({}\\\\][^,]*")
7582 (goto-char (match-end 0))
7583 (setq verilog-read-sub-decls-gate-ios (or (car iolist) "input")
7584 iolist (cdr iolist))
7585 (verilog-read-sub-decls-expr
7586 submoddecls comment "primitive_port"
7587 (match-string 0)))
7588 (t
7589 (forward-char 1)
7590 (skip-syntax-forward " ")))))))
7591
7592 (defun verilog-read-sub-decls ()
7593 "Internally parse signals going to modules under this module.
7594 Return a array of [ outputs inouts inputs ] signals for modules that are
7595 instantiated in this module. For example if declare A A (.B(SIG)) and SIG
7596 is a output, then SIG will be included in the list.
7597
7598 This only works on instantiations created with /*AUTOINST*/ converted by
7599 \\[verilog-auto-inst]. Otherwise, it would have to read in the whole
7600 component library to determine connectivity of the design.
7601
7602 One work around for this problem is to manually create // Inputs and //
7603 Outputs comments above subcell signals, for example:
7604
7605 module ModuleName (
7606 // Outputs
7607 .out (out),
7608 // Inputs
7609 .in (in));"
7610 (save-excursion
7611 (let ((end-mod-point (verilog-get-end-of-defun t))
7612 st-point end-inst-point
7613 ;; below 3 modified by verilog-read-sub-decls-line
7614 sigs-out sigs-inout sigs-in sigs-intf sigs-intfd)
7615 (verilog-beg-of-defun)
7616 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
7617 (save-excursion
7618 (goto-char (match-beginning 0))
7619 (unless (verilog-inside-comment-p)
7620 ;; Attempt to snarf a comment
7621 (let* ((submod (verilog-read-inst-module))
7622 (inst (verilog-read-inst-name))
7623 (subprim (member submod verilog-gate-keywords))
7624 (comment (concat inst " of " submod ".v"))
7625 submodi submoddecls)
7626 (cond
7627 (subprim
7628 (setq submodi `primitive
7629 submoddecls (verilog-decls-new nil nil nil nil nil nil nil nil nil)
7630 comment (concat inst " of " submod))
7631 (verilog-backward-open-paren)
7632 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
7633 st-point (point))
7634 (forward-char 1)
7635 (verilog-read-sub-decls-gate submoddecls comment submod end-inst-point))
7636 ;; Non-primitive
7637 (t
7638 (when (setq submodi (verilog-modi-lookup submod t))
7639 (setq submoddecls (verilog-modi-get-decls submodi)
7640 verilog-read-sub-decls-gate-ios nil)
7641 (verilog-backward-open-paren)
7642 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
7643 st-point (point))
7644 ;; This could have used a list created by verilog-auto-inst
7645 ;; However I want it to be runnable even on user's manually added signals
7646 (let ((verilog-read-sub-decls-in-interfaced t))
7647 (while (re-search-forward "\\s *(?\\s *// Interfaced" end-inst-point t)
7648 (verilog-read-sub-decls-line submoddecls comment))) ;; Modifies sigs-ifd
7649 (goto-char st-point)
7650 (while (re-search-forward "\\s *(?\\s *// Interfaces" end-inst-point t)
7651 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
7652 (goto-char st-point)
7653 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
7654 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
7655 (goto-char st-point)
7656 (while (re-search-forward "\\s *(?\\s *// Inouts" end-inst-point t)
7657 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
7658 (goto-char st-point)
7659 (while (re-search-forward "\\s *(?\\s *// Inputs" end-inst-point t)
7660 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
7661 )))))))
7662 ;; Combine duplicate bits
7663 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
7664 (verilog-subdecls-new
7665 (verilog-signals-combine-bus (nreverse sigs-out))
7666 (verilog-signals-combine-bus (nreverse sigs-inout))
7667 (verilog-signals-combine-bus (nreverse sigs-in))
7668 (verilog-signals-combine-bus (nreverse sigs-intf))
7669 (verilog-signals-combine-bus (nreverse sigs-intfd))))))
7670
7671 (defun verilog-read-inst-pins ()
7672 "Return an array of [ pins ] for the current instantiation at point.
7673 For example if declare A A (.B(SIG)) then B will be included in the list."
7674 (save-excursion
7675 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
7676 pins pin)
7677 (verilog-backward-open-paren)
7678 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
7679 (setq pin (match-string 1))
7680 (unless (verilog-inside-comment-p)
7681 (setq pins (cons (list pin) pins))
7682 (when (looking-at "(")
7683 (forward-sexp 1))))
7684 (vector pins))))
7685
7686 (defun verilog-read-arg-pins ()
7687 "Return an array of [ pins ] for the current argument declaration at point."
7688 (save-excursion
7689 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
7690 pins pin)
7691 (verilog-backward-open-paren)
7692 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
7693 (setq pin (match-string 1))
7694 (unless (verilog-inside-comment-p)
7695 (setq pins (cons (list pin) pins))))
7696 (vector pins))))
7697
7698 (defun verilog-read-auto-constants (beg end-mod-point)
7699 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
7700 ;; Insert new
7701 (save-excursion
7702 (let (sig-list tpl-end-pt)
7703 (goto-char beg)
7704 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
7705 (if (not (looking-at "\\s *("))
7706 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
7707 (search-forward "(" end-mod-point)
7708 (setq tpl-end-pt (save-excursion
7709 (backward-char 1)
7710 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7711 (backward-char 1)
7712 (point)))
7713 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
7714 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
7715 sig-list)))
7716
7717 (defvar verilog-cache-has-lisp nil "True if any AUTO_LISP in buffer.")
7718 (make-variable-buffer-local 'verilog-cache-has-lisp)
7719
7720 (defun verilog-read-auto-lisp-present ()
7721 "Set `verilog-cache-has-lisp' if any AUTO_LISP in this buffer."
7722 (save-excursion
7723 (setq verilog-cache-has-lisp (re-search-forward "\\<AUTO_LISP(" nil t))))
7724
7725 (defun verilog-read-auto-lisp (start end)
7726 "Look for and evaluate a AUTO_LISP between START and END.
7727 Must call `verilog-read-auto-lisp-present' before this function."
7728 ;; This function is expensive for large buffers, so we cache if any AUTO_LISP exists
7729 (when verilog-cache-has-lisp
7730 (save-excursion
7731 (goto-char start)
7732 (while (re-search-forward "\\<AUTO_LISP(" end t)
7733 (backward-char)
7734 (let* ((beg-pt (prog1 (point)
7735 (forward-sexp 1))) ;; Closing paren
7736 (end-pt (point)))
7737 (eval-region beg-pt end-pt nil))))))
7738
7739 (eval-when-compile
7740 ;; Prevent compile warnings; these are let's, not globals
7741 ;; Do not remove the eval-when-compile
7742 ;; - we want a error when we are debugging this code if they are refed.
7743 (defvar sigs-in)
7744 (defvar sigs-out)
7745 (defvar sigs-temp)
7746 (defvar uses-delayed)
7747 (defvar vector-skip-list))
7748
7749 (defun verilog-read-always-signals-recurse
7750 (exit-keywd rvalue temp-next)
7751 "Recursive routine for parentheses/bracket matching.
7752 EXIT-KEYWD is expression to stop at, nil if top level.
7753 RVALUE is true if at right hand side of equal.
7754 IGNORE-NEXT is true to ignore next token, fake from inside case statement."
7755 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
7756 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-list end-else-check
7757 ignore-next)
7758 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue temp-next))))
7759 (while (not (or (eobp) gotend))
7760 (cond
7761 ((looking-at "//")
7762 (search-forward "\n"))
7763 ((looking-at "/\\*")
7764 (or (search-forward "*/")
7765 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
7766 ((looking-at "(\\*")
7767 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
7768 (search-forward "*)")
7769 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
7770 (t (setq keywd (buffer-substring-no-properties
7771 (point)
7772 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7773 (forward-char 1))
7774 (point)))
7775 sig-last-tolk sig-tolk
7776 sig-tolk nil)
7777 ;;(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))))
7778 (cond
7779 ((equal keywd "\"")
7780 (or (re-search-forward "[^\\]\"" nil t)
7781 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
7782 ;; else at top level loop, keep parsing
7783 ((and end-else-check (equal keywd "else"))
7784 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
7785 ;; no forward movement, want to see else in lower loop
7786 (setq end-else-check nil))
7787 ;; End at top level loop
7788 ((and end-else-check (looking-at "[^ \t\n\f]"))
7789 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
7790 (setq gotend t))
7791 ;; Final statement?
7792 ((and exit-keywd (equal keywd exit-keywd))
7793 (setq gotend t)
7794 (forward-char (length keywd)))
7795 ;; Standard tokens...
7796 ((equal keywd ";")
7797 (setq ignore-next nil rvalue semi-rvalue)
7798 ;; Final statement at top level loop?
7799 (when (not exit-keywd)
7800 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
7801 (setq end-else-check t))
7802 (forward-char 1))
7803 ((equal keywd "'")
7804 (if (looking-at "'[sS]?[hdxboHDXBO]?[ \t]*[0-9a-fA-F_xzXZ?]+")
7805 (goto-char (match-end 0))
7806 (forward-char 1)))
7807 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
7808 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
7809 (setq ignore-next nil rvalue nil))
7810 ((equal "?" exit-keywd) ;; x?y:z rvalue
7811 ) ;; NOP
7812 ((equal "]" exit-keywd) ;; [x:y] rvalue
7813 ) ;; NOP
7814 (got-sig ;; label: statement
7815 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
7816 ((not rvalue) ;; begin label
7817 (setq ignore-next t rvalue nil)))
7818 (forward-char 1))
7819 ((equal keywd "=")
7820 (if (and (eq (char-before) ?< )
7821 (not rvalue))
7822 (setq uses-delayed 1))
7823 (setq ignore-next nil rvalue t)
7824 (forward-char 1))
7825 ((equal keywd "?")
7826 (forward-char 1)
7827 (verilog-read-always-signals-recurse ":" rvalue nil))
7828 ((equal keywd "[")
7829 (forward-char 1)
7830 (verilog-read-always-signals-recurse "]" t nil))
7831 ((equal keywd "(")
7832 (forward-char 1)
7833 (cond (sig-last-tolk ;; Function call; zap last signal
7834 (setq got-sig nil)))
7835 (cond ((equal last-keywd "for")
7836 ;; temp-next: Variables on LHS are lvalues, but generally we want
7837 ;; to ignore them, assuming they are loop increments
7838 (verilog-read-always-signals-recurse ";" nil t)
7839 (verilog-read-always-signals-recurse ";" t nil)
7840 (verilog-read-always-signals-recurse ")" nil nil))
7841 (t (verilog-read-always-signals-recurse ")" t nil))))
7842 ((equal keywd "begin")
7843 (skip-syntax-forward "w_")
7844 (verilog-read-always-signals-recurse "end" nil nil)
7845 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
7846 (setq ignore-next nil rvalue semi-rvalue)
7847 (if (not exit-keywd) (setq end-else-check t)))
7848 ((member keywd '("case" "casex" "casez"))
7849 (skip-syntax-forward "w_")
7850 (verilog-read-always-signals-recurse "endcase" t nil)
7851 (setq ignore-next nil rvalue semi-rvalue)
7852 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
7853 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
7854 (cond ((member keywd '("`ifdef" "`ifndef" "`elsif"))
7855 (setq ignore-next t))
7856 ((or ignore-next
7857 (member keywd verilog-keywords)
7858 (string-match "^\\$" keywd)) ;; PLI task
7859 (setq ignore-next nil))
7860 (t
7861 (setq keywd (verilog-symbol-detick-denumber keywd))
7862 (when got-sig
7863 (set got-list (cons got-sig (symbol-value got-list)))
7864 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S got-list=%S\n" got-sig got-list))))
7865 )
7866 (setq got-list (cond (temp-next 'sigs-temp)
7867 (rvalue 'sigs-in)
7868 (t 'sigs-out))
7869 got-sig (if (or (not keywd)
7870 (assoc keywd (symbol-value got-list)))
7871 nil (list keywd nil nil))
7872 temp-next nil
7873 sig-tolk t)))
7874 (skip-chars-forward "a-zA-Z0-9$_.%`"))
7875 (t
7876 (forward-char 1)))
7877 ;; End of non-comment token
7878 (setq last-keywd keywd)))
7879 (skip-syntax-forward " "))
7880 ;; Append the final pending signal
7881 (when got-sig
7882 ;;(if dbg (setq dbg (concat dbg (format "\t\tfinal got-sig=%S got-list=%s\n" got-sig got-list))))
7883 (set got-list (cons got-sig (symbol-value got-list)))
7884 (setq got-sig nil))
7885 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
7886 ))
7887
7888 (defun verilog-read-always-signals ()
7889 "Parse always block at point and return list of (outputs inout inputs)."
7890 (save-excursion
7891 (let* (;;(dbg "")
7892 sigs-out sigs-temp sigs-in
7893 uses-delayed) ;; Found signal/rvalue; push if not function
7894 (search-forward ")")
7895 (verilog-read-always-signals-recurse nil nil nil)
7896 ;;(if dbg (with-current-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg ""))
7897 ;; Return what was found
7898 (verilog-alw-new sigs-out sigs-temp sigs-in uses-delayed))))
7899
7900 (defun verilog-read-instants ()
7901 "Parse module at point and return list of ( ( file instance ) ... )."
7902 (verilog-beg-of-defun)
7903 (let* ((end-mod-point (verilog-get-end-of-defun t))
7904 (state nil)
7905 (instants-list nil))
7906 (save-excursion
7907 (while (< (point) end-mod-point)
7908 ;; Stay at level 0, no comments
7909 (while (progn
7910 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
7911 (or (> (car state) 0) ; in parens
7912 (nth 5 state) ; comment
7913 ))
7914 (forward-line 1))
7915 (beginning-of-line)
7916 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
7917 ;;(if (looking-at "^\\(.+\\)$")
7918 (let ((module (match-string 1))
7919 (instant (match-string 2)))
7920 (if (not (member module verilog-keywords))
7921 (setq instants-list (cons (list module instant) instants-list)))))
7922 (forward-line 1)))
7923 instants-list))
7924
7925
7926 (defun verilog-read-auto-template (module)
7927 "Look for a auto_template for the instantiation of the given MODULE.
7928 If found returns the signal name connections. Return REGEXP and
7929 list of ( (signal_name connection_name)... )."
7930 (save-excursion
7931 ;; Find beginning
7932 (let ((tpl-regexp "\\([0-9]+\\)")
7933 (lineno 0)
7934 (templateno 0)
7935 (pt (point))
7936 tpl-sig-list tpl-wild-list tpl-end-pt rep)
7937 ;; Note this search is expensive, as we hunt from mod-begin to point
7938 ;; for every instantiation. Likewise in verilog-read-auto-lisp.
7939 ;; So, we look first for an exact string rather than a slow regexp.
7940 ;; Someday we may keep a cache of every template, but this would also
7941 ;; need to record the relative position of each AUTOINST, as multiple
7942 ;; templates exist for each module, and we're inserting lines.
7943 (cond ((or
7944 (verilog-re-search-backward-substr
7945 "AUTO_TEMPLATE"
7946 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
7947 ;; Also try forward of this AUTOINST
7948 ;; This is for historical support; this isn't speced as working
7949 (progn
7950 (goto-char pt)
7951 (verilog-re-search-forward-substr
7952 "AUTO_TEMPLATE"
7953 (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
7954 (goto-char (match-end 0))
7955 ;; Parse "REGEXP"
7956 ;; We reserve @"..." for future lisp expressions that evaluate
7957 ;; once-per-AUTOINST
7958 (when (looking-at "\\s-*\"\\([^\"]*\\)\"")
7959 (setq tpl-regexp (match-string 1))
7960 (goto-char (match-end 0)))
7961 (search-forward "(")
7962 ;; Parse lines in the template
7963 (when verilog-auto-inst-template-numbers
7964 (save-excursion
7965 (goto-char (point-min))
7966 (while (search-forward "AUTO_TEMPLATE" nil t)
7967 (setq templateno (1+ templateno)))))
7968 (setq tpl-end-pt (save-excursion
7969 (backward-char 1)
7970 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7971 (backward-char 1)
7972 (point)))
7973 ;;
7974 (while (< (point) tpl-end-pt)
7975 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7976 (setq tpl-sig-list (cons (list
7977 (match-string-no-properties 1)
7978 (match-string-no-properties 2)
7979 templateno lineno)
7980 tpl-sig-list))
7981 (goto-char (match-end 0)))
7982 ;; Regexp form??
7983 ((looking-at
7984 ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
7985 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
7986 (setq rep (match-string-no-properties 3))
7987 (goto-char (match-end 0))
7988 (setq tpl-wild-list
7989 (cons (list
7990 (concat "^"
7991 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
7992 (match-string 1))
7993 "$")
7994 rep
7995 templateno lineno)
7996 tpl-wild-list)))
7997 ((looking-at "[ \t\f]+")
7998 (goto-char (match-end 0)))
7999 ((looking-at "\n")
8000 (setq lineno (1+ lineno))
8001 (goto-char (match-end 0)))
8002 ((looking-at "//")
8003 (search-forward "\n"))
8004 ((looking-at "/\\*")
8005 (forward-char 2)
8006 (or (search-forward "*/")
8007 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
8008 (t
8009 (error "%s: AUTO_TEMPLATE parsing error: %s"
8010 (verilog-point-text)
8011 (progn (looking-at ".*$") (match-string 0))))))
8012 ;; Return
8013 (vector tpl-regexp
8014 (list tpl-sig-list tpl-wild-list)))
8015 ;; If no template found
8016 (t (vector tpl-regexp nil))))))
8017 ;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
8018
8019 (defun verilog-set-define (defname defvalue &optional buffer enumname)
8020 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
8021 Optionally associate it with the specified enumeration ENUMNAME."
8022 (with-current-buffer (or buffer (current-buffer))
8023 (let ((mac (intern (concat "vh-" defname))))
8024 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
8025 ;; Need to define to a constant if no value given
8026 (set (make-local-variable mac)
8027 (if (equal defvalue "") "1" defvalue)))
8028 (if enumname
8029 (let ((enumvar (intern (concat "venum-" enumname))))
8030 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
8031 (unless (boundp enumvar) (set enumvar nil))
8032 (add-to-list (make-local-variable enumvar) defname)))))
8033
8034 (defun verilog-read-defines (&optional filename recurse subcall)
8035 "Read `defines and parameters for the current file, or optional FILENAME.
8036 If the filename is provided, `verilog-library-flags' will be used to
8037 resolve it. If optional RECURSE is non-nil, recurse through `includes.
8038
8039 Parameters must be simple assignments to constants, or have their own
8040 \"parameter\" label rather than a list of parameters. Thus:
8041
8042 parameter X = 5, Y = 10; // Ok
8043 parameter X = {1'b1, 2'h2}; // Ok
8044 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
8045
8046 Defines must be simple text substitutions, one on a line, starting
8047 at the beginning of the line. Any ifdefs or multiline comments around the
8048 define are ignored.
8049
8050 Defines are stored inside Emacs variables using the name vh-{definename}.
8051
8052 This function is useful for setting vh-* variables. The file variables
8053 feature can be used to set defines that `verilog-mode' can see; put at the
8054 *END* of your file something like:
8055
8056 // Local Variables:
8057 // vh-macro:\"macro_definition\"
8058 // End:
8059
8060 If macros are defined earlier in the same file and you want their values,
8061 you can read them automatically (provided `enable-local-eval' is on):
8062
8063 // Local Variables:
8064 // eval:(verilog-read-defines)
8065 // eval:(verilog-read-defines \"group_standard_includes.v\")
8066 // End:
8067
8068 Note these are only read when the file is first visited, you must use
8069 \\[find-alternate-file] RET to have these take effect after editing them!
8070
8071 If you want to disable the \"Process `eval' or hook local variables\"
8072 warning message, you need to add to your .emacs file:
8073
8074 (setq enable-local-eval t)"
8075 (let ((origbuf (current-buffer)))
8076 (save-excursion
8077 (unless subcall (verilog-getopt-flags))
8078 (when filename
8079 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
8080 (if fns
8081 (set-buffer (find-file-noselect (car fns)))
8082 (error (concat (verilog-point-text)
8083 ": Can't find verilog-read-defines file: " filename)))))
8084 (when recurse
8085 (goto-char (point-min))
8086 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
8087 (let ((inc (verilog-string-replace-matches
8088 "\"" "" nil nil (match-string-no-properties 1))))
8089 (unless (verilog-inside-comment-p)
8090 (verilog-read-defines inc recurse t)))))
8091 ;; Read `defines
8092 ;; note we don't use verilog-re... it's faster this way, and that
8093 ;; function has problems when comments are at the end of the define
8094 (goto-char (point-min))
8095 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
8096 (let ((defname (match-string-no-properties 1))
8097 (defvalue (match-string-no-properties 2)))
8098 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
8099 (verilog-set-define defname defvalue origbuf)))
8100 ;; Hack: Read parameters
8101 (goto-char (point-min))
8102 (while (re-search-forward
8103 "^\\s-*\\(parameter\\|localparam\\)\\(\\s-*\\[[^]]*\\]\\)?\\s-+" nil t)
8104 (let (enumname)
8105 ;; The primary way of getting defines is verilog-read-decls
8106 ;; However, that isn't called yet for included files, so we'll add another scheme
8107 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
8108 (setq enumname (match-string-no-properties 1)))
8109 (forward-comment 999)
8110 (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
8111 (verilog-set-define (match-string-no-properties 1)
8112 (match-string-no-properties 2) origbuf enumname)
8113 (goto-char (match-end 0))
8114 (forward-comment 999)))))))
8115
8116 (defun verilog-read-includes ()
8117 "Read `includes for the current file.
8118 This will find all of the `includes which are at the beginning of lines,
8119 ignoring any ifdefs or multiline comments around them.
8120 `verilog-read-defines' is then performed on the current and each included
8121 file.
8122
8123 It is often useful put at the *END* of your file something like:
8124
8125 // Local Variables:
8126 // eval:(verilog-read-defines)
8127 // eval:(verilog-read-includes)
8128 // End:
8129
8130 Note includes are only read when the file is first visited, you must use
8131 \\[find-alternate-file] RET to have these take effect after editing them!
8132
8133 It is good to get in the habit of including all needed files in each .v
8134 file that needs it, rather than waiting for compile time. This will aid
8135 this process, Verilint, and readability. To prevent defining the same
8136 variable over and over when many modules are compiled together, put a test
8137 around the inside each include file:
8138
8139 foo.v (a include):
8140 `ifdef _FOO_V // include if not already included
8141 `else
8142 `define _FOO_V
8143 ... contents of file
8144 `endif // _FOO_V"
8145 ;;slow: (verilog-read-defines nil t))
8146 (save-excursion
8147 (verilog-getopt-flags)
8148 (goto-char (point-min))
8149 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
8150 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
8151 (verilog-read-defines inc nil t)))))
8152
8153 (defun verilog-read-signals (&optional start end)
8154 "Return a simple list of all possible signals in the file.
8155 Bounded by optional region from START to END. Overly aggressive but fast.
8156 Some macros and such are also found and included. For dinotrace.el."
8157 (let (sigs-all keywd)
8158 (progn;save-excursion
8159 (goto-char (or start (point-min)))
8160 (setq end (or end (point-max)))
8161 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
8162 (forward-char -1)
8163 (cond
8164 ((looking-at "//")
8165 (search-forward "\n"))
8166 ((looking-at "/\\*")
8167 (search-forward "*/"))
8168 ((looking-at "(\\*")
8169 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
8170 (search-forward "*)")))
8171 ((eq ?\" (following-char))
8172 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
8173 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
8174 (goto-char (match-end 0))
8175 (setq keywd (match-string-no-properties 1))
8176 (or (member keywd verilog-keywords)
8177 (member keywd sigs-all)
8178 (setq sigs-all (cons keywd sigs-all))))
8179 (t (forward-char 1))))
8180 ;; Return list
8181 sigs-all)))
8182
8183 ;;
8184 ;; Argument file parsing
8185 ;;
8186
8187 (defun verilog-getopt (arglist)
8188 "Parse -f, -v etc arguments in ARGLIST list or string."
8189 (unless (listp arglist) (setq arglist (list arglist)))
8190 (let ((space-args '())
8191 arg next-param)
8192 ;; Split on spaces, so users can pass whole command lines
8193 (while arglist
8194 (setq arg (car arglist)
8195 arglist (cdr arglist))
8196 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
8197 (setq space-args (append space-args
8198 (list (match-string-no-properties 1 arg))))
8199 (setq arg (match-string 2 arg))))
8200 ;; Parse arguments
8201 (while space-args
8202 (setq arg (car space-args)
8203 space-args (cdr space-args))
8204 (cond
8205 ;; Need another arg
8206 ((equal arg "-f")
8207 (setq next-param arg))
8208 ((equal arg "-v")
8209 (setq next-param arg))
8210 ((equal arg "-y")
8211 (setq next-param arg))
8212 ;; +libext+(ext1)+(ext2)...
8213 ((string-match "^\\+libext\\+\\(.*\\)" arg)
8214 (setq arg (match-string 1 arg))
8215 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
8216 (verilog-add-list-unique `verilog-library-extensions
8217 (match-string 1 arg))
8218 (setq arg (match-string 2 arg))))
8219 ;;
8220 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
8221 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
8222 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
8223 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
8224 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
8225 ;;
8226 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
8227 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
8228 (verilog-add-list-unique `verilog-library-directories
8229 (match-string 1 (substitute-in-file-name arg))))
8230 ;; Ignore
8231 ((equal "+librescan" arg))
8232 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
8233 ;; Second parameters
8234 ((equal next-param "-f")
8235 (setq next-param nil)
8236 (verilog-getopt-file (substitute-in-file-name arg)))
8237 ((equal next-param "-v")
8238 (setq next-param nil)
8239 (verilog-add-list-unique `verilog-library-files
8240 (substitute-in-file-name arg)))
8241 ((equal next-param "-y")
8242 (setq next-param nil)
8243 (verilog-add-list-unique `verilog-library-directories
8244 (substitute-in-file-name arg)))
8245 ;; Filename
8246 ((string-match "^[^-+]" arg)
8247 (verilog-add-list-unique `verilog-library-files
8248 (substitute-in-file-name arg)))
8249 ;; Default - ignore; no warning
8250 ))))
8251 ;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
8252
8253 (defun verilog-getopt-file (filename)
8254 "Read Verilog options from the specified FILENAME."
8255 (save-excursion
8256 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
8257 (orig-buffer (current-buffer))
8258 line)
8259 (if fns
8260 (set-buffer (find-file-noselect (car fns)))
8261 (error (concat (verilog-point-text)
8262 ": Can't find verilog-getopt-file -f file: " filename)))
8263 (goto-char (point-min))
8264 (while (not (eobp))
8265 (setq line (buffer-substring (point) (point-at-eol)))
8266 (forward-line 1)
8267 (when (string-match "//" line)
8268 (setq line (substring line 0 (match-beginning 0))))
8269 (with-current-buffer orig-buffer ; Variables are buffer-local, so need right context.
8270 (verilog-getopt line))))))
8271
8272 (defun verilog-getopt-flags ()
8273 "Convert `verilog-library-flags' into standard library variables."
8274 ;; If the flags are local, then all the outputs should be local also
8275 (when (local-variable-p `verilog-library-flags (current-buffer))
8276 (mapc 'make-local-variable '(verilog-library-extensions
8277 verilog-library-directories
8278 verilog-library-files
8279 verilog-library-flags)))
8280 ;; Allow user to customize
8281 (run-hooks 'verilog-before-getopt-flags-hook)
8282 ;; Process arguments
8283 (verilog-getopt verilog-library-flags)
8284 ;; Allow user to customize
8285 (run-hooks 'verilog-getopt-flags-hook))
8286
8287 (defun verilog-add-list-unique (varref object)
8288 "Append to VARREF list the given OBJECT,
8289 unless it is already a member of the variable's list."
8290 (unless (member object (symbol-value varref))
8291 (set varref (append (symbol-value varref) (list object))))
8292 varref)
8293 ;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
8294
8295 (defun verilog-current-flags ()
8296 "Convert `verilog-library-flags' and similar variables to command line.
8297 Used for __FLAGS__ in `verilog-expand-command'."
8298 (let ((cmd (mapconcat `concat verilog-library-flags " ")))
8299 (when (equal cmd "")
8300 (setq cmd (concat
8301 "+libext+" (mapconcat `concat verilog-library-extensions "+")
8302 (mapconcat (lambda (i) (concat " -y " i " +incdir+" i))
8303 verilog-library-directories "")
8304 (mapconcat (lambda (i) (concat " -v " i))
8305 verilog-library-files ""))))
8306 cmd))
8307 ;;(verilog-current-flags)
8308
8309 \f
8310 ;;
8311 ;; Cached directory support
8312 ;;
8313
8314 (defvar verilog-dir-cache-preserving nil
8315 "If set, the directory cache is enabled, and file system changes are ignored.
8316 See `verilog-dir-exists-p' and `verilog-dir-files'.")
8317
8318 ;; If adding new cached variable, add also to verilog-preserve-dir-cache
8319 (defvar verilog-dir-cache-list nil
8320 "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
8321 (defvar verilog-dir-cache-lib-filenames nil
8322 "Cached data for `verilog-library-filenames'.")
8323
8324 (defmacro verilog-preserve-dir-cache (&rest body)
8325 "Execute the BODY forms, allowing directory cache preservation within BODY.
8326 This means that changes inside BODY made to the file system will not be
8327 seen by the `verilog-dir-files' and related functions."
8328 `(let ((verilog-dir-cache-preserving (current-buffer))
8329 verilog-dir-cache-list
8330 verilog-dir-cache-lib-filenames)
8331 (progn ,@body)))
8332
8333 (defun verilog-dir-files (dirname)
8334 "Return all filenames in the DIRNAME directory.
8335 Relative paths depend on the `default-directory'.
8336 Results are cached if inside `verilog-preserve-dir-cache'."
8337 (unless verilog-dir-cache-preserving
8338 (setq verilog-dir-cache-list nil)) ;; Cache disabled
8339 ;; We don't use expand-file-name on the dirname to make key, as it's slow
8340 (let* ((cache-key (list dirname default-directory))
8341 (fass (assoc cache-key verilog-dir-cache-list))
8342 exp-dirname data)
8343 (cond (fass ;; Return data from cache hit
8344 (nth 1 fass))
8345 (t
8346 (setq exp-dirname (expand-file-name dirname)
8347 data (and (file-directory-p exp-dirname)
8348 (directory-files exp-dirname nil nil nil)))
8349 ;; Note we also encache nil for non-existing dirs.
8350 (setq verilog-dir-cache-list (cons (list cache-key data)
8351 verilog-dir-cache-list))
8352 data))))
8353 ;; Miss-and-hit test:
8354 ;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
8355 ;; (prin1 (verilog-dir-files ".")) nil)
8356
8357 (defun verilog-dir-file-exists-p (filename)
8358 "Return true if FILENAME exists.
8359 Like `file-exists-p' but results are cached if inside
8360 `verilog-preserve-dir-cache'."
8361 (let* ((dirname (file-name-directory filename))
8362 ;; Correct for file-name-nondirectory returning same if no slash.
8363 (dirnamed (if (or (not dirname) (equal dirname filename))
8364 default-directory dirname))
8365 (flist (verilog-dir-files dirnamed)))
8366 (and flist
8367 (member (file-name-nondirectory filename) flist)
8368 t)))
8369 ;;(verilog-dir-file-exists-p "verilog-mode.el")
8370 ;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
8371
8372 \f
8373 ;;
8374 ;; Module name lookup
8375 ;;
8376
8377 (defun verilog-module-inside-filename-p (module filename)
8378 "Return modi if MODULE is specified inside FILENAME, else nil.
8379 Allows version control to check out the file if need be."
8380 (and (or (file-exists-p filename)
8381 (and (fboundp 'vc-backend)
8382 (vc-backend filename)))
8383 (let (modi type)
8384 (with-current-buffer (find-file-noselect filename)
8385 (save-excursion
8386 (goto-char (point-min))
8387 (while (and
8388 ;; It may be tempting to look for verilog-defun-re,
8389 ;; don't, it slows things down a lot!
8390 (verilog-re-search-forward-quick "\\<\\(module\\|interface\\)\\>" nil t)
8391 (setq type (match-string-no-properties 0))
8392 (verilog-re-search-forward-quick "[(;]" nil t))
8393 (if (equal module (verilog-read-module-name))
8394 (setq modi (verilog-modi-new module filename (point) type))))
8395 modi)))))
8396
8397 (defun verilog-is-number (symbol)
8398 "Return true if SYMBOL is number-like."
8399 (or (string-match "^[0-9 \t:]+$" symbol)
8400 (string-match "^[---]*[0-9]+$" symbol)
8401 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
8402
8403 (defun verilog-symbol-detick (symbol wing-it)
8404 "Return an expanded SYMBOL name without any defines.
8405 If the variable vh-{symbol} is defined, return that value.
8406 If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
8407 (while (and symbol (string-match "^`" symbol))
8408 (setq symbol (substring symbol 1))
8409 (setq symbol
8410 (if (boundp (intern (concat "vh-" symbol)))
8411 ;; Emacs has a bug where boundp on a buffer-local
8412 ;; variable in only one buffer returns t in another.
8413 ;; This can confuse, so check for nil.
8414 (let ((val (eval (intern (concat "vh-" symbol)))))
8415 (if (eq val nil)
8416 (if wing-it symbol nil)
8417 val))
8418 (if wing-it symbol nil))))
8419 symbol)
8420 ;;(verilog-symbol-detick "`mod" nil)
8421
8422 (defun verilog-symbol-detick-denumber (symbol)
8423 "Return SYMBOL with defines converted and any numbers dropped to nil."
8424 (when (string-match "^`" symbol)
8425 ;; This only will work if the define is a simple signal, not
8426 ;; something like a[b]. Sorry, it should be substituted into the parser
8427 (setq symbol
8428 (verilog-string-replace-matches
8429 "\[[^0-9: \t]+\]" "" nil nil
8430 (or (verilog-symbol-detick symbol nil)
8431 (if verilog-auto-sense-defines-constant
8432 "0"
8433 symbol)))))
8434 (if (verilog-is-number symbol)
8435 nil
8436 symbol))
8437
8438 (defun verilog-symbol-detick-text (text)
8439 "Return TEXT without any known defines.
8440 If the variable vh-{symbol} is defined, substitute that value."
8441 (let ((ok t) symbol val)
8442 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
8443 (setq symbol (match-string 1 text))
8444 ;;(message symbol)
8445 (cond ((and
8446 (boundp (intern (concat "vh-" symbol)))
8447 ;; Emacs has a bug where boundp on a buffer-local
8448 ;; variable in only one buffer returns t in another.
8449 ;; This can confuse, so check for nil.
8450 (setq val (eval (intern (concat "vh-" symbol)))))
8451 (setq text (replace-match val nil nil text)))
8452 (t (setq ok nil)))))
8453 text)
8454 ;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
8455
8456 (defun verilog-expand-dirnames (&optional dirnames)
8457 "Return a list of existing directories given a list of wildcarded DIRNAMES.
8458 Or, just the existing dirnames themselves if there are no wildcards."
8459 ;; Note this function is performance critical.
8460 ;; Do not call anything that requires disk access that cannot be cached.
8461 (interactive)
8462 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
8463 (setq dirnames (reverse dirnames)) ; not nreverse
8464 (let ((dirlist nil)
8465 pattern dirfile dirfiles dirname root filename rest basefile)
8466 (while dirnames
8467 (setq dirname (substitute-in-file-name (car dirnames))
8468 dirnames (cdr dirnames))
8469 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
8470 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
8471 "\\(.*\\)") ;; rest
8472 dirname)
8473 (setq root (match-string 1 dirname)
8474 filename (match-string 2 dirname)
8475 rest (match-string 3 dirname)
8476 pattern filename)
8477 ;; now replace those * and ? with .+ and .
8478 ;; use ^ and /> to get only whole file names
8479 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
8480 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
8481 pattern (concat "^" pattern "$")
8482 dirfiles (verilog-dir-files root))
8483 (while dirfiles
8484 (setq basefile (car dirfiles)
8485 dirfile (expand-file-name (concat root basefile rest))
8486 dirfiles (cdr dirfiles))
8487 (if (and (string-match pattern basefile)
8488 ;; Don't allow abc/*/rtl to match abc/rtl via ..
8489 (not (equal basefile "."))
8490 (not (equal basefile ".."))
8491 (file-directory-p dirfile))
8492 (setq dirlist (cons dirfile dirlist)))))
8493 ;; Defaults
8494 (t
8495 (if (file-directory-p dirname)
8496 (setq dirlist (cons dirname dirlist))))))
8497 dirlist))
8498 ;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
8499
8500 (defun verilog-library-filenames (filename &optional current check-ext)
8501 "Return a search path to find the given FILENAME or module name.
8502 Uses the optional CURRENT filename or buffer-file-name, plus
8503 `verilog-library-directories' and `verilog-library-extensions'
8504 variables to build the path. With optional CHECK-EXT also check
8505 `verilog-library-extensions'."
8506 (unless current (setq current (buffer-file-name)))
8507 (unless verilog-dir-cache-preserving
8508 (setq verilog-dir-cache-lib-filenames nil))
8509 (let* ((cache-key (list filename current check-ext))
8510 (fass (assoc cache-key verilog-dir-cache-lib-filenames))
8511 chkdirs chkdir chkexts fn outlist)
8512 (cond (fass ;; Return data from cache hit
8513 (nth 1 fass))
8514 (t
8515 ;; Note this expand can't be easily cached, as we need to
8516 ;; pick up buffer-local variables for newly read sub-module files
8517 (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
8518 (while chkdirs
8519 (setq chkdir (expand-file-name (car chkdirs)
8520 (file-name-directory current))
8521 chkexts (if check-ext verilog-library-extensions `("")))
8522 (while chkexts
8523 (setq fn (expand-file-name (concat filename (car chkexts))
8524 chkdir))
8525 ;;(message "Check for %s" fn)
8526 (if (verilog-dir-file-exists-p fn)
8527 (setq outlist (cons (expand-file-name
8528 fn (file-name-directory current))
8529 outlist)))
8530 (setq chkexts (cdr chkexts)))
8531 (setq chkdirs (cdr chkdirs)))
8532 (setq outlist (nreverse outlist))
8533 (setq verilog-dir-cache-lib-filenames
8534 (cons (list cache-key outlist)
8535 verilog-dir-cache-lib-filenames))
8536 outlist))))
8537
8538 (defun verilog-module-filenames (module current)
8539 "Return a search path to find the given MODULE name.
8540 Uses the CURRENT filename, `verilog-library-extensions',
8541 `verilog-library-directories' and `verilog-library-files'
8542 variables to build the path."
8543 ;; Return search locations for it
8544 (append (list current) ; first, current buffer
8545 (verilog-library-filenames module current t)
8546 verilog-library-files)) ; finally, any libraries
8547
8548 ;;
8549 ;; Module Information
8550 ;;
8551 ;; Many of these functions work on "modi" a module information structure
8552 ;; A modi is: [module-name-string file-name begin-point]
8553
8554 (defvar verilog-cache-enabled t
8555 "If true, enable caching of signals, etc. Set to nil for debugging to make things SLOW!")
8556
8557 (defvar verilog-modi-cache-list nil
8558 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
8559 For speeding up verilog-modi-get-* commands.
8560 Buffer-local.")
8561 (make-variable-buffer-local 'verilog-modi-cache-list)
8562
8563 (defvar verilog-modi-cache-preserve-tick nil
8564 "Modification tick after which the cache is still considered valid.
8565 Use `verilog-preserve-modi-cache' to set it.")
8566 (defvar verilog-modi-cache-preserve-buffer nil
8567 "Modification tick after which the cache is still considered valid.
8568 Use `verilog-preserve-modi-cache' to set it.")
8569 (defvar verilog-modi-cache-current-enable nil
8570 "If true, allow caching `verilog-modi-current', set by let().")
8571 (defvar verilog-modi-cache-current nil
8572 "Currently active `verilog-modi-current', if any, set by let().")
8573 (defvar verilog-modi-cache-current-max nil
8574 "Current endmodule point for `verilog-modi-cache-current', if any.")
8575
8576 (defun verilog-modi-current ()
8577 "Return the modi structure for the module currently at point, possibly cached."
8578 (cond ((and verilog-modi-cache-current
8579 (>= (point) (verilog-modi-get-point verilog-modi-cache-current))
8580 (<= (point) verilog-modi-cache-current-max))
8581 ;; Slow assertion, for debugging the cache:
8582 ;;(or (equal verilog-modi-cache-current (verilog-modi-current-get)) (debug))
8583 verilog-modi-cache-current)
8584 (verilog-modi-cache-current-enable
8585 (setq verilog-modi-cache-current (verilog-modi-current-get)
8586 verilog-modi-cache-current-max
8587 ;; The cache expires when we pass "endmodule" as then the
8588 ;; current modi may change to the next module
8589 ;; This relies on the AUTOs generally inserting, not deleting text
8590 (save-excursion
8591 (verilog-re-search-forward-quick verilog-end-defun-re nil nil)))
8592 verilog-modi-cache-current)
8593 (t
8594 (verilog-modi-current-get))))
8595
8596 (defun verilog-modi-current-get ()
8597 "Return the modi structure for the module currently at point."
8598 (let* (name type pt)
8599 ;; read current module's name
8600 (save-excursion
8601 (verilog-re-search-backward-quick verilog-defun-re nil nil)
8602 (setq type (match-string-no-properties 0))
8603 (verilog-re-search-forward-quick "(" nil nil)
8604 (setq name (verilog-read-module-name))
8605 (setq pt (point)))
8606 ;; return modi - note this vector built two places
8607 (verilog-modi-new name (or (buffer-file-name) (current-buffer)) pt type)))
8608
8609 (defvar verilog-modi-lookup-cache nil "Hash of (modulename modi).")
8610 (make-variable-buffer-local 'verilog-modi-lookup-cache)
8611 (defvar verilog-modi-lookup-last-current nil "Cache of `current-buffer' at last lookup.")
8612 (defvar verilog-modi-lookup-last-tick nil "Cache of `buffer-chars-modified-tick' at last lookup.")
8613
8614 (defun verilog-modi-lookup (module allow-cache &optional ignore-error)
8615 "Find the file and point at which MODULE is defined.
8616 If ALLOW-CACHE is set, check and remember cache of previous lookups.
8617 Return modi if successful, else print message unless IGNORE-ERROR is true."
8618 (let* ((current (or (buffer-file-name) (current-buffer)))
8619 modi)
8620 ;; Check cache
8621 ;;(message "verilog-modi-lookup: %s" module)
8622 (cond ((and verilog-modi-lookup-cache
8623 verilog-cache-enabled
8624 allow-cache
8625 (setq modi (gethash module verilog-modi-lookup-cache))
8626 (equal verilog-modi-lookup-last-current current)
8627 ;; Iff hit is in current buffer, then tick must match
8628 (or (equal verilog-modi-lookup-last-tick (buffer-chars-modified-tick))
8629 (not (equal current (verilog-modi-file-or-buffer modi)))))
8630 ;;(message "verilog-modi-lookup: HIT %S" modi)
8631 modi)
8632 ;; Miss
8633 (t (let* ((realmod (verilog-symbol-detick module t))
8634 (orig-filenames (verilog-module-filenames realmod current))
8635 (filenames orig-filenames)
8636 mif)
8637 (while (and filenames (not mif))
8638 (if (not (setq mif (verilog-module-inside-filename-p realmod (car filenames))))
8639 (setq filenames (cdr filenames))))
8640 ;; mif has correct form to become later elements of modi
8641 (cond (mif (setq modi mif))
8642 (t (setq modi nil)
8643 (or ignore-error
8644 (error (concat (verilog-point-text)
8645 ": Can't locate " module " module definition"
8646 (if (not (equal module realmod))
8647 (concat " (Expanded macro to " realmod ")")
8648 "")
8649 "\n Check the verilog-library-directories variable."
8650 "\n I looked in (if not listed, doesn't exist):\n\t"
8651 (mapconcat 'concat orig-filenames "\n\t"))))))
8652 (when (eval-when-compile (fboundp 'make-hash-table))
8653 (unless verilog-modi-lookup-cache
8654 (setq verilog-modi-lookup-cache
8655 (make-hash-table :test 'equal :rehash-size 4.0)))
8656 (puthash module modi verilog-modi-lookup-cache))
8657 (setq verilog-modi-lookup-last-current current
8658 verilog-modi-lookup-last-tick (buffer-chars-modified-tick)))))
8659 modi))
8660
8661 (defun verilog-modi-filename (modi)
8662 "Filename of MODI, or name of buffer if it's never been saved."
8663 (if (bufferp (verilog-modi-file-or-buffer modi))
8664 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
8665 (buffer-name (verilog-modi-file-or-buffer modi)))
8666 (verilog-modi-file-or-buffer modi)))
8667
8668 (defun verilog-modi-goto (modi)
8669 "Move point/buffer to specified MODI."
8670 (or modi (error "Passed unfound modi to goto, check earlier"))
8671 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
8672 (verilog-modi-file-or-buffer modi)
8673 (find-file-noselect (verilog-modi-file-or-buffer modi))))
8674 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
8675 (verilog-mode))
8676 (goto-char (verilog-modi-get-point modi)))
8677
8678 (defun verilog-goto-defun-file (module)
8679 "Move point to the file at which a given MODULE is defined."
8680 (interactive "sGoto File for Module: ")
8681 (let* ((modi (verilog-modi-lookup module nil)))
8682 (when modi
8683 (verilog-modi-goto modi)
8684 (switch-to-buffer (current-buffer)))))
8685
8686 (defun verilog-modi-cache-results (modi function)
8687 "Run on MODI the given FUNCTION. Locate the module in a file.
8688 Cache the output of function so next call may have faster access."
8689 (let (fass)
8690 (save-excursion ;; Cache is buffer-local so can't avoid this.
8691 (verilog-modi-goto modi)
8692 (if (and (setq fass (assoc (list modi function)
8693 verilog-modi-cache-list))
8694 ;; Destroy caching when incorrect; Modified or file changed
8695 (not (and verilog-cache-enabled
8696 (or (equal (buffer-chars-modified-tick) (nth 1 fass))
8697 (and verilog-modi-cache-preserve-tick
8698 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
8699 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
8700 (equal (visited-file-modtime) (nth 2 fass)))))
8701 (setq verilog-modi-cache-list nil
8702 fass nil))
8703 (cond (fass
8704 ;; Return data from cache hit
8705 (nth 3 fass))
8706 (t
8707 ;; Read from file
8708 ;; Clear then restore any highlighting to make emacs19 happy
8709 (let ((fontlocked (when (and (boundp 'font-lock-mode)
8710 font-lock-mode)
8711 (font-lock-mode 0)
8712 t))
8713 func-returns)
8714 (setq func-returns (funcall function))
8715 (when fontlocked (font-lock-mode t))
8716 ;; Cache for next time
8717 (setq verilog-modi-cache-list
8718 (cons (list (list modi function)
8719 (buffer-chars-modified-tick)
8720 (visited-file-modtime)
8721 func-returns)
8722 verilog-modi-cache-list))
8723 func-returns))))))
8724
8725 (defun verilog-modi-cache-add (modi function element sig-list)
8726 "Add function return results to the module cache.
8727 Update MODI's cache for given FUNCTION so that the return ELEMENT of that
8728 function now contains the additional SIG-LIST parameters."
8729 (let (fass)
8730 (save-excursion
8731 (verilog-modi-goto modi)
8732 (if (setq fass (assoc (list modi function)
8733 verilog-modi-cache-list))
8734 (let ((func-returns (nth 3 fass)))
8735 (aset func-returns element
8736 (append sig-list (aref func-returns element))))))))
8737
8738 (defmacro verilog-preserve-modi-cache (&rest body)
8739 "Execute the BODY forms, allowing cache preservation within BODY.
8740 This means that changes to the buffer will not result in the cache being
8741 flushed. If the changes affect the modsig state, they must call the
8742 modsig-cache-add-* function, else the results of later calls may be
8743 incorrect. Without this, changes are assumed to be adding/removing signals
8744 and invalidating the cache."
8745 `(let ((verilog-modi-cache-preserve-tick (buffer-chars-modified-tick))
8746 (verilog-modi-cache-preserve-buffer (current-buffer)))
8747 (progn ,@body)))
8748
8749
8750 (defun verilog-signals-matching-enum (in-list enum)
8751 "Return all signals in IN-LIST matching the given ENUM."
8752 (let (out-list)
8753 (while in-list
8754 (if (equal (verilog-sig-enum (car in-list)) enum)
8755 (setq out-list (cons (car in-list) out-list)))
8756 (setq in-list (cdr in-list)))
8757 ;; New scheme
8758 (let* ((enumvar (intern (concat "venum-" enum)))
8759 (enumlist (and (boundp enumvar) (eval enumvar))))
8760 (while enumlist
8761 (add-to-list 'out-list (list (car enumlist)))
8762 (setq enumlist (cdr enumlist))))
8763 (nreverse out-list)))
8764
8765 (defun verilog-signals-matching-regexp (in-list regexp)
8766 "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
8767 (if (or (not regexp) (equal regexp ""))
8768 in-list
8769 (let (out-list)
8770 (while in-list
8771 (if (string-match regexp (verilog-sig-name (car in-list)))
8772 (setq out-list (cons (car in-list) out-list)))
8773 (setq in-list (cdr in-list)))
8774 (nreverse out-list))))
8775
8776 (defun verilog-signals-not-matching-regexp (in-list regexp)
8777 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
8778 (if (or (not regexp) (equal regexp ""))
8779 in-list
8780 (let (out-list)
8781 (while in-list
8782 (if (not (string-match regexp (verilog-sig-name (car in-list))))
8783 (setq out-list (cons (car in-list) out-list)))
8784 (setq in-list (cdr in-list)))
8785 (nreverse out-list))))
8786
8787 (defun verilog-signals-matching-dir-re (in-list decl-type regexp)
8788 "Return all signals in IN-LIST matching the given DECL-TYPE and REGEXP,
8789 if non-nil."
8790 (if (or (not regexp) (equal regexp ""))
8791 in-list
8792 (let (out-list to-match)
8793 (while in-list
8794 ;; Note verilog-insert-one-definition matches on this order
8795 (setq to-match (concat
8796 decl-type
8797 " " (verilog-sig-signed (car in-list))
8798 " " (verilog-sig-multidim (car in-list))
8799 (verilog-sig-bits (car in-list))))
8800 (if (string-match regexp to-match)
8801 (setq out-list (cons (car in-list) out-list)))
8802 (setq in-list (cdr in-list)))
8803 (nreverse out-list))))
8804
8805 ;; Combined
8806 (defun verilog-decls-get-signals (decls)
8807 (append
8808 (verilog-decls-get-outputs decls)
8809 (verilog-decls-get-inouts decls)
8810 (verilog-decls-get-inputs decls)
8811 (verilog-decls-get-wires decls)
8812 (verilog-decls-get-regs decls)
8813 (verilog-decls-get-assigns decls)
8814 (verilog-decls-get-consts decls)
8815 (verilog-decls-get-gparams decls)))
8816
8817 (defun verilog-decls-get-ports (decls)
8818 (append
8819 (verilog-decls-get-outputs decls)
8820 (verilog-decls-get-inouts decls)
8821 (verilog-decls-get-inputs decls)))
8822
8823 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
8824 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
8825 (defsubst verilog-modi-cache-add-inouts (modi sig-list)
8826 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
8827 (defsubst verilog-modi-cache-add-inputs (modi sig-list)
8828 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
8829 (defsubst verilog-modi-cache-add-wires (modi sig-list)
8830 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
8831 (defsubst verilog-modi-cache-add-regs (modi sig-list)
8832 (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
8833
8834 (defun verilog-signals-from-signame (signame-list)
8835 "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
8836 (mapcar (function (lambda (name) (list name nil nil)))
8837 signame-list))
8838 \f
8839 ;;
8840 ;; Auto creation utilities
8841 ;;
8842
8843 (defun verilog-auto-re-search-do (search-for func)
8844 "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
8845 (goto-char (point-min))
8846 (while (verilog-re-search-forward search-for nil t)
8847 (funcall func)))
8848
8849 (defun verilog-insert-one-definition (sig type indent-pt)
8850 "Print out a definition for SIG of the given TYPE,
8851 with appropriate INDENT-PT indentation."
8852 (indent-to indent-pt)
8853 ;; Note verilog-signals-matching-dir-re matches on this order
8854 (insert type)
8855 (when (verilog-sig-modport sig)
8856 (insert "." (verilog-sig-modport sig)))
8857 (when (verilog-sig-signed sig)
8858 (insert " " (verilog-sig-signed sig)))
8859 (when (verilog-sig-multidim sig)
8860 (insert " " (verilog-sig-multidim-string sig)))
8861 (when (verilog-sig-bits sig)
8862 (insert " " (verilog-sig-bits sig)))
8863 (indent-to (max 24 (+ indent-pt 16)))
8864 (unless (= (char-syntax (preceding-char)) ?\ )
8865 (insert " ")) ; Need space between "]name" if indent-to did nothing
8866 (insert (verilog-sig-name sig))
8867 (when (verilog-sig-memory sig)
8868 (insert " " (verilog-sig-memory sig))))
8869
8870 (defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
8871 "Print out a definition for a list of SIGS of the given DIRECTION,
8872 with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
8873 format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output."
8874 (or dont-sort
8875 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
8876 (while sigs
8877 (let ((sig (car sigs)))
8878 (verilog-insert-one-definition
8879 sig
8880 ;; Want "type x" or "output type x", not "wire type x"
8881 (cond ((verilog-sig-type sig)
8882 (concat
8883 (if (not (member direction '("wire" "interface")))
8884 (concat direction " "))
8885 (verilog-sig-type sig)))
8886 (t direction))
8887 indent-pt)
8888 (insert (if v2k "," ";"))
8889 (if (or (not (verilog-sig-comment sig))
8890 (equal "" (verilog-sig-comment sig)))
8891 (insert "\n")
8892 (indent-to (max 48 (+ indent-pt 40)))
8893 (verilog-insert "// " (verilog-sig-comment sig) "\n"))
8894 (setq sigs (cdr sigs)))))
8895
8896 (eval-when-compile
8897 (if (not (boundp 'indent-pt))
8898 (defvar indent-pt nil "Local used by insert-indent")))
8899
8900 (defun verilog-insert-indent (&rest stuff)
8901 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
8902 Presumes that any newlines end a list element."
8903 (let ((need-indent t))
8904 (while stuff
8905 (if need-indent (indent-to indent-pt))
8906 (setq need-indent nil)
8907 (verilog-insert (car stuff))
8908 (setq need-indent (string-match "\n$" (car stuff))
8909 stuff (cdr stuff)))))
8910 ;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
8911
8912 (defun verilog-repair-open-comma ()
8913 "Insert comma if previous argument is other than a open parenthesis or endif."
8914 ;; We can't just search backward for ) as it might be inside another expression.
8915 ;; Also want "`ifdef X input foo `endif" to just leave things to the human to deal with
8916 (save-excursion
8917 (verilog-backward-syntactic-ws)
8918 (when (and (not (save-excursion ;; Not beginning (, or existing ,
8919 (backward-char 1)
8920 (looking-at "[(,]")))
8921 (not (save-excursion ;; Not `endif, or user define
8922 (backward-char 1)
8923 (skip-chars-backward "[a-zA-Z0-9_`]")
8924 (looking-at "`"))))
8925 (insert ","))))
8926
8927 (defun verilog-repair-close-comma ()
8928 "If point is at a comma followed by a close parenthesis, fix it.
8929 This repairs those mis-inserted by a AUTOARG."
8930 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
8931 (save-excursion
8932 (verilog-forward-close-paren)
8933 (backward-char 1)
8934 (verilog-backward-syntactic-ws)
8935 (backward-char 1)
8936 (when (looking-at ",")
8937 (delete-char 1))))
8938
8939 (defun verilog-get-list (start end)
8940 "Return the elements of a comma separated list between START and END."
8941 (interactive)
8942 (let ((my-list (list))
8943 my-string)
8944 (save-excursion
8945 (while (< (point) end)
8946 (when (re-search-forward "\\([^,{]+\\)" end t)
8947 (setq my-string (verilog-string-remove-spaces (match-string 1)))
8948 (setq my-list (nconc my-list (list my-string) ))
8949 (goto-char (match-end 0))))
8950 my-list)))
8951
8952 (defun verilog-make-width-expression (range-exp)
8953 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
8954 ;; strip off the []
8955 (cond ((not range-exp)
8956 "1")
8957 (t
8958 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
8959 (setq range-exp (match-string 1 range-exp)))
8960 (cond ((not range-exp)
8961 "1")
8962 ;; [#:#] We can compute a numeric result
8963 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
8964 range-exp)
8965 (int-to-string
8966 (1+ (abs (- (string-to-number (match-string 1 range-exp))
8967 (string-to-number (match-string 2 range-exp)))))))
8968 ;; [PARAM-1:0] can just return PARAM
8969 ((string-match "^\\s *\\([a-zA-Z_][a-zA-Z0-9_]*\\)\\s *-\\s *1\\s *:\\s *0\\s *$" range-exp)
8970 (match-string 1 range-exp))
8971 ;; [arbitrary] need math
8972 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
8973 (concat "(1+(" (match-string 1 range-exp) ")"
8974 (if (equal "0" (match-string 2 range-exp))
8975 "" ;; Don't bother with -(0)
8976 (concat "-(" (match-string 2 range-exp) ")"))
8977 ")"))
8978 (t nil)))))
8979 ;;(verilog-make-width-expression "`A:`B")
8980
8981 (defun verilog-simplify-range-expression (range-exp)
8982 "Return a simplified range expression with constants eliminated from RANGE-EXP."
8983 (let ((out range-exp)
8984 (last-pass ""))
8985 (while (not (equal last-pass out))
8986 (setq last-pass out)
8987 (while (string-match "(\\<\\([0-9A-Z-az_]+\\)\\>)" out)
8988 (setq out (replace-match "\\1" nil nil out)))
8989 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\+\\s *\\<\\([0-9]+\\)\\>" out)
8990 (setq out (replace-match
8991 (int-to-string (+ (string-to-number (match-string 1 out))
8992 (string-to-number (match-string 2 out))))
8993 nil nil out)))
8994 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\-\\s *\\<\\([0-9]+\\)\\>" out)
8995 (setq out (replace-match
8996 (int-to-string (- (string-to-number (match-string 1 out))
8997 (string-to-number (match-string 2 out))))
8998 nil nil out))))
8999 out))
9000 ;;(verilog-simplify-range-expression "1")
9001 ;;(verilog-simplify-range-expression "(((16)+1)-3)")
9002
9003 (defun verilog-typedef-name-p (variable-name)
9004 "Return true if the VARIABLE-NAME is a type definition."
9005 (when verilog-typedef-regexp
9006 (string-match verilog-typedef-regexp variable-name)))
9007 \f
9008 ;;
9009 ;; Auto deletion
9010 ;;
9011
9012 (defun verilog-delete-autos-lined ()
9013 "Delete autos that occupy multiple lines, between begin and end comments."
9014 (let ((pt (point)))
9015 (forward-line 1)
9016 (when (and
9017 (looking-at "\\s-*// Beginning")
9018 (search-forward "// End of automatic" nil t))
9019 ;; End exists
9020 (end-of-line)
9021 (delete-region pt (point))
9022 (forward-line 1))))
9023
9024 (defun verilog-delete-empty-auto-pair ()
9025 "Delete begin/end auto pair at point, if empty."
9026 (forward-line 0)
9027 (when (looking-at (concat "\\s-*// Beginning of automatic.*\n"
9028 "\\s-*// End of automatics\n"))
9029 (delete-region (point) (save-excursion (forward-line 2) (point)))))
9030
9031 (defun verilog-forward-close-paren ()
9032 "Find the close parenthesis that match the current point.
9033 Ignore other close parenthesis with matching open parens."
9034 (let ((parens 1))
9035 (while (> parens 0)
9036 (unless (verilog-re-search-forward-quick "[()]" nil t)
9037 (error "%s: Mismatching ()" (verilog-point-text)))
9038 (cond ((= (preceding-char) ?\( )
9039 (setq parens (1+ parens)))
9040 ((= (preceding-char) ?\) )
9041 (setq parens (1- parens)))))))
9042
9043 (defun verilog-backward-open-paren ()
9044 "Find the open parenthesis that match the current point.
9045 Ignore other open parenthesis with matching close parens."
9046 (let ((parens 1))
9047 (while (> parens 0)
9048 (unless (verilog-re-search-backward-quick "[()]" nil t)
9049 (error "%s: Mismatching ()" (verilog-point-text)))
9050 (cond ((= (following-char) ?\) )
9051 (setq parens (1+ parens)))
9052 ((= (following-char) ?\( )
9053 (setq parens (1- parens)))))))
9054
9055 (defun verilog-backward-open-bracket ()
9056 "Find the open bracket that match the current point.
9057 Ignore other open bracket with matching close bracket."
9058 (let ((parens 1))
9059 (while (> parens 0)
9060 (unless (verilog-re-search-backward-quick "[][]" nil t)
9061 (error "%s: Mismatching []" (verilog-point-text)))
9062 (cond ((= (following-char) ?\] )
9063 (setq parens (1+ parens)))
9064 ((= (following-char) ?\[ )
9065 (setq parens (1- parens)))))))
9066
9067 (defun verilog-delete-to-paren ()
9068 "Delete the automatic inst/sense/arg created by autos.
9069 Deletion stops at the matching end parenthesis."
9070 (delete-region (point)
9071 (save-excursion
9072 (verilog-backward-open-paren)
9073 (forward-sexp 1) ;; Moves to paren that closes argdecl's
9074 (backward-char 1)
9075 (point))))
9076
9077 (defun verilog-auto-star-safe ()
9078 "Return if a .* AUTOINST is safe to delete or expand.
9079 It was created by the AUTOS themselves, or by the user."
9080 (and verilog-auto-star-expand
9081 (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\|Interfaces\\)\\)")))
9082
9083 (defun verilog-delete-auto-star-all ()
9084 "Delete a .* AUTOINST, if it is safe."
9085 (when (verilog-auto-star-safe)
9086 (verilog-delete-to-paren)))
9087
9088 (defun verilog-delete-auto-star-implicit ()
9089 "Delete all .* implicit connections created by `verilog-auto-star'.
9090 This function will be called automatically at save unless
9091 `verilog-auto-star-save' is set, any non-templated expanded pins will be
9092 removed."
9093 (interactive)
9094 (let (paren-pt indent have-close-paren)
9095 (save-excursion
9096 (goto-char (point-min))
9097 ;; We need to match these even outside of comments.
9098 ;; For reasonable performance, we don't check if inside comments, sorry.
9099 (while (re-search-forward "// Implicit \\.\\*" nil t)
9100 (setq paren-pt (point))
9101 (beginning-of-line)
9102 (setq have-close-paren
9103 (save-excursion
9104 (when (search-forward ");" paren-pt t)
9105 (setq indent (current-indentation))
9106 t)))
9107 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
9108 (when have-close-paren
9109 ;; Delete extra commentary
9110 (save-excursion
9111 (while (progn
9112 (forward-line -1)
9113 (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\|Interfaces\\)\n"))
9114 (delete-region (match-beginning 0) (match-end 0))))
9115 ;; If it is simple, we can put the ); on the same line as the last text
9116 (let ((rtn-pt (point)))
9117 (save-excursion
9118 (while (progn (backward-char 1)
9119 (looking-at "[ \t\n\f]")))
9120 (when (looking-at ",")
9121 (delete-region (+ 1 (point)) rtn-pt))))
9122 (when (bolp)
9123 (indent-to indent))
9124 (insert ");\n")
9125 ;; Still need to kill final comma - always is one as we put one after the .*
9126 (re-search-backward ",")
9127 (delete-char 1))))))
9128
9129 (defun verilog-delete-auto ()
9130 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
9131 Use \\[verilog-auto] to re-insert the updated AUTOs.
9132
9133 The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
9134 called before and after this function, respectively."
9135 (interactive)
9136 (save-excursion
9137 (if (buffer-file-name)
9138 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
9139 (verilog-save-no-change-functions
9140 (verilog-save-scan-cache
9141 ;; Allow user to customize
9142 (run-hooks 'verilog-before-delete-auto-hook)
9143
9144 ;; Remove those that have multi-line insertions, possibly with parameters
9145 (verilog-auto-re-search-do
9146 (concat "/\\*"
9147 (eval-when-compile
9148 (verilog-regexp-words
9149 `("AUTOASCIIENUM" "AUTOCONCATCOMMENT" "AUTODEFINEVALUE"
9150 "AUTOINOUT" "AUTOINOUTCOMP" "AUTOINOUTMODULE"
9151 "AUTOINPUT" "AUTOINSERTLISP" "AUTOOUTPUT" "AUTOOUTPUTEVERY"
9152 "AUTOREG" "AUTOREGINPUT" "AUTORESET" "AUTOTIEOFF"
9153 "AUTOUNUSED" "AUTOWIRE")))
9154 ;; Optional parens or quoted parameter or .* for (((...)))
9155 "\\(\\|([^)]*)\\|(\"[^\"]*\")\\).*?"
9156 "\\*/")
9157 'verilog-delete-autos-lined)
9158 ;; Remove those that are in parenthesis
9159 (verilog-auto-re-search-do
9160 (concat "/\\*"
9161 (eval-when-compile
9162 (verilog-regexp-words
9163 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
9164 "AUTOSENSE")))
9165 "\\*/")
9166 'verilog-delete-to-paren)
9167 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
9168 (verilog-auto-re-search-do "\\.\\*"
9169 'verilog-delete-auto-star-all)
9170 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
9171 (goto-char (point-min))
9172 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
9173 (replace-match ""))
9174
9175 ;; Final customize
9176 (run-hooks 'verilog-delete-auto-hook)))))
9177 \f
9178 ;;
9179 ;; Auto inject
9180 ;;
9181
9182 (defun verilog-inject-auto ()
9183 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
9184
9185 Any always @ blocks with sensitivity lists that match computed lists will
9186 be replaced with /*AS*/ comments.
9187
9188 Any cells will get /*AUTOINST*/ added to the end of the pin list.
9189 Pins with have identical names will be deleted.
9190
9191 Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
9192 support adding new ports. You may wish to delete older ports yourself.
9193
9194 For example:
9195
9196 module ExampInject (i, o);
9197 input i;
9198 input j;
9199 output o;
9200 always @ (i or j)
9201 o = i | j;
9202 InstModule instName
9203 (.foobar(baz),
9204 j(j));
9205 endmodule
9206
9207 Typing \\[verilog-inject-auto] will make this into:
9208
9209 module ExampInject (i, o/*AUTOARG*/
9210 // Inputs
9211 j);
9212 input i;
9213 output o;
9214 always @ (/*AS*/i or j)
9215 o = i | j;
9216 InstModule instName
9217 (.foobar(baz),
9218 /*AUTOINST*/
9219 // Outputs
9220 j(j));
9221 endmodule"
9222 (interactive)
9223 (verilog-auto t))
9224
9225 (defun verilog-inject-arg ()
9226 "Inject AUTOARG into new code. See `verilog-inject-auto'."
9227 ;; Presume one module per file.
9228 (save-excursion
9229 (goto-char (point-min))
9230 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
9231 (let ((endmodp (save-excursion
9232 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
9233 (point))))
9234 ;; See if there's already a comment .. inside a comment so not verilog-re-search
9235 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
9236 (verilog-re-search-forward-quick ";" nil t)
9237 (backward-char 1)
9238 (verilog-backward-syntactic-ws)
9239 (backward-char 1) ; Moves to paren that closes argdecl's
9240 (when (looking-at ")")
9241 (verilog-insert "/*AUTOARG*/")))))))
9242
9243 (defun verilog-inject-sense ()
9244 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
9245 (save-excursion
9246 (goto-char (point-min))
9247 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
9248 (let* ((start-pt (point))
9249 (modi (verilog-modi-current))
9250 (moddecls (verilog-modi-get-decls modi))
9251 pre-sigs
9252 got-sigs)
9253 (backward-char 1)
9254 (forward-sexp 1)
9255 (backward-char 1) ;; End )
9256 (when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
9257 (setq pre-sigs (verilog-signals-from-signame
9258 (verilog-read-signals start-pt (point)))
9259 got-sigs (verilog-auto-sense-sigs moddecls nil))
9260 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
9261 (verilog-signals-not-in got-sigs pre-sigs)))
9262 (delete-region start-pt (point))
9263 (verilog-insert "/*AS*/")))))))
9264
9265 (defun verilog-inject-inst ()
9266 "Inject AUTOINST into new code. See `verilog-inject-auto'."
9267 (save-excursion
9268 (goto-char (point-min))
9269 ;; It's hard to distinguish modules; we'll instead search for pins.
9270 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
9271 (verilog-backward-open-paren) ;; Inst start
9272 (cond
9273 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
9274 (forward-char 1)
9275 (verilog-forward-close-paren)) ;; Parameters done
9276 (t
9277 (forward-char 1)
9278 (let ((indent-pt (+ (current-column)))
9279 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
9280 (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
9281 (goto-char end-pt)) ;; Already there, continue search with next instance
9282 (t
9283 ;; Delete identical interconnect
9284 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
9285 (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
9286 (delete-region (match-beginning 0) (match-end 0))
9287 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
9288 (while (or (looking-at "[ \t\n\f,]+")
9289 (looking-at "//[^\n]*"))
9290 (delete-region (match-beginning 0) (match-end 0))
9291 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
9292 (verilog-forward-close-paren)
9293 (backward-char 1)
9294 ;; Not verilog-re-search, as we don't want to strip comments
9295 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
9296 (delete-region (match-beginning 0) (match-end 0)))
9297 (verilog-insert "\n")
9298 (verilog-insert-indent "/*AUTOINST*/")))))))))
9299 \f
9300 ;;
9301 ;; Auto save
9302 ;;
9303
9304 (defun verilog-auto-save-check ()
9305 "On saving see if we need auto update."
9306 (cond ((not verilog-auto-save-policy)) ; disabled
9307 ((not (save-excursion
9308 (save-match-data
9309 (let ((case-fold-search nil))
9310 (goto-char (point-min))
9311 (re-search-forward "AUTO" nil t))))))
9312 ((eq verilog-auto-save-policy 'force)
9313 (verilog-auto))
9314 ((not (buffer-modified-p)))
9315 ((eq verilog-auto-update-tick (buffer-chars-modified-tick))) ; up-to-date
9316 ((eq verilog-auto-save-policy 'detect)
9317 (verilog-auto))
9318 (t
9319 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
9320 (verilog-auto))
9321 ;; Don't ask again if didn't update
9322 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))))
9323 (when (not verilog-auto-star-save)
9324 (verilog-delete-auto-star-implicit))
9325 nil) ;; Always return nil -- we don't write the file ourselves
9326
9327 (defun verilog-auto-read-locals ()
9328 "Return file local variable segment at bottom of file."
9329 (save-excursion
9330 (goto-char (point-max))
9331 (if (re-search-backward "Local Variables:" nil t)
9332 (buffer-substring-no-properties (point) (point-max))
9333 "")))
9334
9335 (defun verilog-auto-reeval-locals (&optional force)
9336 "Read file local variable segment at bottom of file if it has changed.
9337 If FORCE, always reread it."
9338 (let ((curlocal (verilog-auto-read-locals)))
9339 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
9340 (set (make-local-variable 'verilog-auto-last-file-locals) curlocal)
9341 ;; Note this may cause this function to be recursively invoked,
9342 ;; because hack-local-variables may call (verilog-mode)
9343 ;; The above when statement will prevent it from recursing forever.
9344 (hack-local-variables)
9345 t)))
9346 \f
9347 ;;
9348 ;; Auto creation
9349 ;;
9350
9351 (defun verilog-auto-arg-ports (sigs message indent-pt)
9352 "Print a list of ports for a AUTOINST.
9353 Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
9354 (when sigs
9355 (when verilog-auto-arg-sort
9356 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
9357 (insert "\n")
9358 (indent-to indent-pt)
9359 (insert message)
9360 (insert "\n")
9361 (let ((space ""))
9362 (indent-to indent-pt)
9363 (while sigs
9364 (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
9365 (insert "\n")
9366 (indent-to indent-pt))
9367 (t (insert space)))
9368 (insert (verilog-sig-name (car sigs)) ",")
9369 (setq sigs (cdr sigs)
9370 space " ")))))
9371
9372 (defun verilog-auto-arg ()
9373 "Expand AUTOARG statements.
9374 Replace the argument declarations at the beginning of the
9375 module with ones automatically derived from input and output
9376 statements. This can be dangerous if the module is instantiated
9377 using position-based connections, so use only name-based when
9378 instantiating the resulting module. Long lines are split based
9379 on the `fill-column', see \\[set-fill-column].
9380
9381 Limitations:
9382 Concatenation and outputting partial busses is not supported.
9383
9384 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9385
9386 For example:
9387
9388 module ExampArg (/*AUTOARG*/);
9389 input i;
9390 output o;
9391 endmodule
9392
9393 Typing \\[verilog-auto] will make this into:
9394
9395 module ExampArg (/*AUTOARG*/
9396 // Outputs
9397 o,
9398 // Inputs
9399 i
9400 );
9401 input i;
9402 output o;
9403 endmodule
9404
9405 The argument declarations may be printed in declaration order to best suit
9406 order based instantiations, or alphabetically, based on the
9407 `verilog-auto-arg-sort' variable.
9408
9409 Any ports declared between the ( and /*AUTOARG*/ are presumed to be
9410 predeclared and are not redeclared by AUTOARG. AUTOARG will make a
9411 conservative guess on adding a comma for the first signal, if you have
9412 any ifdefs or complicated expressions before the AUTOARG you will need
9413 to choose the comma yourself.
9414
9415 Avoid declaring ports manually, as it makes code harder to maintain."
9416 (save-excursion
9417 (let* ((modi (verilog-modi-current))
9418 (moddecls (verilog-modi-get-decls modi))
9419 (skip-pins (aref (verilog-read-arg-pins) 0)))
9420 (verilog-repair-open-comma)
9421 (verilog-auto-arg-ports (verilog-signals-not-in
9422 (verilog-decls-get-outputs moddecls)
9423 skip-pins)
9424 "// Outputs"
9425 verilog-indent-level-declaration)
9426 (verilog-auto-arg-ports (verilog-signals-not-in
9427 (verilog-decls-get-inouts moddecls)
9428 skip-pins)
9429 "// Inouts"
9430 verilog-indent-level-declaration)
9431 (verilog-auto-arg-ports (verilog-signals-not-in
9432 (verilog-decls-get-inputs moddecls)
9433 skip-pins)
9434 "// Inputs"
9435 verilog-indent-level-declaration)
9436 (verilog-repair-close-comma)
9437 (unless (eq (char-before) ?/ )
9438 (insert "\n"))
9439 (indent-to verilog-indent-level-declaration))))
9440
9441 (defun verilog-auto-inst-port-map (port-st)
9442 nil)
9443
9444 (defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
9445 (defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
9446 (defvar vl-modport nil "See `verilog-auto-inst'.") ; Prevent compile warning
9447 (defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
9448 (defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
9449 (defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
9450 (defvar vl-bits nil "See `verilog-auto-inst'.") ; Prevent compile warning
9451 (defvar vl-mbits nil "See `verilog-auto-inst'.") ; Prevent compile warning
9452
9453 (defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
9454 "Print out a instantiation connection for this PORT-ST.
9455 Insert to INDENT-PT, use template TPL-LIST.
9456 @ are instantiation numbers, replaced with TPL-NUM.
9457 @\"(expression @)\" are evaluated, with @ as a variable.
9458 If FOR-STAR add comment it is a .* expansion.
9459 If PAR-VALUES replace final strings with these parameter values."
9460 (let* ((port (verilog-sig-name port-st))
9461 (tpl-ass (or (assoc port (car tpl-list))
9462 (verilog-auto-inst-port-map port-st)))
9463 ;; vl-* are documented for user use
9464 (vl-name (verilog-sig-name port-st))
9465 (vl-width (verilog-sig-width port-st))
9466 (vl-modport (verilog-sig-modport port-st))
9467 (vl-mbits (if (verilog-sig-multidim port-st)
9468 (verilog-sig-multidim-string port-st) ""))
9469 (vl-bits (if (or verilog-auto-inst-vector
9470 (not (assoc port vector-skip-list))
9471 (not (equal (verilog-sig-bits port-st)
9472 (verilog-sig-bits (assoc port vector-skip-list)))))
9473 (or (verilog-sig-bits port-st) "")
9474 ""))
9475 (case-fold-search nil)
9476 (check-values par-values)
9477 tpl-net)
9478 ;; Replace parameters in bit-width
9479 (when (and check-values
9480 (not (equal vl-bits "")))
9481 (while check-values
9482 (setq vl-bits (verilog-string-replace-matches
9483 (concat "\\<" (nth 0 (car check-values)) "\\>")
9484 (concat "(" (nth 1 (car check-values)) ")")
9485 t t vl-bits)
9486 check-values (cdr check-values)))
9487 (setq vl-bits (verilog-simplify-range-expression vl-bits))) ; Not in the loop for speed
9488 ;; Default net value if not found
9489 (setq tpl-net (concat port
9490 (if vl-modport (concat "." vl-modport) "")
9491 (if (verilog-sig-multidim port-st)
9492 (concat "/*" (verilog-sig-multidim-string port-st)
9493 vl-bits "*/")
9494 (concat vl-bits))))
9495 ;; Find template
9496 (cond (tpl-ass ; Template of exact port name
9497 (setq tpl-net (nth 1 tpl-ass)))
9498 ((nth 1 tpl-list) ; Wildcards in template, search them
9499 (let ((wildcards (nth 1 tpl-list)))
9500 (while wildcards
9501 (when (string-match (nth 0 (car wildcards)) port)
9502 (setq tpl-ass (car wildcards) ; so allow @ parsing
9503 tpl-net (replace-match (nth 1 (car wildcards))
9504 t nil port)))
9505 (setq wildcards (cdr wildcards))))))
9506 ;; Parse Templated variable
9507 (when tpl-ass
9508 ;; Evaluate @"(lispcode)"
9509 (when (string-match "@\".*[^\\]\"" tpl-net)
9510 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
9511 (setq tpl-net
9512 (concat
9513 (substring tpl-net 0 (match-beginning 0))
9514 (save-match-data
9515 (let* ((expr (match-string 1 tpl-net))
9516 (value
9517 (progn
9518 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
9519 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
9520 (prin1 (eval (car (read-from-string expr)))
9521 (lambda (ch) ())))))
9522 (if (numberp value) (setq value (number-to-string value)))
9523 value))
9524 (substring tpl-net (match-end 0))))))
9525 ;; Replace @ and [] magic variables in final output
9526 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
9527 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
9528 ;; Insert it
9529 (indent-to indent-pt)
9530 (insert "." port)
9531 (unless (and verilog-auto-inst-dot-name
9532 (equal port tpl-net))
9533 (indent-to verilog-auto-inst-column)
9534 (insert "(" tpl-net ")"))
9535 (insert ",")
9536 (cond (tpl-ass
9537 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
9538 verilog-auto-inst-column))
9539 (if verilog-auto-inst-template-numbers
9540 (verilog-insert " // Templated"
9541 " T" (int-to-string (nth 2 tpl-ass))
9542 " L" (int-to-string (nth 3 tpl-ass)))
9543 (verilog-insert " // Templated")))
9544 (for-star
9545 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
9546 verilog-auto-inst-column))
9547 (verilog-insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
9548 (insert "\n")))
9549 ;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
9550 ;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
9551 ;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
9552
9553 (defun verilog-auto-inst-first ()
9554 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
9555 ;; Do we need a trailing comma?
9556 ;; There maybe a ifdef or something similar before us. What a mess. Thus
9557 ;; to avoid trouble we only insert on preceding ) or *.
9558 ;; Insert first port on new line
9559 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
9560 (save-excursion
9561 (verilog-re-search-backward "[^ \t\n\f]" nil nil)
9562 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
9563 (forward-char 1)
9564 (insert ","))))
9565
9566 (defun verilog-auto-star ()
9567 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
9568
9569 If `verilog-auto-star-expand' is set, .* pins are treated if they were
9570 AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
9571 will also ignore any .* that are not last in your pin list (this prevents
9572 it from deleting pins following the .* when it expands the AUTOINST.)
9573
9574 On writing your file, unless `verilog-auto-star-save' is set, any
9575 non-templated expanded pins will be removed. You may do this at any time
9576 with \\[verilog-delete-auto-star-implicit].
9577
9578 If you are converting a module to use .* for the first time, you may wish
9579 to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
9580
9581 See `verilog-auto-inst' for examples, templates, and more information."
9582 (when (verilog-auto-star-safe)
9583 (verilog-auto-inst)))
9584
9585 (defun verilog-auto-inst ()
9586 "Expand AUTOINST statements, as part of \\[verilog-auto].
9587 Replace the pin connections to an instantiation or interface
9588 declaration with ones automatically derived from the module or
9589 interface header of the instantiated item.
9590
9591 If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
9592 and delete them before saving unless `verilog-auto-star-save' is set.
9593 See `verilog-auto-star' for more information.
9594
9595 Limitations:
9596 Module names must be resolvable to filenames by adding a
9597 `verilog-library-extensions', and being found in the same directory, or
9598 by changing the variable `verilog-library-flags' or
9599 `verilog-library-directories'. Macros `modname are translated through the
9600 vh-{name} Emacs variable, if that is not found, it just ignores the `.
9601
9602 In templates you must have one signal per line, ending in a ), or ));,
9603 and have proper () nesting, including a final ); to end the template.
9604
9605 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9606
9607 SystemVerilog multidimensional input/output has only experimental support.
9608
9609 SystemVerilog .name syntax is used if `verilog-auto-inst-dot-name' is set.
9610
9611 Parameters referenced by the instantiation will remain symbolic, unless
9612 `verilog-auto-inst-param-value' is set.
9613
9614 Gate primitives (and/or) may have AUTOINST for the purpose of
9615 AUTOWIRE declarations, etc. Gates are the only case when
9616 position based connections are passed.
9617
9618 For example, first take the submodule InstModule.v:
9619
9620 module InstModule (o,i);
9621 output [31:0] o;
9622 input i;
9623 wire [31:0] o = {32{i}};
9624 endmodule
9625
9626 This is then used in a upper level module:
9627
9628 module ExampInst (o,i);
9629 output o;
9630 input i;
9631 InstModule instName
9632 (/*AUTOINST*/);
9633 endmodule
9634
9635 Typing \\[verilog-auto] will make this into:
9636
9637 module ExampInst (o,i);
9638 output o;
9639 input i;
9640 InstModule instName
9641 (/*AUTOINST*/
9642 // Outputs
9643 .ov (ov[31:0]),
9644 // Inputs
9645 .i (i));
9646 endmodule
9647
9648 Where the list of inputs and outputs came from the inst module.
9649 \f
9650 Exceptions:
9651
9652 Unless you are instantiating a module multiple times, or the module is
9653 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
9654 It just makes for unmaintainable code. To sanitize signal names, try
9655 vrename from URL `http://www.veripool.org'.
9656
9657 When you need to violate this suggestion there are two ways to list
9658 exceptions, placing them before the AUTOINST, or using templates.
9659
9660 Any ports defined before the /*AUTOINST*/ are not included in the list of
9661 automatics. This is similar to making a template as described below, but
9662 is restricted to simple connections just like you normally make. Also note
9663 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
9664 you have the appropriate // Input or // Output comment, and exactly the
9665 same line formatting as AUTOINST itself uses.
9666
9667 InstModule instName
9668 (// Inputs
9669 .i (my_i_dont_mess_with_it),
9670 /*AUTOINST*/
9671 // Outputs
9672 .ov (ov[31:0]));
9673
9674 \f
9675 Templates:
9676
9677 For multiple instantiations based upon a single template, create a
9678 commented out template:
9679
9680 /* InstModule AUTO_TEMPLATE (
9681 .sig3 (sigz[]),
9682 );
9683 */
9684
9685 Templates go ABOVE the instantiation(s). When an instantiation is
9686 expanded `verilog-mode' simply searches up for the closest template.
9687 Thus you can have multiple templates for the same module, just alternate
9688 between the template for an instantiation and the instantiation itself.
9689
9690 The module name must be the same as the name of the module in the
9691 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
9692 words and capitalized. Only signals that must be different for each
9693 instantiation need to be listed.
9694
9695 Inside a template, a [] in a connection name (with nothing else inside
9696 the brackets) will be replaced by the same bus subscript as it is being
9697 connected to, or the [] will be removed if it is a single bit signal.
9698 Generally it is a good idea to do this for all connections in a template,
9699 as then they will work for any width signal, and with AUTOWIRE. See
9700 PTL_BUS becoming PTL_BUSNEW below.
9701
9702 If you have a complicated template, set `verilog-auto-inst-template-numbers'
9703 to see which regexps are matching. Don't leave that mode set after
9704 debugging is completed though, it will result in lots of extra differences
9705 and merge conflicts.
9706
9707 For example:
9708
9709 /* InstModule AUTO_TEMPLATE (
9710 .ptl_bus (ptl_busnew[]),
9711 );
9712 */
9713 InstModule ms2m (/*AUTOINST*/);
9714
9715 Typing \\[verilog-auto] will make this into:
9716
9717 InstModule ms2m (/*AUTOINST*/
9718 // Outputs
9719 .NotInTemplate (NotInTemplate),
9720 .ptl_bus (ptl_busnew[3:0]), // Templated
9721 ....
9722 \f
9723 @ Templates:
9724
9725 It is common to instantiate a cell multiple times, so templates make it
9726 trivial to substitute part of the cell name into the connection name.
9727
9728 /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
9729 .sig1 (sigx[@]),
9730 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
9731 );
9732 */
9733
9734 If no regular expression is provided immediately after the AUTO_TEMPLATE
9735 keyword, then the @ character in any connection names will be replaced
9736 with the instantiation number; the first digits found in the cell's
9737 instantiation name.
9738
9739 If a regular expression is provided, the @ character will be replaced
9740 with the first \(\) grouping that matches against the cell name. Using a
9741 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
9742 regexp is provided. If you use multiple layers of parenthesis,
9743 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
9744 characters after test and before _, whereas
9745 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
9746 match.
9747
9748 For example:
9749
9750 /* InstModule AUTO_TEMPLATE (
9751 .ptl_mapvalidx (ptl_mapvalid[@]),
9752 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
9753 );
9754 */
9755 InstModule ms2m (/*AUTOINST*/);
9756
9757 Typing \\[verilog-auto] will make this into:
9758
9759 InstModule ms2m (/*AUTOINST*/
9760 // Outputs
9761 .ptl_mapvalidx (ptl_mapvalid[2]),
9762 .ptl_mapvalidp1x (ptl_mapvalid[3]));
9763
9764 Note the @ character was replaced with the 2 from \"ms2m\".
9765
9766 Alternatively, using a regular expression for @:
9767
9768 /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
9769 .ptl_mapvalidx (@_ptl_mapvalid),
9770 .ptl_mapvalidp1x (ptl_mapvalid_@),
9771 );
9772 */
9773 InstModule ms2_FOO (/*AUTOINST*/);
9774 InstModule ms2_BAR (/*AUTOINST*/);
9775
9776 Typing \\[verilog-auto] will make this into:
9777
9778 InstModule ms2_FOO (/*AUTOINST*/
9779 // Outputs
9780 .ptl_mapvalidx (FOO_ptl_mapvalid),
9781 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
9782 InstModule ms2_BAR (/*AUTOINST*/
9783 // Outputs
9784 .ptl_mapvalidx (BAR_ptl_mapvalid),
9785 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
9786
9787 \f
9788 Regexp Templates:
9789
9790 A template entry of the form
9791
9792 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
9793
9794 will apply an Emacs style regular expression search for any port beginning
9795 in pci_req followed by numbers and ending in _l and connecting that to
9796 the pci_req_jtag_[] net, with the bus subscript coming from what matches
9797 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
9798
9799 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
9800 does the same thing. (Note a @ in the connection/replacement text is
9801 completely different -- still use \\1 there!) Thus this is the same as
9802 the above template:
9803
9804 .pci_req@_l (pci_req_jtag_[\\1]),
9805
9806 Here's another example to remove the _l, useful when naming conventions
9807 specify _ alone to mean active low. Note the use of [] to keep the bus
9808 subscript:
9809
9810 .\\(.*\\)_l (\\1_[]),
9811 \f
9812 Lisp Templates:
9813
9814 First any regular expression template is expanded.
9815
9816 If the syntax @\"( ... )\" is found in a connection, the expression in
9817 quotes will be evaluated as a Lisp expression, with @ replaced by the
9818 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
9819 4 into the brackets. Quote all double-quotes inside the expression with
9820 a leading backslash (\\\"...\\\"); or if the Lisp template is also a
9821 regexp template backslash the backslash quote (\\\\\"...\\\\\").
9822
9823 There are special variables defined that are useful in these
9824 Lisp functions:
9825
9826 vl-name Name portion of the input/output port.
9827 vl-bits Bus bits portion of the input/output port ('[2:0]').
9828 vl-mbits Multidimensional array bits for port ('[2:0][3:0]').
9829 vl-width Width of the input/output port ('3' for [2:0]).
9830 May be a (...) expression if bits isn't a constant.
9831 vl-dir Direction of the pin input/output/inout/interface.
9832 vl-modport The modport, if an interface with a modport.
9833 vl-cell-type Module name/type of the cell ('InstModule').
9834 vl-cell-name Instance name of the cell ('instName').
9835
9836 Normal Lisp variables may be used in expressions. See
9837 `verilog-read-defines' which can set vh-{definename} variables for use
9838 here. Also, any comments of the form:
9839
9840 /*AUTO_LISP(setq foo 1)*/
9841
9842 will evaluate any Lisp expression inside the parenthesis between the
9843 beginning of the buffer and the point of the AUTOINST. This allows
9844 functions to be defined or variables to be changed between instantiations.
9845 (See also `verilog-auto-insert-lisp' if you want the output from your
9846 lisp function to be inserted.)
9847
9848 Note that when using lisp expressions errors may occur when @ is not a
9849 number; you may need to use the standard Emacs Lisp functions
9850 `number-to-string' and `string-to-number'.
9851
9852 After the evaluation is completed, @ substitution and [] substitution
9853 occur.
9854
9855 For more information see the \\[verilog-faq] and forums at URL
9856 `http://www.veripool.org'."
9857 (save-excursion
9858 ;; Find beginning
9859 (let* ((pt (point))
9860 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
9861 (indent-pt (save-excursion (verilog-backward-open-paren)
9862 (1+ (current-column))))
9863 (verilog-auto-inst-column (max verilog-auto-inst-column
9864 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
9865 (modi (verilog-modi-current))
9866 (moddecls (verilog-modi-get-decls modi))
9867 (vector-skip-list (unless verilog-auto-inst-vector
9868 (verilog-decls-get-signals moddecls)))
9869 submod submodi submoddecls
9870 inst skip-pins tpl-list tpl-num did-first par-values)
9871
9872 ;; Find module name that is instantiated
9873 (setq submod (verilog-read-inst-module)
9874 inst (verilog-read-inst-name)
9875 vl-cell-type submod
9876 vl-cell-name inst
9877 skip-pins (aref (verilog-read-inst-pins) 0))
9878
9879 ;; Parse any AUTO_LISP() before here
9880 (verilog-read-auto-lisp (point-min) pt)
9881
9882 ;; Read parameters (after AUTO_LISP)
9883 (setq par-values (and verilog-auto-inst-param-value
9884 (verilog-read-inst-param-value)))
9885
9886 ;; Lookup position, etc of submodule
9887 ;; Note this may raise an error
9888 (when (and (not (member submod verilog-gate-keywords))
9889 (setq submodi (verilog-modi-lookup submod t)))
9890 (setq submoddecls (verilog-modi-get-decls submodi))
9891 ;; If there's a number in the instantiation, it may be a argument to the
9892 ;; automatic variable instantiation program.
9893 (let* ((tpl-info (verilog-read-auto-template submod))
9894 (tpl-regexp (aref tpl-info 0)))
9895 (setq tpl-num (if (string-match tpl-regexp inst)
9896 (match-string 1 inst)
9897 "")
9898 tpl-list (aref tpl-info 1)))
9899 ;; Find submodule's signals and dump
9900 (let ((sig-list (and (equal (verilog-modi-get-type submodi) "interface")
9901 (verilog-signals-not-in
9902 (append (verilog-decls-get-wires submoddecls)
9903 (verilog-decls-get-regs submoddecls))
9904 skip-pins)))
9905 (vl-dir "interfaced"))
9906 (when sig-list
9907 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9908 ;; Note these are searched for in verilog-read-sub-decls.
9909 (verilog-insert-indent "// Interfaced\n")
9910 (mapc (lambda (port)
9911 (verilog-auto-inst-port port indent-pt
9912 tpl-list tpl-num for-star par-values))
9913 sig-list)))
9914 (let ((sig-list (verilog-signals-not-in
9915 (verilog-decls-get-interfaces submoddecls)
9916 skip-pins))
9917 (vl-dir "interface"))
9918 (when sig-list
9919 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9920 ;; Note these are searched for in verilog-read-sub-decls.
9921 (verilog-insert-indent "// Interfaces\n")
9922 (mapc (lambda (port)
9923 (verilog-auto-inst-port port indent-pt
9924 tpl-list tpl-num for-star par-values))
9925 sig-list)))
9926 (let ((sig-list (verilog-signals-not-in
9927 (verilog-decls-get-outputs submoddecls)
9928 skip-pins))
9929 (vl-dir "output"))
9930 (when sig-list
9931 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9932 (verilog-insert-indent "// Outputs\n")
9933 (mapc (lambda (port)
9934 (verilog-auto-inst-port port indent-pt
9935 tpl-list tpl-num for-star par-values))
9936 sig-list)))
9937 (let ((sig-list (verilog-signals-not-in
9938 (verilog-decls-get-inouts submoddecls)
9939 skip-pins))
9940 (vl-dir "inout"))
9941 (when sig-list
9942 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9943 (verilog-insert-indent "// Inouts\n")
9944 (mapc (lambda (port)
9945 (verilog-auto-inst-port port indent-pt
9946 tpl-list tpl-num for-star par-values))
9947 sig-list)))
9948 (let ((sig-list (verilog-signals-not-in
9949 (verilog-decls-get-inputs submoddecls)
9950 skip-pins))
9951 (vl-dir "input"))
9952 (when sig-list
9953 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
9954 (verilog-insert-indent "// Inputs\n")
9955 (mapc (lambda (port)
9956 (verilog-auto-inst-port port indent-pt
9957 tpl-list tpl-num for-star par-values))
9958 sig-list)))
9959 ;; Kill extra semi
9960 (save-excursion
9961 (cond (did-first
9962 (re-search-backward "," pt t)
9963 (delete-char 1)
9964 (insert ");")
9965 (search-forward "\n") ;; Added by inst-port
9966 (delete-char -1)
9967 (if (search-forward ")" nil t) ;; From user, moved up a line
9968 (delete-char -1))
9969 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
9970 (delete-char -1)))))))))
9971
9972 (defun verilog-auto-inst-param ()
9973 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
9974 Replace the parameter connections to an instantiation with ones
9975 automatically derived from the module header of the instantiated netlist.
9976
9977 See \\[verilog-auto-inst] for limitations, and templates to customize the
9978 output.
9979
9980 For example, first take the submodule InstModule.v:
9981
9982 module InstModule (o,i);
9983 parameter PAR;
9984 endmodule
9985
9986 This is then used in a upper level module:
9987
9988 module ExampInst (o,i);
9989 parameter PAR;
9990 InstModule #(/*AUTOINSTPARAM*/)
9991 instName (/*AUTOINST*/);
9992 endmodule
9993
9994 Typing \\[verilog-auto] will make this into:
9995
9996 module ExampInst (o,i);
9997 output o;
9998 input i;
9999 InstModule #(/*AUTOINSTPARAM*/
10000 // Parameters
10001 .PAR (PAR));
10002 instName (/*AUTOINST*/);
10003 endmodule
10004
10005 Where the list of parameter connections come from the inst module.
10006 \f
10007 Templates:
10008
10009 You can customize the parameter connections using AUTO_TEMPLATEs,
10010 just as you would with \\[verilog-auto-inst]."
10011 (save-excursion
10012 ;; Find beginning
10013 (let* ((pt (point))
10014 (indent-pt (save-excursion (verilog-backward-open-paren)
10015 (1+ (current-column))))
10016 (verilog-auto-inst-column (max verilog-auto-inst-column
10017 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
10018 (modi (verilog-modi-current))
10019 (moddecls (verilog-modi-get-decls modi))
10020 (vector-skip-list (unless verilog-auto-inst-vector
10021 (verilog-decls-get-signals moddecls)))
10022 submod submodi submoddecls
10023 inst skip-pins tpl-list tpl-num did-first)
10024 ;; Find module name that is instantiated
10025 (setq submod (save-excursion
10026 ;; Get to the point where AUTOINST normally is to read the module
10027 (verilog-re-search-forward-quick "[(;]" nil nil)
10028 (verilog-read-inst-module))
10029 inst (save-excursion
10030 ;; Get to the point where AUTOINST normally is to read the module
10031 (verilog-re-search-forward-quick "[(;]" nil nil)
10032 (verilog-read-inst-name))
10033 vl-cell-type submod
10034 vl-cell-name inst
10035 skip-pins (aref (verilog-read-inst-pins) 0))
10036
10037 ;; Parse any AUTO_LISP() before here
10038 (verilog-read-auto-lisp (point-min) pt)
10039
10040 ;; Lookup position, etc of submodule
10041 ;; Note this may raise an error
10042 (when (setq submodi (verilog-modi-lookup submod t))
10043 (setq submoddecls (verilog-modi-get-decls submodi))
10044 ;; If there's a number in the instantiation, it may be a argument to the
10045 ;; automatic variable instantiation program.
10046 (let* ((tpl-info (verilog-read-auto-template submod))
10047 (tpl-regexp (aref tpl-info 0)))
10048 (setq tpl-num (if (string-match tpl-regexp inst)
10049 (match-string 1 inst)
10050 "")
10051 tpl-list (aref tpl-info 1)))
10052 ;; Find submodule's signals and dump
10053 (let ((sig-list (verilog-signals-not-in
10054 (verilog-decls-get-gparams submoddecls)
10055 skip-pins))
10056 (vl-dir "parameter"))
10057 (when sig-list
10058 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
10059 ;; Note these are searched for in verilog-read-sub-decls.
10060 (verilog-insert-indent "// Parameters\n")
10061 (mapc (lambda (port)
10062 (verilog-auto-inst-port port indent-pt
10063 tpl-list tpl-num nil nil))
10064 sig-list)))
10065 ;; Kill extra semi
10066 (save-excursion
10067 (cond (did-first
10068 (re-search-backward "," pt t)
10069 (delete-char 1)
10070 (insert ")")
10071 (search-forward "\n") ;; Added by inst-port
10072 (delete-char -1)
10073 (if (search-forward ")" nil t) ;; From user, moved up a line
10074 (delete-char -1)))))))))
10075
10076 (defun verilog-auto-reg ()
10077 "Expand AUTOREG statements, as part of \\[verilog-auto].
10078 Make reg statements for any output that isn't already declared,
10079 and isn't a wire output from a block.
10080
10081 Limitations:
10082 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10083
10084 This does NOT work on memories, declare those yourself.
10085
10086 An example:
10087
10088 module ExampReg (o,i);
10089 output o;
10090 input i;
10091 /*AUTOREG*/
10092 always o = i;
10093 endmodule
10094
10095 Typing \\[verilog-auto] will make this into:
10096
10097 module ExampReg (o,i);
10098 output o;
10099 input i;
10100 /*AUTOREG*/
10101 // Beginning of automatic regs (for this module's undeclared outputs)
10102 reg o;
10103 // End of automatics
10104 always o = i;
10105 endmodule"
10106 (save-excursion
10107 ;; Point must be at insertion point.
10108 (let* ((indent-pt (current-indentation))
10109 (modi (verilog-modi-current))
10110 (moddecls (verilog-modi-get-decls modi))
10111 (modsubdecls (verilog-modi-get-sub-decls modi))
10112 (sig-list (verilog-signals-not-in
10113 (verilog-decls-get-outputs moddecls)
10114 (append (verilog-decls-get-wires moddecls)
10115 (verilog-decls-get-regs moddecls)
10116 (verilog-decls-get-assigns moddecls)
10117 (verilog-decls-get-consts moddecls)
10118 (verilog-decls-get-gparams moddecls)
10119 (verilog-subdecls-get-interfaced modsubdecls)
10120 (verilog-subdecls-get-outputs modsubdecls)
10121 (verilog-subdecls-get-inouts modsubdecls)))))
10122 (forward-line 1)
10123 (when sig-list
10124 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
10125 (verilog-insert-definition sig-list "reg" indent-pt nil)
10126 (verilog-modi-cache-add-regs modi sig-list)
10127 (verilog-insert-indent "// End of automatics\n")))))
10128
10129 (defun verilog-auto-reg-input ()
10130 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
10131 Make reg statements instantiation inputs that aren't already declared.
10132 This is useful for making a top level shell for testing the module that is
10133 to be instantiated.
10134
10135 Limitations:
10136 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
10137
10138 This does NOT work on memories, declare those yourself.
10139
10140 An example (see `verilog-auto-inst' for what else is going on here):
10141
10142 module ExampRegInput (o,i);
10143 output o;
10144 input i;
10145 /*AUTOREGINPUT*/
10146 InstModule instName
10147 (/*AUTOINST*/);
10148 endmodule
10149
10150 Typing \\[verilog-auto] will make this into:
10151
10152 module ExampRegInput (o,i);
10153 output o;
10154 input i;
10155 /*AUTOREGINPUT*/
10156 // Beginning of automatic reg inputs (for undeclared ...
10157 reg [31:0] iv; // From inst of inst.v
10158 // End of automatics
10159 InstModule instName
10160 (/*AUTOINST*/
10161 // Outputs
10162 .o (o[31:0]),
10163 // Inputs
10164 .iv (iv));
10165 endmodule"
10166 (save-excursion
10167 ;; Point must be at insertion point.
10168 (let* ((indent-pt (current-indentation))
10169 (modi (verilog-modi-current))
10170 (moddecls (verilog-modi-get-decls modi))
10171 (modsubdecls (verilog-modi-get-sub-decls modi))
10172 (sig-list (verilog-signals-combine-bus
10173 (verilog-signals-not-in
10174 (append (verilog-subdecls-get-inputs modsubdecls)
10175 (verilog-subdecls-get-inouts modsubdecls))
10176 (verilog-decls-get-signals moddecls)))))
10177 (forward-line 1)
10178 (when sig-list
10179 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
10180 (verilog-insert-definition sig-list "reg" indent-pt nil)
10181 (verilog-modi-cache-add-regs modi sig-list)
10182 (verilog-insert-indent "// End of automatics\n")))))
10183
10184 (defun verilog-auto-wire ()
10185 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
10186 Make wire statements for instantiations outputs that aren't
10187 already declared.
10188
10189 Limitations:
10190 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
10191 and all busses must have widths, such as those from AUTOINST, or using []
10192 in AUTO_TEMPLATEs.
10193
10194 This does NOT work on memories or SystemVerilog .name connections,
10195 declare those yourself.
10196
10197 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
10198 determine how to bus together. This occurs when you have ports with
10199 non-numeric or non-sequential bus subscripts. If Verilog mode
10200 mis-guessed, you'll have to declare them yourself.
10201
10202 An example (see `verilog-auto-inst' for what else is going on here):
10203
10204 module ExampWire (o,i);
10205 output o;
10206 input i;
10207 /*AUTOWIRE*/
10208 InstModule instName
10209 (/*AUTOINST*/);
10210 endmodule
10211
10212 Typing \\[verilog-auto] will make this into:
10213
10214 module ExampWire (o,i);
10215 output o;
10216 input i;
10217 /*AUTOWIRE*/
10218 // Beginning of automatic wires
10219 wire [31:0] ov; // From inst of inst.v
10220 // End of automatics
10221 InstModule instName
10222 (/*AUTOINST*/
10223 // Outputs
10224 .ov (ov[31:0]),
10225 // Inputs
10226 .i (i));
10227 wire o = | ov;
10228 endmodule"
10229 (save-excursion
10230 ;; Point must be at insertion point.
10231 (let* ((indent-pt (current-indentation))
10232 (modi (verilog-modi-current))
10233 (moddecls (verilog-modi-get-decls modi))
10234 (modsubdecls (verilog-modi-get-sub-decls modi))
10235 (sig-list (verilog-signals-combine-bus
10236 (verilog-signals-not-in
10237 (append (verilog-subdecls-get-outputs modsubdecls)
10238 (verilog-subdecls-get-inouts modsubdecls))
10239 (verilog-decls-get-signals moddecls)))))
10240 (forward-line 1)
10241 (when sig-list
10242 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
10243 (verilog-insert-definition sig-list "wire" indent-pt nil)
10244 (verilog-modi-cache-add-wires modi sig-list)
10245 (verilog-insert-indent "// End of automatics\n")
10246 (when nil ;; Too slow on huge modules, plus makes everyone's module change
10247 (beginning-of-line)
10248 (setq pnt (point))
10249 (verilog-pretty-declarations quiet)
10250 (goto-char pnt)
10251 (verilog-pretty-expr t "//"))))))
10252
10253 (defun verilog-auto-output (&optional with-params)
10254 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
10255 Make output statements for any output signal from an /*AUTOINST*/ that
10256 isn't a input to another AUTOINST. This is useful for modules which
10257 only instantiate other modules.
10258
10259 Limitations:
10260 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10261
10262 If placed inside the parenthesis of a module declaration, it creates
10263 Verilog 2001 style, else uses Verilog 1995 style.
10264
10265 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10266 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10267
10268 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10269
10270 Signals matching `verilog-auto-output-ignore-regexp' are not included.
10271
10272 An example (see `verilog-auto-inst' for what else is going on here):
10273
10274 module ExampOutput (ov,i);
10275 input i;
10276 /*AUTOOUTPUT*/
10277 InstModule instName
10278 (/*AUTOINST*/);
10279 endmodule
10280
10281 Typing \\[verilog-auto] will make this into:
10282
10283 module ExampOutput (ov,i);
10284 input i;
10285 /*AUTOOUTPUT*/
10286 // Beginning of automatic outputs (from unused autoinst outputs)
10287 output [31:0] ov; // From inst of inst.v
10288 // End of automatics
10289 InstModule instName
10290 (/*AUTOINST*/
10291 // Outputs
10292 .ov (ov[31:0]),
10293 // Inputs
10294 .i (i));
10295 endmodule
10296
10297 You may also provide an optional regular expression, in which case only
10298 signals matching the regular expression will be included. For example the
10299 same expansion will result from only extracting outputs starting with ov:
10300
10301 /*AUTOOUTPUT(\"^ov\")*/"
10302 (save-excursion
10303 ;; Point must be at insertion point.
10304 (let* ((indent-pt (current-indentation))
10305 (regexp (and with-params
10306 (nth 0 (verilog-read-auto-params 1))))
10307 (v2k (verilog-in-paren))
10308 (modi (verilog-modi-current))
10309 (moddecls (verilog-modi-get-decls modi))
10310 (modsubdecls (verilog-modi-get-sub-decls modi))
10311 (sig-list (verilog-signals-not-in
10312 (verilog-subdecls-get-outputs modsubdecls)
10313 (append (verilog-decls-get-outputs moddecls)
10314 (verilog-decls-get-inouts moddecls)
10315 (verilog-subdecls-get-inputs modsubdecls)
10316 (verilog-subdecls-get-inouts modsubdecls)))))
10317 (when regexp
10318 (setq sig-list (verilog-signals-matching-regexp
10319 sig-list regexp)))
10320 (setq sig-list (verilog-signals-not-matching-regexp
10321 sig-list verilog-auto-output-ignore-regexp))
10322 (forward-line 1)
10323 (when v2k (verilog-repair-open-comma))
10324 (when sig-list
10325 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
10326 (verilog-insert-definition sig-list "output" indent-pt v2k)
10327 (verilog-modi-cache-add-outputs modi sig-list)
10328 (verilog-insert-indent "// End of automatics\n"))
10329 (when v2k (verilog-repair-close-comma)))))
10330
10331 (defun verilog-auto-output-every ()
10332 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
10333 Make output statements for any signals that aren't primary inputs or
10334 outputs already. This makes every signal in the design a output. This is
10335 useful to get Synopsys to preserve every signal in the design, since it
10336 won't optimize away the outputs.
10337
10338 An example:
10339
10340 module ExampOutputEvery (o,i,tempa,tempb);
10341 output o;
10342 input i;
10343 /*AUTOOUTPUTEVERY*/
10344 wire tempa = i;
10345 wire tempb = tempa;
10346 wire o = tempb;
10347 endmodule
10348
10349 Typing \\[verilog-auto] will make this into:
10350
10351 module ExampOutputEvery (o,i,tempa,tempb);
10352 output o;
10353 input i;
10354 /*AUTOOUTPUTEVERY*/
10355 // Beginning of automatic outputs (every signal)
10356 output tempb;
10357 output tempa;
10358 // End of automatics
10359 wire tempa = i;
10360 wire tempb = tempa;
10361 wire o = tempb;
10362 endmodule"
10363 (save-excursion
10364 ;;Point must be at insertion point
10365 (let* ((indent-pt (current-indentation))
10366 (v2k (verilog-in-paren))
10367 (modi (verilog-modi-current))
10368 (moddecls (verilog-modi-get-decls modi))
10369 (sig-list (verilog-signals-combine-bus
10370 (verilog-signals-not-in
10371 (verilog-decls-get-signals moddecls)
10372 (verilog-decls-get-ports moddecls)))))
10373 (forward-line 1)
10374 (when v2k (verilog-repair-open-comma))
10375 (when sig-list
10376 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
10377 (verilog-insert-definition sig-list "output" indent-pt v2k)
10378 (verilog-modi-cache-add-outputs modi sig-list)
10379 (verilog-insert-indent "// End of automatics\n"))
10380 (when v2k (verilog-repair-close-comma)))))
10381
10382 (defun verilog-auto-input (&optional with-params)
10383 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
10384 Make input statements for any input signal into an /*AUTOINST*/ that
10385 isn't declared elsewhere inside the module. This is useful for modules which
10386 only instantiate other modules.
10387
10388 Limitations:
10389 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10390
10391 If placed inside the parenthesis of a module declaration, it creates
10392 Verilog 2001 style, else uses Verilog 1995 style.
10393
10394 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10395 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10396
10397 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10398
10399 Signals matching `verilog-auto-input-ignore-regexp' are not included.
10400
10401 An example (see `verilog-auto-inst' for what else is going on here):
10402
10403 module ExampInput (ov,i);
10404 output [31:0] ov;
10405 /*AUTOINPUT*/
10406 InstModule instName
10407 (/*AUTOINST*/);
10408 endmodule
10409
10410 Typing \\[verilog-auto] will make this into:
10411
10412 module ExampInput (ov,i);
10413 output [31:0] ov;
10414 /*AUTOINPUT*/
10415 // Beginning of automatic inputs (from unused autoinst inputs)
10416 input i; // From inst of inst.v
10417 // End of automatics
10418 InstModule instName
10419 (/*AUTOINST*/
10420 // Outputs
10421 .ov (ov[31:0]),
10422 // Inputs
10423 .i (i));
10424 endmodule
10425
10426 You may also provide an optional regular expression, in which case only
10427 signals matching the regular expression will be included. For example the
10428 same expansion will result from only extracting inputs starting with i:
10429
10430 /*AUTOINPUT(\"^i\")*/"
10431 (save-excursion
10432 (let* ((indent-pt (current-indentation))
10433 (regexp (and with-params
10434 (nth 0 (verilog-read-auto-params 1))))
10435 (v2k (verilog-in-paren))
10436 (modi (verilog-modi-current))
10437 (moddecls (verilog-modi-get-decls modi))
10438 (modsubdecls (verilog-modi-get-sub-decls modi))
10439 (sig-list (verilog-signals-not-in
10440 (verilog-subdecls-get-inputs modsubdecls)
10441 (append (verilog-decls-get-inputs moddecls)
10442 (verilog-decls-get-inouts moddecls)
10443 (verilog-decls-get-wires moddecls)
10444 (verilog-decls-get-regs moddecls)
10445 (verilog-decls-get-consts moddecls)
10446 (verilog-decls-get-gparams moddecls)
10447 (verilog-subdecls-get-interfaced modsubdecls)
10448 (verilog-subdecls-get-outputs modsubdecls)
10449 (verilog-subdecls-get-inouts modsubdecls)))))
10450 (when regexp
10451 (setq sig-list (verilog-signals-matching-regexp
10452 sig-list regexp)))
10453 (setq sig-list (verilog-signals-not-matching-regexp
10454 sig-list verilog-auto-input-ignore-regexp))
10455 (forward-line 1)
10456 (when v2k (verilog-repair-open-comma))
10457 (when sig-list
10458 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
10459 (verilog-insert-definition sig-list "input" indent-pt v2k)
10460 (verilog-modi-cache-add-inputs modi sig-list)
10461 (verilog-insert-indent "// End of automatics\n"))
10462 (when v2k (verilog-repair-close-comma)))))
10463
10464 (defun verilog-auto-inout (&optional with-params)
10465 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
10466 Make inout statements for any inout signal in an /*AUTOINST*/ that
10467 isn't declared elsewhere inside the module.
10468
10469 Limitations:
10470 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
10471
10472 If placed inside the parenthesis of a module declaration, it creates
10473 Verilog 2001 style, else uses Verilog 1995 style.
10474
10475 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
10476 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
10477
10478 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
10479
10480 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
10481
10482 An example (see `verilog-auto-inst' for what else is going on here):
10483
10484 module ExampInout (ov,i);
10485 input i;
10486 /*AUTOINOUT*/
10487 InstModule instName
10488 (/*AUTOINST*/);
10489 endmodule
10490
10491 Typing \\[verilog-auto] will make this into:
10492
10493 module ExampInout (ov,i);
10494 input i;
10495 /*AUTOINOUT*/
10496 // Beginning of automatic inouts (from unused autoinst inouts)
10497 inout [31:0] ov; // From inst of inst.v
10498 // End of automatics
10499 InstModule instName
10500 (/*AUTOINST*/
10501 // Inouts
10502 .ov (ov[31:0]),
10503 // Inputs
10504 .i (i));
10505 endmodule
10506
10507 You may also provide an optional regular expression, in which case only
10508 signals matching the regular expression will be included. For example the
10509 same expansion will result from only extracting inouts starting with i:
10510
10511 /*AUTOINOUT(\"^i\")*/"
10512 (save-excursion
10513 ;; Point must be at insertion point.
10514 (let* ((indent-pt (current-indentation))
10515 (regexp (and with-params
10516 (nth 0 (verilog-read-auto-params 1))))
10517 (v2k (verilog-in-paren))
10518 (modi (verilog-modi-current))
10519 (moddecls (verilog-modi-get-decls modi))
10520 (modsubdecls (verilog-modi-get-sub-decls modi))
10521 (sig-list (verilog-signals-not-in
10522 (verilog-subdecls-get-inouts modsubdecls)
10523 (append (verilog-decls-get-outputs moddecls)
10524 (verilog-decls-get-inouts moddecls)
10525 (verilog-decls-get-inputs moddecls)
10526 (verilog-subdecls-get-inputs modsubdecls)
10527 (verilog-subdecls-get-outputs modsubdecls)))))
10528 (when regexp
10529 (setq sig-list (verilog-signals-matching-regexp
10530 sig-list regexp)))
10531 (setq sig-list (verilog-signals-not-matching-regexp
10532 sig-list verilog-auto-inout-ignore-regexp))
10533 (forward-line 1)
10534 (when v2k (verilog-repair-open-comma))
10535 (when sig-list
10536 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
10537 (verilog-insert-definition sig-list "inout" indent-pt v2k)
10538 (verilog-modi-cache-add-inouts modi sig-list)
10539 (verilog-insert-indent "// End of automatics\n"))
10540 (when v2k (verilog-repair-close-comma)))))
10541
10542 (defun verilog-auto-inout-module (&optional complement)
10543 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
10544 Take input/output/inout statements from the specified module and insert
10545 into the current module. This is useful for making null templates and
10546 shell modules which need to have identical I/O with another module.
10547 Any I/O which are already defined in this module will not be redefined.
10548 For the complement of this function, see `verilog-auto-inout-comp'.
10549
10550 Limitations:
10551 If placed inside the parenthesis of a module declaration, it creates
10552 Verilog 2001 style, else uses Verilog 1995 style.
10553
10554 Concatenation and outputting partial busses is not supported.
10555
10556 Module names must be resolvable to filenames. See `verilog-auto-inst'.
10557
10558 Signals are not inserted in the same order as in the original module,
10559 though they will appear to be in the same order to a AUTOINST
10560 instantiating either module.
10561
10562 An example:
10563
10564 module ExampShell (/*AUTOARG*/);
10565 /*AUTOINOUTMODULE(\"ExampMain\")*/
10566 endmodule
10567
10568 module ExampMain (i,o,io);
10569 input i;
10570 output o;
10571 inout io;
10572 endmodule
10573
10574 Typing \\[verilog-auto] will make this into:
10575
10576 module ExampShell (/*AUTOARG*/i,o,io);
10577 /*AUTOINOUTMODULE(\"ExampMain\")*/
10578 // Beginning of automatic in/out/inouts (from specific module)
10579 output o;
10580 inout io;
10581 input i;
10582 // End of automatics
10583 endmodule
10584
10585 You may also provide an optional regular expression, in which case only
10586 signals matching the regular expression will be included. For example the
10587 same expansion will result from only extracting signals starting with i:
10588
10589 /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/
10590
10591 You may also provide an optional second regular expression, in
10592 which case only signals which have that pin direction and data
10593 type will be included. This matches against everything before
10594 the signal name in the declaration, for example against
10595 \"input\" (single bit), \"output logic\" (direction and type) or
10596 \"output [1:0]\" (direction and implicit type). You also
10597 probably want to skip spaces in your regexp.
10598
10599 For example, the below will result in matching the output \"o\"
10600 against the previous example's module:
10601
10602 /*AUTOINOUTMODULE(\"ExampMain\",\"\",\"^output.*\")*/"
10603 (save-excursion
10604 (let* ((params (verilog-read-auto-params 1 3))
10605 (submod (nth 0 params))
10606 (regexp (nth 1 params))
10607 (direction-re (nth 2 params))
10608 submodi)
10609 ;; Lookup position, etc of co-module
10610 ;; Note this may raise an error
10611 (when (setq submodi (verilog-modi-lookup submod t))
10612 (let* ((indent-pt (current-indentation))
10613 (v2k (verilog-in-paren))
10614 (modi (verilog-modi-current))
10615 (moddecls (verilog-modi-get-decls modi))
10616 (submoddecls (verilog-modi-get-decls submodi))
10617 (sig-list-i (verilog-signals-not-in
10618 (if complement
10619 (verilog-decls-get-outputs submoddecls)
10620 (verilog-decls-get-inputs submoddecls))
10621 (append (verilog-decls-get-inputs moddecls))))
10622 (sig-list-o (verilog-signals-not-in
10623 (if complement
10624 (verilog-decls-get-inputs submoddecls)
10625 (verilog-decls-get-outputs submoddecls))
10626 (append (verilog-decls-get-outputs moddecls))))
10627 (sig-list-io (verilog-signals-not-in
10628 (verilog-decls-get-inouts submoddecls)
10629 (append (verilog-decls-get-inouts moddecls))))
10630 (sig-list-if (verilog-signals-not-in
10631 (verilog-decls-get-interfaces submoddecls)
10632 (append (verilog-decls-get-interfaces moddecls)))))
10633 (forward-line 1)
10634 (setq sig-list-i (verilog-signals-matching-dir-re
10635 (verilog-signals-matching-regexp sig-list-i regexp)
10636 "input" direction-re)
10637 sig-list-o (verilog-signals-matching-dir-re
10638 (verilog-signals-matching-regexp sig-list-o regexp)
10639 "output" direction-re)
10640 sig-list-io (verilog-signals-matching-dir-re
10641 (verilog-signals-matching-regexp sig-list-io regexp)
10642 "inout" direction-re)
10643 sig-list-if (verilog-signals-matching-dir-re
10644 (verilog-signals-matching-regexp sig-list-if regexp)
10645 "interface" direction-re))
10646 (when v2k (verilog-repair-open-comma))
10647 (when (or sig-list-i sig-list-o sig-list-io)
10648 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
10649 ;; Don't sort them so a upper AUTOINST will match the main module
10650 (verilog-insert-definition sig-list-o "output" indent-pt v2k t)
10651 (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
10652 (verilog-insert-definition sig-list-i "input" indent-pt v2k t)
10653 (verilog-insert-definition sig-list-if "interface" indent-pt v2k t)
10654 (verilog-modi-cache-add-inputs modi sig-list-i)
10655 (verilog-modi-cache-add-outputs modi sig-list-o)
10656 (verilog-modi-cache-add-inouts modi sig-list-io)
10657 (verilog-insert-indent "// End of automatics\n"))
10658 (when v2k (verilog-repair-close-comma)))))))
10659
10660 (defun verilog-auto-inout-comp ()
10661 "Expand AUTOINOUTCOMP statements, as part of \\[verilog-auto].
10662 Take input/output/inout statements from the specified module and
10663 insert the inverse into the current module (inputs become outputs
10664 and vice-versa.) This is useful for making test and stimulus
10665 modules which need to have complementing I/O with another module.
10666 Any I/O which are already defined in this module will not be
10667 redefined. For the complement of this function, see
10668 `verilog-auto-inout-module'.
10669
10670 Limitations:
10671 If placed inside the parenthesis of a module declaration, it creates
10672 Verilog 2001 style, else uses Verilog 1995 style.
10673
10674 Concatenation and outputting partial busses is not supported.
10675
10676 Module names must be resolvable to filenames. See `verilog-auto-inst'.
10677
10678 Signals are not inserted in the same order as in the original module,
10679 though they will appear to be in the same order to a AUTOINST
10680 instantiating either module.
10681
10682 An example:
10683
10684 module ExampShell (/*AUTOARG*/);
10685 /*AUTOINOUTCOMP(\"ExampMain\")*/
10686 endmodule
10687
10688 module ExampMain (i,o,io);
10689 input i;
10690 output o;
10691 inout io;
10692 endmodule
10693
10694 Typing \\[verilog-auto] will make this into:
10695
10696 module ExampShell (/*AUTOARG*/i,o,io);
10697 /*AUTOINOUTCOMP(\"ExampMain\")*/
10698 // Beginning of automatic in/out/inouts (from specific module)
10699 output i;
10700 inout io;
10701 input o;
10702 // End of automatics
10703 endmodule
10704
10705 You may also provide an optional regular expression, in which case only
10706 signals matching the regular expression will be included. For example the
10707 same expansion will result from only extracting signals starting with i:
10708
10709 /*AUTOINOUTCOMP(\"ExampMain\",\"^i\")*/"
10710 (verilog-auto-inout-module t))
10711
10712 (defun verilog-auto-insert-lisp ()
10713 "Expand AUTOINSERTLISP statements, as part of \\[verilog-auto].
10714 The Lisp code provided is called, and the Lisp code calls
10715 `insert` to insert text into the current file beginning on the
10716 line after the AUTOINSERTLISP.
10717
10718 See also AUTO_LISP, which takes a Lisp expression and evaluates
10719 it during `verilog-auto-inst' but does not insert any text.
10720
10721 An example:
10722
10723 module ExampInsertLisp;
10724 /*AUTOINSERTLISP(my-verilog-insert-hello \"world\")*/
10725 endmodule
10726
10727 // For this example we declare the function in the
10728 // module's file itself. Often you'd define it instead
10729 // in a site-start.el or .emacs file.
10730 /*
10731 Local Variables:
10732 eval:
10733 (defun my-verilog-insert-hello (who)
10734 (insert (concat \"initial $write(\\\"hello \" who \"\\\");\\n\")))
10735 End:
10736 */
10737
10738 Typing \\[verilog-auto] will call my-verilog-insert-hello and
10739 expand the above into:
10740
10741 // Beginning of automatic insert lisp
10742 initial $write(\"hello world\");
10743 // End of automatics
10744
10745 You can also call an external program and insert the returned
10746 text:
10747
10748 /*AUTOINSERTLISP(insert (shell-command-to-string \"echo //hello\"))*/
10749 // Beginning of automatic insert lisp
10750 //hello
10751 // End of automatics"
10752 (save-excursion
10753 ;; Point is at end of /*AUTO...*/
10754 (let* ((indent-pt (current-indentation))
10755 (cmd-end-pt (save-excursion (search-backward ")")
10756 (forward-char)
10757 (point))) ;; Closing paren
10758 (cmd-beg-pt (save-excursion (goto-char cmd-end-pt)
10759 (backward-sexp 1)
10760 (point))) ;; Beginning paren
10761 (cmd (buffer-substring-no-properties cmd-beg-pt cmd-end-pt)))
10762 (forward-line 1)
10763 ;; Some commands don't move point (like insert-file) so we always
10764 ;; add the begin/end comments, then delete it if not needed
10765 (verilog-insert-indent "// Beginning of automatic insert lisp\n")
10766 (verilog-insert-indent "// End of automatics\n")
10767 (forward-line -1)
10768 (eval (read cmd))
10769 (forward-line -1)
10770 (setq verilog-scan-cache-tick nil) ;; Clear cache; inserted unknown text
10771 (verilog-delete-empty-auto-pair))))
10772
10773 (defun verilog-auto-sense-sigs (moddecls presense-sigs)
10774 "Return list of signals for current AUTOSENSE block."
10775 (let* ((sigss (verilog-read-always-signals))
10776 (sig-list (verilog-signals-not-params
10777 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
10778 (append (and (not verilog-auto-sense-include-inputs)
10779 (verilog-alw-get-outputs sigss))
10780 (verilog-alw-get-temps sigss)
10781 (verilog-decls-get-consts moddecls)
10782 (verilog-decls-get-gparams moddecls)
10783 presense-sigs)))))
10784 sig-list))
10785
10786 (defun verilog-auto-sense ()
10787 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
10788 Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
10789 with one automatically derived from all inputs declared in the always
10790 statement. Signals that are generated within the same always block are NOT
10791 placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
10792 Long lines are split based on the `fill-column', see \\[set-fill-column].
10793
10794 Limitations:
10795 Verilog does not allow memories (multidimensional arrays) in sensitivity
10796 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
10797
10798 Constant signals:
10799 AUTOSENSE cannot always determine if a `define is a constant or a signal
10800 (it could be in a include file for example). If a `define or other signal
10801 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
10802 declaration anywhere in the module (parenthesis are required):
10803
10804 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
10805
10806 Better yet, use a parameter, which will be understood to be constant
10807 automatically.
10808
10809 OOps!
10810 If AUTOSENSE makes a mistake, please report it. (First try putting
10811 a begin/end after your always!) As a workaround, if a signal that
10812 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
10813 If a signal should be in the sensitivity list wasn't, placing it before
10814 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
10815 autos are updated (or added if it occurs there already).
10816
10817 An example:
10818
10819 always @ (/*AS*/) begin
10820 /* AUTO_CONSTANT (`constant) */
10821 outin = ina | inb | `constant;
10822 out = outin;
10823 end
10824
10825 Typing \\[verilog-auto] will make this into:
10826
10827 always @ (/*AS*/ina or inb) begin
10828 /* AUTO_CONSTANT (`constant) */
10829 outin = ina | inb | `constant;
10830 out = outin;
10831 end
10832
10833 Note in Verilog 2001, you can often get the same result from the new @*
10834 operator. (This was added to the language in part due to AUTOSENSE!)
10835
10836 always @* begin
10837 outin = ina | inb | `constant;
10838 out = outin;
10839 end"
10840 (save-excursion
10841 ;; Find beginning
10842 (let* ((start-pt (save-excursion
10843 (verilog-re-search-backward "(" nil t)
10844 (point)))
10845 (indent-pt (save-excursion
10846 (or (and (goto-char start-pt) (1+ (current-column)))
10847 (current-indentation))))
10848 (modi (verilog-modi-current))
10849 (moddecls (verilog-modi-get-decls modi))
10850 (sig-memories (verilog-signals-memory
10851 (append
10852 (verilog-decls-get-regs moddecls)
10853 (verilog-decls-get-wires moddecls))))
10854 sig-list not-first presense-sigs)
10855 ;; Read signals in always, eliminate outputs from sense list
10856 (setq presense-sigs (verilog-signals-from-signame
10857 (save-excursion
10858 (verilog-read-signals start-pt (point)))))
10859 (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
10860 (when sig-memories
10861 (let ((tlen (length sig-list)))
10862 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
10863 (if (not (eq tlen (length sig-list))) (verilog-insert " /*memory or*/ "))))
10864 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
10865 (save-excursion (goto-char (point))
10866 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10867 (verilog-re-search-backward "\\s-" start-pt t)
10868 (while (looking-at "\\s-`endif")
10869 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
10870 (verilog-re-search-backward "\\s-" start-pt t))
10871 (not (looking-at "\\s-or\\b"))))
10872 (setq not-first t))
10873 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10874 (while sig-list
10875 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
10876 (insert "\n")
10877 (indent-to indent-pt)
10878 (if not-first (insert "or ")))
10879 (not-first (insert " or ")))
10880 (insert (verilog-sig-name (car sig-list)))
10881 (setq sig-list (cdr sig-list)
10882 not-first t)))))
10883
10884 (defun verilog-auto-reset ()
10885 "Expand AUTORESET statements, as part of \\[verilog-auto].
10886 Replace the /*AUTORESET*/ comment with code to initialize all
10887 registers set elsewhere in the always block.
10888
10889 Limitations:
10890 AUTORESET will not clear memories.
10891
10892 AUTORESET uses <= if there are any <= assignments in the block,
10893 else it uses =.
10894
10895 /*AUTORESET*/ presumes that any signals mentioned between the previous
10896 begin/case/if statement and the AUTORESET comment are being reset manually
10897 and should not be automatically reset. This includes omitting any signals
10898 used on the right hand side of assignments.
10899
10900 By default, AUTORESET will include the width of the signal in the autos,
10901 this is a recent change. To control this behavior, see
10902 `verilog-auto-reset-widths'.
10903
10904 AUTORESET ties signals to deasserted, which is presumed to be zero.
10905 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
10906 them to a one.
10907
10908 An example:
10909
10910 always @(posedge clk or negedge reset_l) begin
10911 if (!reset_l) begin
10912 c <= 1;
10913 /*AUTORESET*/
10914 end
10915 else begin
10916 a <= in_a;
10917 b <= in_b;
10918 c <= in_c;
10919 end
10920 end
10921
10922 Typing \\[verilog-auto] will make this into:
10923
10924 always @(posedge core_clk or negedge reset_l) begin
10925 if (!reset_l) begin
10926 c <= 1;
10927 /*AUTORESET*/
10928 // Beginning of autoreset for uninitialized flops
10929 a <= 0;
10930 b <= 0;
10931 // End of automatics
10932 end
10933 else begin
10934 a <= in_a;
10935 b <= in_b;
10936 c <= in_c;
10937 end
10938 end"
10939
10940 (interactive)
10941 (save-excursion
10942 ;; Find beginning
10943 (let* ((indent-pt (current-indentation))
10944 (modi (verilog-modi-current))
10945 (moddecls (verilog-modi-get-decls modi))
10946 (all-list (verilog-decls-get-signals moddecls))
10947 sigss sig-list prereset-sigs assignment-str)
10948 ;; Read signals in always, eliminate outputs from reset list
10949 (setq prereset-sigs (verilog-signals-from-signame
10950 (save-excursion
10951 (verilog-read-signals
10952 (save-excursion
10953 (verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
10954 (point))
10955 (point)))))
10956 (save-excursion
10957 (verilog-re-search-backward "@" nil t)
10958 (setq sigss (verilog-read-always-signals)))
10959 (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
10960 (concat " <= " verilog-assignment-delay)
10961 " = "))
10962 (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
10963 (append
10964 (verilog-alw-get-temps sigss)
10965 prereset-sigs)))
10966 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
10967 (when sig-list
10968 (insert "\n");
10969 (verilog-insert-indent "// Beginning of autoreset for uninitialized flops\n");
10970 (indent-to indent-pt)
10971 (while sig-list
10972 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
10973 (car sig-list))))
10974 (insert (verilog-sig-name sig)
10975 assignment-str
10976 (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
10977 ";\n")
10978 (indent-to indent-pt)
10979 (setq sig-list (cdr sig-list))))
10980 (verilog-insert "// End of automatics")))))
10981
10982 (defun verilog-auto-tieoff ()
10983 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
10984 Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
10985 signals to deasserted.
10986
10987 /*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
10988 input/output list as another module, but no internals. Specifically, it
10989 finds all outputs in the module, and if that input is not otherwise declared
10990 as a register or wire, creates a tieoff.
10991
10992 AUTORESET ties signals to deasserted, which is presumed to be zero.
10993 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
10994 them to a one.
10995
10996 You can add signals you do not want included in AUTOTIEOFF with
10997 `verilog-auto-tieoff-ignore-regexp'.
10998
10999 An example of making a stub for another module:
11000
11001 module ExampStub (/*AUTOINST*/);
11002 /*AUTOINOUTMODULE(\"Foo\")*/
11003 /*AUTOTIEOFF*/
11004 // verilator lint_off UNUSED
11005 wire _unused_ok = &{1'b0,
11006 /*AUTOUNUSED*/
11007 1'b0};
11008 // verilator lint_on UNUSED
11009 endmodule
11010
11011 Typing \\[verilog-auto] will make this into:
11012
11013 module ExampStub (/*AUTOINST*/...);
11014 /*AUTOINOUTMODULE(\"Foo\")*/
11015 // Beginning of autotieoff
11016 output [2:0] foo;
11017 // End of automatics
11018
11019 /*AUTOTIEOFF*/
11020 // Beginning of autotieoff
11021 wire [2:0] foo = 3'b0;
11022 // End of automatics
11023 ...
11024 endmodule"
11025 (interactive)
11026 (save-excursion
11027 ;; Find beginning
11028 (let* ((indent-pt (current-indentation))
11029 (modi (verilog-modi-current))
11030 (moddecls (verilog-modi-get-decls modi))
11031 (modsubdecls (verilog-modi-get-sub-decls modi))
11032 (sig-list (verilog-signals-not-in
11033 (verilog-decls-get-outputs moddecls)
11034 (append (verilog-decls-get-wires moddecls)
11035 (verilog-decls-get-regs moddecls)
11036 (verilog-decls-get-assigns moddecls)
11037 (verilog-decls-get-consts moddecls)
11038 (verilog-decls-get-gparams moddecls)
11039 (verilog-subdecls-get-interfaced modsubdecls)
11040 (verilog-subdecls-get-outputs modsubdecls)
11041 (verilog-subdecls-get-inouts modsubdecls)))))
11042 (setq sig-list (verilog-signals-not-matching-regexp
11043 sig-list verilog-auto-tieoff-ignore-regexp))
11044 (when sig-list
11045 (forward-line 1)
11046 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
11047 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
11048 (verilog-modi-cache-add-wires modi sig-list) ; Before we trash list
11049 (while sig-list
11050 (let ((sig (car sig-list)))
11051 (verilog-insert-one-definition sig "wire" indent-pt)
11052 (indent-to (max 48 (+ indent-pt 40)))
11053 (insert "= " (verilog-sig-tieoff sig)
11054 ";\n")
11055 (setq sig-list (cdr sig-list))))
11056 (verilog-insert-indent "// End of automatics\n")))))
11057
11058 (defun verilog-auto-unused ()
11059 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
11060 Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
11061 input and inout signals.
11062
11063 /*AUTOUNUSED*/ is used to make stub modules; modules that have the same
11064 input/output list as another module, but no internals. Specifically, it
11065 finds all inputs and inouts in the module, and if that input is not otherwise
11066 used, adds it to a comma separated list.
11067
11068 The comma separated list is intended to be used to create a _unused_ok
11069 signal. Using the exact name \"_unused_ok\" for name of the temporary
11070 signal is recommended as it will insure maximum forward compatibility, it
11071 also makes lint warnings easy to understand; ignore any unused warnings
11072 with \"unused\" in the signal name.
11073
11074 To reduce simulation time, the _unused_ok signal should be forced to a
11075 constant to prevent wiggling. The easiest thing to do is use a
11076 reduction-and with 1'b0 as shown.
11077
11078 This way all unused signals are in one place, making it convenient to add
11079 your tool's specific pragmas around the assignment to disable any unused
11080 warnings.
11081
11082 You can add signals you do not want included in AUTOUNUSED with
11083 `verilog-auto-unused-ignore-regexp'.
11084
11085 An example of making a stub for another module:
11086
11087 module ExampStub (/*AUTOINST*/);
11088 /*AUTOINOUTMODULE(\"Examp\")*/
11089 /*AUTOTIEOFF*/
11090 // verilator lint_off UNUSED
11091 wire _unused_ok = &{1'b0,
11092 /*AUTOUNUSED*/
11093 1'b0};
11094 // verilator lint_on UNUSED
11095 endmodule
11096
11097 Typing \\[verilog-auto] will make this into:
11098
11099 ...
11100 // verilator lint_off UNUSED
11101 wire _unused_ok = &{1'b0,
11102 /*AUTOUNUSED*/
11103 // Beginning of automatics
11104 unused_input_a,
11105 unused_input_b,
11106 unused_input_c,
11107 // End of automatics
11108 1'b0};
11109 // verilator lint_on UNUSED
11110 endmodule"
11111 (interactive)
11112 (save-excursion
11113 ;; Find beginning
11114 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
11115 (modi (verilog-modi-current))
11116 (moddecls (verilog-modi-get-decls modi))
11117 (modsubdecls (verilog-modi-get-sub-decls modi))
11118 (sig-list (verilog-signals-not-in
11119 (append (verilog-decls-get-inputs moddecls)
11120 (verilog-decls-get-inouts moddecls))
11121 (append (verilog-subdecls-get-inputs modsubdecls)
11122 (verilog-subdecls-get-inouts modsubdecls)))))
11123 (setq sig-list (verilog-signals-not-matching-regexp
11124 sig-list verilog-auto-unused-ignore-regexp))
11125 (when sig-list
11126 (forward-line 1)
11127 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
11128 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
11129 (while sig-list
11130 (let ((sig (car sig-list)))
11131 (indent-to indent-pt)
11132 (insert (verilog-sig-name sig) ",\n")
11133 (setq sig-list (cdr sig-list))))
11134 (verilog-insert-indent "// End of automatics\n")))))
11135
11136 (defun verilog-enum-ascii (signm elim-regexp)
11137 "Convert an enum name SIGNM to an ascii string for insertion.
11138 Remove user provided prefix ELIM-REGEXP."
11139 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
11140 (let ((case-fold-search t))
11141 ;; All upper becomes all lower for readability
11142 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
11143
11144 (defun verilog-auto-ascii-enum ()
11145 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
11146 Create a register to contain the ASCII decode of a enumerated signal type.
11147 This will allow trace viewers to show the ASCII name of states.
11148
11149 First, parameters are built into a enumeration using the synopsys enum
11150 comment. The comment must be between the keyword and the symbol.
11151 \(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
11152
11153 Next, registers which that enum applies to are also tagged with the same
11154 enum. Synopsys also suggests labeling state vectors, but `verilog-mode'
11155 doesn't care.
11156
11157 Finally, a AUTOASCIIENUM command is used.
11158
11159 The first parameter is the name of the signal to be decoded.
11160 If and only if the first parameter width is 2^(number of states
11161 in enum) and does NOT match the width of the enum, the signal
11162 is assumed to be a one hot decode. Otherwise, it's a normal
11163 encoded state vector.
11164
11165 The second parameter is the name to store the ASCII code into. For the
11166 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
11167 a signal that is just for simulation, and the magic characters _ascii
11168 tell viewers like Dinotrace to display in ASCII format.
11169
11170 The final optional parameter is a string which will be removed from the
11171 state names.
11172
11173 An example:
11174
11175 //== State enumeration
11176 parameter [2:0] // synopsys enum state_info
11177 SM_IDLE = 3'b000,
11178 SM_SEND = 3'b001,
11179 SM_WAIT1 = 3'b010;
11180 //== State variables
11181 reg [2:0] /* synopsys enum state_info */
11182 state_r; /* synopsys state_vector state_r */
11183 reg [2:0] /* synopsys enum state_info */
11184 state_e1;
11185
11186 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
11187
11188 Typing \\[verilog-auto] will make this into:
11189
11190 ... same front matter ...
11191
11192 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
11193 // Beginning of automatic ASCII enum decoding
11194 reg [39:0] state_ascii_r; // Decode of state_r
11195 always @(state_r) begin
11196 case ({state_r})
11197 SM_IDLE: state_ascii_r = \"idle \";
11198 SM_SEND: state_ascii_r = \"send \";
11199 SM_WAIT1: state_ascii_r = \"wait1\";
11200 default: state_ascii_r = \"%Erro\";
11201 endcase
11202 end
11203 // End of automatics"
11204 (save-excursion
11205 (let* ((params (verilog-read-auto-params 2 3))
11206 (undecode-name (nth 0 params))
11207 (ascii-name (nth 1 params))
11208 (elim-regexp (nth 2 params))
11209 ;;
11210 (indent-pt (current-indentation))
11211 (modi (verilog-modi-current))
11212 (moddecls (verilog-modi-get-decls modi))
11213 ;;
11214 (sig-list-consts (append (verilog-decls-get-consts moddecls)
11215 (verilog-decls-get-gparams moddecls)))
11216 (sig-list-all (append (verilog-decls-get-regs moddecls)
11217 (verilog-decls-get-outputs moddecls)
11218 (verilog-decls-get-inouts moddecls)
11219 (verilog-decls-get-inputs moddecls)
11220 (verilog-decls-get-wires moddecls)))
11221 ;;
11222 (undecode-sig (or (assoc undecode-name sig-list-all)
11223 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
11224 (undecode-enum (or (verilog-sig-enum undecode-sig)
11225 (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
11226 ;;
11227 (enum-sigs (verilog-signals-not-in
11228 (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
11229 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum))
11230 nil))
11231 ;;
11232 (one-hot (and ;; width(enum) != width(sig)
11233 (or (not (verilog-sig-bits (car enum-sigs)))
11234 (not (equal (verilog-sig-width (car enum-sigs))
11235 (verilog-sig-width undecode-sig))))
11236 ;; count(enums) == width(sig)
11237 (equal (number-to-string (length enum-sigs))
11238 (verilog-sig-width undecode-sig))))
11239 (enum-chars 0)
11240 (ascii-chars 0))
11241 ;;
11242 ;; Find number of ascii chars needed
11243 (let ((tmp-sigs enum-sigs))
11244 (while tmp-sigs
11245 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
11246 ascii-chars (max ascii-chars (length (verilog-enum-ascii
11247 (verilog-sig-name (car tmp-sigs))
11248 elim-regexp)))
11249 tmp-sigs (cdr tmp-sigs))))
11250 ;;
11251 (forward-line 1)
11252 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
11253 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
11254 (concat "Decode of " undecode-name) nil nil))))
11255 (verilog-insert-definition decode-sig-list "reg" indent-pt nil)
11256 (verilog-modi-cache-add-regs modi decode-sig-list))
11257 ;;
11258 (verilog-insert-indent "always @(" undecode-name ") begin\n")
11259 (setq indent-pt (+ indent-pt verilog-indent-level))
11260 (indent-to indent-pt)
11261 (insert "case ({" undecode-name "})\n")
11262 (setq indent-pt (+ indent-pt verilog-case-indent))
11263 ;;
11264 (let ((tmp-sigs enum-sigs)
11265 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n"
11266 (+ (if one-hot 9 1) (max 8 enum-chars))
11267 ascii-name ascii-chars))
11268 (errname (substring "%Error" 0 (min 6 ascii-chars))))
11269 (while tmp-sigs
11270 (verilog-insert-indent
11271 (concat
11272 (format chrfmt
11273 (concat (if one-hot "(")
11274 (if one-hot (verilog-sig-width undecode-sig))
11275 ;; We use a shift instead of var[index]
11276 ;; so that a non-one hot value will show as error.
11277 (if one-hot "'b1<<")
11278 (verilog-sig-name (car tmp-sigs))
11279 (if one-hot ")") ":")
11280 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
11281 elim-regexp))))
11282 (setq tmp-sigs (cdr tmp-sigs)))
11283 (verilog-insert-indent (format chrfmt "default:" errname)))
11284 ;;
11285 (setq indent-pt (- indent-pt verilog-case-indent))
11286 (verilog-insert-indent "endcase\n")
11287 (setq indent-pt (- indent-pt verilog-indent-level))
11288 (verilog-insert-indent "end\n"
11289 "// End of automatics\n"))))
11290
11291 (defun verilog-auto-templated-rel ()
11292 "Replace Templated relative line numbers with absolute line numbers.
11293 Internal use only. This hacks around the line numbers in AUTOINST Templates
11294 being different from the final output's line numbering."
11295 (let ((templateno 0) (template-line (list 0)) (buf-line 1))
11296 ;; Find line number each template is on
11297 ;; Count lines as we go, as otherwise it's O(n^2) to use count-lines
11298 (goto-char (point-min))
11299 (while (not (eobp))
11300 (when (looking-at ".*AUTO_TEMPLATE")
11301 (setq templateno (1+ templateno))
11302 (setq template-line (cons buf-line template-line)))
11303 (setq buf-line (1+ buf-line))
11304 (forward-line 1))
11305 (setq template-line (nreverse template-line))
11306 ;; Replace T# L# with absolute line number
11307 (goto-char (point-min))
11308 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
11309 (replace-match
11310 (concat " Templated "
11311 (int-to-string (+ (nth (string-to-number (match-string 1))
11312 template-line)
11313 (string-to-number (match-string 2)))))
11314 t t))))
11315
11316 \f
11317 ;;
11318 ;; Auto top level
11319 ;;
11320
11321 (defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing a arg
11322 "Expand AUTO statements.
11323 Look for any /*AUTO...*/ commands in the code, as used in
11324 instantiations or argument headers. Update the list of signals
11325 following the /*AUTO...*/ command.
11326
11327 Use \\[verilog-delete-auto] to remove the AUTOs.
11328
11329 Use \\[verilog-inject-auto] to insert AUTOs for the first time.
11330
11331 Use \\[verilog-faq] for a pointer to frequently asked questions.
11332
11333 The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
11334 called before and after this function, respectively.
11335
11336 For example:
11337 module ModuleName (/*AUTOARG*/);
11338 /*AUTOINPUT*/
11339 /*AUTOOUTPUT*/
11340 /*AUTOWIRE*/
11341 /*AUTOREG*/
11342 InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
11343
11344 You can also update the AUTOs from the shell using:
11345 emacs --batch <filenames.v> -f verilog-batch-auto
11346 Or fix indentation with:
11347 emacs --batch <filenames.v> -f verilog-batch-indent
11348 Likewise, you can delete or inject AUTOs with:
11349 emacs --batch <filenames.v> -f verilog-batch-delete-auto
11350 emacs --batch <filenames.v> -f verilog-batch-inject-auto
11351
11352 Using \\[describe-function], see also:
11353 `verilog-auto-arg' for AUTOARG module instantiations
11354 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
11355 `verilog-auto-inout-comp' for AUTOINOUTCOMP copy complemented i/o
11356 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
11357 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
11358 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
11359 `verilog-auto-insert-lisp' for AUTOINSERTLISP insert code from lisp function
11360 `verilog-auto-inst' for AUTOINST instantiation pins
11361 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
11362 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
11363 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
11364 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
11365 `verilog-auto-reg' for AUTOREG registers
11366 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
11367 `verilog-auto-reset' for AUTORESET flop resets
11368 `verilog-auto-sense' for AUTOSENSE always sensitivity lists
11369 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
11370 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
11371 `verilog-auto-wire' for AUTOWIRE instantiation wires
11372
11373 `verilog-read-defines' for reading `define values
11374 `verilog-read-includes' for reading `includes
11375
11376 If you have bugs with these autos, please file an issue at
11377 URL `http://www.veripool.org/verilog-mode' or contact the AUTOAUTHOR
11378 Wilson Snyder (wsnyder@wsnyder.org)."
11379 (interactive)
11380 (unless noninteractive (message "Updating AUTOs..."))
11381 (if (fboundp 'dinotrace-unannotate-all)
11382 (dinotrace-unannotate-all))
11383 (let ((oldbuf (if (not (buffer-modified-p))
11384 (buffer-string)))
11385 ;; Before version 20, match-string with font-lock returns a
11386 ;; vector that is not equal to the string. IE if on "input"
11387 ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
11388 (fontlocked (when (and (boundp 'font-lock-mode)
11389 font-lock-mode)
11390 (font-lock-mode 0)
11391 t))
11392 ;; Cache directories; we don't write new files, so can't change
11393 (verilog-dir-cache-preserving t)
11394 ;; Cache current module
11395 (verilog-modi-cache-current-enable t)
11396 (verilog-modi-cache-current-max (point-min)) ; IE it's invalid
11397 verilog-modi-cache-current)
11398 (unwind-protect
11399 ;; Disable change hooks for speed
11400 ;; This let can't be part of above let; must restore
11401 ;; after-change-functions before font-lock resumes
11402 (verilog-save-no-change-functions
11403 (verilog-save-scan-cache
11404 (save-excursion
11405 ;; If we're not in verilog-mode, change syntax table so parsing works right
11406 (unless (eq major-mode `verilog-mode) (verilog-mode))
11407 ;; Allow user to customize
11408 (run-hooks 'verilog-before-auto-hook)
11409 ;; Try to save the user from needing to revert-file to reread file local-variables
11410 (verilog-auto-reeval-locals)
11411 (verilog-read-auto-lisp-present)
11412 (verilog-read-auto-lisp (point-min) (point-max))
11413 (verilog-getopt-flags)
11414 ;; From here on out, we can cache anything we read from disk
11415 (verilog-preserve-dir-cache
11416 ;; These two may seem obvious to do always, but on large includes it can be way too slow
11417 (when verilog-auto-read-includes
11418 (verilog-read-includes)
11419 (verilog-read-defines nil nil t))
11420 ;; This particular ordering is important
11421 ;; INST: Lower modules correct, no internal dependencies, FIRST
11422 (verilog-preserve-modi-cache
11423 ;; Clear existing autos else we'll be screwed by existing ones
11424 (verilog-delete-auto)
11425 ;; Injection if appropriate
11426 (when inject
11427 (verilog-inject-inst)
11428 (verilog-inject-sense)
11429 (verilog-inject-arg))
11430 ;;
11431 ;; Do user inserts first, so their code can insert AUTOs
11432 ;; We may provide a AUTOINSERTLISPLAST if another cleanup pass is needed
11433 (verilog-auto-re-search-do "/\\*AUTOINSERTLISP(.*?)\\*/"
11434 'verilog-auto-insert-lisp)
11435 ;; Expand instances before need the signals the instances input/output
11436 (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
11437 (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
11438 (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
11439 ;; Doesn't matter when done, but combine it with a common changer
11440 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
11441 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
11442 ;; Must be done before autoin/out as creates a reg
11443 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
11444 ;;
11445 ;; first in/outs from other files
11446 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
11447 (verilog-auto-re-search-do "/\\*AUTOINOUTCOMP([^)]*)\\*/" 'verilog-auto-inout-comp)
11448 ;; next in/outs which need previous sucked inputs first
11449 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((\"[^\"]*\")\\)\\*/"
11450 '(lambda () (verilog-auto-output t)))
11451 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\*/" 'verilog-auto-output)
11452 (verilog-auto-re-search-do "/\\*AUTOINPUT\\((\"[^\"]*\")\\)\\*/"
11453 '(lambda () (verilog-auto-input t)))
11454 (verilog-auto-re-search-do "/\\*AUTOINPUT\\*/" 'verilog-auto-input)
11455 (verilog-auto-re-search-do "/\\*AUTOINOUT\\((\"[^\"]*\")\\)\\*/"
11456 '(lambda () (verilog-auto-inout t)))
11457 (verilog-auto-re-search-do "/\\*AUTOINOUT\\*/" 'verilog-auto-inout)
11458 ;; Then tie off those in/outs
11459 (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
11460 ;; Wires/regs must be after inputs/outputs
11461 (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
11462 (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
11463 (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
11464 ;; outputevery needs AUTOOUTPUTs done first
11465 (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\*/" 'verilog-auto-output-every)
11466 ;; After we've created all new variables
11467 (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
11468 ;; Must be after all inputs outputs are generated
11469 (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
11470 ;; Fix line numbers (comments only)
11471 (when verilog-auto-inst-template-numbers
11472 (verilog-auto-templated-rel))))
11473 ;;
11474 (run-hooks 'verilog-auto-hook)
11475 ;;
11476 (set (make-local-variable 'verilog-auto-update-tick) (buffer-chars-modified-tick))
11477 ;;
11478 ;; If end result is same as when started, clear modified flag
11479 (cond ((and oldbuf (equal oldbuf (buffer-string)))
11480 (set-buffer-modified-p nil)
11481 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
11482 (t (unless noninteractive (message "Updating AUTOs...done"))))
11483 ;; End of after-change protection
11484 )))
11485 ;; Unwind forms
11486 (progn
11487 ;; Restore font-lock
11488 (when fontlocked (font-lock-mode t))))))
11489 \f
11490
11491 ;;
11492 ;; Skeleton based code insertion
11493 ;;
11494 (defvar verilog-template-map
11495 (let ((map (make-sparse-keymap)))
11496 (define-key map "a" 'verilog-sk-always)
11497 (define-key map "b" 'verilog-sk-begin)
11498 (define-key map "c" 'verilog-sk-case)
11499 (define-key map "f" 'verilog-sk-for)
11500 (define-key map "g" 'verilog-sk-generate)
11501 (define-key map "h" 'verilog-sk-header)
11502 (define-key map "i" 'verilog-sk-initial)
11503 (define-key map "j" 'verilog-sk-fork)
11504 (define-key map "m" 'verilog-sk-module)
11505 (define-key map "p" 'verilog-sk-primitive)
11506 (define-key map "r" 'verilog-sk-repeat)
11507 (define-key map "s" 'verilog-sk-specify)
11508 (define-key map "t" 'verilog-sk-task)
11509 (define-key map "w" 'verilog-sk-while)
11510 (define-key map "x" 'verilog-sk-casex)
11511 (define-key map "z" 'verilog-sk-casez)
11512 (define-key map "?" 'verilog-sk-if)
11513 (define-key map ":" 'verilog-sk-else-if)
11514 (define-key map "/" 'verilog-sk-comment)
11515 (define-key map "A" 'verilog-sk-assign)
11516 (define-key map "F" 'verilog-sk-function)
11517 (define-key map "I" 'verilog-sk-input)
11518 (define-key map "O" 'verilog-sk-output)
11519 (define-key map "S" 'verilog-sk-state-machine)
11520 (define-key map "=" 'verilog-sk-inout)
11521 (define-key map "W" 'verilog-sk-wire)
11522 (define-key map "R" 'verilog-sk-reg)
11523 (define-key map "D" 'verilog-sk-define-signal)
11524 map)
11525 "Keymap used in Verilog mode for smart template operations.")
11526
11527
11528 ;;
11529 ;; Place the templates into Verilog Mode. They may be inserted under any key.
11530 ;; C-c C-t will be the default. If you use templates a lot, you
11531 ;; may want to consider moving the binding to another key in your .emacs
11532 ;; file.
11533 ;;
11534 ;(define-key verilog-mode-map "\C-ct" verilog-template-map)
11535 (define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
11536
11537 ;;; ---- statement skeletons ------------------------------------------
11538
11539 (define-skeleton verilog-sk-prompt-condition
11540 "Prompt for the loop condition."
11541 "[condition]: " str )
11542
11543 (define-skeleton verilog-sk-prompt-init
11544 "Prompt for the loop init statement."
11545 "[initial statement]: " str )
11546
11547 (define-skeleton verilog-sk-prompt-inc
11548 "Prompt for the loop increment statement."
11549 "[increment statement]: " str )
11550
11551 (define-skeleton verilog-sk-prompt-name
11552 "Prompt for the name of something."
11553 "[name]: " str)
11554
11555 (define-skeleton verilog-sk-prompt-clock
11556 "Prompt for the name of something."
11557 "name and edge of clock(s): " str)
11558
11559 (defvar verilog-sk-reset nil)
11560 (defun verilog-sk-prompt-reset ()
11561 "Prompt for the name of a state machine reset."
11562 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
11563
11564
11565 (define-skeleton verilog-sk-prompt-state-selector
11566 "Prompt for the name of a state machine selector."
11567 "name of selector (eg {a,b,c,d}): " str )
11568
11569 (define-skeleton verilog-sk-prompt-output
11570 "Prompt for the name of something."
11571 "output: " str)
11572
11573 (define-skeleton verilog-sk-prompt-msb
11574 "Prompt for least significant bit specification."
11575 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
11576
11577 (define-skeleton verilog-sk-prompt-lsb
11578 "Prompt for least significant bit specification."
11579 "lsb:" str )
11580
11581 (defvar verilog-sk-p nil)
11582 (define-skeleton verilog-sk-prompt-width
11583 "Prompt for a width specification."
11584 ()
11585 (progn
11586 (setq verilog-sk-p (point))
11587 (verilog-sk-prompt-msb)
11588 (if (> (point) verilog-sk-p) "] " " ")))
11589
11590 (defun verilog-sk-header ()
11591 "Insert a descriptive header at the top of the file.
11592 See also `verilog-header' for an alternative format."
11593 (interactive "*")
11594 (save-excursion
11595 (goto-char (point-min))
11596 (verilog-sk-header-tmpl)))
11597
11598 (define-skeleton verilog-sk-header-tmpl
11599 "Insert a comment block containing the module title, author, etc."
11600 "[Description]: "
11601 "// -*- Mode: Verilog -*-"
11602 "\n// Filename : " (buffer-name)
11603 "\n// Description : " str
11604 "\n// Author : " (user-full-name)
11605 "\n// Created On : " (current-time-string)
11606 "\n// Last Modified By: " (user-full-name)
11607 "\n// Last Modified On: " (current-time-string)
11608 "\n// Update Count : 0"
11609 "\n// Status : Unknown, Use with caution!"
11610 "\n")
11611
11612 (define-skeleton verilog-sk-module
11613 "Insert a module definition."
11614 ()
11615 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
11616 > _ \n
11617 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
11618
11619 (define-skeleton verilog-sk-primitive
11620 "Insert a task definition."
11621 ()
11622 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
11623 > _ \n
11624 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
11625
11626 (define-skeleton verilog-sk-task
11627 "Insert a task definition."
11628 ()
11629 > "task " '(verilog-sk-prompt-name) & ?; \n
11630 > _ \n
11631 > "begin" \n
11632 > \n
11633 > (- verilog-indent-level-behavioral) "end" \n
11634 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
11635
11636 (define-skeleton verilog-sk-function
11637 "Insert a function definition."
11638 ()
11639 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
11640 > _ \n
11641 > "begin" \n
11642 > \n
11643 > (- verilog-indent-level-behavioral) "end" \n
11644 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
11645
11646 (define-skeleton verilog-sk-always
11647 "Insert always block. Uses the minibuffer to prompt
11648 for sensitivity list."
11649 ()
11650 > "always @ ( /*AUTOSENSE*/ ) begin\n"
11651 > _ \n
11652 > (- verilog-indent-level-behavioral) "end" \n >
11653 )
11654
11655 (define-skeleton verilog-sk-initial
11656 "Insert an initial block."
11657 ()
11658 > "initial begin\n"
11659 > _ \n
11660 > (- verilog-indent-level-behavioral) "end" \n > )
11661
11662 (define-skeleton verilog-sk-specify
11663 "Insert specify block. "
11664 ()
11665 > "specify\n"
11666 > _ \n
11667 > (- verilog-indent-level-behavioral) "endspecify" \n > )
11668
11669 (define-skeleton verilog-sk-generate
11670 "Insert generate block. "
11671 ()
11672 > "generate\n"
11673 > _ \n
11674 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
11675
11676 (define-skeleton verilog-sk-begin
11677 "Insert begin end block. Uses the minibuffer to prompt for name."
11678 ()
11679 > "begin" '(verilog-sk-prompt-name) \n
11680 > _ \n
11681 > (- verilog-indent-level-behavioral) "end"
11682 )
11683
11684 (define-skeleton verilog-sk-fork
11685 "Insert a fork join block."
11686 ()
11687 > "fork\n"
11688 > "begin" \n
11689 > _ \n
11690 > (- verilog-indent-level-behavioral) "end" \n
11691 > "begin" \n
11692 > \n
11693 > (- verilog-indent-level-behavioral) "end" \n
11694 > (- verilog-indent-level-behavioral) "join" \n
11695 > )
11696
11697
11698 (define-skeleton verilog-sk-case
11699 "Build skeleton case statement, prompting for the selector expression,
11700 and the case items."
11701 "[selector expression]: "
11702 > "case (" str ") " \n
11703 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
11704 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11705
11706 (define-skeleton verilog-sk-casex
11707 "Build skeleton casex statement, prompting for the selector expression,
11708 and the case items."
11709 "[selector expression]: "
11710 > "casex (" str ") " \n
11711 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
11712 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11713
11714 (define-skeleton verilog-sk-casez
11715 "Build skeleton casez statement, prompting for the selector expression,
11716 and the case items."
11717 "[selector expression]: "
11718 > "casez (" str ") " \n
11719 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n > )
11720 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
11721
11722 (define-skeleton verilog-sk-if
11723 "Insert a skeleton if statement."
11724 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
11725 > _ \n
11726 > (- verilog-indent-level-behavioral) "end " \n )
11727
11728 (define-skeleton verilog-sk-else-if
11729 "Insert a skeleton else if statement."
11730 > (verilog-indent-line) "else if ("
11731 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
11732 > _ \n
11733 > "end" (progn (electric-verilog-terminate-line) nil))
11734
11735 (define-skeleton verilog-sk-datadef
11736 "Common routine to get data definition."
11737 ()
11738 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
11739
11740 (define-skeleton verilog-sk-input
11741 "Insert an input definition."
11742 ()
11743 > "input [" '(verilog-sk-datadef))
11744
11745 (define-skeleton verilog-sk-output
11746 "Insert an output definition."
11747 ()
11748 > "output [" '(verilog-sk-datadef))
11749
11750 (define-skeleton verilog-sk-inout
11751 "Insert an inout definition."
11752 ()
11753 > "inout [" '(verilog-sk-datadef))
11754
11755 (defvar verilog-sk-signal nil)
11756 (define-skeleton verilog-sk-def-reg
11757 "Insert a reg definition."
11758 ()
11759 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
11760
11761 (defun verilog-sk-define-signal ()
11762 "Insert a definition of signal under point at top of module."
11763 (interactive "*")
11764 (let* ((sig-re "[a-zA-Z0-9_]*")
11765 (v1 (buffer-substring
11766 (save-excursion
11767 (skip-chars-backward sig-re)
11768 (point))
11769 (save-excursion
11770 (skip-chars-forward sig-re)
11771 (point)))))
11772 (if (not (member v1 verilog-keywords))
11773 (save-excursion
11774 (setq verilog-sk-signal v1)
11775 (verilog-beg-of-defun)
11776 (verilog-end-of-statement)
11777 (verilog-forward-syntactic-ws)
11778 (verilog-sk-def-reg)
11779 (message "signal at point is %s" v1))
11780 (message "object at point (%s) is a keyword" v1))))
11781
11782 (define-skeleton verilog-sk-wire
11783 "Insert a wire definition."
11784 ()
11785 > "wire [" '(verilog-sk-datadef))
11786
11787 (define-skeleton verilog-sk-reg
11788 "Insert a reg definition."
11789 ()
11790 > "reg [" '(verilog-sk-datadef))
11791
11792 (define-skeleton verilog-sk-assign
11793 "Insert a skeleton assign statement."
11794 ()
11795 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
11796
11797 (define-skeleton verilog-sk-while
11798 "Insert a skeleton while loop statement."
11799 ()
11800 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
11801 > _ \n
11802 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11803
11804 (define-skeleton verilog-sk-repeat
11805 "Insert a skeleton repeat loop statement."
11806 ()
11807 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
11808 > _ \n
11809 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11810
11811 (define-skeleton verilog-sk-for
11812 "Insert a skeleton while loop statement."
11813 ()
11814 > "for ("
11815 '(verilog-sk-prompt-init) "; "
11816 '(verilog-sk-prompt-condition) "; "
11817 '(verilog-sk-prompt-inc)
11818 ") begin" \n
11819 > _ \n
11820 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
11821
11822 (define-skeleton verilog-sk-comment
11823 "Inserts three comment lines, making a display comment."
11824 ()
11825 > "/*\n"
11826 > "* " _ \n
11827 > "*/")
11828
11829 (define-skeleton verilog-sk-state-machine
11830 "Insert a state machine definition."
11831 "Name of state variable: "
11832 '(setq input "state")
11833 > "// State registers for " str | -23 \n
11834 '(setq verilog-sk-state str)
11835 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
11836 '(setq input nil)
11837 > \n
11838 > "// State FF for " verilog-sk-state \n
11839 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
11840 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
11841 > verilog-sk-state " = next_" verilog-sk-state ?; \n
11842 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
11843 > \n
11844 > "// Next State Logic for " verilog-sk-state \n
11845 > "always @ ( /*AUTOSENSE*/ ) begin\n"
11846 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
11847 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
11848 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
11849 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
11850 \f
11851
11852 ;;
11853 ;; Include file loading with mouse/return event
11854 ;;
11855 ;; idea & first impl.: M. Rouat (eldo-mode.el)
11856 ;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
11857
11858 (if (featurep 'xemacs)
11859 (require 'overlay))
11860
11861 (defconst verilog-include-file-regexp
11862 "^`include\\s-+\"\\([^\n\"]*\\)\""
11863 "Regexp that matches the include file.")
11864
11865 (defvar verilog-mode-mouse-map
11866 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
11867 (set-keymap-parent map verilog-mode-map)
11868 ;; mouse button bindings
11869 (define-key map "\r" 'verilog-load-file-at-point)
11870 (if (featurep 'xemacs)
11871 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
11872 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
11873 (if (featurep 'xemacs)
11874 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
11875 (define-key map [S-mouse-2] 'mouse-yank-at-click))
11876 map)
11877 "Map containing mouse bindings for `verilog-mode'.")
11878
11879
11880 (defun verilog-highlight-region (beg end old-len)
11881 "Colorize included files and modules in the (changed?) region.
11882 Clicking on the middle-mouse button loads them in a buffer (as in dired)."
11883 (when (or verilog-highlight-includes
11884 verilog-highlight-modules)
11885 (save-excursion
11886 (save-match-data ;; A query-replace may call this function - do not disturb
11887 (verilog-save-buffer-state
11888 (verilog-save-scan-cache
11889 (let (end-point)
11890 (goto-char end)
11891 (setq end-point (point-at-eol))
11892 (goto-char beg)
11893 (beginning-of-line) ; scan entire line
11894 ;; delete overlays existing on this line
11895 (let ((overlays (overlays-in (point) end-point)))
11896 (while overlays
11897 (if (and
11898 (overlay-get (car overlays) 'detachable)
11899 (or (overlay-get (car overlays) 'verilog-include-file)
11900 (overlay-get (car overlays) 'verilog-inst-module)))
11901 (delete-overlay (car overlays)))
11902 (setq overlays (cdr overlays))))
11903 ;;
11904 ;; make new include overlays
11905 (when verilog-highlight-includes
11906 (while (search-forward-regexp verilog-include-file-regexp end-point t)
11907 (goto-char (match-beginning 1))
11908 (let ((ov (make-overlay (match-beginning 1) (match-end 1))))
11909 (overlay-put ov 'start-closed 't)
11910 (overlay-put ov 'end-closed 't)
11911 (overlay-put ov 'evaporate 't)
11912 (overlay-put ov 'verilog-include-file 't)
11913 (overlay-put ov 'mouse-face 'highlight)
11914 (overlay-put ov 'local-map verilog-mode-mouse-map))))
11915 ;;
11916 ;; make new module overlays
11917 (goto-char beg)
11918 ;; This scanner is syntax-fragile, so don't get bent
11919 (when verilog-highlight-modules
11920 (condition-case nil
11921 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-point t)
11922 (save-excursion
11923 (goto-char (match-beginning 0))
11924 (unless (verilog-inside-comment-p)
11925 (verilog-read-inst-module-matcher) ;; sets match 0
11926 (let* ((ov (make-overlay (match-beginning 0) (match-end 0))))
11927 (overlay-put ov 'start-closed 't)
11928 (overlay-put ov 'end-closed 't)
11929 (overlay-put ov 'evaporate 't)
11930 (overlay-put ov 'verilog-inst-module 't)
11931 (overlay-put ov 'mouse-face 'highlight)
11932 (overlay-put ov 'local-map verilog-mode-mouse-map)))))
11933 (error nil)))
11934 ;;
11935 ;; Future highlights:
11936 ;; variables - make an Occur buffer of where referenced
11937 ;; pins - make an Occur buffer of the sig in the declaration module
11938 )))))))
11939
11940 (defun verilog-highlight-buffer ()
11941 "Colorize included files and modules across the whole buffer."
11942 ;; Invoked via verilog-mode calling font-lock then `font-lock-mode-hook'
11943 (interactive)
11944 ;; delete and remake overlays
11945 (verilog-highlight-region (point-min) (point-max) nil))
11946
11947 ;; Deprecated, but was interactive, so we'll keep it around
11948 (defalias 'verilog-colorize-include-files-buffer 'verilog-highlight-buffer)
11949
11950 ;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
11951 ;; so define this function to do more or less the same as ffap-at-mouse
11952 ;; but first resolve filename...
11953 (defun verilog-load-file-at-mouse (event)
11954 "Load file under button 2 click's EVENT.
11955 Files are checked based on `verilog-library-flags'."
11956 (interactive "@e")
11957 (save-excursion ;; implement a Verilog specific ffap-at-mouse
11958 (mouse-set-point event)
11959 (verilog-load-file-at-point t)))
11960
11961 ;; ffap isn't useable for Verilog mode. It uses library paths.
11962 ;; so define this function to do more or less the same as ffap
11963 ;; but first resolve filename...
11964 (defun verilog-load-file-at-point (&optional warn)
11965 "Load file under point.
11966 If WARN, throw warning if not found.
11967 Files are checked based on `verilog-library-flags'."
11968 (interactive)
11969 (save-excursion ;; implement a Verilog specific ffap
11970 (let ((overlays (overlays-in (point) (point)))
11971 hit)
11972 (while (and overlays (not hit))
11973 (when (overlay-get (car overlays) 'verilog-inst-module)
11974 (verilog-goto-defun-file (buffer-substring
11975 (overlay-start (car overlays))
11976 (overlay-end (car overlays))))
11977 (setq hit t))
11978 (setq overlays (cdr overlays)))
11979 ;; Include?
11980 (beginning-of-line)
11981 (when (and (not hit)
11982 (looking-at verilog-include-file-regexp))
11983 (if (and (car (verilog-library-filenames
11984 (match-string 1) (buffer-file-name)))
11985 (file-readable-p (car (verilog-library-filenames
11986 (match-string 1) (buffer-file-name)))))
11987 (find-file (car (verilog-library-filenames
11988 (match-string 1) (buffer-file-name))))
11989 (when warn
11990 (message
11991 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
11992 (match-string 1))))))))
11993
11994 ;;
11995 ;; Bug reporting
11996 ;;
11997
11998 (defun verilog-faq ()
11999 "Tell the user their current version, and where to get the FAQ etc."
12000 (interactive)
12001 (with-output-to-temp-buffer "*verilog-mode help*"
12002 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
12003 (princ "\n")
12004 (princ "For new releases, see http://www.verilog.com\n")
12005 (princ "\n")
12006 (princ "For frequently asked questions, see http://www.veripool.org/verilog-mode-faq.html\n")
12007 (princ "\n")
12008 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
12009 (princ "\n")))
12010
12011 (autoload 'reporter-submit-bug-report "reporter")
12012 (defvar reporter-prompt-for-summary-p)
12013
12014 (defun verilog-submit-bug-report ()
12015 "Submit via mail a bug report on verilog-mode.el."
12016 (interactive)
12017 (let ((reporter-prompt-for-summary-p t))
12018 (reporter-submit-bug-report
12019 "mac@verilog.com, wsnyder@wsnyder.org"
12020 (concat "verilog-mode v" verilog-mode-version)
12021 '(
12022 verilog-active-low-regexp
12023 verilog-align-ifelse
12024 verilog-assignment-delay
12025 verilog-auto-arg-sort
12026 verilog-auto-endcomments
12027 verilog-auto-hook
12028 verilog-auto-ignore-concat
12029 verilog-auto-indent-on-newline
12030 verilog-auto-inout-ignore-regexp
12031 verilog-auto-input-ignore-regexp
12032 verilog-auto-inst-column
12033 verilog-auto-inst-dot-name
12034 verilog-auto-inst-param-value
12035 verilog-auto-inst-template-numbers
12036 verilog-auto-inst-vector
12037 verilog-auto-lineup
12038 verilog-auto-newline
12039 verilog-auto-output-ignore-regexp
12040 verilog-auto-read-includes
12041 verilog-auto-reset-widths
12042 verilog-auto-save-policy
12043 verilog-auto-sense-defines-constant
12044 verilog-auto-sense-include-inputs
12045 verilog-auto-star-expand
12046 verilog-auto-star-save
12047 verilog-auto-unused-ignore-regexp
12048 verilog-before-auto-hook
12049 verilog-before-delete-auto-hook
12050 verilog-before-getopt-flags-hook
12051 verilog-case-indent
12052 verilog-cexp-indent
12053 verilog-compiler
12054 verilog-coverage
12055 verilog-delete-auto-hook
12056 verilog-getopt-flags-hook
12057 verilog-highlight-grouping-keywords
12058 verilog-highlight-p1800-keywords
12059 verilog-highlight-translate-off
12060 verilog-indent-begin-after-if
12061 verilog-indent-declaration-macros
12062 verilog-indent-level
12063 verilog-indent-level-behavioral
12064 verilog-indent-level-declaration
12065 verilog-indent-level-directive
12066 verilog-indent-level-module
12067 verilog-indent-lists
12068 verilog-library-directories
12069 verilog-library-extensions
12070 verilog-library-files
12071 verilog-library-flags
12072 verilog-linter
12073 verilog-minimum-comment-distance
12074 verilog-mode-hook
12075 verilog-preprocessor
12076 verilog-simulator
12077 verilog-tab-always-indent
12078 verilog-tab-to-comment
12079 verilog-typedef-regexp
12080 )
12081 nil nil
12082 (concat "Hi Mac,
12083
12084 I want to report a bug.
12085
12086 Before I go further, I want to say that Verilog mode has changed my life.
12087 I save so much time, my files are colored nicely, my co workers respect
12088 my coding ability... until now. I'd really appreciate anything you
12089 could do to help me out with this minor deficiency in the product.
12090
12091 I've taken a look at the Verilog-Mode FAQ at
12092 http://www.veripool.org/verilog-mode-faq.html.
12093
12094 And, I've considered filing the bug on the issue tracker at
12095 http://www.veripool.org/verilog-mode-bugs
12096 since I realize that public bugs are easier for you to track,
12097 and for others to search, but would prefer to email.
12098
12099 So, to reproduce the bug, start a fresh Emacs via " invocation-name "
12100 -no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
12101 the code included below.
12102
12103 Given those lines, I expected [[Fill in here]] to happen;
12104 but instead, [[Fill in here]] happens!.
12105
12106 == The code: =="))))
12107
12108 (provide 'verilog-mode)
12109
12110 ;; Local Variables:
12111 ;; checkdoc-permit-comma-termination-flag:t
12112 ;; checkdoc-force-docstrings-flag:nil
12113 ;; End:
12114
12115 ;;; verilog-mode.el ends here