Merge from emacs--rel--22
[bpt/emacs.git] / lisp / progmodes / verilog-mode.el
1 ;; verilog-mode.el --- major mode for editing verilog source in Emacs
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: Michael McNamara (mac@verilog.com)
7 ;; http://www.verilog.com
8 ;;
9 ;; AUTO features, signal, modsig; by: Wilson Snyder
10 ;; (wsnyder@wsnyder.org)
11 ;; http://www.veripool.com
12 ;; Keywords: languages
13
14 ;; Yoni Rabkin <yoni@rabkins.net> contacted the maintainer of this
15 ;; file on 19/3/2008, and the maintainer agreed that when a bug is
16 ;; filed in the Emacs bug reporting system against this file, a copy
17 ;; of the bug report be sent to the maintainer's email address.
18
19 ;; This code supports Emacs 21.1 and later
20 ;; And XEmacs 21.1 and later
21 ;; Please do not make changes that break Emacs 21. Thanks!
22 ;;
23 ;;
24
25 ;; This file is part of GNU Emacs.
26
27 ;; GNU Emacs is free software: you can redistribute it and/or modify
28 ;; it under the terms of the GNU General Public License as published by
29 ;; the Free Software Foundation, either version 3 of the License, or
30 ;; (at your option) any later version.
31
32 ;; GNU Emacs is distributed in the hope that it will be useful,
33 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
34 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 ;; GNU General Public License for more details.
36
37 ;; You should have received a copy of the GNU General Public License
38 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
39
40 ;;; Commentary:
41
42 ;; This mode borrows heavily from the Pascal-mode and the cc-mode of Emacs
43
44 ;; USAGE
45 ;; =====
46
47 ;; A major mode for editing Verilog HDL source code. When you have
48 ;; entered Verilog mode, you may get more info by pressing C-h m. You
49 ;; may also get online help describing various functions by: C-h f
50 ;; <Name of function you want described>
51
52 ;; KNOWN BUGS / BUG REPORTS
53 ;; =======================
54
55 ;; Verilog is a rapidly evolving language, and hence this mode is
56 ;; under continuous development. Hence this is beta code, and likely
57 ;; has bugs. Please report any and all bugs to me at mac@verilog.com.
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 ; (setq auto-mode-alist (cons '("\\.v\\'" . verilog-mode) auto-mode-alist))
82 ; (setq auto-mode-alist (cons '("\\.dv\\'" . verilog-mode) auto-mode-alist))
83
84 ;; If you want to customize Verilog mode to fit your needs better,
85 ;; you may add these lines (the values of the variables presented
86 ;; here are the defaults). Note also that if you use an Emacs that
87 ;; supports custom, it's probably better to use the custom menu to
88 ;; edit these.
89 ;;
90 ;; Be sure to examine at the help for verilog-auto, and the other
91 ;; verilog-auto-* functions for some major coding time savers.
92 ;;
93 ; ;; User customization for Verilog mode
94 ; (setq verilog-indent-level 3
95 ; verilog-indent-level-module 3
96 ; verilog-indent-level-declaration 3
97 ; verilog-indent-level-behavioral 3
98 ; verilog-indent-level-directive 1
99 ; verilog-case-indent 2
100 ; verilog-auto-newline t
101 ; verilog-auto-indent-on-newline t
102 ; verilog-tab-always-indent t
103 ; verilog-auto-endcomments t
104 ; verilog-minimum-comment-distance 40
105 ; verilog-indent-begin-after-if t
106 ; verilog-auto-lineup '(all)
107 ; verilog-highlight-p1800-keywords nil
108 ; verilog-linter "my_lint_shell_command"
109 ; )
110
111 ;; \f
112
113 ;;; History:
114 ;;
115 ;; See commit history at http://www.veripool.com/verilog-mode.html
116 ;; (This section is required to appease checkdoc.)
117
118 ;;; Code:
119
120 ;; This variable will always hold the version number of the mode
121 (defconst verilog-mode-version "429"
122 "Version of this Verilog mode.")
123 (defconst verilog-mode-release-date "2008-06-23-GNU"
124 "Release date of this Verilog mode.")
125 (defconst verilog-mode-release-emacs t
126 "If non-nil, this version of Verilog mode was released with Emacs itself.")
127
128 (defun verilog-version ()
129 "Inform caller of the version of this file."
130 (interactive)
131 (message "Using verilog-mode version %s" verilog-mode-version))
132
133 ;; Insure we have certain packages, and deal with it if we don't
134 ;; Be sure to note which Emacs flavor and version added each feature.
135 (eval-when-compile
136 ;; The below were disabled when GNU Emacs 22 was released;
137 ;; perhaps some still need to be there to support Emacs 21.
138 (when (featurep 'xemacs)
139 (condition-case nil
140 (require 'easymenu)
141 (error nil))
142 (condition-case nil
143 (require 'regexp-opt)
144 (error nil))
145 ;; Bug in 19.28 through 19.30 skeleton.el, not provided.
146 (condition-case nil
147 (load "skeleton")
148 (error nil))
149 (condition-case nil
150 (if (fboundp 'when)
151 nil ;; fab
152 (defmacro when (cond &rest body)
153 (list 'if cond (cons 'progn body))))
154 (error nil))
155 (condition-case nil
156 (if (fboundp 'unless)
157 nil ;; fab
158 (defmacro unless (cond &rest body)
159 (cons 'if (cons cond (cons nil body)))))
160 (error nil))
161 (condition-case nil
162 (if (fboundp 'store-match-data)
163 nil ;; fab
164 (defmacro store-match-data (&rest args) nil))
165 (error nil))
166 (condition-case nil
167 (if (fboundp 'char-before)
168 nil ;; great
169 (defmacro char-before (&rest body)
170 (char-after (1- (point)))))
171 (error nil))
172 (condition-case nil
173 (require 'custom)
174 (error nil))
175 (condition-case nil
176 (if (fboundp 'match-string-no-properties)
177 nil ;; great
178 (defsubst match-string-no-properties (num &optional string)
179 "Return string of text matched by last search, without text properties.
180 NUM specifies which parenthesized expression in the last regexp.
181 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
182 Zero means the entire text matched by the whole regexp or whole string.
183 STRING should be given if the last search was by `string-match' on STRING."
184 (if (match-beginning num)
185 (if string
186 (let ((result
187 (substring string
188 (match-beginning num) (match-end num))))
189 (set-text-properties 0 (length result) nil result)
190 result)
191 (buffer-substring-no-properties (match-beginning num)
192 (match-end num)
193 (current-buffer)))))
194 )
195 (error nil))
196 (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
197 nil ;; We've got what we needed
198 ;; We have the old custom-library, hack around it!
199 (defmacro defgroup (&rest args) nil)
200 (defmacro customize (&rest args)
201 (message
202 "Sorry, Customize is not available with this version of Emacs"))
203 (defmacro defcustom (var value doc &rest args)
204 `(defvar ,var ,value ,doc))
205 )
206 (if (fboundp 'defface)
207 nil ; great!
208 (defmacro defface (var values doc &rest args)
209 `(make-face ,var))
210 )
211
212 (if (and (featurep 'custom) (fboundp 'customize-group))
213 nil ;; We've got what we needed
214 ;; We have an intermediate custom-library, hack around it!
215 (defmacro customize-group (var &rest args)
216 `(customize ,var))
217 )))
218
219 ;; Provide a regular expression optimization routine, using regexp-opt
220 ;; if provided by the user's elisp libraries
221 (eval-and-compile
222 ;; The below were disabled when GNU Emacs 22 was released;
223 ;; perhaps some still need to be there to support Emacs 21.
224 (if (featurep 'xemacs)
225 (if (fboundp 'regexp-opt)
226 ;; regexp-opt is defined, does it take 3 or 2 arguments?
227 (if (fboundp 'function-max-args)
228 (let ((args (function-max-args `regexp-opt)))
229 (cond
230 ((eq args 3) ;; It takes 3
231 (condition-case nil ; Hide this defun from emacses
232 ;with just a two input regexp
233 (defun verilog-regexp-opt (a b)
234 "Deal with differing number of required arguments for `regexp-opt'.
235 Call 'regexp-opt' on A and B."
236 (regexp-opt a b 't))
237 (error nil))
238 )
239 ((eq args 2) ;; It takes 2
240 (defun verilog-regexp-opt (a b)
241 "Call 'regexp-opt' on A and B."
242 (regexp-opt a b))
243 )
244 (t nil)))
245 ;; We can't tell; assume it takes 2
246 (defun verilog-regexp-opt (a b)
247 "Call 'regexp-opt' on A and B."
248 (regexp-opt a b))
249 )
250 ;; There is no regexp-opt, provide our own
251 (defun verilog-regexp-opt (strings &optional paren shy)
252 (let ((open (if paren "\\(" "")) (close (if paren "\\)" "")))
253 (concat open (mapconcat 'regexp-quote strings "\\|") close)))
254 )
255 ;; Emacs.
256 (defalias 'verilog-regexp-opt 'regexp-opt)))
257
258 (eval-when-compile
259 (defun verilog-regexp-words (a)
260 "Call 'regexp-opt' with word delimiters for the words A."
261 (concat "\\<" (verilog-regexp-opt a t) "\\>")))
262
263 (defun verilog-easy-menu-filter (menu)
264 "Filter a easy-menu-define to support new features."
265 (cond ((not (featurep 'xemacs))
266 menu) ;; GNU Emacs - passthru
267 ;; Xemacs doesn't support :help. Strip it.
268 ;; Recursively filter the a submenu
269 ((listp menu)
270 (mapcar 'verilog-easy-menu-filter menu))
271 ;; Look for [:help "blah"] and remove
272 ((vectorp menu)
273 (let ((i 0) (out []))
274 (while (< i (length menu))
275 (if (equal `:help (aref menu i))
276 (setq i (+ 2 i))
277 (setq out (vconcat out (vector (aref menu i)))
278 i (1+ i))))
279 out))
280 (t menu))) ;; Default - ok
281 ;;(verilog-easy-menu-filter
282 ;; `("Verilog" ("MA" ["SAA" nil :help "Help SAA"] ["SAB" nil :help "Help SAA"])
283 ;; "----" ["MB" nil :help "Help MB"]))
284
285 (defun verilog-customize ()
286 "Customize variables and other settings used by Verilog-Mode."
287 (interactive)
288 (customize-group 'verilog-mode))
289
290 (defun verilog-font-customize ()
291 "Customize fonts used by Verilog-Mode."
292 (interactive)
293 (if (fboundp 'customize-apropos)
294 (customize-apropos "font-lock-*" 'faces)))
295
296 (defun verilog-booleanp (value)
297 "Return t if VALUE is boolean.
298 This implements GNU Emacs 22.1's `booleanp' function in earlier Emacs.
299 This function may be removed when Emacs 21 is no longer supported."
300 (or (equal value t) (equal value nil)))
301
302 (defalias 'verilog-syntax-ppss
303 (if (fboundp 'syntax-ppss) 'syntax-ppss
304 (lambda (&optional pos) (parse-partial-sexp (point-min) (or pos (point))))))
305
306 (defgroup verilog-mode nil
307 "Facilitates easy editing of Verilog source text."
308 :version "22.2"
309 :group 'languages)
310
311 ; (defgroup verilog-mode-fonts nil
312 ; "Facilitates easy customization fonts used in Verilog source text"
313 ; :link '(customize-apropos "font-lock-*" 'faces)
314 ; :group 'verilog-mode)
315
316 (defgroup verilog-mode-indent nil
317 "Customize indentation and highlighting of Verilog source text."
318 :group 'verilog-mode)
319
320 (defgroup verilog-mode-actions nil
321 "Customize actions on Verilog source text."
322 :group 'verilog-mode)
323
324 (defgroup verilog-mode-auto nil
325 "Customize AUTO actions when expanding Verilog source text."
326 :group 'verilog-mode)
327
328 (defcustom verilog-linter
329 "echo 'No verilog-linter set, see \"M-x describe-variable verilog-linter\"'"
330 "*Unix program and arguments to call to run a lint checker on Verilog source.
331 Depending on the `verilog-set-compile-command', this may be invoked when
332 you type \\[compile]. When the compile completes, \\[next-error] will take
333 you to the next lint error."
334 :type 'string
335 :group 'verilog-mode-actions)
336 ;; We don't mark it safe, as it's used as a shell command
337
338 (defcustom verilog-coverage
339 "echo 'No verilog-coverage set, see \"M-x describe-variable verilog-coverage\"'"
340 "*Program and arguments to use to annotate for coverage Verilog source.
341 Depending on the `verilog-set-compile-command', this may be invoked when
342 you type \\[compile]. When the compile completes, \\[next-error] will take
343 you to the next lint error."
344 :type 'string
345 :group 'verilog-mode-actions)
346 ;; We don't mark it safe, as it's used as a shell command
347
348 (defcustom verilog-simulator
349 "echo 'No verilog-simulator set, see \"M-x describe-variable verilog-simulator\"'"
350 "*Program and arguments to use to interpret Verilog source.
351 Depending on the `verilog-set-compile-command', this may be invoked when
352 you type \\[compile]. When the compile completes, \\[next-error] will take
353 you to the next lint error."
354 :type 'string
355 :group 'verilog-mode-actions)
356 ;; We don't mark it safe, as it's used as a shell command
357
358 (defcustom verilog-compiler
359 "echo 'No verilog-compiler set, see \"M-x describe-variable verilog-compiler\"'"
360 "*Program and arguments to use to compile Verilog source.
361 Depending on the `verilog-set-compile-command', this may be invoked when
362 you type \\[compile]. When the compile completes, \\[next-error] will take
363 you to the next lint error."
364 :type 'string
365 :group 'verilog-mode-actions)
366 ;; We don't mark it safe, as it's used as a shell command
367
368 (defvar verilog-tool 'verilog-linter
369 "Which tool to use for building compiler-command.
370 Either nil, `verilog-linter, `verilog-coverage, `verilog-simulator, or
371 `verilog-compiler. Alternatively use the \"Choose Compilation Action\"
372 menu. See `verilog-set-compile-command' for more information.")
373
374 (defcustom verilog-highlight-translate-off nil
375 "*Non-nil means background-highlight code excluded from translation.
376 That is, all code between \"// synopsys translate_off\" and
377 \"// synopsys translate_on\" is highlighted using a different background color
378 \(face `verilog-font-lock-translate-off-face').
379
380 Note: This will slow down on-the-fly fontification (and thus editing).
381
382 Note: Activate the new setting in a Verilog buffer by re-fontifying it (menu
383 entry \"Fontify Buffer\"). XEmacs: turn off and on font locking."
384 :type 'boolean
385 :group 'verilog-mode-indent)
386 ;; Note we don't use :safe, as that would break on Emacsen before 22.0.
387 (put 'verilog-highlight-translate-off 'safe-local-variable 'verilog-booleanp)
388
389 (defcustom verilog-indent-level 3
390 "*Indentation of Verilog statements with respect to containing block."
391 :group 'verilog-mode-indent
392 :type 'integer)
393 (put 'verilog-indent-level 'safe-local-variable 'integerp)
394
395 (defcustom verilog-indent-level-module 3
396 "*Indentation of Module level Verilog statements (eg always, initial).
397 Set to 0 to get initial and always statements lined up on the left side of
398 your screen."
399 :group 'verilog-mode-indent
400 :type 'integer)
401 (put 'verilog-indent-level-module 'safe-local-variable 'integerp)
402
403 (defcustom verilog-indent-level-declaration 3
404 "*Indentation of declarations with respect to containing block.
405 Set to 0 to get them list right under containing block."
406 :group 'verilog-mode-indent
407 :type 'integer)
408 (put 'verilog-indent-level-declaration 'safe-local-variable 'integerp)
409
410 (defcustom verilog-indent-declaration-macros nil
411 "*How to treat macro expansions in a declaration.
412 If nil, indent as:
413 input [31:0] a;
414 input `CP;
415 output c;
416 If non nil, treat as:
417 input [31:0] a;
418 input `CP ;
419 output c;"
420 :group 'verilog-mode-indent
421 :type 'boolean)
422 (put 'verilog-indent-declaration-macros 'safe-local-variable 'verilog-booleanp)
423
424 (defcustom verilog-indent-lists t
425 "*How to treat indenting items in a list.
426 If t (the default), indent as:
427 always @( posedge a or
428 reset ) begin
429
430 If nil, treat as:
431 always @( posedge a or
432 reset ) begin"
433 :group 'verilog-mode-indent
434 :type 'boolean)
435 (put 'verilog-indent-lists 'safe-local-variable 'verilog-booleanp)
436
437 (defcustom verilog-indent-level-behavioral 3
438 "*Absolute indentation of first begin in a task or function block.
439 Set to 0 to get such code to start at the left side of the screen."
440 :group 'verilog-mode-indent
441 :type 'integer)
442 (put 'verilog-indent-level-behavioral 'safe-local-variable 'integerp)
443
444 (defcustom verilog-indent-level-directive 1
445 "*Indentation to add to each level of `ifdef declarations.
446 Set to 0 to have all directives start at the left side of the screen."
447 :group 'verilog-mode-indent
448 :type 'integer)
449 (put 'verilog-indent-level-directive 'safe-local-variable 'integerp)
450
451 (defcustom verilog-cexp-indent 2
452 "*Indentation of Verilog statements split across lines."
453 :group 'verilog-mode-indent
454 :type 'integer)
455 (put 'verilog-cexp-indent 'safe-local-variable 'integerp)
456
457 (defcustom verilog-case-indent 2
458 "*Indentation for case statements."
459 :group 'verilog-mode-indent
460 :type 'integer)
461 (put 'verilog-case-indent 'safe-local-variable 'integerp)
462
463 (defcustom verilog-auto-newline t
464 "*True means automatically newline after semicolons."
465 :group 'verilog-mode-indent
466 :type 'boolean)
467 (put 'verilog-auto-newline 'safe-local-variable 'verilog-booleanp)
468
469 (defcustom verilog-auto-indent-on-newline t
470 "*True means automatically indent line after newline."
471 :group 'verilog-mode-indent
472 :type 'boolean)
473 (put 'verilog-auto-indent-on-newline 'safe-local-variable 'verilog-booleanp)
474
475 (defcustom verilog-tab-always-indent t
476 "*True means TAB should always re-indent the current line.
477 A nil value means TAB will only reindent when at the beginning of the line."
478 :group 'verilog-mode-indent
479 :type 'boolean)
480 (put 'verilog-tab-always-indent 'safe-local-variable 'verilog-booleanp)
481
482 (defcustom verilog-tab-to-comment nil
483 "*True means TAB moves to the right hand column in preparation for a comment."
484 :group 'verilog-mode-actions
485 :type 'boolean)
486 (put 'verilog-tab-to-comment 'safe-local-variable 'verilog-booleanp)
487
488 (defcustom verilog-indent-begin-after-if t
489 "*If true, indent begin statements following if, else, while, for and repeat.
490 Otherwise, line them up."
491 :group 'verilog-mode-indent
492 :type 'boolean)
493 (put 'verilog-indent-begin-after-if 'safe-local-variable 'verilog-booleanp)
494
495
496 (defcustom verilog-align-ifelse nil
497 "*If true, align `else' under matching `if'.
498 Otherwise else is lined up with first character on line holding matching if."
499 :group 'verilog-mode-indent
500 :type 'boolean)
501 (put 'verilog-align-ifelse 'safe-local-variable 'verilog-booleanp)
502
503 (defcustom verilog-minimum-comment-distance 10
504 "*Minimum distance (in lines) between begin and end required before a comment.
505 Setting this variable to zero results in every end acquiring a comment; the
506 default avoids too many redundant comments in tight quarters."
507 :group 'verilog-mode-indent
508 :type 'integer)
509 (put 'verilog-minimum-comment-distance 'safe-local-variable 'integerp)
510
511 (defcustom verilog-auto-lineup '(declaration)
512 "*Algorithm for lining up statements on multiple lines.
513
514 If this list contains the symbol 'all', then all line ups described below
515 are done.
516
517 If this list contains the symbol 'declaration', then declarations are lined up
518 with any preceding declarations, taking into account widths and the like, so
519 for example the code:
520 reg [31:0] a;
521 reg b;
522 would become
523 reg [31:0] a;
524 reg b;
525
526 If this list contains the symbol 'assignment', then assignments are lined up
527 with any preceding assignments, so for example the code
528 a_long_variable = b + c;
529 d = e + f;
530 would become
531 a_long_variable = b + c;
532 d = e + f;"
533
534 ;; The following is not implemented:
535 ;If this list contains the symbol 'case', then case items are lined up
536 ;with any preceding case items, so for example the code
537 ; case (a) begin
538 ; a_long_state : a = 3;
539 ; b: a = 4;
540 ; endcase
541 ;would become
542 ; case (a) begin
543 ; a_long_state : a = 3;
544 ; b : a = 4;
545 ; endcase
546 ;
547
548 :group 'verilog-mode-indent
549 :type 'list)
550 (put 'verilog-auto-lineup 'safe-local-variable 'listp)
551
552 (defcustom verilog-highlight-p1800-keywords nil
553 "*True means highlight words newly reserved by IEEE-1800.
554 These will appear in `verilog-font-lock-p1800-face' in order to gently
555 suggest changing where these words are used as variables to something else.
556 A nil value means highlight these words as appropriate for the SystemVerilog
557 IEEE-1800 standard. Note that changing this will require restarting Emacs
558 to see the effect as font color choices are cached by Emacs."
559 :group 'verilog-mode-indent
560 :type 'boolean)
561 (put 'verilog-highlight-p1800-keywords 'safe-local-variable 'verilog-booleanp)
562
563 (defcustom verilog-highlight-grouping-keywords nil
564 "*True means highlight grouping keywords 'begin' and 'end' more dramatically.
565 If false, these words are in the font-lock-type-face; if True then they are in
566 `verilog-font-lock-ams-face'. Some find that special highlighting on these
567 grouping constructs allow the structure of the code to be understood at a glance."
568 :group 'verilog-mode-indent
569 :type 'boolean)
570 (put 'verilog-highlight-grouping-keywords 'safe-local-variable 'verilog-booleanp)
571
572 (defcustom verilog-auto-endcomments t
573 "*True means insert a comment /* ... */ after 'end's.
574 The name of the function or case will be set between the braces."
575 :group 'verilog-mode-actions
576 :type 'boolean)
577 (put 'verilog-auto-endcomments 'safe-local-variable 'verilog-booleanp)
578
579 (defcustom verilog-auto-read-includes nil
580 "*True means to automatically read includes before AUTOs.
581 This will do a `verilog-read-defines' and `verilog-read-includes' before
582 each AUTO expansion. This makes it easier to embed defines and includes,
583 but can result in very slow reading times if there are many or large
584 include files."
585 :group 'verilog-mode-actions
586 :type 'boolean)
587 (put 'verilog-auto-read-includes 'safe-local-variable 'verilog-booleanp)
588
589 (defcustom verilog-auto-save-policy nil
590 "*Non-nil indicates action to take when saving a Verilog buffer with AUTOs.
591 A value of `force' will always do a \\[verilog-auto] automatically if
592 needed on every save. A value of `detect' will do \\[verilog-auto]
593 automatically when it thinks necessary. A value of `ask' will query the
594 user when it thinks updating is needed.
595
596 You should not rely on the 'ask or 'detect policies, they are safeguards
597 only. They do not detect when AUTOINSTs need to be updated because a
598 sub-module's port list has changed."
599 :group 'verilog-mode-actions
600 :type '(choice (const nil) (const ask) (const detect) (const force)))
601
602 (defcustom verilog-auto-star-expand t
603 "*Non-nil indicates to expand a SystemVerilog .* instance ports.
604 They will be expanded in the same way as if there was a AUTOINST in the
605 instantiation. See also `verilog-auto-star' and `verilog-auto-star-save'."
606 :group 'verilog-mode-actions
607 :type 'boolean)
608 (put 'verilog-auto-star-expand 'safe-local-variable 'verilog-booleanp)
609
610 (defcustom verilog-auto-star-save nil
611 "*Non-nil indicates to save to disk SystemVerilog .* instance expansions.
612 A nil value indicates direct connections will be removed before saving.
613 Only meaningful to those created due to `verilog-auto-star-expand' being set.
614
615 Instead of setting this, you may want to use /*AUTOINST*/, which will
616 always be saved."
617 :group 'verilog-mode-actions
618 :type 'boolean)
619 (put 'verilog-auto-star-save 'safe-local-variable 'verilog-booleanp)
620
621 (defvar verilog-auto-update-tick nil
622 "Modification tick at which autos were last performed.")
623
624 (defvar verilog-auto-last-file-locals nil
625 "Text from file-local-variables during last evaluation.")
626
627 (defvar verilog-error-regexp-add-didit nil)
628 (defvar verilog-error-regexp nil)
629 (setq verilog-error-regexp-add-didit nil
630 verilog-error-regexp
631 '(
632 ; SureLint
633 ;; ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 2)
634 ; Most SureFire tools
635 ("\\(WARNING\\|ERROR\\|INFO\\)[^:]*: \\([^,]+\\), \\(line \\|\\)\\([0-9]+\\):" 2 4 )
636 ("\
637 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
638 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 2 5)
639 ; xsim
640 ; Error! in file /homes/mac/Axis/Xsim/test.v at line 13 [OBJ_NOT_DECLARED]
641 ("\\(Error\\|Warning\\).*in file (\\([^ \t]+\\) at line *\\([0-9]+\\))" 2 3)
642 ; vcs
643 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 3)
644 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 2)
645 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 3)
646 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 2)
647 ; Verilator
648 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
649 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 4)
650 ; vxl
651 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 3)
652 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 2) ; vxl
653 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 2)
654 ; nc-verilog
655 (".*\\*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 2)
656 ; Leda
657 ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 2)
658 )
659 ; "*List of regexps for Verilog compilers, like verilint. See compilation-error-regexp-alist for the formatting."
660 )
661
662 (defvar verilog-error-font-lock-keywords
663 '(
664 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 1 bold t)
665 ("[^\n]*\\[\\([^:]+\\):\\([0-9]+\\)\\]" 2 bold t)
666
667 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 2 bold t)
668 ("\\(WARNING\\|ERROR\\|INFO\\): \\([^,]+\\), line \\([0-9]+\\):" 3 bold t)
669
670 ("\
671 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
672 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
673 ("\
674 \\([a-zA-Z]?:?[^:( \t\n]+\\)[:(][ \t]*\\([0-9]+\\)\\([) \t]\\|\
675 :\\([^0-9\n]\\|\\([0-9]+:\\)\\)\\)" 1 bold t)
676
677 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 2 bold t)
678 ("\\(Error\\|Warning\\):[^(]*(\\([^ \t]+\\) line *\\([0-9]+\\))" 3 bold t)
679
680 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 3 bold t)
681 ("%?\\(Error\\|Warning\\)\\(-[^:]+\\|\\):[\n ]*\\([^ \t:]+\\):\\([0-9]+\\):" 4 bold t)
682
683 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
684 ("Warning:.*(port.*(\\([^ \t]+\\) line \\([0-9]+\\))" 1 bold t)
685
686 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
687 ("\\(Error\\|Warning\\):[\n.]*\\([^ \t]+\\) *\\([0-9]+\\):" 3 bold t)
688
689 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 1 bold t)
690 ("syntax error:.*\n\\([^ \t]+\\) *\\([0-9]+\\):" 2 bold t)
691 ; vxl
692 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
693 ("\\(Error\\|Warning\\)!.*\n?.*\"\\([^\"]+\\)\", \\([0-9]+\\)" 2 bold t)
694
695 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 1 bold t)
696 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+\\([0-9]+\\):.*$" 2 bold t)
697
698 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 1 bold t)
699 ("([WE][0-9A-Z]+)[ \t]+\\([^ \t\n,]+\\)[, \t]+line[ \t]+\\([0-9]+\\):.*$" 2 bold t)
700 ; nc-verilog
701 (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 1 bold t)
702 (".*[WE],[0-9A-Z]+ (\\([^ \t,]+\\),\\([0-9]+\\)|" 2 bold t)
703 ; Leda
704 ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 1 bold t)
705 ("In file \\([^ \t]+\\)[ \t]+line[ \t]+\\([0-9]+\\):\n[^\n]*\n[^\n]*\n\\[\\(Warning\\|Error\\|Failure\\)\\][^\n]*" 2 bold t)
706 )
707 "*Keywords to also highlight in Verilog *compilation* buffers.")
708
709 (defcustom verilog-library-flags '("")
710 "*List of standard Verilog arguments to use for /*AUTOINST*/.
711 These arguments are used to find files for `verilog-auto', and match
712 the flags accepted by a standard Verilog-XL simulator.
713
714 -f filename Reads more `verilog-library-flags' from the filename.
715 +incdir+dir Adds the directory to `verilog-library-directories'.
716 -Idir Adds the directory to `verilog-library-directories'.
717 -y dir Adds the directory to `verilog-library-directories'.
718 +libext+.v Adds the extensions to `verilog-library-extensions'.
719 -v filename Adds the filename to `verilog-library-files'.
720
721 filename Adds the filename to `verilog-library-files'.
722 This is not recommended, -v is a better choice.
723
724 You might want these defined in each file; put at the *END* of your file
725 something like:
726
727 // Local Variables:
728 // verilog-library-flags:(\"-y dir -y otherdir\")
729 // End:
730
731 Verilog-mode attempts to detect changes to this local variable, but they
732 are only insured to be correct when the file is first visited. Thus if you
733 have problems, use \\[find-alternate-file] RET to have these take effect.
734
735 See also the variables mentioned above."
736 :group 'verilog-mode-auto
737 :type '(repeat string))
738 (put 'verilog-library-flags 'safe-local-variable 'listp)
739
740 (defcustom verilog-library-directories '(".")
741 "*List of directories when looking for files for /*AUTOINST*/.
742 The directory may be relative to the current file, or absolute.
743 Environment variables are also expanded in the directory names.
744 Having at least the current directory is a good idea.
745
746 You might want these defined in each file; put at the *END* of your file
747 something like:
748
749 // Local Variables:
750 // verilog-library-directories:(\".\" \"subdir\" \"subdir2\")
751 // End:
752
753 Verilog-mode attempts to detect changes to this local variable, but they
754 are only insured to be correct when the file is first visited. Thus if you
755 have problems, use \\[find-alternate-file] RET to have these take effect.
756
757 See also `verilog-library-flags', `verilog-library-files'
758 and `verilog-library-extensions'."
759 :group 'verilog-mode-auto
760 :type '(repeat file))
761 (put 'verilog-library-directories 'safe-local-variable 'listp)
762
763 (defcustom verilog-library-files '()
764 "*List of files to search for modules.
765 AUTOINST will use this when it needs to resolve a module name.
766 This is a complete path, usually to a technology file with many standard
767 cells defined in it.
768
769 You might want these defined in each file; put at the *END* of your file
770 something like:
771
772 // Local Variables:
773 // verilog-library-files:(\"/some/path/technology.v\" \"/some/path/tech2.v\")
774 // End:
775
776 Verilog-mode attempts to detect changes to this local variable, but they
777 are only insured to be correct when the file is first visited. Thus if you
778 have problems, use \\[find-alternate-file] RET to have these take effect.
779
780 See also `verilog-library-flags', `verilog-library-directories'."
781 :group 'verilog-mode-auto
782 :type '(repeat directory))
783 (put 'verilog-library-files 'safe-local-variable 'listp)
784
785 (defcustom verilog-library-extensions '(".v")
786 "*List of extensions to use when looking for files for /*AUTOINST*/.
787 See also `verilog-library-flags', `verilog-library-directories'."
788 :type '(repeat string)
789 :group 'verilog-mode-auto)
790 (put 'verilog-library-extensions 'safe-local-variable 'listp)
791
792 (defcustom verilog-active-low-regexp nil
793 "*If set, treat signals matching this regexp as active low.
794 This is used for AUTORESET and AUTOTIEOFF. For proper behavior,
795 you will probably also need `verilog-auto-reset-widths' set."
796 :group 'verilog-mode-auto
797 :type 'string)
798 (put 'verilog-active-low-regexp 'safe-local-variable 'stringp)
799
800 (defcustom verilog-auto-sense-include-inputs nil
801 "*If true, AUTOSENSE should include all inputs.
802 If nil, only inputs that are NOT output signals in the same block are
803 included."
804 :group 'verilog-mode-auto
805 :type 'boolean)
806 (put 'verilog-auto-sense-include-inputs 'safe-local-variable 'verilog-booleanp)
807
808 (defcustom verilog-auto-sense-defines-constant nil
809 "*If true, AUTOSENSE should assume all defines represent constants.
810 When true, the defines will not be included in sensitivity lists. To
811 maintain compatibility with other sites, this should be set at the bottom
812 of each Verilog file that requires it, rather than being set globally."
813 :group 'verilog-mode-auto
814 :type 'boolean)
815 (put 'verilog-auto-sense-defines-constant 'safe-local-variable 'verilog-booleanp)
816
817 (defcustom verilog-auto-reset-widths t
818 "*If true, AUTORESET should determine the width of signals.
819 This is then used to set the width of the zero (32'h0 for example). This
820 is required by some lint tools that aren't smart enough to ignore widths of
821 the constant zero. This may result in ugly code when parameters determine
822 the MSB or LSB of a signal inside an AUTORESET."
823 :type 'boolean
824 :group 'verilog-mode-auto)
825 (put 'verilog-auto-reset-widths 'safe-local-variable 'verilog-booleanp)
826
827 (defcustom verilog-assignment-delay ""
828 "*Text used for delays in delayed assignments. Add a trailing space if set."
829 :group 'verilog-mode-auto
830 :type 'string)
831 (put 'verilog-assignment-delay 'safe-local-variable 'stringp)
832
833 (defcustom verilog-auto-inst-param-value nil
834 "*If set, AUTOINST will replace parameters with the parameter value.
835 If nil, leave parameters as symbolic names.
836
837 Parameters must be in Verilog 2001 format #(...), and if a parameter is not
838 listed as such there (as when the default value is acceptable), it will not
839 be replaced, and will remain symbolic.
840
841 For example, imagine a submodule uses parameters to declare the size of its
842 inputs. This is then used by a upper module:
843
844 module InstModule (o,i)
845 parameter WIDTH;
846 input [WIDTH-1:0] i;
847 endmodule
848
849 module ExampInst;
850 InstModule
851 #(PARAM(10))
852 instName
853 (/*AUTOINST*/
854 .i (i[PARAM-1:0]));
855
856 Note even though PARAM=10, the AUTOINST has left the parameter as a
857 symbolic name. If `verilog-auto-inst-param-value' is set, this will
858 instead expand to:
859
860 module ExampInst;
861 InstModule
862 #(PARAM(10))
863 instName
864 (/*AUTOINST*/
865 .i (i[9:0]));"
866 :group 'verilog-mode-auto
867 :type 'boolean)
868 (put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-auto-inst-param-value)
869
870 (defcustom verilog-auto-inst-vector t
871 "*If true, when creating default ports with AUTOINST, use bus subscripts.
872 If nil, skip the subscript when it matches the entire bus as declared in
873 the module (AUTOWIRE signals always are subscripted, you must manually
874 declare the wire to have the subscripts removed.) Setting this to nil may
875 speed up some simulators, but is less general and harder to read, so avoid."
876 :group 'verilog-mode-auto
877 :type 'boolean)
878 (put 'verilog-auto-inst-vector 'safe-local-variable 'verilog-booleanp)
879
880 (defcustom verilog-auto-inst-template-numbers nil
881 "*If true, when creating templated ports with AUTOINST, add a comment.
882 The comment will add the line number of the template that was used for that
883 port declaration. Setting this aids in debugging, but nil is suggested for
884 regular use to prevent large numbers of merge conflicts."
885 :group 'verilog-mode-auto
886 :type 'boolean)
887 (put 'verilog-auto-inst-template-numbers 'safe-local-variable 'verilog-booleanp)
888
889 (defcustom verilog-auto-inst-column 40
890 "*Indent-to column number for net name part of AUTOINST created pin."
891 :group 'verilog-mode-indent
892 :type 'integer)
893 (put 'verilog-auto-inst-column 'safe-local-variable 'integerp)
894
895 (defcustom verilog-auto-input-ignore-regexp nil
896 "*If set, when creating AUTOINPUT list, ignore signals matching this regexp.
897 See the \\[verilog-faq] for examples on using this."
898 :group 'verilog-mode-auto
899 :type 'string)
900 (put 'verilog-auto-input-ignore-regexp 'safe-local-variable 'stringp)
901
902 (defcustom verilog-auto-inout-ignore-regexp nil
903 "*If set, when creating AUTOINOUT list, ignore signals matching this regexp.
904 See the \\[verilog-faq] for examples on using this."
905 :group 'verilog-mode-auto
906 :type 'string)
907 (put 'verilog-auto-inout-ignore-regexp 'safe-local-variable 'stringp)
908
909 (defcustom verilog-auto-output-ignore-regexp nil
910 "*If set, when creating AUTOOUTPUT list, ignore signals matching this regexp.
911 See the \\[verilog-faq] for examples on using this."
912 :group 'verilog-mode-auto
913 :type 'string)
914 (put 'verilog-auto-output-ignore-regexp 'safe-local-variable 'stringp)
915
916 (defcustom verilog-auto-unused-ignore-regexp nil
917 "*If set, when creating AUTOUNUSED list, ignore signals matching this regexp.
918 See the \\[verilog-faq] for examples on using this."
919 :group 'verilog-mode-auto
920 :type 'string)
921 (put 'verilog-auto-unused-ignore-regexp 'safe-local-variable 'stringp)
922
923 (defcustom verilog-typedef-regexp nil
924 "*If non-nil, regular expression that matches Verilog-2001 typedef names.
925 For example, \"_t$\" matches typedefs named with _t, as in the C language."
926 :group 'verilog-mode-auto
927 :type 'string)
928 (put 'verilog-typedef-regexp 'safe-local-variable 'stringp)
929
930 (defcustom verilog-mode-hook 'verilog-set-compile-command
931 "*Hook run after Verilog mode is loaded."
932 :type 'hook
933 :group 'verilog-mode)
934
935 (defcustom verilog-auto-hook nil
936 "*Hook run after `verilog-mode' updates AUTOs."
937 :group 'verilog-mode-auto
938 :type 'hook)
939
940 (defcustom verilog-before-auto-hook nil
941 "*Hook run before `verilog-mode' updates AUTOs."
942 :group 'verilog-mode-auto
943 :type 'hook)
944
945 (defcustom verilog-delete-auto-hook nil
946 "*Hook run after `verilog-mode' deletes AUTOs."
947 :group 'verilog-mode-auto
948 :type 'hook)
949
950 (defcustom verilog-before-delete-auto-hook nil
951 "*Hook run before `verilog-mode' deletes AUTOs."
952 :group 'verilog-mode-auto
953 :type 'hook)
954
955 (defcustom verilog-getopt-flags-hook nil
956 "*Hook run after `verilog-getopt-flags' determines the Verilog option lists."
957 :group 'verilog-mode-auto
958 :type 'hook)
959
960 (defcustom verilog-before-getopt-flags-hook nil
961 "*Hook run before `verilog-getopt-flags' determines the Verilog option lists."
962 :group 'verilog-mode-auto
963 :type 'hook)
964
965 (defvar verilog-imenu-generic-expression
966 '((nil "^\\s-*\\(\\(m\\(odule\\|acromodule\\)\\)\\|primitive\\)\\s-+\\([a-zA-Z0-9_.:]+\\)" 4)
967 ("*Vars*" "^\\s-*\\(reg\\|wire\\)\\s-+\\(\\|\\[[^]]+\\]\\s-+\\)\\([A-Za-z0-9_]+\\)" 3))
968 "Imenu expression for Verilog mode. See `imenu-generic-expression'.")
969
970 ;;
971 ;; provide a verilog-header function.
972 ;; Customization variables:
973 ;;
974 (defvar verilog-date-scientific-format nil
975 "*If non-nil, dates are written in scientific format (e.g. 1997/09/17).
976 If nil, in European format (e.g. 17.09.1997). The brain-dead American
977 format (e.g. 09/17/1997) is not supported.")
978
979 (defvar verilog-company nil
980 "*Default name of Company for Verilog header.
981 If set will become buffer local.")
982 (make-variable-buffer-local 'verilog-company)
983
984 (defvar verilog-project nil
985 "*Default name of Project for Verilog header.
986 If set will become buffer local.")
987 (make-variable-buffer-local 'verilog-project)
988
989 (defvar verilog-mode-map
990 (let ((map (make-sparse-keymap)))
991 (define-key map ";" 'electric-verilog-semi)
992 (define-key map [(control 59)] 'electric-verilog-semi-with-comment)
993 (define-key map ":" 'electric-verilog-colon)
994 ;;(define-key map "=" 'electric-verilog-equal)
995 (define-key map "\`" 'electric-verilog-tick)
996 (define-key map "\t" 'electric-verilog-tab)
997 (define-key map "\r" 'electric-verilog-terminate-line)
998 ;; backspace/delete key bindings
999 (define-key map [backspace] 'backward-delete-char-untabify)
1000 (unless (boundp 'delete-key-deletes-forward) ; XEmacs variable
1001 (define-key map [delete] 'delete-char)
1002 (define-key map [(meta delete)] 'kill-word))
1003 (define-key map "\M-\C-b" 'electric-verilog-backward-sexp)
1004 (define-key map "\M-\C-f" 'electric-verilog-forward-sexp)
1005 (define-key map "\M-\r" `electric-verilog-terminate-and-indent)
1006 (define-key map "\M-\t" 'verilog-complete-word)
1007 (define-key map "\M-?" 'verilog-show-completions)
1008 (define-key map "\C-c\`" 'verilog-lint-off)
1009 (define-key map "\C-c\*" 'verilog-delete-auto-star-implicit)
1010 (define-key map "\C-c\C-r" 'verilog-label-be)
1011 (define-key map "\C-c\C-i" 'verilog-pretty-declarations)
1012 (define-key map "\C-c=" 'verilog-pretty-expr)
1013 (define-key map "\C-c\C-b" 'verilog-submit-bug-report)
1014 (define-key map "\M-*" 'verilog-star-comment)
1015 (define-key map "\C-c\C-c" 'verilog-comment-region)
1016 (define-key map "\C-c\C-u" 'verilog-uncomment-region)
1017 (when (featurep 'xemacs)
1018 (define-key map [(meta control h)] 'verilog-mark-defun)
1019 (define-key map "\M-\C-a" 'verilog-beg-of-defun)
1020 (define-key map "\M-\C-e" 'verilog-end-of-defun))
1021 (define-key map "\C-c\C-d" 'verilog-goto-defun)
1022 (define-key map "\C-c\C-k" 'verilog-delete-auto)
1023 (define-key map "\C-c\C-a" 'verilog-auto)
1024 (define-key map "\C-c\C-s" 'verilog-auto-save-compile)
1025 (define-key map "\C-c\C-z" 'verilog-inject-auto)
1026 (define-key map "\C-c\C-e" 'verilog-expand-vector)
1027 (define-key map "\C-c\C-h" 'verilog-header)
1028 map)
1029 "Keymap used in Verilog mode.")
1030
1031 ;; menus
1032 (easy-menu-define
1033 verilog-menu verilog-mode-map "Menu for Verilog mode"
1034 (verilog-easy-menu-filter
1035 '("Verilog"
1036 ("Choose Compilation Action"
1037 ["None"
1038 (progn
1039 (setq verilog-tool nil)
1040 (verilog-set-compile-command))
1041 :style radio
1042 :selected (equal verilog-tool nil)
1043 :help "When invoking compilation, use compile-command"]
1044 ["Lint"
1045 (progn
1046 (setq verilog-tool 'verilog-linter)
1047 (verilog-set-compile-command))
1048 :style radio
1049 :selected (equal verilog-tool `verilog-linter)
1050 :help "When invoking compilation, use lint checker"]
1051 ["Coverage"
1052 (progn
1053 (setq verilog-tool 'verilog-coverage)
1054 (verilog-set-compile-command))
1055 :style radio
1056 :selected (equal verilog-tool `verilog-coverage)
1057 :help "When invoking compilation, annotate for coverage"]
1058 ["Simulator"
1059 (progn
1060 (setq verilog-tool 'verilog-simulator)
1061 (verilog-set-compile-command))
1062 :style radio
1063 :selected (equal verilog-tool `verilog-simulator)
1064 :help "When invoking compilation, interpret Verilog source"]
1065 ["Compiler"
1066 (progn
1067 (setq verilog-tool 'verilog-compiler)
1068 (verilog-set-compile-command))
1069 :style radio
1070 :selected (equal verilog-tool `verilog-compiler)
1071 :help "When invoking compilation, compile Verilog source"]
1072 )
1073 ("Move"
1074 ["Beginning of function" verilog-beg-of-defun
1075 :keys "C-M-a"
1076 :help "Move backward to the beginning of the current function or procedure"]
1077 ["End of function" verilog-end-of-defun
1078 :keys "C-M-e"
1079 :help "Move forward to the end of the current function or procedure"]
1080 ["Mark function" verilog-mark-defun
1081 :keys "C-M-h"
1082 :help "Mark the current Verilog function or procedure"]
1083 ["Goto function/module" verilog-goto-defun
1084 :help "Move to specified Verilog module/task/function"]
1085 ["Move to beginning of block" electric-verilog-backward-sexp
1086 :help "Move backward over one balanced expression"]
1087 ["Move to end of block" electric-verilog-forward-sexp
1088 :help "Move forward over one balanced expression"]
1089 )
1090 ("Comments"
1091 ["Comment Region" verilog-comment-region
1092 :help "Put marked area into a comment"]
1093 ["UnComment Region" verilog-uncomment-region
1094 :help "Uncomment an area commented with Comment Region"]
1095 ["Multi-line comment insert" verilog-star-comment
1096 :help "Insert Verilog /* */ comment at point"]
1097 ["Lint error to comment" verilog-lint-off
1098 :help "Convert a Verilog linter warning line into a disable statement"]
1099 )
1100 "----"
1101 ["Compile" compile
1102 :help "Perform compilation-action (above) on the current buffer"]
1103 ["AUTO, Save, Compile" verilog-auto-save-compile
1104 :help "Recompute AUTOs, save buffer, and compile"]
1105 ["Next Compile Error" next-error
1106 :help "Visit next compilation error message and corresponding source code"]
1107 ["Ignore Lint Warning at point" verilog-lint-off
1108 :help "Convert a Verilog linter warning line into a disable statement"]
1109 "----"
1110 ["Line up declarations around point" verilog-pretty-declarations
1111 :help "Line up declarations around point"]
1112 ["Line up equations around point" verilog-pretty-expr
1113 :help "Line up expressions around point"]
1114 ["Redo/insert comments on every end" verilog-label-be
1115 :help "Label matching begin ... end statements"]
1116 ["Expand [x:y] vector line" verilog-expand-vector
1117 :help "Take a signal vector on the current line and expand it to multiple lines"]
1118 ["Insert begin-end block" verilog-insert-block
1119 :help "Insert begin ... end"]
1120 ["Complete word" verilog-complete-word
1121 :help "Complete word at point"]
1122 "----"
1123 ["Recompute AUTOs" verilog-auto
1124 :help "Expand AUTO meta-comment statements"]
1125 ["Kill AUTOs" verilog-delete-auto
1126 :help "Remove AUTO expansions"]
1127 ["Inject AUTOs" verilog-inject-auto
1128 :help "Inject AUTOs into legacy non-AUTO buffer"]
1129 ("AUTO Help..."
1130 ["AUTO General" (describe-function 'verilog-auto)
1131 :help "Help introduction on AUTOs"]
1132 ["AUTO Library Flags" (describe-variable 'verilog-library-flags)
1133 :help "Help on verilog-library-flags"]
1134 ["AUTO Library Path" (describe-variable 'verilog-library-directories)
1135 :help "Help on verilog-library-directories"]
1136 ["AUTO Library Files" (describe-variable 'verilog-library-files)
1137 :help "Help on verilog-library-files"]
1138 ["AUTO Library Extensions" (describe-variable 'verilog-library-extensions)
1139 :help "Help on verilog-library-extensions"]
1140 ["AUTO `define Reading" (describe-function 'verilog-read-defines)
1141 :help "Help on reading `defines"]
1142 ["AUTO `include Reading" (describe-function 'verilog-read-includes)
1143 :help "Help on parsing `includes"]
1144 ["AUTOARG" (describe-function 'verilog-auto-arg)
1145 :help "Help on AUTOARG - declaring module port list"]
1146 ["AUTOASCIIENUM" (describe-function 'verilog-auto-ascii-enum)
1147 :help "Help on AUTOASCIIENUM - creating ASCII for enumerations"]
1148 ["AUTOINOUTMODULE" (describe-function 'verilog-auto-inout-module)
1149 :help "Help on AUTOINOUTMODULE - copying i/o from another file"]
1150 ["AUTOINOUT" (describe-function 'verilog-auto-inout)
1151 :help "Help on AUTOINOUT - adding inouts from cells"]
1152 ["AUTOINPUT" (describe-function 'verilog-auto-input)
1153 :help "Help on AUTOINPUT - adding inputs from cells"]
1154 ["AUTOINST" (describe-function 'verilog-auto-inst)
1155 :help "Help on AUTOINST - adding pins for cells"]
1156 ["AUTOINST (.*)" (describe-function 'verilog-auto-star)
1157 :help "Help on expanding Verilog-2001 .* pins"]
1158 ["AUTOINSTPARAM" (describe-function 'verilog-auto-inst-param)
1159 :help "Help on AUTOINSTPARAM - adding parameter pins to cells"]
1160 ["AUTOOUTPUT" (describe-function 'verilog-auto-output)
1161 :help "Help on AUTOOUTPUT - adding outputs from cells"]
1162 ["AUTOOUTPUTEVERY" (describe-function 'verilog-auto-output-every)
1163 :help "Help on AUTOOUTPUTEVERY - adding outputs of all signals"]
1164 ["AUTOREG" (describe-function 'verilog-auto-reg)
1165 :help "Help on AUTOREG - declaring registers for non-wires"]
1166 ["AUTOREGINPUT" (describe-function 'verilog-auto-reg-input)
1167 :help "Help on AUTOREGINPUT - declaring inputs for non-wires"]
1168 ["AUTORESET" (describe-function 'verilog-auto-reset)
1169 :help "Help on AUTORESET - resetting always blocks"]
1170 ["AUTOSENSE" (describe-function 'verilog-auto-sense)
1171 :help "Help on AUTOSENSE - sensitivity lists for always blocks"]
1172 ["AUTOTIEOFF" (describe-function 'verilog-auto-tieoff)
1173 :help "Help on AUTOTIEOFF - tieing off unused outputs"]
1174 ["AUTOUNUSED" (describe-function 'verilog-auto-unused)
1175 :help "Help on AUTOUNUSED - terminating unused inputs"]
1176 ["AUTOWIRE" (describe-function 'verilog-auto-wire)
1177 :help "Help on AUTOWIRE - declaring wires for cells"]
1178 )
1179 "----"
1180 ["Submit bug report" verilog-submit-bug-report
1181 :help "Submit via mail a bug report on verilog-mode.el"]
1182 ["Version and FAQ" verilog-faq
1183 :help "Show the current version, and where to get the FAQ etc"]
1184 ["Customize Verilog Mode..." verilog-customize
1185 :help "Customize variables and other settings used by Verilog-Mode"]
1186 ["Customize Verilog Fonts & Colors" verilog-font-customize
1187 :help "Customize fonts used by Verilog-Mode."])))
1188
1189 (easy-menu-define
1190 verilog-stmt-menu verilog-mode-map "Menu for statement templates in Verilog."
1191 (verilog-easy-menu-filter
1192 '("Statements"
1193 ["Header" verilog-sk-header
1194 :help "Insert a header block at the top of file"]
1195 ["Comment" verilog-sk-comment
1196 :help "Insert a comment block"]
1197 "----"
1198 ["Module" verilog-sk-module
1199 :help "Insert a module .. (/*AUTOARG*/);.. endmodule block"]
1200 ["Primitive" verilog-sk-primitive
1201 :help "Insert a primitive .. (.. );.. endprimitive block"]
1202 "----"
1203 ["Input" verilog-sk-input
1204 :help "Insert an input declaration"]
1205 ["Output" verilog-sk-output
1206 :help "Insert an output declaration"]
1207 ["Inout" verilog-sk-inout
1208 :help "Insert an inout declaration"]
1209 ["Wire" verilog-sk-wire
1210 :help "Insert a wire declaration"]
1211 ["Reg" verilog-sk-reg
1212 :help "Insert a register declaration"]
1213 ["Define thing under point as a register" verilog-sk-define-signal
1214 :help "Define signal under point as a register at the top of the module"]
1215 "----"
1216 ["Initial" verilog-sk-initial
1217 :help "Insert an initial begin .. end block"]
1218 ["Always" verilog-sk-always
1219 :help "Insert an always @(AS) begin .. end block"]
1220 ["Function" verilog-sk-function
1221 :help "Insert a function .. begin .. end endfunction block"]
1222 ["Task" verilog-sk-task
1223 :help "Insert a task .. begin .. end endtask block"]
1224 ["Specify" verilog-sk-specify
1225 :help "Insert a specify .. endspecify block"]
1226 ["Generate" verilog-sk-generate
1227 :help "Insert a generate .. endgenerate block"]
1228 "----"
1229 ["Begin" verilog-sk-begin
1230 :help "Insert a begin .. end block"]
1231 ["If" verilog-sk-if
1232 :help "Insert an if (..) begin .. end block"]
1233 ["(if) else" verilog-sk-else-if
1234 :help "Insert an else if (..) begin .. end block"]
1235 ["For" verilog-sk-for
1236 :help "Insert a for (...) begin .. end block"]
1237 ["While" verilog-sk-while
1238 :help "Insert a while (...) begin .. end block"]
1239 ["Fork" verilog-sk-fork
1240 :help "Insert a fork begin .. end .. join block"]
1241 ["Repeat" verilog-sk-repeat
1242 :help "Insert a repeat (..) begin .. end block"]
1243 ["Case" verilog-sk-case
1244 :help "Insert a case block, prompting for details"]
1245 ["Casex" verilog-sk-casex
1246 :help "Insert a casex (...) item: begin.. end endcase block"]
1247 ["Casez" verilog-sk-casez
1248 :help "Insert a casez (...) item: begin.. end endcase block"])))
1249
1250 (defvar verilog-mode-abbrev-table nil
1251 "Abbrev table in use in Verilog-mode buffers.")
1252
1253 (define-abbrev-table 'verilog-mode-abbrev-table ())
1254
1255 ;;
1256 ;; Macros
1257 ;;
1258
1259 (defsubst verilog-string-replace-matches (from-string to-string fixedcase literal string)
1260 "Replace occurrences of FROM-STRING with TO-STRING.
1261 FIXEDCASE and LITERAL as in `replace-match`. STRING is what to replace.
1262 The case (verilog-string-replace-matches \"o\" \"oo\" nil nil \"foobar\")
1263 will break, as the o's continuously replace. xa -> x works ok though."
1264 ;; Hopefully soon to a emacs built-in
1265 (let ((start 0))
1266 (while (string-match from-string string start)
1267 (setq string (replace-match to-string fixedcase literal string)
1268 start (min (length string) (+ (match-beginning 0) (length to-string)))))
1269 string))
1270
1271 (defsubst verilog-string-remove-spaces (string)
1272 "Remove spaces surrounding STRING."
1273 (save-match-data
1274 (setq string (verilog-string-replace-matches "^\\s-+" "" nil nil string))
1275 (setq string (verilog-string-replace-matches "\\s-+$" "" nil nil string))
1276 string))
1277
1278 (defsubst verilog-re-search-forward (REGEXP BOUND NOERROR)
1279 ; checkdoc-params: (REGEXP BOUND NOERROR)
1280 "Like `re-search-forward', but skips over match in comments or strings."
1281 (store-match-data '(nil nil)) ;; So match-end will return nil if no matches found
1282 (while (and
1283 (re-search-forward REGEXP BOUND NOERROR)
1284 (and (verilog-skip-forward-comment-or-string)
1285 (progn
1286 (store-match-data '(nil nil))
1287 (if BOUND
1288 (< (point) BOUND)
1289 t)))))
1290 (match-end 0))
1291
1292 (defsubst verilog-re-search-backward (REGEXP BOUND NOERROR)
1293 ; checkdoc-params: (REGEXP BOUND NOERROR)
1294 "Like `re-search-backward', but skips over match in comments or strings."
1295 (store-match-data '(nil nil)) ;; So match-end will return nil if no matches found
1296 (while (and
1297 (re-search-backward REGEXP BOUND NOERROR)
1298 (and (verilog-skip-backward-comment-or-string)
1299 (progn
1300 (store-match-data '(nil nil))
1301 (if BOUND
1302 (> (point) BOUND)
1303 t)))))
1304 (match-end 0))
1305
1306 (defsubst verilog-re-search-forward-quick (regexp bound noerror)
1307 "Like `verilog-re-search-forward', including use of REGEXP BOUND and NOERROR,
1308 but trashes match data and is faster for REGEXP that doesn't match often.
1309 This may at some point use text properties to ignore comments,
1310 so there may be a large up front penalty for the first search."
1311 (let (pt)
1312 (while (and (not pt)
1313 (re-search-forward regexp bound noerror))
1314 (if (not (verilog-inside-comment-p))
1315 (setq pt (match-end 0))))
1316 pt))
1317
1318 (defsubst verilog-re-search-backward-quick (regexp bound noerror)
1319 ; checkdoc-params: (REGEXP BOUND NOERROR)
1320 "Like `verilog-re-search-backward', including use of REGEXP BOUND and NOERROR,
1321 but trashes match data and is faster for REGEXP that doesn't match often.
1322 This may at some point use text properties to ignore comments,
1323 so there may be a large up front penalty for the first search."
1324 (let (pt)
1325 (while (and (not pt)
1326 (re-search-backward regexp bound noerror))
1327 (if (not (verilog-inside-comment-p))
1328 (setq pt (match-end 0))))
1329 pt))
1330
1331 (defsubst verilog-get-beg-of-line (&optional arg)
1332 (save-excursion
1333 (beginning-of-line arg)
1334 (point)))
1335
1336 (defsubst verilog-get-end-of-line (&optional arg)
1337 (save-excursion
1338 (end-of-line arg)
1339 (point)))
1340
1341 (defsubst verilog-within-string ()
1342 (save-excursion
1343 (nth 3 (parse-partial-sexp (verilog-get-beg-of-line) (point)))))
1344
1345 (defvar compile-command)
1346
1347 ;; compilation program
1348 (defun verilog-set-compile-command ()
1349 "Function to compute shell command to compile Verilog.
1350
1351 This reads `verilog-tool' and sets `compile-command'. This specifies the
1352 program that executes when you type \\[compile] or
1353 \\[verilog-auto-save-compile].
1354
1355 By default `verilog-tool' uses a Makefile if one exists in the current
1356 directory. If not, it is set to the `verilog-linter', `verilog-coverage',
1357 `verilog-simulator', or `verilog-compiler' variables, as selected with the
1358 Verilog -> \"Choose Compilation Action\" menu.
1359
1360 You should set `verilog-tool' or the other variables to the path and
1361 arguments for your Verilog simulator. For example:
1362 \"vcs -p123 -O\"
1363 or a string like:
1364 \"(cd /tmp; surecov %s)\".
1365
1366 In the former case, the path to the current buffer is concat'ed to the
1367 value of `verilog-tool'; in the later, the path to the current buffer is
1368 substituted for the %s.
1369
1370 Where __FILE__ appears in the string, the `buffer-file-name' of the
1371 current buffer, without the directory portion, will be substituted."
1372 (interactive)
1373 (cond
1374 ((or (file-exists-p "makefile") ;If there is a makefile, use it
1375 (file-exists-p "Makefile"))
1376 (make-local-variable 'compile-command)
1377 (setq compile-command "make "))
1378 (t
1379 (make-local-variable 'compile-command)
1380 (setq compile-command
1381 (if verilog-tool
1382 (if (string-match "%s" (eval verilog-tool))
1383 (format (eval verilog-tool) (or buffer-file-name ""))
1384 (concat (eval verilog-tool) " " (or buffer-file-name "")))
1385 ""))))
1386 (verilog-modify-compile-command))
1387
1388 (defun verilog-modify-compile-command ()
1389 "Replace meta-information in `compile-command'.
1390 Where __FILE__ appears in the string, the current buffer's file-name,
1391 without the directory portion, will be substituted."
1392 (when (and
1393 (stringp compile-command)
1394 (string-match "\\b__FILE__\\b" compile-command))
1395 (make-local-variable 'compile-command)
1396 (setq compile-command
1397 (verilog-string-replace-matches
1398 "\\b__FILE__\\b" (file-name-nondirectory (buffer-file-name))
1399 t t compile-command))))
1400
1401 ;; Following code only gets called from compilation-mode-hook.
1402 (defvar compilation-error-regexp-alist)
1403
1404 (defun verilog-error-regexp-add ()
1405 "Add the messages to the `compilation-error-regexp-alist'.
1406 Called by `compilation-mode-hook'. This allows \\[next-error] to
1407 find the errors."
1408 (if (not verilog-error-regexp-add-didit)
1409 (progn
1410 (setq verilog-error-regexp-add-didit t)
1411 (setq-default compilation-error-regexp-alist
1412 (append verilog-error-regexp
1413 (default-value 'compilation-error-regexp-alist)))
1414 ;; Could be buffer local at this point; maybe also in let; change all three
1415 (setq compilation-error-regexp-alist
1416 (default-value 'compilation-error-regexp-alist))
1417 (set (make-local-variable 'compilation-error-regexp-alist)
1418 (default-value 'compilation-error-regexp-alist)))))
1419
1420 (add-hook 'compilation-mode-hook 'verilog-error-regexp-add)
1421
1422 (defconst verilog-directive-re
1423 ;; "`case" "`default" "`define" "`define" "`else" "`endfor" "`endif"
1424 ;; "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1425 ;; "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1426 ;; "`time_scale" "`undef" "`while"
1427 "\\<`\\(case\\|def\\(ault\\|ine\\(\\)?\\)\\|e\\(lse\\|nd\\(for\\|if\\|protect\\|switch\\|while\\)\\)\\|for\\(mat\\)?\\|i\\(f\\(def\\|ndef\\)?\\|nclude\\)\\|let\\|protect\\|switch\\|time\\(_scale\\|scale\\)\\|undef\\|while\\)\\>")
1428
1429 (defconst verilog-directive-begin
1430 "\\<`\\(for\\|i\\(f\\|fdef\\|fndef\\)\\|switch\\|while\\)\\>")
1431
1432 (defconst verilog-directive-middle
1433 "\\<`\\(else\\|default\\|case\\)\\>")
1434
1435 (defconst verilog-directive-end
1436 "`\\(endfor\\|endif\\|endswitch\\|endwhile\\)\\>")
1437
1438 (defconst verilog-directive-re-1
1439 (concat "[ \t]*" verilog-directive-re))
1440
1441 ;;
1442 ;; Regular expressions used to calculate indent, etc.
1443 ;;
1444 (defconst verilog-symbol-re "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
1445 (defconst verilog-case-re "\\(\\<case[xz]?\\>\\|\\<randcase\\>\\)")
1446 ;; Want to match
1447 ;; aa :
1448 ;; aa,bb :
1449 ;; a[34:32] :
1450 ;; a,
1451 ;; b :
1452
1453 (defconst verilog-no-indent-begin-re
1454 "\\<\\(if\\|else\\|while\\|for\\|repeat\\|always\\|always_comb\\|always_ff\\|always_latch\\)\\>")
1455
1456 (defconst verilog-ends-re
1457 ;; Parenthesis indicate type of keyword found
1458 (concat
1459 "\\(\\<else\\>\\)\\|" ; 1
1460 "\\(\\<if\\>\\)\\|" ; 2
1461 "\\(\\<end\\>\\)\\|" ; 3
1462 "\\(\\<endcase\\>\\)\\|" ; 4
1463 "\\(\\<endfunction\\>\\)\\|" ; 5
1464 "\\(\\<endtask\\>\\)\\|" ; 6
1465 "\\(\\<endspecify\\>\\)\\|" ; 7
1466 "\\(\\<endtable\\>\\)\\|" ; 8
1467 "\\(\\<endgenerate\\>\\)\\|" ; 9
1468 "\\(\\<join\\(_any\\|_none\\)?\\>\\)\\|" ; 10
1469 "\\(\\<endclass\\>\\)\\|" ; 11
1470 "\\(\\<endgroup\\>\\)" ; 12
1471 ))
1472
1473 (defconst verilog-auto-end-comment-lines-re
1474 ;; Matches to names in this list cause auto-end-commentation
1475 (concat "\\("
1476 verilog-directive-re "\\)\\|\\("
1477 (eval-when-compile
1478 (verilog-regexp-words
1479 `( "begin"
1480 "else"
1481 "end"
1482 "endcase"
1483 "endclass"
1484 "endclocking"
1485 "endgroup"
1486 "endfunction"
1487 "endmodule"
1488 "endprogram"
1489 "endprimitive"
1490 "endinterface"
1491 "endpackage"
1492 "endsequence"
1493 "endspecify"
1494 "endtable"
1495 "endtask"
1496 "join"
1497 "join_any"
1498 "join_none"
1499 "module"
1500 "macromodule"
1501 "primitive"
1502 "interface"
1503 "package")))
1504 "\\)"))
1505
1506 ;;; NOTE: verilog-leap-to-head expects that verilog-end-block-re and
1507 ;;; verilog-end-block-ordered-re matches exactly the same strings.
1508 (defconst verilog-end-block-ordered-re
1509 ;; Parenthesis indicate type of keyword found
1510 (concat "\\(\\<endcase\\>\\)\\|" ; 1
1511 "\\(\\<end\\>\\)\\|" ; 2
1512 "\\(\\<end" ; 3, but not used
1513 "\\(" ; 4, but not used
1514 "\\(function\\)\\|" ; 5
1515 "\\(task\\)\\|" ; 6
1516 "\\(module\\)\\|" ; 7
1517 "\\(primitive\\)\\|" ; 8
1518 "\\(interface\\)\\|" ; 9
1519 "\\(package\\)\\|" ; 10
1520 "\\(class\\)\\|" ; 11
1521 "\\(group\\)\\|" ; 12
1522 "\\(program\\)\\|" ; 13
1523 "\\(sequence\\)\\|" ; 14
1524 "\\(clocking\\)\\|" ; 15
1525 "\\)\\>\\)"))
1526 (defconst verilog-end-block-re
1527 (eval-when-compile
1528 (verilog-regexp-words
1529
1530 `("end" ;; closes begin
1531 "endcase" ;; closes any of case, casex casez or randcase
1532 "join" "join_any" "join_none" ;; closes fork
1533 "endclass"
1534 "endtable"
1535 "endspecify"
1536 "endfunction"
1537 "endgenerate"
1538 "endtask"
1539 "endgroup"
1540 "endproperty"
1541 "endinterface"
1542 "endpackage"
1543 "endprogram"
1544 "endsequence"
1545 "endclocking"
1546 ))))
1547
1548
1549 (defconst verilog-endcomment-reason-re
1550 ;; Parenthesis indicate type of keyword found
1551 (concat
1552 "\\(\\<fork\\>\\)\\|"
1553 "\\(\\<begin\\>\\)\\|"
1554 "\\(\\<if\\>\\)\\|"
1555 "\\(\\<clocking\\>\\)\\|"
1556 "\\(\\<else\\>\\)\\|"
1557 "\\(\\<end\\>.*\\<else\\>\\)\\|"
1558 "\\(\\<task\\>\\)\\|"
1559 "\\(\\<function\\>\\)\\|"
1560 "\\(\\<initial\\>\\)\\|"
1561 "\\(\\<interface\\>\\)\\|"
1562 "\\(\\<package\\>\\)\\|"
1563 "\\(\\<final\\>\\)\\|"
1564 "\\(\\<always\\>\\(\[ \t\]*@\\)?\\)\\|"
1565 "\\(\\<always_comb\\>\\(\[ \t\]*@\\)?\\)\\|"
1566 "\\(\\<always_ff\\>\\(\[ \t\]*@\\)?\\)\\|"
1567 "\\(\\<always_latch\\>\\(\[ \t\]*@\\)?\\)\\|"
1568 "\\(@\\)\\|"
1569 "\\(\\<while\\>\\)\\|"
1570 "\\(\\<for\\(ever\\|each\\)?\\>\\)\\|"
1571 "\\(\\<repeat\\>\\)\\|\\(\\<wait\\>\\)\\|"
1572 "#"))
1573
1574 (defconst verilog-named-block-re "begin[ \t]*:")
1575
1576 ;; These words begin a block which can occur inside a module which should be indented,
1577 ;; and closed with the respective word from the end-block list
1578
1579 (defconst verilog-beg-block-re
1580 (eval-when-compile
1581 (verilog-regexp-words
1582 `("begin"
1583 "case" "casex" "casez" "randcase"
1584 "clocking"
1585 "generate"
1586 "fork"
1587 "function"
1588 "property"
1589 "specify"
1590 "table"
1591 "task"
1592 ))))
1593 ;; These are the same words, in a specific order in the regular
1594 ;; expression so that matching will work nicely for
1595 ;; verilog-forward-sexp and verilog-calc-indent
1596
1597 (defconst verilog-beg-block-re-ordered
1598 ( concat "\\(\\<begin\\>\\)" ;1
1599 "\\|\\(\\<randcase\\>\\|\\(\\<unique\\s-+\\|priority\\s-+\\)?case[xz]?\\>\\)" ; 2,3
1600 "\\|\\(\\(\\<disable\\>\\s-+\\)?fork\\>\\)" ;4,5
1601 "\\|\\(\\<class\\>\\)" ;6
1602 "\\|\\(\\<table\\>\\)" ;7
1603 "\\|\\(\\<specify\\>\\)" ;8
1604 "\\|\\(\\<function\\>\\)" ;9
1605 "\\|\\(\\<task\\>\\)" ;10
1606 "\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)*\\<task\\>\\)" ;11
1607 "\\|\\(\\<generate\\>\\)" ;15
1608 "\\|\\(\\<covergroup\\>\\)" ;16
1609 "\\|\\(\\<property\\>\\)" ;17
1610 "\\|\\(\\<\\(rand\\)?sequence\\>\\)" ;18
1611 "\\|\\(\\<clocking\\>\\)" ;19
1612 ))
1613
1614 (defconst verilog-end-block-ordered-rry
1615 [ "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1616 "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)"
1617 "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)"
1618 "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)"
1619 "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)"
1620 "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)"
1621 "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)"
1622 "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)"
1623 "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)"
1624 "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)"
1625 "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)"
1626 "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)"
1627 "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)"
1628 ] )
1629
1630 (defconst verilog-nameable-item-re
1631 (eval-when-compile
1632 (verilog-regexp-words
1633 `("begin"
1634 "fork"
1635 "join" "join_any" "join_none"
1636 "end"
1637 "endcase"
1638 "endconfig"
1639 "endclass"
1640 "endclocking"
1641 "endfunction"
1642 "endgenerate"
1643 "endmodule"
1644 "endprimative"
1645 "endinterface"
1646 "endpackage"
1647 "endspecify"
1648 "endtable"
1649 "endtask" )
1650 )))
1651
1652 (defconst verilog-declaration-opener
1653 (eval-when-compile
1654 (verilog-regexp-words
1655 `("module" "begin" "task" "function"))))
1656
1657 (defconst verilog-declaration-prefix-re
1658 (eval-when-compile
1659 (verilog-regexp-words
1660 `(
1661 ;; port direction
1662 "inout" "input" "output" "ref"
1663 ;; changeableness
1664 "const" "static" "protected" "local"
1665 ;; parameters
1666 "localparam" "parameter" "var"
1667 ;; type creation
1668 "typedef"
1669 ))))
1670 (defconst verilog-declaration-core-re
1671 (eval-when-compile
1672 (verilog-regexp-words
1673 `(
1674 ;; port direction (by themselves)
1675 "inout" "input" "output"
1676 ;; integer_atom_type
1677 "byte" "shortint" "int" "longint" "integer" "time"
1678 ;; integer_vector_type
1679 "bit" "logic" "reg"
1680 ;; non_integer_type
1681 "shortreal" "real" "realtime"
1682 ;; net_type
1683 "supply0" "supply1" "tri" "triand" "trior" "trireg" "tri0" "tri1" "uwire" "wire" "wand" "wor"
1684 ;; misc
1685 "string" "event" "chandle" "virtual" "enum" "genvar"
1686 "struct" "union"
1687 ;; builtin classes
1688 "mailbox" "semaphore"
1689 ))))
1690 (defconst verilog-declaration-re
1691 (concat "\\(" verilog-declaration-prefix-re "\\s-*\\)?" verilog-declaration-core-re))
1692 (defconst verilog-range-re "\\(\\[[^]]*\\]\\s-*\\)+")
1693 (defconst verilog-optional-signed-re "\\s-*\\(signed\\)?")
1694 (defconst verilog-optional-signed-range-re
1695 (concat
1696 "\\s-*\\(\\<\\(reg\\|wire\\)\\>\\s-*\\)?\\(\\<signed\\>\\s-*\\)?\\(" verilog-range-re "\\)?"))
1697 (defconst verilog-macroexp-re "`\\sw+")
1698
1699 (defconst verilog-delay-re "#\\s-*\\(\\([0-9_]+\\('s?[hdxbo][0-9a-fA-F_xz]+\\)?\\)\\|\\(([^()]*)\\)\\|\\(\\sw+\\)\\)")
1700 (defconst verilog-declaration-re-2-no-macro
1701 (concat "\\s-*" verilog-declaration-re
1702 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1703 "\\)?"))
1704 (defconst verilog-declaration-re-2-macro
1705 (concat "\\s-*" verilog-declaration-re
1706 "\\s-*\\(\\(" verilog-optional-signed-range-re "\\)\\|\\(" verilog-delay-re "\\)"
1707 "\\|\\(" verilog-macroexp-re "\\)"
1708 "\\)?"))
1709 (defconst verilog-declaration-re-1-macro
1710 (concat "^" verilog-declaration-re-2-macro))
1711
1712 (defconst verilog-declaration-re-1-no-macro (concat "^" verilog-declaration-re-2-no-macro))
1713
1714 (defconst verilog-defun-re
1715 (eval-when-compile (verilog-regexp-words `("macromodule" "module" "class" "program" "interface" "package" "primitive" "config"))))
1716 (defconst verilog-end-defun-re
1717 (eval-when-compile (verilog-regexp-words `("endmodule" "endclass" "endprogram" "endinterface" "endpackage" "endprimitive" "endconfig"))))
1718 (defconst verilog-zero-indent-re
1719 (concat verilog-defun-re "\\|" verilog-end-defun-re))
1720
1721 (defconst verilog-behavioral-block-beg-re
1722 (eval-when-compile (verilog-regexp-words `("initial" "final" "always" "always_comb" "always_latch" "always_ff"
1723 "function" "task"))))
1724
1725 (defconst verilog-indent-re
1726 (eval-when-compile
1727 (verilog-regexp-words
1728 `(
1729 "{"
1730 "always" "always_latch" "always_ff" "always_comb"
1731 "begin" "end"
1732 ; "unique" "priority"
1733 "case" "casex" "casez" "randcase" "endcase"
1734 "class" "endclass"
1735 "clocking" "endclocking"
1736 "config" "endconfig"
1737 "covergroup" "endgroup"
1738 "fork" "join" "join_any" "join_none"
1739 "function" "endfunction"
1740 "final"
1741 "generate" "endgenerate"
1742 "initial"
1743 "interface" "endinterface"
1744 "module" "macromodule" "endmodule"
1745 "package" "endpackage"
1746 "primitive" "endprimative"
1747 "program" "endprogram"
1748 "property" "endproperty"
1749 "sequence" "randsequence" "endsequence"
1750 "specify" "endspecify"
1751 "table" "endtable"
1752 "task" "endtask"
1753 "virtual"
1754 "`case"
1755 "`default"
1756 "`define" "`undef"
1757 "`if" "`ifdef" "`ifndef" "`else" "`endif"
1758 "`while" "`endwhile"
1759 "`for" "`endfor"
1760 "`format"
1761 "`include"
1762 "`let"
1763 "`protect" "`endprotect"
1764 "`switch" "`endswitch"
1765 "`timescale"
1766 "`time_scale"
1767 ))))
1768
1769 (defconst verilog-defun-level-re
1770 (eval-when-compile
1771 (verilog-regexp-words
1772 `(
1773 "module" "macromodule" "primitive" "class" "program" "initial" "final" "always" "always_comb"
1774 "always_ff" "always_latch" "endtask" "endfunction" "interface" "package"
1775 "config"))))
1776
1777 (defconst verilog-defun-level-not-generate-re
1778 (eval-when-compile
1779 (verilog-regexp-words
1780 `(
1781 "module" "macromodule" "primitive" "class" "program" "interface" "package" "config"))))
1782
1783 (defconst verilog-cpp-level-re
1784 (eval-when-compile
1785 (verilog-regexp-words
1786 `(
1787 "endmodule" "endprimitive" "endinterface" "endpackage" "endprogram" "endclass"
1788 ))))
1789 (defconst verilog-disable-fork-re "disable\\s-+fork")
1790 (defconst verilog-extended-case-re "\\(unique\\s-+\\|priority\\s-+\\)?case[xz]?")
1791 (defconst verilog-extended-complete-re
1792 (concat "\\(\\<extern\\s-+\\|\\<virtual\\s-+\\|\\<protected\\s-+\\)*\\(\\<function\\>\\|\\<task\\>\\)"
1793 "\\|\\(\\<typedef\\>\\s-+\\)*\\(\\<struct\\>\\|\\<union\\>\\|\\<class\\>\\)"
1794 "\\|" verilog-extended-case-re ))
1795 (defconst verilog-basic-complete-re
1796 (eval-when-compile
1797 (verilog-regexp-words
1798 `(
1799 "always" "assign" "always_latch" "always_ff" "always_comb" "constraint"
1800 "import" "initial" "final" "module" "macromodule" "repeat" "randcase" "while"
1801 "if" "for" "forever" "foreach" "else" "parameter" "do"
1802 ))))
1803 (defconst verilog-complete-reg
1804 (concat
1805 verilog-extended-complete-re
1806 "\\|"
1807 verilog-basic-complete-re))
1808
1809 (defconst verilog-end-statement-re
1810 (concat "\\(" verilog-beg-block-re "\\)\\|\\("
1811 verilog-end-block-re "\\)"))
1812
1813 (defconst verilog-endcase-re
1814 (concat verilog-case-re "\\|"
1815 "\\(endcase\\)\\|"
1816 verilog-defun-re
1817 ))
1818
1819 (defconst verilog-exclude-str-start "/* -----\\/----- EXCLUDED -----\\/-----"
1820 "String used to mark beginning of excluded text.")
1821 (defconst verilog-exclude-str-end " -----/\\----- EXCLUDED -----/\\----- */"
1822 "String used to mark end of excluded text.")
1823 (defconst verilog-preprocessor-re
1824 (eval-when-compile
1825 (verilog-regexp-words
1826 `(
1827 "`define" "`include" "`ifdef" "`ifndef" "`if" "`endif" "`else"
1828 ))))
1829
1830 (defconst verilog-keywords
1831 '( "`case" "`default" "`define" "`else" "`endfor" "`endif"
1832 "`endprotect" "`endswitch" "`endwhile" "`for" "`format" "`if" "`ifdef"
1833 "`ifndef" "`include" "`let" "`protect" "`switch" "`timescale"
1834 "`time_scale" "`undef" "`while"
1835
1836 "after" "alias" "always" "always_comb" "always_ff" "always_latch" "and"
1837 "assert" "assign" "assume" "automatic" "before" "begin" "bind"
1838 "bins" "binsof" "bit" "break" "buf" "bufif0" "bufif1" "byte"
1839 "case" "casex" "casez" "cell" "chandle" "class" "clocking" "cmos"
1840 "config" "const" "constraint" "context" "continue" "cover"
1841 "covergroup" "coverpoint" "cross" "deassign" "default" "defparam"
1842 "design" "disable" "dist" "do" "edge" "else" "end" "endcase"
1843 "endclass" "endclocking" "endconfig" "endfunction" "endgenerate"
1844 "endgroup" "endinterface" "endmodule" "endpackage" "endprimitive"
1845 "endprogram" "endproperty" "endspecify" "endsequence" "endtable"
1846 "endtask" "enum" "event" "expect" "export" "extends" "extern"
1847 "final" "first_match" "for" "force" "foreach" "forever" "fork"
1848 "forkjoin" "function" "generate" "genvar" "highz0" "highz1" "if"
1849 "iff" "ifnone" "ignore_bins" "illegal_bins" "import" "incdir"
1850 "include" "initial" "inout" "input" "inside" "instance" "int"
1851 "integer" "interface" "intersect" "join" "join_any" "join_none"
1852 "large" "liblist" "library" "local" "localparam" "logic"
1853 "longint" "macromodule" "mailbox" "matches" "medium" "modport" "module"
1854 "nand" "negedge" "new" "nmos" "nor" "noshowcancelled" "not"
1855 "notif0" "notif1" "null" "or" "output" "package" "packed"
1856 "parameter" "pmos" "posedge" "primitive" "priority" "program"
1857 "property" "protected" "pull0" "pull1" "pulldown" "pullup"
1858 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
1859 "randcase" "randsequence" "rcmos" "real" "realtime" "ref" "reg"
1860 "release" "repeat" "return" "rnmos" "rpmos" "rtran" "rtranif0"
1861 "rtranif1" "scalared" "semaphore" "sequence" "shortint" "shortreal"
1862 "showcancelled" "signed" "small" "solve" "specify" "specparam"
1863 "static" "string" "strong0" "strong1" "struct" "super" "supply0"
1864 "supply1" "table" "tagged" "task" "this" "throughout" "time"
1865 "timeprecision" "timeunit" "tran" "tranif0" "tranif1" "tri"
1866 "tri0" "tri1" "triand" "trior" "trireg" "type" "typedef" "union"
1867 "unique" "unsigned" "use" "uwire" "var" "vectored" "virtual" "void"
1868 "wait" "wait_order" "wand" "weak0" "weak1" "while" "wildcard"
1869 "wire" "with" "within" "wor" "xnor" "xor"
1870 )
1871 "List of Verilog keywords.")
1872
1873 (defconst verilog-comment-start-regexp "//\\|/\\*"
1874 "Dual comment value for `comment-start-regexp'.")
1875
1876 (defvar verilog-mode-syntax-table
1877 (let ((table (make-syntax-table)))
1878 ;; Populate the syntax TABLE.
1879 (modify-syntax-entry ?\\ "\\" table)
1880 (modify-syntax-entry ?+ "." table)
1881 (modify-syntax-entry ?- "." table)
1882 (modify-syntax-entry ?= "." table)
1883 (modify-syntax-entry ?% "." table)
1884 (modify-syntax-entry ?< "." table)
1885 (modify-syntax-entry ?> "." table)
1886 (modify-syntax-entry ?& "." table)
1887 (modify-syntax-entry ?| "." table)
1888 (modify-syntax-entry ?` "w" table)
1889 (modify-syntax-entry ?_ "w" table)
1890 (modify-syntax-entry ?\' "." table)
1891
1892 ;; Set up TABLE to handle block and line style comments.
1893 (if (featurep 'xemacs)
1894 (progn
1895 ;; XEmacs (formerly Lucid) has the best implementation
1896 (modify-syntax-entry ?/ ". 1456" table)
1897 (modify-syntax-entry ?* ". 23" table)
1898 (modify-syntax-entry ?\n "> b" table))
1899 ;; Emacs does things differently, but we can work with it
1900 (modify-syntax-entry ?/ ". 124b" table)
1901 (modify-syntax-entry ?* ". 23" table)
1902 (modify-syntax-entry ?\n "> b" table))
1903 table)
1904 "Syntax table used in Verilog mode buffers.")
1905
1906 (defvar verilog-font-lock-keywords nil
1907 "Default highlighting for Verilog mode.")
1908
1909 (defvar verilog-font-lock-keywords-1 nil
1910 "Subdued level highlighting for Verilog mode.")
1911
1912 (defvar verilog-font-lock-keywords-2 nil
1913 "Medium level highlighting for Verilog mode.
1914 See also `verilog-font-lock-extra-types'.")
1915
1916 (defvar verilog-font-lock-keywords-3 nil
1917 "Gaudy level highlighting for Verilog mode.
1918 See also `verilog-font-lock-extra-types'.")
1919 (defvar verilog-font-lock-translate-off-face
1920 'verilog-font-lock-translate-off-face
1921 "Font to use for translated off regions.")
1922 (defface verilog-font-lock-translate-off-face
1923 '((((class color)
1924 (background light))
1925 (:background "gray90" :italic t ))
1926 (((class color)
1927 (background dark))
1928 (:background "gray10" :italic t ))
1929 (((class grayscale) (background light))
1930 (:foreground "DimGray" :italic t))
1931 (((class grayscale) (background dark))
1932 (:foreground "LightGray" :italic t))
1933 (t (:italis t)))
1934 "Font lock mode face used to background highlight translate-off regions."
1935 :group 'font-lock-highlighting-faces)
1936
1937 (defvar verilog-font-lock-p1800-face
1938 'verilog-font-lock-p1800-face
1939 "Font to use for p1800 keywords.")
1940 (defface verilog-font-lock-p1800-face
1941 '((((class color)
1942 (background light))
1943 (:foreground "DarkOrange3" :bold t ))
1944 (((class color)
1945 (background dark))
1946 (:foreground "orange1" :bold t ))
1947 (t (:italic t)))
1948 "Font lock mode face used to highlight P1800 keywords."
1949 :group 'font-lock-highlighting-faces)
1950
1951 (defvar verilog-font-lock-ams-face
1952 'verilog-font-lock-ams-face
1953 "Font to use for Analog/Mixed Signal keywords.")
1954 (defface verilog-font-lock-ams-face
1955 '((((class color)
1956 (background light))
1957 (:foreground "Purple" :bold t ))
1958 (((class color)
1959 (background dark))
1960 (:foreground "orange1" :bold t ))
1961 (t (:italic t)))
1962 "Font lock mode face used to highlight AMS keywords."
1963 :group 'font-lock-highlighting-faces)
1964
1965 (defvar verilog-font-grouping-keywords-face
1966 'verilog-font-lock-grouping-keywords-face
1967 "Font to use for Verilog Grouping Keywords (such as begin..end).")
1968 (defface verilog-font-lock-grouping-keywords-face
1969 '((((class color)
1970 (background light))
1971 (:foreground "red4" :bold t ))
1972 (((class color)
1973 (background dark))
1974 (:foreground "red4" :bold t ))
1975 (t (:italic t)))
1976 "Font lock mode face used to highlight verilog grouping keywords."
1977 :group 'font-lock-highlighting-faces)
1978
1979 (let* ((verilog-type-font-keywords
1980 (eval-when-compile
1981 (verilog-regexp-opt
1982 '(
1983 "and" "bit" "buf" "bufif0" "bufif1" "cmos" "defparam"
1984 "event" "genvar" "inout" "input" "integer" "localparam"
1985 "logic" "mailbox" "nand" "nmos" "not" "notif0" "notif1" "or"
1986 "output" "parameter" "pmos" "pull0" "pull1" "pullup"
1987 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran"
1988 "rtranif0" "rtranif1" "semaphore" "signed" "struct" "supply"
1989 "supply0" "supply1" "time" "tran" "tranif0" "tranif1"
1990 "tri" "tri0" "tri1" "triand" "trior" "trireg" "typedef"
1991 "uwire" "vectored" "wand" "wire" "wor" "xnor" "xor"
1992 ) nil )))
1993
1994 (verilog-pragma-keywords
1995 (eval-when-compile
1996 (verilog-regexp-opt
1997 '("surefire" "synopsys" "rtl_synthesis" "verilint" "leda" "0in") nil
1998 )))
1999
2000 (verilog-p1800-keywords
2001 (eval-when-compile
2002 (verilog-regexp-opt
2003 '("alias" "assert" "assume" "automatic" "before" "bind"
2004 "bins" "binsof" "break" "byte" "cell" "chandle" "class"
2005 "clocking" "config" "const" "constraint" "context" "continue"
2006 "cover" "covergroup" "coverpoint" "cross" "deassign" "design"
2007 "dist" "do" "edge" "endclass" "endclocking" "endconfig"
2008 "endgroup" "endprogram" "endproperty" "endsequence" "enum"
2009 "expect" "export" "extends" "extern" "first_match" "foreach"
2010 "forkjoin" "genvar" "highz0" "highz1" "ifnone" "ignore_bins"
2011 "illegal_bins" "import" "incdir" "include" "inside" "instance"
2012 "int" "intersect" "large" "liblist" "library" "local" "longint"
2013 "matches" "medium" "modport" "new" "noshowcancelled" "null"
2014 "packed" "program" "property" "protected" "pull0" "pull1"
2015 "pulsestyle_onevent" "pulsestyle_ondetect" "pure" "rand" "randc"
2016 "randcase" "randsequence" "ref" "release" "return" "scalared"
2017 "sequence" "shortint" "shortreal" "showcancelled" "small" "solve"
2018 "specparam" "static" "string" "strong0" "strong1" "struct"
2019 "super" "tagged" "this" "throughout" "timeprecision" "timeunit"
2020 "type" "union" "unsigned" "use" "var" "virtual" "void"
2021 "wait_order" "weak0" "weak1" "wildcard" "with" "within"
2022 ) nil )))
2023
2024 (verilog-ams-keywords
2025 (eval-when-compile
2026 (verilog-regexp-opt
2027 '("above" "abs" "absdelay" "acos" "acosh" "ac_stim"
2028 "aliasparam" "analog" "analysis" "asin" "asinh" "atan" "atan2" "atanh"
2029 "branch" "ceil" "connectmodule" "connectrules" "cos" "cosh" "ddt"
2030 "ddx" "discipline" "driver_update" "enddiscipline" "endconnectrules"
2031 "endnature" "endparamset" "exclude" "exp" "final_step" "flicker_noise"
2032 "floor" "flow" "from" "ground" "hypot" "idt" "idtmod" "inf"
2033 "initial_step" "laplace_nd" "laplace_np" "laplace_zd" "laplace_zp"
2034 "last_crossing" "limexp" "ln" "log" "max" "min" "nature"
2035 "net_resolution" "noise_table" "paramset" "potential" "pow" "sin"
2036 "sinh" "slew" "sqrt" "tan" "tanh" "timer" "transition" "white_noise"
2037 "wreal" "zi_nd" "zi_np" "zi_zd" ) nil )))
2038
2039 (verilog-font-keywords
2040 (eval-when-compile
2041 (verilog-regexp-opt
2042 '(
2043 "assign" "case" "casex" "casez" "randcase" "deassign"
2044 "default" "disable" "else" "endcase" "endfunction"
2045 "endgenerate" "endinterface" "endmodule" "endprimitive"
2046 "endspecify" "endtable" "endtask" "final" "for" "force" "return" "break"
2047 "continue" "forever" "fork" "function" "generate" "if" "iff" "initial"
2048 "interface" "join" "join_any" "join_none" "macromodule" "module" "negedge"
2049 "package" "endpackage" "always" "always_comb" "always_ff"
2050 "always_latch" "posedge" "primitive" "priority" "release"
2051 "repeat" "specify" "table" "task" "unique" "wait" "while"
2052 "class" "program" "endclass" "endprogram"
2053 ) nil )))
2054
2055 (verilog-font-grouping-keywords
2056 (eval-when-compile
2057 (verilog-regexp-opt
2058 '( "begin" "end" ) nil ))))
2059
2060 (setq verilog-font-lock-keywords
2061 (list
2062 ;; Fontify all builtin keywords
2063 (concat "\\<\\(" verilog-font-keywords "\\|"
2064 ;; And user/system tasks and functions
2065 "\\$[a-zA-Z][a-zA-Z0-9_\\$]*"
2066 "\\)\\>")
2067 ;; Fontify all types
2068 (if verilog-highlight-grouping-keywords
2069 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2070 'verilog-font-lock-ams-face)
2071 (cons (concat "\\<\\(" verilog-font-grouping-keywords "\\)\\>")
2072 'font-lock-type-face))
2073 (cons (concat "\\<\\(" verilog-type-font-keywords "\\)\\>")
2074 'font-lock-type-face)
2075 ;; Fontify IEEE-P1800 keywords appropriately
2076 (if verilog-highlight-p1800-keywords
2077 (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
2078 'verilog-font-lock-p1800-face)
2079 (cons (concat "\\<\\(" verilog-p1800-keywords "\\)\\>")
2080 'font-lock-type-face))
2081 ;; Fontify Verilog-AMS keywords
2082 (cons (concat "\\<\\(" verilog-ams-keywords "\\)\\>")
2083 'verilog-font-lock-ams-face)))
2084
2085 (setq verilog-font-lock-keywords-1
2086 (append verilog-font-lock-keywords
2087 (list
2088 ;; Fontify module definitions
2089 (list
2090 "\\<\\(\\(macro\\)?module\\|primitive\\|class\\|program\\|interface\\|package\\|task\\)\\>\\s-*\\(\\sw+\\)"
2091 '(1 font-lock-keyword-face)
2092 '(3 font-lock-function-name-face 'prepend))
2093 ;; Fontify function definitions
2094 (list
2095 (concat "\\<function\\>\\s-+\\(integer\\|real\\(time\\)?\\|time\\)\\s-+\\(\\sw+\\)" )
2096 '(1 font-lock-keyword-face)
2097 '(3 font-lock-reference-face prepend))
2098 '("\\<function\\>\\s-+\\(\\[[^]]+\\]\\)\\s-+\\(\\sw+\\)"
2099 (1 font-lock-keyword-face)
2100 (2 font-lock-reference-face append))
2101 '("\\<function\\>\\s-+\\(\\sw+\\)"
2102 1 'font-lock-reference-face append))))
2103
2104 (setq verilog-font-lock-keywords-2
2105 (append verilog-font-lock-keywords-1
2106 (list
2107 ;; Fontify pragmas
2108 (concat "\\(//\\s-*" verilog-pragma-keywords "\\s-.*\\)")
2109 ;; Fontify escaped names
2110 '("\\(\\\\\\S-*\\s-\\)" 0 font-lock-function-name-face)
2111 ;; Fontify macro definitions/ uses
2112 '("`\\s-*[A-Za-z][A-Za-z0-9_]*" 0 (if (boundp 'font-lock-preprocessor-face)
2113 'font-lock-preprocessor-face
2114 'font-lock-type-face))
2115 ;; Fontify delays/numbers
2116 '("\\(@\\)\\|\\(#\\s-*\\(\\(\[0-9_.\]+\\('s?[hdxbo][0-9a-fA-F_xz]*\\)?\\)\\|\\(([^()]+)\\|\\sw+\\)\\)\\)"
2117 0 font-lock-type-face append)
2118 ;; Fontify instantiation names
2119 '("\\([A-Za-z][A-Za-z0-9_]+\\)\\s-*(" 1 font-lock-function-name-face)
2120 )))
2121
2122 (setq verilog-font-lock-keywords-3
2123 (append verilog-font-lock-keywords-2
2124 (when verilog-highlight-translate-off
2125 (list
2126 ;; Fontify things in translate off regions
2127 '(verilog-match-translate-off
2128 (0 'verilog-font-lock-translate-off-face prepend))
2129 )))))
2130
2131
2132 (defun verilog-inside-comment-p ()
2133 "Check if point inside a nested comment."
2134 (save-excursion
2135 (let ((st-point (point)) hitbeg)
2136 (or (search-backward "//" (verilog-get-beg-of-line) t)
2137 (if (progn
2138 ;; This is for tricky case //*, we keep searching if /*
2139 ;; is proceeded by // on same line.
2140 (while
2141 (and (setq hitbeg (search-backward "/*" nil t))
2142 (progn
2143 (forward-char 1)
2144 (search-backward "//" (verilog-get-beg-of-line) t))))
2145 hitbeg)
2146 (not (search-forward "*/" st-point t)))))))
2147
2148 (defun verilog-declaration-end ()
2149 (search-forward ";"))
2150
2151 (defun verilog-point-text (&optional pointnum)
2152 "Return text describing where POINTNUM or current point is (for errors).
2153 Use filename, if current buffer being edited shorten to just buffer name."
2154 (concat (or (and (equal (window-buffer (selected-window)) (current-buffer))
2155 (buffer-name))
2156 buffer-file-name
2157 (buffer-name))
2158 ":" (int-to-string (count-lines (point-min) (or pointnum (point))))))
2159
2160 (defun electric-verilog-backward-sexp ()
2161 "Move backward over one balanced expression."
2162 (interactive)
2163 ;; before that see if we are in a comment
2164 (verilog-backward-sexp))
2165
2166 (defun electric-verilog-forward-sexp ()
2167 "Move forward over one balanced expression."
2168 (interactive)
2169 ;; before that see if we are in a comment
2170 (verilog-forward-sexp))
2171
2172 ;;;used by hs-minor-mode
2173 (defun verilog-forward-sexp-function (arg)
2174 (if (< arg 0)
2175 (verilog-backward-sexp)
2176 (verilog-forward-sexp)))
2177
2178
2179 (defun verilog-backward-sexp ()
2180 (let ((reg)
2181 (elsec 1)
2182 (found nil)
2183 (st (point)))
2184 (if (not (looking-at "\\<"))
2185 (forward-word -1))
2186 (cond
2187 ((verilog-skip-backward-comment-or-string))
2188 ((looking-at "\\<else\\>")
2189 (setq reg (concat
2190 verilog-end-block-re
2191 "\\|\\(\\<else\\>\\)"
2192 "\\|\\(\\<if\\>\\)"))
2193 (while (and (not found)
2194 (verilog-re-search-backward reg nil 'move))
2195 (cond
2196 ((match-end 1) ; matched verilog-end-block-re
2197 ; try to leap back to matching outward block by striding across
2198 ; indent level changing tokens then immediately
2199 ; previous line governs indentation.
2200 (verilog-leap-to-head))
2201 ((match-end 2) ; else, we're in deep
2202 (setq elsec (1+ elsec)))
2203 ((match-end 3) ; found it
2204 (setq elsec (1- elsec))
2205 (if (= 0 elsec)
2206 ;; Now previous line describes syntax
2207 (setq found 't))))))
2208 ((looking-at verilog-end-block-re)
2209 (verilog-leap-to-head))
2210 ((looking-at "\\(endmodule\\>\\)\\|\\(\\<endprimitive\\>\\)\\|\\(\\<endclass\\>\\)\\|\\(\\<endprogram\\>\\)\\|\\(\\<endinterface\\>\\)\\|\\(\\<endpackage\\>\\)")
2211 (cond
2212 ((match-end 1)
2213 (verilog-re-search-backward "\\<\\(macro\\)?module\\>" nil 'move))
2214 ((match-end 2)
2215 (verilog-re-search-backward "\\<primitive\\>" nil 'move))
2216 ((match-end 3)
2217 (verilog-re-search-backward "\\<class\\>" nil 'move))
2218 ((match-end 4)
2219 (verilog-re-search-backward "\\<program\\>" nil 'move))
2220 ((match-end 5)
2221 (verilog-re-search-backward "\\<interface\\>" nil 'move))
2222 ((match-end 6)
2223 (verilog-re-search-backward "\\<package\\>" nil 'move))
2224 (t
2225 (goto-char st)
2226 (backward-sexp 1))))
2227 (t
2228 (goto-char st)
2229 (backward-sexp)))))
2230
2231 (defun verilog-forward-sexp ()
2232 (let ((reg)
2233 (md 2)
2234 (st (point))
2235 (nest 'yes))
2236 (if (not (looking-at "\\<"))
2237 (forward-word -1))
2238 (cond
2239 ((verilog-skip-forward-comment-or-string)
2240 (verilog-forward-syntactic-ws))
2241 ((looking-at verilog-beg-block-re-ordered)
2242 (cond
2243 ((match-end 1);
2244 ;; Search forward for matching end
2245 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
2246 ((match-end 2)
2247 ;; Search forward for matching endcase
2248 (setq reg "\\(\\<randcase\\>\\|\\(\\<unique\\>\\s-+\\|\\<priority\\>\\s-+\\)?\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" )
2249 (setq md 3) ;; ender is third item in regexp
2250 )
2251 ((match-end 4)
2252 ;; might be "disable fork"
2253 (if (or
2254 (looking-at verilog-disable-fork-re)
2255 (and (looking-at "fork")
2256 (progn
2257 (forward-word -1)
2258 (looking-at verilog-disable-fork-re))))
2259 (progn
2260 (goto-char (match-end 0))
2261 (forward-word)
2262 (setq reg nil))
2263 (progn
2264 ;; Search forward for matching join
2265 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))))
2266 ((match-end 6)
2267 ;; Search forward for matching endclass
2268 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
2269
2270 ((match-end 7)
2271 ;; Search forward for matching endtable
2272 (setq reg "\\<endtable\\>" )
2273 (setq nest 'no))
2274 ((match-end 8)
2275 ;; Search forward for matching endspecify
2276 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
2277 ((match-end 9)
2278 ;; Search forward for matching endfunction
2279 (setq reg "\\<endfunction\\>" )
2280 (setq nest 'no))
2281 ((match-end 10)
2282 ;; Search forward for matching endtask
2283 (setq reg "\\<endtask\\>" )
2284 (setq nest 'no))
2285 ((match-end 11)
2286 ;; Search forward for matching endtask
2287 (setq reg "\\<endtask\\>" )
2288 (setq nest 'no))
2289 ((match-end 15)
2290 ;; Search forward for matching endgenerate
2291 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
2292 ((match-end 16)
2293 ;; Search forward for matching endgroup
2294 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
2295 ((match-end 17)
2296 ;; Search forward for matching endproperty
2297 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
2298 ((match-end 18)
2299 ;; Search forward for matching endsequence
2300 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" )
2301 (setq md 3)) ; 3 to get to endsequence in the reg above
2302 ((match-end 19)
2303 ;; Search forward for matching endclocking
2304 (setq reg "\\(\\<clocking\\>\\)\\|\\(\\<endclocking\\>\\)" )))
2305 (if (and reg
2306 (forward-word 1))
2307 (catch 'skip
2308 (if (eq nest 'yes)
2309 (let ((depth 1))
2310 (while (verilog-re-search-forward reg nil 'move)
2311 (cond
2312 ((match-end md) ; the closer in reg, so we are climbing out
2313 (setq depth (1- depth))
2314 (if (= 0 depth) ; we are out!
2315 (throw 'skip 1)))
2316 ((match-end 1) ; the opener in reg, so we are deeper now
2317 (setq depth (1+ depth))))))
2318 (if (verilog-re-search-forward reg nil 'move)
2319 (throw 'skip 1))))))
2320
2321 ((looking-at (concat
2322 "\\(\\<\\(macro\\)?module\\>\\)\\|"
2323 "\\(\\<primitive\\>\\)\\|"
2324 "\\(\\<class\\>\\)\\|"
2325 "\\(\\<program\\>\\)\\|"
2326 "\\(\\<interface\\>\\)\\|"
2327 "\\(\\<package\\>\\)"))
2328 (cond
2329 ((match-end 1)
2330 (verilog-re-search-forward "\\<endmodule\\>" nil 'move))
2331 ((match-end 2)
2332 (verilog-re-search-forward "\\<endprimitive\\>" nil 'move))
2333 ((match-end 3)
2334 (verilog-re-search-forward "\\<endclass\\>" nil 'move))
2335 ((match-end 4)
2336 (verilog-re-search-forward "\\<endprogram\\>" nil 'move))
2337 ((match-end 5)
2338 (verilog-re-search-forward "\\<endinterface\\>" nil 'move))
2339 ((match-end 6)
2340 (verilog-re-search-forward "\\<endpackage\\>" nil 'move))
2341 (t
2342 (goto-char st)
2343 (if (= (following-char) ?\) )
2344 (forward-char 1)
2345 (forward-sexp 1)))))
2346 (t
2347 (goto-char st)
2348 (if (= (following-char) ?\) )
2349 (forward-char 1)
2350 (forward-sexp 1))))))
2351
2352 (defun verilog-declaration-beg ()
2353 (verilog-re-search-backward verilog-declaration-re (bobp) t))
2354
2355 (defun verilog-font-lock-init ()
2356 "Initialize fontification."
2357 ;; highlight keywords and standardized types, attributes, enumeration
2358 ;; values, and subprograms
2359 (setq verilog-font-lock-keywords-3
2360 (append verilog-font-lock-keywords-2
2361 (when verilog-highlight-translate-off
2362 (list
2363 ;; Fontify things in translate off regions
2364 '(verilog-match-translate-off
2365 (0 'verilog-font-lock-translate-off-face prepend))))))
2366 (put 'verilog-mode 'font-lock-defaults
2367 '((verilog-font-lock-keywords
2368 verilog-font-lock-keywords-1
2369 verilog-font-lock-keywords-2
2370 verilog-font-lock-keywords-3)
2371 nil ; nil means highlight strings & comments as well as keywords
2372 nil ; nil means keywords must match case
2373 nil ; syntax table handled elsewhere
2374 ;; Function to move to beginning of reasonable region to highlight
2375 verilog-beg-of-defun)))
2376
2377 ;; initialize fontification for Verilog Mode
2378 (verilog-font-lock-init)
2379
2380 ;;
2381 ;;
2382 ;; Mode
2383 ;;
2384 (defvar verilog-which-tool 1)
2385 ;;;###autoload
2386 (defun verilog-mode ()
2387 "Major mode for editing Verilog code.
2388 \\<verilog-mode-map>
2389 See \\[describe-function] verilog-auto (\\[verilog-auto]) for details on how
2390 AUTOs can improve coding efficiency.
2391
2392 Use \\[verilog-faq] for a pointer to frequently asked questions.
2393
2394 NEWLINE, TAB indents for Verilog code.
2395 Delete converts tabs to spaces as it moves back.
2396
2397 Supports highlighting.
2398
2399 Turning on Verilog mode calls the value of the variable `verilog-mode-hook'
2400 with no args, if that value is non-nil.
2401
2402 Variables controlling indentation/edit style:
2403
2404 variable `verilog-indent-level' (default 3)
2405 Indentation of Verilog statements with respect to containing block.
2406 `verilog-indent-level-module' (default 3)
2407 Absolute indentation of Module level Verilog statements.
2408 Set to 0 to get initial and always statements lined up
2409 on the left side of your screen.
2410 `verilog-indent-level-declaration' (default 3)
2411 Indentation of declarations with respect to containing block.
2412 Set to 0 to get them list right under containing block.
2413 `verilog-indent-level-behavioral' (default 3)
2414 Indentation of first begin in a task or function block
2415 Set to 0 to get such code to lined up underneath the task or
2416 function keyword.
2417 `verilog-indent-level-directive' (default 1)
2418 Indentation of `ifdef/`endif blocks.
2419 `verilog-cexp-indent' (default 1)
2420 Indentation of Verilog statements broken across lines i.e.:
2421 if (a)
2422 begin
2423 `verilog-case-indent' (default 2)
2424 Indentation for case statements.
2425 `verilog-auto-newline' (default nil)
2426 Non-nil means automatically newline after semicolons and the punctuation
2427 mark after an end.
2428 `verilog-auto-indent-on-newline' (default t)
2429 Non-nil means automatically indent line after newline.
2430 `verilog-tab-always-indent' (default t)
2431 Non-nil means TAB in Verilog mode should always reindent the current line,
2432 regardless of where in the line point is when the TAB command is used.
2433 `verilog-indent-begin-after-if' (default t)
2434 Non-nil means to indent begin statements following a preceding
2435 if, else, while, for and repeat statements, if any. Otherwise,
2436 the begin is lined up with the preceding token. If t, you get:
2437 if (a)
2438 begin // amount of indent based on `verilog-cexp-indent'
2439 otherwise you get:
2440 if (a)
2441 begin
2442 `verilog-auto-endcomments' (default t)
2443 Non-nil means a comment /* ... */ is set after the ends which ends
2444 cases, tasks, functions and modules.
2445 The type and name of the object will be set between the braces.
2446 `verilog-minimum-comment-distance' (default 10)
2447 Minimum distance (in lines) between begin and end required before a comment
2448 will be inserted. Setting this variable to zero results in every
2449 end acquiring a comment; the default avoids too many redundant
2450 comments in tight quarters.
2451 `verilog-auto-lineup' (default `(all))
2452 List of contexts where auto lineup of code should be done.
2453
2454 Variables controlling other actions:
2455
2456 `verilog-linter' (default surelint)
2457 Unix program to call to run the lint checker. This is the default
2458 command for \\[compile-command] and \\[verilog-auto-save-compile].
2459
2460 See \\[customize] for the complete list of variables.
2461
2462 AUTO expansion functions are, in part:
2463
2464 \\[verilog-auto] Expand AUTO statements.
2465 \\[verilog-delete-auto] Remove the AUTOs.
2466 \\[verilog-inject-auto] Insert AUTOs for the first time.
2467
2468 Some other functions are:
2469
2470 \\[verilog-complete-word] Complete word with appropriate possibilities.
2471 \\[verilog-mark-defun] Mark function.
2472 \\[verilog-beg-of-defun] Move to beginning of current function.
2473 \\[verilog-end-of-defun] Move to end of current function.
2474 \\[verilog-label-be] Label matching begin ... end, fork ... join, etc statements.
2475
2476 \\[verilog-comment-region] Put marked area in a comment.
2477 \\[verilog-uncomment-region] Uncomment an area commented with \\[verilog-comment-region].
2478 \\[verilog-insert-block] Insert begin ... end.
2479 \\[verilog-star-comment] Insert /* ... */.
2480
2481 \\[verilog-sk-always] Insert an always @(AS) begin .. end block.
2482 \\[verilog-sk-begin] Insert a begin .. end block.
2483 \\[verilog-sk-case] Insert a case block, prompting for details.
2484 \\[verilog-sk-for] Insert a for (...) begin .. end block, prompting for details.
2485 \\[verilog-sk-generate] Insert a generate .. endgenerate block.
2486 \\[verilog-sk-header] Insert a header block at the top of file.
2487 \\[verilog-sk-initial] Insert an initial begin .. end block.
2488 \\[verilog-sk-fork] Insert a fork begin .. end .. join block.
2489 \\[verilog-sk-module] Insert a module .. (/*AUTOARG*/);.. endmodule block.
2490 \\[verilog-sk-primitive] Insert a primitive .. (.. );.. endprimitive block.
2491 \\[verilog-sk-repeat] Insert a repeat (..) begin .. end block.
2492 \\[verilog-sk-specify] Insert a specify .. endspecify block.
2493 \\[verilog-sk-task] Insert a task .. begin .. end endtask block.
2494 \\[verilog-sk-while] Insert a while (...) begin .. end block, prompting for details.
2495 \\[verilog-sk-casex] Insert a casex (...) item: begin.. end endcase block, prompting for details.
2496 \\[verilog-sk-casez] Insert a casez (...) item: begin.. end endcase block, prompting for details.
2497 \\[verilog-sk-if] Insert an if (..) begin .. end block.
2498 \\[verilog-sk-else-if] Insert an else if (..) begin .. end block.
2499 \\[verilog-sk-comment] Insert a comment block.
2500 \\[verilog-sk-assign] Insert an assign .. = ..; statement.
2501 \\[verilog-sk-function] Insert a function .. begin .. end endfunction block.
2502 \\[verilog-sk-input] Insert an input declaration, prompting for details.
2503 \\[verilog-sk-output] Insert an output declaration, prompting for details.
2504 \\[verilog-sk-state-machine] Insert a state machine definition, prompting for details.
2505 \\[verilog-sk-inout] Insert an inout declaration, prompting for details.
2506 \\[verilog-sk-wire] Insert a wire declaration, prompting for details.
2507 \\[verilog-sk-reg] Insert a register declaration, prompting for details.
2508 \\[verilog-sk-define-signal] Define signal under point as a register at the top of the module.
2509
2510 All key bindings can be seen in a Verilog-buffer with \\[describe-bindings].
2511 Key bindings specific to `verilog-mode-map' are:
2512
2513 \\{verilog-mode-map}"
2514 (interactive)
2515 (kill-all-local-variables)
2516 (use-local-map verilog-mode-map)
2517 (setq major-mode 'verilog-mode)
2518 (setq mode-name "Verilog")
2519 (setq local-abbrev-table verilog-mode-abbrev-table)
2520 (set (make-local-variable 'beginning-of-defun-function)
2521 'verilog-beg-of-defun)
2522 (set (make-local-variable 'end-of-defun-function)
2523 'verilog-end-of-defun)
2524 (set-syntax-table verilog-mode-syntax-table)
2525 (make-local-variable 'indent-line-function)
2526 (setq indent-line-function 'verilog-indent-line-relative)
2527 (setq comment-indent-function 'verilog-comment-indent)
2528 (make-local-variable 'parse-sexp-ignore-comments)
2529 (setq parse-sexp-ignore-comments nil)
2530 (make-local-variable 'comment-start)
2531 (make-local-variable 'comment-end)
2532 (make-local-variable 'comment-multi-line)
2533 (make-local-variable 'comment-start-skip)
2534 (setq comment-start "// "
2535 comment-end ""
2536 comment-start-skip "/\\*+ *\\|// *"
2537 comment-multi-line nil)
2538 ;; Set up for compilation
2539 (setq verilog-which-tool 1)
2540 (setq verilog-tool 'verilog-linter)
2541 (verilog-set-compile-command)
2542 (when (boundp 'hack-local-variables-hook) ;; Also modify any file-local-variables
2543 (add-hook 'hack-local-variables-hook 'verilog-modify-compile-command t))
2544
2545 ;; Setting up menus
2546 (when (featurep 'xemacs)
2547 (easy-menu-add verilog-stmt-menu)
2548 (easy-menu-add verilog-menu)
2549 (setq mode-popup-menu (cons "Verilog Mode" verilog-stmt-menu)))
2550
2551 ;; Stuff for GNU Emacs
2552 (set (make-local-variable 'font-lock-defaults)
2553 '((verilog-font-lock-keywords verilog-font-lock-keywords-1
2554 verilog-font-lock-keywords-2
2555 verilog-font-lock-keywords-3)
2556 nil nil nil verilog-beg-of-defun))
2557 ;;------------------------------------------------------------
2558 ;; now hook in 'verilog-colorize-include-files (eldo-mode.el&spice-mode.el)
2559 ;; all buffer local:
2560 (when (featurep 'xemacs)
2561 (make-local-hook 'font-lock-mode-hook)
2562 (make-local-hook 'font-lock-after-fontify-buffer-hook); doesn't exist in Emacs
2563 (make-local-hook 'after-change-functions))
2564 (add-hook 'font-lock-mode-hook 'verilog-colorize-include-files-buffer t t)
2565 (add-hook 'font-lock-after-fontify-buffer-hook 'verilog-colorize-include-files-buffer t t) ; not in Emacs
2566 (add-hook 'after-change-functions 'verilog-colorize-include-files t t)
2567
2568 ;; Tell imenu how to handle Verilog.
2569 (make-local-variable 'imenu-generic-expression)
2570 (setq imenu-generic-expression verilog-imenu-generic-expression)
2571 ;; Tell which-func-modes that imenu knows about verilog
2572 (when (boundp 'which-function-modes)
2573 (add-to-list 'which-func-modes 'verilog-mode))
2574 ;; hideshow support
2575 (when (boundp 'hs-special-modes-alist)
2576 (unless (assq 'verilog-mode hs-special-modes-alist)
2577 (setq hs-special-modes-alist
2578 (cons '(verilog-mode-mode "\\<begin\\>" "\\<end\\>" nil
2579 verilog-forward-sexp-function)
2580 hs-special-modes-alist))))
2581
2582 ;; Stuff for autos
2583 (add-hook 'write-contents-hooks 'verilog-auto-save-check) ; already local
2584 ;; (verilog-auto-reeval-locals t) ; Save locals in case user changes them
2585 ;; (verilog-getopt-flags)
2586 (run-hooks 'verilog-mode-hook))
2587 \f
2588
2589 ;;
2590 ;; Electric functions
2591 ;;
2592 (defun electric-verilog-terminate-line (&optional arg)
2593 "Terminate line and indent next line.
2594 With optional ARG, remove existing end of line comments."
2595 (interactive)
2596 ;; before that see if we are in a comment
2597 (let ((state (save-excursion (verilog-syntax-ppss))))
2598 (cond
2599 ((nth 7 state) ; Inside // comment
2600 (if (eolp)
2601 (progn
2602 (delete-horizontal-space)
2603 (newline))
2604 (progn
2605 (newline)
2606 (insert "// ")
2607 (beginning-of-line)))
2608 (verilog-indent-line))
2609 ((nth 4 state) ; Inside any comment (hence /**/)
2610 (newline)
2611 (verilog-more-comment))
2612 ((eolp)
2613 ;; First, check if current line should be indented
2614 (if (save-excursion
2615 (delete-horizontal-space)
2616 (beginning-of-line)
2617 (skip-chars-forward " \t")
2618 (if (looking-at verilog-auto-end-comment-lines-re)
2619 (let ((indent-str (verilog-indent-line)))
2620 ;; Maybe we should set some endcomments
2621 (if verilog-auto-endcomments
2622 (verilog-set-auto-endcomments indent-str arg))
2623 (end-of-line)
2624 (delete-horizontal-space)
2625 (if arg
2626 ()
2627 (newline))
2628 nil)
2629 (progn
2630 (end-of-line)
2631 (delete-horizontal-space)
2632 't)))
2633 ;; see if we should line up assignments
2634 (progn
2635 (if (or (memq 'all verilog-auto-lineup)
2636 (memq 'assignments verilog-auto-lineup))
2637 (verilog-pretty-expr))
2638 (newline))
2639 (forward-line 1))
2640 ;; Indent next line
2641 (if verilog-auto-indent-on-newline
2642 (verilog-indent-line)))
2643 (t
2644 (newline)))))
2645
2646 (defun electric-verilog-terminate-and-indent ()
2647 "Insert a newline and indent for the next statement."
2648 (interactive)
2649 (electric-verilog-terminate-line 1))
2650
2651 (defun electric-verilog-semi ()
2652 "Insert `;' character and reindent the line."
2653 (interactive)
2654 (insert last-command-char)
2655
2656 (if (or (verilog-in-comment-or-string-p)
2657 (verilog-in-escaped-name-p))
2658 ()
2659 (save-excursion
2660 (beginning-of-line)
2661 (verilog-forward-ws&directives)
2662 (verilog-indent-line))
2663 (if (and verilog-auto-newline
2664 (not (verilog-parenthesis-depth)))
2665 (electric-verilog-terminate-line))))
2666
2667 (defun electric-verilog-semi-with-comment ()
2668 "Insert `;' character, reindent the line and indent for comment."
2669 (interactive)
2670 (insert "\;")
2671 (save-excursion
2672 (beginning-of-line)
2673 (verilog-indent-line))
2674 (indent-for-comment))
2675
2676 (defun electric-verilog-colon ()
2677 "Insert `:' and do all indentations except line indent on this line."
2678 (interactive)
2679 (insert last-command-char)
2680 ;; Do nothing if within string.
2681 (if (or
2682 (verilog-within-string)
2683 (not (verilog-in-case-region-p)))
2684 ()
2685 (save-excursion
2686 (let ((p (point))
2687 (lim (progn (verilog-beg-of-statement) (point))))
2688 (goto-char p)
2689 (verilog-backward-case-item lim)
2690 (verilog-indent-line)))
2691 ;; (let ((verilog-tab-always-indent nil))
2692 ;; (verilog-indent-line))
2693 ))
2694
2695 ;;(defun electric-verilog-equal ()
2696 ;; "Insert `=', and do indentation if within block."
2697 ;; (interactive)
2698 ;; (insert last-command-char)
2699 ;; Could auto line up expressions, but not yet
2700 ;; (if (eq (car (verilog-calculate-indent)) 'block)
2701 ;; (let ((verilog-tab-always-indent nil))
2702 ;; (verilog-indent-command)))
2703 ;; )
2704
2705 (defun electric-verilog-tick ()
2706 "Insert back-tick, and indent to column 0 if this is a CPP directive."
2707 (interactive)
2708 (insert last-command-char)
2709 (save-excursion
2710 (if (progn
2711 (beginning-of-line)
2712 (looking-at verilog-directive-re-1))
2713 (verilog-indent-line))))
2714
2715 (defun electric-verilog-tab ()
2716 "Function called when TAB is pressed in Verilog mode."
2717 (interactive)
2718 ;; If verilog-tab-always-indent, indent the beginning of the line.
2719 (if (or verilog-tab-always-indent
2720 (save-excursion
2721 (skip-chars-backward " \t")
2722 (bolp)))
2723 (let* ((oldpnt (point))
2724 (boi-point
2725 (save-excursion
2726 (beginning-of-line)
2727 (skip-chars-forward " \t")
2728 (verilog-indent-line)
2729 (back-to-indentation)
2730 (point))))
2731 (if (< (point) boi-point)
2732 (back-to-indentation)
2733 (cond ((not verilog-tab-to-comment))
2734 ((not (eolp))
2735 (end-of-line))
2736 (t
2737 (indent-for-comment)
2738 (when (and (eolp) (= oldpnt (point)))
2739 ; kill existing comment
2740 (beginning-of-line)
2741 (re-search-forward comment-start-skip oldpnt 'move)
2742 (goto-char (match-beginning 0))
2743 (skip-chars-backward " \t")
2744 (kill-region (point) oldpnt))))))
2745 (progn (insert "\t"))))
2746
2747 \f
2748
2749 ;;
2750 ;; Interactive functions
2751 ;;
2752
2753 (defun verilog-indent-buffer ()
2754 "Indent-region the entire buffer as Verilog code.
2755 To call this from the command line, see \\[verilog-batch-indent]."
2756 (interactive)
2757 (verilog-mode)
2758 (indent-region (point-min) (point-max) nil))
2759
2760 (defun verilog-insert-block ()
2761 "Insert Verilog begin ... end; block in the code with right indentation."
2762 (interactive)
2763 (verilog-indent-line)
2764 (insert "begin")
2765 (electric-verilog-terminate-line)
2766 (save-excursion
2767 (electric-verilog-terminate-line)
2768 (insert "end")
2769 (beginning-of-line)
2770 (verilog-indent-line)))
2771
2772 (defun verilog-star-comment ()
2773 "Insert Verilog star comment at point."
2774 (interactive)
2775 (verilog-indent-line)
2776 (insert "/*")
2777 (save-excursion
2778 (newline)
2779 (insert " */"))
2780 (newline)
2781 (insert " * "))
2782
2783 (defun verilog-insert-1 (fmt max)
2784 "Use format string FMT to insert integers 0 to MAX - 1.
2785 Inserts one integer per line, at the current column. Stops early
2786 if it reaches the end of the buffer."
2787 (let ((col (current-column))
2788 (n 0))
2789 (save-excursion
2790 (while (< n max)
2791 (insert (format fmt n))
2792 (forward-line 1)
2793 ;; Note that this function does not bother to check for lines
2794 ;; shorter than col.
2795 (if (eobp)
2796 (setq n max)
2797 (setq n (1+ n))
2798 (move-to-column col))))))
2799
2800 (defun verilog-insert-indices (max)
2801 "Insert a set of indices into a rectangle.
2802 The upper left corner is defined by point. Indices begin with 0
2803 and extend to the MAX - 1. If no prefix arg is given, the user
2804 is prompted for a value. The indices are surrounded by square
2805 brackets \[]. For example, the following code with the point
2806 located after the first 'a' gives:
2807
2808 a = b a[ 0] = b
2809 a = b a[ 1] = b
2810 a = b a[ 2] = b
2811 a = b a[ 3] = b
2812 a = b ==> insert-indices ==> a[ 4] = b
2813 a = b a[ 5] = b
2814 a = b a[ 6] = b
2815 a = b a[ 7] = b
2816 a = b a[ 8] = b"
2817
2818 (interactive "NMAX: ")
2819 (verilog-insert-1 "[%3d]" max))
2820
2821 (defun verilog-generate-numbers (max)
2822 "Insert a set of generated numbers into a rectangle.
2823 The upper left corner is defined by point. The numbers are padded to three
2824 digits, starting with 000 and extending to (MAX - 1). If no prefix argument
2825 is supplied, then the user is prompted for the MAX number. Consider the
2826 following code fragment:
2827
2828 buf buf buf buf000
2829 buf buf buf buf001
2830 buf buf buf buf002
2831 buf buf buf buf003
2832 buf buf ==> generate-numbers ==> buf buf004
2833 buf buf buf buf005
2834 buf buf buf buf006
2835 buf buf buf buf007
2836 buf buf buf buf008"
2837
2838 (interactive "NMAX: ")
2839 (verilog-insert-1 "%3.3d" max))
2840
2841 (defun verilog-mark-defun ()
2842 "Mark the current Verilog function (or procedure).
2843 This puts the mark at the end, and point at the beginning."
2844 (interactive)
2845 (if (featurep 'xemacs)
2846 (progn
2847 (push-mark (point))
2848 (verilog-end-of-defun)
2849 (push-mark (point))
2850 (verilog-beg-of-defun)
2851 (if (fboundp 'zmacs-activate-region)
2852 (zmacs-activate-region)))
2853 (mark-defun)))
2854
2855 (defun verilog-comment-region (start end)
2856 ; checkdoc-params: (start end)
2857 "Put the region into a Verilog comment.
2858 The comments that are in this area are \"deformed\":
2859 `*)' becomes `!(*' and `}' becomes `!{'.
2860 These deformed comments are returned to normal if you use
2861 \\[verilog-uncomment-region] to undo the commenting.
2862
2863 The commented area starts with `verilog-exclude-str-start', and ends with
2864 `verilog-exclude-str-end'. But if you change these variables,
2865 \\[verilog-uncomment-region] won't recognize the comments."
2866 (interactive "r")
2867 (save-excursion
2868 ;; Insert start and endcomments
2869 (goto-char end)
2870 (if (and (save-excursion (skip-chars-forward " \t") (eolp))
2871 (not (save-excursion (skip-chars-backward " \t") (bolp))))
2872 (forward-line 1)
2873 (beginning-of-line))
2874 (insert verilog-exclude-str-end)
2875 (setq end (point))
2876 (newline)
2877 (goto-char start)
2878 (beginning-of-line)
2879 (insert verilog-exclude-str-start)
2880 (newline)
2881 ;; Replace end-comments within commented area
2882 (goto-char end)
2883 (save-excursion
2884 (while (re-search-backward "\\*/" start t)
2885 (replace-match "*-/" t t)))
2886 (save-excursion
2887 (let ((s+1 (1+ start)))
2888 (while (re-search-backward "/\\*" s+1 t)
2889 (replace-match "/-*" t t))))))
2890
2891 (defun verilog-uncomment-region ()
2892 "Uncomment a commented area; change deformed comments back to normal.
2893 This command does nothing if the pointer is not in a commented
2894 area. See also `verilog-comment-region'."
2895 (interactive)
2896 (save-excursion
2897 (let ((start (point))
2898 (end (point)))
2899 ;; Find the boundaries of the comment
2900 (save-excursion
2901 (setq start (progn (search-backward verilog-exclude-str-start nil t)
2902 (point)))
2903 (setq end (progn (search-forward verilog-exclude-str-end nil t)
2904 (point))))
2905 ;; Check if we're really inside a comment
2906 (if (or (equal start (point)) (<= end (point)))
2907 (message "Not standing within commented area.")
2908 (progn
2909 ;; Remove endcomment
2910 (goto-char end)
2911 (beginning-of-line)
2912 (let ((pos (point)))
2913 (end-of-line)
2914 (delete-region pos (1+ (point))))
2915 ;; Change comments back to normal
2916 (save-excursion
2917 (while (re-search-backward "\\*-/" start t)
2918 (replace-match "*/" t t)))
2919 (save-excursion
2920 (while (re-search-backward "/-\\*" start t)
2921 (replace-match "/*" t t)))
2922 ;; Remove start comment
2923 (goto-char start)
2924 (beginning-of-line)
2925 (let ((pos (point)))
2926 (end-of-line)
2927 (delete-region pos (1+ (point)))))))))
2928
2929 (defun verilog-beg-of-defun ()
2930 "Move backward to the beginning of the current function or procedure."
2931 (interactive)
2932 (verilog-re-search-backward verilog-defun-re nil 'move))
2933
2934 (defun verilog-end-of-defun ()
2935 "Move forward to the end of the current function or procedure."
2936 (interactive)
2937 (verilog-re-search-forward verilog-end-defun-re nil 'move))
2938
2939 (defun verilog-get-beg-of-defun (&optional warn)
2940 (save-excursion
2941 (cond ((verilog-re-search-forward-quick verilog-defun-re nil t)
2942 (point))
2943 (t
2944 (error "%s: Can't find module beginning" (verilog-point-text))
2945 (point-max)))))
2946 (defun verilog-get-end-of-defun (&optional warn)
2947 (save-excursion
2948 (cond ((verilog-re-search-forward-quick verilog-end-defun-re nil t)
2949 (point))
2950 (t
2951 (error "%s: Can't find endmodule" (verilog-point-text))
2952 (point-max)))))
2953
2954 (defun verilog-label-be (&optional arg)
2955 "Label matching begin ... end, fork ... join and case ... endcase statements.
2956 With ARG, first kill any existing labels."
2957 (interactive)
2958 (let ((cnt 0)
2959 (oldpos (point))
2960 (b (progn
2961 (verilog-beg-of-defun)
2962 (point-marker)))
2963 (e (progn
2964 (verilog-end-of-defun)
2965 (point-marker))))
2966 (goto-char (marker-position b))
2967 (if (> (- e b) 200)
2968 (message "Relabeling module..."))
2969 (while (and
2970 (> (marker-position e) (point))
2971 (verilog-re-search-forward
2972 (concat
2973 "\\<end\\(\\(function\\)\\|\\(task\\)\\|\\(module\\)\\|\\(primitive\\)\\|\\(interface\\)\\|\\(package\\)\\|\\(case\\)\\)?\\>"
2974 "\\|\\(`endif\\)\\|\\(`else\\)")
2975 nil 'move))
2976 (goto-char (match-beginning 0))
2977 (let ((indent-str (verilog-indent-line)))
2978 (verilog-set-auto-endcomments indent-str 't)
2979 (end-of-line)
2980 (delete-horizontal-space))
2981 (setq cnt (1+ cnt))
2982 (if (= 9 (% cnt 10))
2983 (message "%d..." cnt)))
2984 (goto-char oldpos)
2985 (if (or
2986 (> (- e b) 200)
2987 (> cnt 20))
2988 (message "%d lines auto commented" cnt))))
2989
2990 (defun verilog-beg-of-statement ()
2991 "Move backward to beginning of statement."
2992 (interactive)
2993 ;; Move back token by token until we see the end
2994 ;; of some ealier line.
2995 (while
2996 ;; If the current point does not begin a new
2997 ;; statement, as in the character ahead of us is a ';', or SOF
2998 ;; or the string after us unambiguosly starts a statement,
2999 ;; or the token before us unambiguously ends a statement,
3000 ;; then move back a token and test again.
3001 (not (or
3002 (bolp)
3003 (= (preceding-char) ?\;)
3004 (not (or
3005 (looking-at "\\<")
3006 (forward-word -1)))
3007 (and
3008 (looking-at verilog-extended-complete-re)
3009 (not (save-excursion
3010 (verilog-backward-token)
3011 (looking-at verilog-extended-complete-re))))
3012 (looking-at verilog-basic-complete-re)
3013 (save-excursion
3014 (verilog-backward-token)
3015 (or
3016 (looking-at verilog-end-block-re)
3017 (looking-at verilog-preprocessor-re)))))
3018 (verilog-backward-syntactic-ws)
3019 (verilog-backward-token))
3020 ;; Now point is where the previous line ended.
3021 (verilog-forward-syntactic-ws))
3022
3023 (defun verilog-beg-of-statement-1 ()
3024 "Move backward to beginning of statement."
3025 (interactive)
3026 (let ((pt (point)))
3027
3028 (while (and (not (looking-at verilog-complete-reg))
3029 (setq pt (point))
3030 (verilog-backward-token)
3031 (not (looking-at verilog-complete-reg))
3032 (verilog-backward-syntactic-ws)
3033 (setq pt (point))
3034 (not (bolp))
3035 (not (= (preceding-char) ?\;))))
3036 (goto-char pt)
3037 (verilog-forward-ws&directives)))
3038
3039 (defun verilog-end-of-statement ()
3040 "Move forward to end of current statement."
3041 (interactive)
3042 (let ((nest 0) pos)
3043 (or (looking-at verilog-beg-block-re)
3044 ;; Skip to end of statement
3045 (setq pos (catch 'found
3046 (while t
3047 (forward-sexp 1)
3048 (verilog-skip-forward-comment-or-string)
3049 (cond ((looking-at "[ \t]*;")
3050 (skip-chars-forward "^;")
3051 (forward-char 1)
3052 (throw 'found (point)))
3053 ((save-excursion
3054 (forward-sexp -1)
3055 (looking-at verilog-beg-block-re))
3056 (goto-char (match-beginning 0))
3057 (throw 'found nil))
3058 ((looking-at "[ \t]*)")
3059 (throw 'found (point)))
3060 ((eobp)
3061 (throw 'found (point))))))))
3062 (if (not pos)
3063 ;; Skip a whole block
3064 (catch 'found
3065 (while t
3066 (verilog-re-search-forward verilog-end-statement-re nil 'move)
3067 (setq nest (if (match-end 1)
3068 (1+ nest)
3069 (1- nest)))
3070 (cond ((eobp)
3071 (throw 'found (point)))
3072 ((= 0 nest)
3073 (throw 'found (verilog-end-of-statement))))))
3074 pos)))
3075
3076 (defun verilog-in-case-region-p ()
3077 "Return true if in a case region.
3078 More specifically, point @ in the line foo : @ begin"
3079 (interactive)
3080 (save-excursion
3081 (if (and
3082 (progn (verilog-forward-syntactic-ws)
3083 (looking-at "\\<begin\\>"))
3084 (progn (verilog-backward-syntactic-ws)
3085 (= (preceding-char) ?\:)))
3086 (catch 'found
3087 (let ((nest 1))
3088 (while t
3089 (verilog-re-search-backward
3090 (concat "\\(\\<module\\>\\)\\|\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|"
3091 "\\(\\<endcase\\>\\)\\>")
3092 nil 'move)
3093 (cond
3094 ((match-end 3)
3095 (setq nest (1+ nest)))
3096 ((match-end 2)
3097 (if (= nest 1)
3098 (throw 'found 1))
3099 (setq nest (1- nest)))
3100 (t
3101 (throw 'found (= nest 0)))))))
3102 nil)))
3103 (defun verilog-in-struct-region-p ()
3104 "Return true if in a struct region.
3105 More specifically, in a list after a struct|union keyword."
3106 (interactive)
3107 (save-excursion
3108 (let* ((state (verilog-syntax-ppss))
3109 (depth (nth 0 state)))
3110 (if depth
3111 (progn (backward-up-list depth)
3112 (verilog-beg-of-statement)
3113 (looking-at "\\<typedef\\>?\\s-*\\<struct\\|union\\>"))))))
3114
3115 (defun verilog-in-generate-region-p ()
3116 "Return true if in a generate region.
3117 More specifically, after a generate and before an endgenerate."
3118 (interactive)
3119 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
3120 (nest 1))
3121 (save-excursion
3122 (while (and
3123 (/= nest 0)
3124 (verilog-re-search-backward "\\<\\(generate\\)\\|\\(endgenerate\\)\\>" lim 'move)
3125 (cond
3126 ((match-end 1) ; generate
3127 (setq nest (1- nest)))
3128 ((match-end 2) ; endgenerate
3129 (setq nest (1+ nest)))))))
3130 (= nest 0) )) ; return nest
3131
3132 (defun verilog-in-fork-region-p ()
3133 "Return true if between a fork and join."
3134 (interactive)
3135 (let ((lim (save-excursion (verilog-beg-of-defun) (point)))
3136 (nest 1))
3137 (save-excursion
3138 (while (and
3139 (/= nest 0)
3140 (verilog-re-search-backward "\\<\\(fork\\)\\|\\(join\\(_any\\|_none\\)?\\)\\>" lim 'move)
3141 (cond
3142 ((match-end 1) ; fork
3143 (setq nest (1- nest)))
3144 ((match-end 2) ; join
3145 (setq nest (1+ nest)))))))
3146 (= nest 0) )) ; return nest
3147
3148 (defun verilog-backward-case-item (lim)
3149 "Skip backward to nearest enclosing case item.
3150 Limit search to point LIM."
3151 (interactive)
3152 (let ((str 'nil)
3153 (lim1
3154 (progn
3155 (save-excursion
3156 (verilog-re-search-backward verilog-endcomment-reason-re
3157 lim 'move)
3158 (point)))))
3159 ;; Try to find the real :
3160 (if (save-excursion (search-backward ":" lim1 t))
3161 (let ((colon 0)
3162 b e )
3163 (while
3164 (and
3165 (< colon 1)
3166 (verilog-re-search-backward "\\(\\[\\)\\|\\(\\]\\)\\|\\(:\\)"
3167 lim1 'move))
3168 (cond
3169 ((match-end 1) ;; [
3170 (setq colon (1+ colon))
3171 (if (>= colon 0)
3172 (error "%s: unbalanced [" (verilog-point-text))))
3173 ((match-end 2) ;; ]
3174 (setq colon (1- colon)))
3175
3176 ((match-end 3) ;; :
3177 (setq colon (1+ colon)))))
3178 ;; Skip back to beginning of case item
3179 (skip-chars-backward "\t ")
3180 (verilog-skip-backward-comment-or-string)
3181 (setq e (point))
3182 (setq b
3183 (progn
3184 (if
3185 (verilog-re-search-backward
3186 "\\<\\(case[zx]?\\)\\>\\|;\\|\\<end\\>" nil 'move)
3187 (progn
3188 (cond
3189 ((match-end 1)
3190 (goto-char (match-end 1))
3191 (verilog-forward-ws&directives)
3192 (if (looking-at "(")
3193 (progn
3194 (forward-sexp)
3195 (verilog-forward-ws&directives)))
3196 (point))
3197 (t
3198 (goto-char (match-end 0))
3199 (verilog-forward-ws&directives)
3200 (point))))
3201 (error "Malformed case item"))))
3202 (setq str (buffer-substring b e))
3203 (if
3204 (setq e
3205 (string-match
3206 "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3207 (setq str (concat (substring str 0 e) "...")))
3208 str)
3209 'nil)))
3210 \f
3211
3212 ;;
3213 ;; Other functions
3214 ;;
3215
3216 (defun verilog-kill-existing-comment ()
3217 "Kill auto comment on this line."
3218 (save-excursion
3219 (let* (
3220 (e (progn
3221 (end-of-line)
3222 (point)))
3223 (b (progn
3224 (beginning-of-line)
3225 (search-forward "//" e t))))
3226 (if b
3227 (delete-region (- b 2) e)))))
3228
3229 (defconst verilog-directive-nest-re
3230 (concat "\\(`else\\>\\)\\|"
3231 "\\(`endif\\>\\)\\|"
3232 "\\(`if\\>\\)\\|"
3233 "\\(`ifdef\\>\\)\\|"
3234 "\\(`ifndef\\>\\)"))
3235 (defun verilog-set-auto-endcomments (indent-str kill-existing-comment)
3236 "Add ending comment with given INDENT-STR.
3237 With KILL-EXISTING-COMMENT, remove what was there before.
3238 Insert `// case: 7 ' or `// NAME ' on this line if appropriate.
3239 Insert `// case expr ' if this line ends a case block.
3240 Insert `// ifdef FOO ' if this line ends code conditional on FOO.
3241 Insert `// NAME ' if this line ends a function, task, module,
3242 primitive or interface named NAME."
3243 (save-excursion
3244 (cond
3245 (; Comment close preprocessor directives
3246 (and
3247 (looking-at "\\(`endif\\)\\|\\(`else\\)")
3248 (or kill-existing-comment
3249 (not (save-excursion
3250 (end-of-line)
3251 (search-backward "//" (verilog-get-beg-of-line) t)))))
3252 (let ((nest 1) b e
3253 m
3254 (else (if (match-end 2) "!" " ")))
3255 (end-of-line)
3256 (if kill-existing-comment
3257 (verilog-kill-existing-comment))
3258 (delete-horizontal-space)
3259 (save-excursion
3260 (backward-sexp 1)
3261 (while (and (/= nest 0)
3262 (verilog-re-search-backward verilog-directive-nest-re nil 'move))
3263 (cond
3264 ((match-end 1) ; `else
3265 (if (= nest 1)
3266 (setq else "!")))
3267 ((match-end 2) ; `endif
3268 (setq nest (1+ nest)))
3269 ((match-end 3) ; `if
3270 (setq nest (1- nest)))
3271 ((match-end 4) ; `ifdef
3272 (setq nest (1- nest)))
3273 ((match-end 5) ; `ifndef
3274 (setq nest (1- nest)))))
3275 (if (match-end 0)
3276 (setq
3277 m (buffer-substring
3278 (match-beginning 0)
3279 (match-end 0))
3280 b (progn
3281 (skip-chars-forward "^ \t")
3282 (verilog-forward-syntactic-ws)
3283 (point))
3284 e (progn
3285 (skip-chars-forward "a-zA-Z0-9_")
3286 (point)))))
3287 (if b
3288 (if (> (count-lines (point) b) verilog-minimum-comment-distance)
3289 (insert (concat " // " else m " " (buffer-substring b e))))
3290 (progn
3291 (insert " // unmatched `else or `endif")
3292 (ding 't)))))
3293
3294 (; Comment close case/class/function/task/module and named block
3295 (and (looking-at "\\<end")
3296 (or kill-existing-comment
3297 (not (save-excursion
3298 (end-of-line)
3299 (search-backward "//" (verilog-get-beg-of-line) t)))))
3300 (let ((type (car indent-str)))
3301 (unless (eq type 'declaration)
3302 (unless (looking-at (concat "\\(" verilog-end-block-ordered-re "\\)[ \t]*:")) ;; ignore named ends
3303 (if (looking-at verilog-end-block-ordered-re)
3304 (cond
3305 (;- This is a case block; search back for the start of this case
3306 (match-end 1) ;; of verilog-end-block-ordered-re
3307
3308 (let ((err 't)
3309 (str "UNMATCHED!!"))
3310 (save-excursion
3311 (verilog-leap-to-head)
3312 (cond
3313 ((looking-at "\\<randcase\\>")
3314 (setq str "randcase")
3315 (setq err nil))
3316 ((match-end 0)
3317 (goto-char (match-end 1))
3318 (if nil
3319 (let (s f)
3320 (setq s (match-beginning 1))
3321 (setq f (progn (end-of-line)
3322 (point)))
3323 (setq str (buffer-substring s f)))
3324 (setq err nil))
3325 (setq str (concat (buffer-substring (match-beginning 1) (match-end 1))
3326 " "
3327 (verilog-get-expr))))))
3328 (end-of-line)
3329 (if kill-existing-comment
3330 (verilog-kill-existing-comment))
3331 (delete-horizontal-space)
3332 (insert (concat " // " str ))
3333 (if err (ding 't))))
3334
3335 (;- This is a begin..end block
3336 (match-end 2) ;; of verilog-end-block-ordered-re
3337 (let ((str " // UNMATCHED !!")
3338 (err 't)
3339 (here (point))
3340 there
3341 cntx)
3342 (save-excursion
3343 (verilog-leap-to-head)
3344 (setq there (point))
3345 (if (not (match-end 0))
3346 (progn
3347 (goto-char here)
3348 (end-of-line)
3349 (if kill-existing-comment
3350 (verilog-kill-existing-comment))
3351 (delete-horizontal-space)
3352 (insert str)
3353 (ding 't))
3354 (let ((lim
3355 (save-excursion (verilog-beg-of-defun) (point)))
3356 (here (point)))
3357 (cond
3358 (;-- handle named block differently
3359 (looking-at verilog-named-block-re)
3360 (search-forward ":")
3361 (setq there (point))
3362 (setq str (verilog-get-expr))
3363 (setq err nil)
3364 (setq str (concat " // block: " str )))
3365
3366 ((verilog-in-case-region-p) ;-- handle case item differently
3367 (goto-char here)
3368 (setq str (verilog-backward-case-item lim))
3369 (setq there (point))
3370 (setq err nil)
3371 (setq str (concat " // case: " str )))
3372
3373 (;- try to find "reason" for this begin
3374 (cond
3375 (;
3376 (eq here (progn
3377 (verilog-backward-token)
3378 (verilog-beg-of-statement-1)
3379 (point)))
3380 (setq err nil)
3381 (setq str ""))
3382 ((looking-at verilog-endcomment-reason-re)
3383 (setq there (match-end 0))
3384 (setq cntx (concat
3385 (buffer-substring (match-beginning 0) (match-end 0)) " "))
3386 (cond
3387 (;- begin
3388 (match-end 2)
3389 (setq err nil)
3390 (save-excursion
3391 (if (and (verilog-continued-line)
3392 (looking-at "\\<repeat\\>\\|\\<wait\\>\\|\\<always\\>"))
3393 (progn
3394 (goto-char (match-end 0))
3395 (setq there (point))
3396 (setq str
3397 (concat " // "
3398 (buffer-substring (match-beginning 0) (match-end 0)) " "
3399 (verilog-get-expr))))
3400 (setq str ""))))
3401
3402 (;- else
3403 (match-end 4)
3404 (let ((nest 0)
3405 ( reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
3406 (catch 'skip
3407 (while (verilog-re-search-backward reg nil 'move)
3408 (cond
3409 ((match-end 1) ; begin
3410 (setq nest (1- nest)))
3411 ((match-end 2) ; end
3412 (setq nest (1+ nest)))
3413 ((match-end 3)
3414 (if (= 0 nest)
3415 (progn
3416 (goto-char (match-end 0))
3417 (setq there (point))
3418 (setq err nil)
3419 (setq str (verilog-get-expr))
3420 (setq str (concat " // else: !if" str ))
3421 (throw 'skip 1)))))))))
3422
3423 (;- end else
3424 (match-end 5)
3425 (goto-char there)
3426 (let ((nest 0)
3427 (reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|\\(\\<if\\>\\)"))
3428 (catch 'skip
3429 (while (verilog-re-search-backward reg nil 'move)
3430 (cond
3431 ((match-end 1) ; begin
3432 (setq nest (1- nest)))
3433 ((match-end 2) ; end
3434 (setq nest (1+ nest)))
3435 ((match-end 3)
3436 (if (= 0 nest)
3437 (progn
3438 (goto-char (match-end 0))
3439 (setq there (point))
3440 (setq err nil)
3441 (setq str (verilog-get-expr))
3442 (setq str (concat " // else: !if" str ))
3443 (throw 'skip 1)))))))))
3444
3445 (;- task/function/initial et cetera
3446 t
3447 (match-end 0)
3448 (goto-char (match-end 0))
3449 (setq there (point))
3450 (setq err nil)
3451 (setq str (verilog-get-expr))
3452 (setq str (concat " // " cntx str )))
3453
3454 (;-- otherwise...
3455 (setq str " // auto-endcomment confused "))))
3456
3457 ((and
3458 (verilog-in-case-region-p) ;-- handle case item differently
3459 (progn
3460 (setq there (point))
3461 (goto-char here)
3462 (setq str (verilog-backward-case-item lim))))
3463 (setq err nil)
3464 (setq str (concat " // case: " str )))
3465
3466 ((verilog-in-fork-region-p)
3467 (setq err nil)
3468 (setq str " // fork branch" ))
3469
3470 ((looking-at "\\<end\\>")
3471 ;; HERE
3472 (forward-word 1)
3473 (verilog-forward-syntactic-ws)
3474 (setq err nil)
3475 (setq str (verilog-get-expr))
3476 (setq str (concat " // " cntx str )))
3477
3478 ))))
3479 (goto-char here)
3480 (end-of-line)
3481 (if kill-existing-comment
3482 (verilog-kill-existing-comment))
3483 (delete-horizontal-space)
3484 (if (or err
3485 (> (count-lines here there) verilog-minimum-comment-distance))
3486 (insert str))
3487 (if err (ding 't))
3488 ))))
3489 (;- this is endclass, which can be nested
3490 (match-end 11) ;; of verilog-end-block-ordered-re
3491 ;;(goto-char there)
3492 (let ((nest 0)
3493 (reg "\\<\\(class\\)\\|\\(endclass\\)\\|\\(package\\|primitive\\|\\(macro\\)?module\\)\\>")
3494 string)
3495 (save-excursion
3496 (catch 'skip
3497 (while (verilog-re-search-backward reg nil 'move)
3498 (cond
3499 ((match-end 3) ; endclass
3500 (ding 't)
3501 (setq string "unmatched endclass")
3502 (throw 'skip 1))
3503
3504 ((match-end 2) ; endclass
3505 (setq nest (1+ nest)))
3506
3507 ((match-end 1) ; class
3508 (setq nest (1- nest))
3509 (if (< nest 0)
3510 (progn
3511 (goto-char (match-end 0))
3512 (let (b e)
3513 (setq b (progn
3514 (skip-chars-forward "^ \t")
3515 (verilog-forward-ws&directives)
3516 (point))
3517 e (progn
3518 (skip-chars-forward "a-zA-Z0-9_")
3519 (point)))
3520 (setq string (buffer-substring b e)))
3521 (throw 'skip 1))))
3522 ))))
3523 (end-of-line)
3524 (insert (concat " // " string ))))
3525
3526 (;- this is end{function,generate,task,module,primitive,table,generate}
3527 ;- which can not be nested.
3528 t
3529 (let (string reg (name-re nil))
3530 (end-of-line)
3531 (if kill-existing-comment
3532 (save-match-data
3533 (verilog-kill-existing-comment)))
3534 (delete-horizontal-space)
3535 (backward-sexp)
3536 (cond
3537 ((match-end 5) ;; of verilog-end-block-ordered-re
3538 (setq reg "\\(\\<function\\>\\)\\|\\(\\<\\(endfunction\\|task\\|\\(macro\\)?module\\|primitive\\)\\>\\)")
3539 (setq name-re "\\w+\\s-*(")
3540 )
3541 ((match-end 6) ;; of verilog-end-block-ordered-re
3542 (setq reg "\\(\\<task\\>\\)\\|\\(\\<\\(endtask\\|function\\|\\(macro\\)?module\\|primitive\\)\\>\\)"))
3543 ((match-end 7) ;; of verilog-end-block-ordered-re
3544 (setq reg "\\(\\<\\(macro\\)?module\\>\\)\\|\\<endmodule\\>"))
3545 ((match-end 8) ;; of verilog-end-block-ordered-re
3546 (setq reg "\\(\\<primitive\\>\\)\\|\\(\\<\\(endprimitive\\|package\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3547 ((match-end 9) ;; of verilog-end-block-ordered-re
3548 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<\\(endinterface\\|package\\|primitive\\|\\(macro\\)?module\\)\\>\\)"))
3549 ((match-end 10) ;; of verilog-end-block-ordered-re
3550 (setq reg "\\(\\<package\\>\\)\\|\\(\\<\\(endpackage\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3551 ((match-end 11) ;; of verilog-end-block-ordered-re
3552 (setq reg "\\(\\<class\\>\\)\\|\\(\\<\\(endclass\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3553 ((match-end 12) ;; of verilog-end-block-ordered-re
3554 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<\\(endcovergroup\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3555 ((match-end 13) ;; of verilog-end-block-ordered-re
3556 (setq reg "\\(\\<program\\>\\)\\|\\(\\<\\(endprogram\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3557 ((match-end 14) ;; of verilog-end-block-ordered-re
3558 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<\\(endsequence\\|primitive\\|interface\\|\\(macro\\)?module\\)\\>\\)"))
3559 ((match-end 15) ;; of verilog-end-block-ordered-re
3560 (setq reg "\\(\\<clocking\\>\\)\\|\\<endclocking\\>"))
3561
3562 (t (error "Problem in verilog-set-auto-endcomments")))
3563 (let (b e)
3564 (save-excursion
3565 (verilog-re-search-backward reg nil 'move)
3566 (cond
3567 ((match-end 1)
3568 (setq b (progn
3569 (skip-chars-forward "^ \t")
3570 (verilog-forward-ws&directives)
3571 (if (and name-re (verilog-re-search-forward name-re nil 'move))
3572 (progn
3573 (goto-char (match-beginning 0))
3574 (verilog-forward-ws&directives)))
3575 (point))
3576 e (progn
3577 (skip-chars-forward "a-zA-Z0-9_")
3578 (point)))
3579 (setq string (buffer-substring b e)))
3580 (t
3581 (ding 't)
3582 (setq string "unmatched end(function|task|module|primitive|interface|package|class|clocking)")))))
3583 (end-of-line)
3584 (insert (concat " // " string )))
3585 ))))))))))
3586
3587 (defun verilog-get-expr()
3588 "Grab expression at point, e.g, case ( a | b & (c ^d))."
3589 (let* ((b (progn
3590 (verilog-forward-syntactic-ws)
3591 (skip-chars-forward " \t")
3592 (point)))
3593 (e (let ((par 1))
3594 (cond
3595 ((looking-at "@")
3596 (forward-char 1)
3597 (verilog-forward-syntactic-ws)
3598 (if (looking-at "(")
3599 (progn
3600 (forward-char 1)
3601 (while (and (/= par 0)
3602 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3603 (cond
3604 ((match-end 1)
3605 (setq par (1+ par)))
3606 ((match-end 2)
3607 (setq par (1- par)))))))
3608 (point))
3609 ((looking-at "(")
3610 (forward-char 1)
3611 (while (and (/= par 0)
3612 (verilog-re-search-forward "\\((\\)\\|\\()\\)" nil 'move))
3613 (cond
3614 ((match-end 1)
3615 (setq par (1+ par)))
3616 ((match-end 2)
3617 (setq par (1- par)))))
3618 (point))
3619 ((looking-at "\\[")
3620 (forward-char 1)
3621 (while (and (/= par 0)
3622 (verilog-re-search-forward "\\(\\[\\)\\|\\(\\]\\)" nil 'move))
3623 (cond
3624 ((match-end 1)
3625 (setq par (1+ par)))
3626 ((match-end 2)
3627 (setq par (1- par)))))
3628 (verilog-forward-syntactic-ws)
3629 (skip-chars-forward "^ \t\n\f")
3630 (point))
3631 ((looking-at "/[/\\*]")
3632 b)
3633 ('t
3634 (skip-chars-forward "^: \t\n\f")
3635 (point)))))
3636 (str (buffer-substring b e)))
3637 (if (setq e (string-match "[ \t]*\\(\\(\n\\)\\|\\(//\\)\\|\\(/\\*\\)\\)" str))
3638 (setq str (concat (substring str 0 e) "...")))
3639 str))
3640
3641 (defun verilog-expand-vector ()
3642 "Take a signal vector on the current line and expand it to multiple lines.
3643 Useful for creating tri's and other expanded fields."
3644 (interactive)
3645 (verilog-expand-vector-internal "[" "]"))
3646
3647 (defun verilog-expand-vector-internal (bra ket)
3648 "Given BRA, the start brace and KET, the end brace, expand one line into many lines."
3649 (save-excursion
3650 (forward-line 0)
3651 (let ((signal-string (buffer-substring (point)
3652 (progn
3653 (end-of-line) (point)))))
3654 (if (string-match
3655 (concat "\\(.*\\)"
3656 (regexp-quote bra)
3657 "\\([0-9]*\\)\\(:[0-9]*\\|\\)\\(::[0-9---]*\\|\\)"
3658 (regexp-quote ket)
3659 "\\(.*\\)$") signal-string)
3660 (let* ((sig-head (match-string 1 signal-string))
3661 (vec-start (string-to-number (match-string 2 signal-string)))
3662 (vec-end (if (= (match-beginning 3) (match-end 3))
3663 vec-start
3664 (string-to-number
3665 (substring signal-string (1+ (match-beginning 3))
3666 (match-end 3)))))
3667 (vec-range
3668 (if (= (match-beginning 4) (match-end 4))
3669 1
3670 (string-to-number
3671 (substring signal-string (+ 2 (match-beginning 4))
3672 (match-end 4)))))
3673 (sig-tail (match-string 5 signal-string))
3674 vec)
3675 ;; Decode vectors
3676 (setq vec nil)
3677 (if (< vec-range 0)
3678 (let ((tmp vec-start))
3679 (setq vec-start vec-end
3680 vec-end tmp
3681 vec-range (- vec-range))))
3682 (if (< vec-end vec-start)
3683 (while (<= vec-end vec-start)
3684 (setq vec (append vec (list vec-start)))
3685 (setq vec-start (- vec-start vec-range)))
3686 (while (<= vec-start vec-end)
3687 (setq vec (append vec (list vec-start)))
3688 (setq vec-start (+ vec-start vec-range))))
3689 ;;
3690 ;; Delete current line
3691 (delete-region (point) (progn (forward-line 0) (point)))
3692 ;;
3693 ;; Expand vector
3694 (while vec
3695 (insert (concat sig-head bra
3696 (int-to-string (car vec)) ket sig-tail "\n"))
3697 (setq vec (cdr vec)))
3698 (delete-char -1)
3699 ;;
3700 )))))
3701
3702 (defun verilog-strip-comments ()
3703 "Strip all comments from the Verilog code."
3704 (interactive)
3705 (goto-char (point-min))
3706 (while (re-search-forward "//" nil t)
3707 (if (verilog-within-string)
3708 (re-search-forward "\"" nil t)
3709 (if (verilog-in-star-comment-p)
3710 (re-search-forward "\*/" nil t)
3711 (let ((bpt (- (point) 2)))
3712 (end-of-line)
3713 (delete-region bpt (point))))))
3714 ;;
3715 (goto-char (point-min))
3716 (while (re-search-forward "/\\*" nil t)
3717 (if (verilog-within-string)
3718 (re-search-forward "\"" nil t)
3719 (let ((bpt (- (point) 2)))
3720 (re-search-forward "\\*/")
3721 (delete-region bpt (point))))))
3722
3723 (defun verilog-one-line ()
3724 "Convert structural Verilog instances to occupy one line."
3725 (interactive)
3726 (goto-char (point-min))
3727 (while (re-search-forward "\\([^;]\\)[ \t]*\n[ \t]*" nil t)
3728 (replace-match "\\1 " nil nil)))
3729
3730 (defun verilog-linter-name ()
3731 "Return name of linter, either surelint or verilint."
3732 (let ((compile-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
3733 compile-command))
3734 (lint-word1 (verilog-string-replace-matches "\\s .*$" "" nil nil
3735 verilog-linter)))
3736 (cond ((equal compile-word1 "surelint") `surelint)
3737 ((equal compile-word1 "verilint") `verilint)
3738 ((equal lint-word1 "surelint") `surelint)
3739 ((equal lint-word1 "verilint") `verilint)
3740 (t `surelint)))) ;; back compatibility
3741
3742 (defun verilog-lint-off ()
3743 "Convert a Verilog linter warning line into a disable statement.
3744 For example:
3745 pci_bfm_null.v, line 46: Unused input: pci_rst_
3746 becomes a comment for the appropriate tool.
3747
3748 The first word of the `compile-command' or `verilog-linter'
3749 variables is used to determine which product is being used.
3750
3751 See \\[verilog-surelint-off] and \\[verilog-verilint-off]."
3752 (interactive)
3753 (let ((linter (verilog-linter-name)))
3754 (cond ((equal linter `surelint)
3755 (verilog-surelint-off))
3756 ((equal linter `verilint)
3757 (verilog-verilint-off))
3758 (t (error "Linter name not set")))))
3759
3760 (defvar compilation-last-buffer)
3761
3762 (defun verilog-surelint-off ()
3763 "Convert a SureLint warning line into a disable statement.
3764 Run from Verilog source window; assumes there is a *compile* buffer
3765 with point set appropriately.
3766
3767 For example:
3768 WARNING [STD-UDDONX]: xx.v, line 8: output out is never assigned.
3769 becomes:
3770 // surefire lint_line_off UDDONX"
3771 (interactive)
3772 (let ((buff (if (boundp 'next-error-last-buffer)
3773 next-error-last-buffer
3774 compilation-last-buffer)))
3775 (when (buffer-live-p buff)
3776 ;; FIXME with-current-buffer?
3777 (save-excursion
3778 (switch-to-buffer buff)
3779 (beginning-of-line)
3780 (when
3781 (looking-at "\\(INFO\\|WARNING\\|ERROR\\) \\[[^-]+-\\([^]]+\\)\\]: \\([^,]+\\), line \\([0-9]+\\): \\(.*\\)$")
3782 (let* ((code (match-string 2))
3783 (file (match-string 3))
3784 (line (match-string 4))
3785 (buffer (get-file-buffer file))
3786 dir filename)
3787 (unless buffer
3788 (progn
3789 (setq buffer
3790 (and (file-exists-p file)
3791 (find-file-noselect file)))
3792 (or buffer
3793 (let* ((pop-up-windows t))
3794 (let ((name (expand-file-name
3795 (read-file-name
3796 (format "Find this error in: (default %s) "
3797 file)
3798 dir file t))))
3799 (if (file-directory-p name)
3800 (setq name (expand-file-name filename name)))
3801 (setq buffer
3802 (and (file-exists-p name)
3803 (find-file-noselect name))))))))
3804 (switch-to-buffer buffer)
3805 (goto-line (string-to-number line))
3806 (end-of-line)
3807 (catch 'already
3808 (cond
3809 ((verilog-in-slash-comment-p)
3810 (re-search-backward "//")
3811 (cond
3812 ((looking-at "// surefire lint_off_line ")
3813 (goto-char (match-end 0))
3814 (let ((lim (save-excursion (end-of-line) (point))))
3815 (if (re-search-forward code lim 'move)
3816 (throw 'already t)
3817 (insert (concat " " code)))))
3818 (t
3819 )))
3820 ((verilog-in-star-comment-p)
3821 (re-search-backward "/\*")
3822 (insert (format " // surefire lint_off_line %6s" code )))
3823 (t
3824 (insert (format " // surefire lint_off_line %6s" code ))
3825 )))))))))
3826
3827 (defun verilog-verilint-off ()
3828 "Convert a Verilint warning line into a disable statement.
3829
3830 For example:
3831 (W240) pci_bfm_null.v, line 46: Unused input: pci_rst_
3832 becomes:
3833 //Verilint 240 off // WARNING: Unused input"
3834 (interactive)
3835 (save-excursion
3836 (beginning-of-line)
3837 (when (looking-at "\\(.*\\)([WE]\\([0-9A-Z]+\\)).*,\\s +line\\s +[0-9]+:\\s +\\([^:\n]+\\):?.*$")
3838 (replace-match (format
3839 ;; %3s makes numbers 1-999 line up nicely
3840 "\\1//Verilint %3s off // WARNING: \\3"
3841 (match-string 2)))
3842 (beginning-of-line)
3843 (verilog-indent-line))))
3844
3845 (defun verilog-auto-save-compile ()
3846 "Update automatics with \\[verilog-auto], save the buffer, and compile."
3847 (interactive)
3848 (verilog-auto) ; Always do it for safety
3849 (save-buffer)
3850 (compile compile-command))
3851
3852 \f
3853
3854 ;;
3855 ;; Batch
3856 ;;
3857
3858 (defmacro verilog-batch-error-wrapper (&rest body)
3859 "Execute BODY and add error prefix to any errors found.
3860 This lets programs calling batch mode to easily extract error messages."
3861 `(condition-case err
3862 (progn ,@body)
3863 (error
3864 (error "%%Error: %s%s" (error-message-string err)
3865 (if (featurep 'xemacs) "\n" ""))))) ;; XEmacs forgets to add a newline
3866
3867 (defun verilog-batch-execute-func (funref)
3868 "Internal processing of a batch command, running FUNREF on all command arguments."
3869 (verilog-batch-error-wrapper
3870 ;; General globals needed
3871 (setq make-backup-files nil)
3872 (setq-default make-backup-files nil)
3873 (setq enable-local-variables t)
3874 (setq enable-local-eval t)
3875 ;; Make sure any sub-files we read get proper mode
3876 (setq default-major-mode `verilog-mode)
3877 ;; Ditto files already read in
3878 (mapc (lambda (buf)
3879 (when (buffer-file-name buf)
3880 (save-excursion
3881 (set-buffer buf)
3882 (verilog-mode))))
3883 (buffer-list))
3884 ;; Process the files
3885 (mapcar '(lambda (buf)
3886 (when (buffer-file-name buf)
3887 (save-excursion
3888 (if (not (file-exists-p (buffer-file-name buf)))
3889 (error
3890 (concat "File not found: " (buffer-file-name buf))))
3891 (message (concat "Processing " (buffer-file-name buf)))
3892 (set-buffer buf)
3893 (funcall funref)
3894 (save-buffer))))
3895 (buffer-list))))
3896
3897 (defun verilog-batch-auto ()
3898 "For use with --batch, perform automatic expansions as a stand-alone tool.
3899 This sets up the appropriate Verilog mode environment, updates automatics
3900 with \\[verilog-auto] on all command-line files, and saves the buffers.
3901 For proper results, multiple filenames need to be passed on the command
3902 line in bottom-up order."
3903 (unless noninteractive
3904 (error "Use verilog-batch-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
3905 (verilog-batch-execute-func `verilog-auto))
3906
3907 (defun verilog-batch-delete-auto ()
3908 "For use with --batch, perform automatic deletion as a stand-alone tool.
3909 This sets up the appropriate Verilog mode environment, deletes automatics
3910 with \\[verilog-delete-auto] on all command-line files, and saves the buffers."
3911 (unless noninteractive
3912 (error "Use verilog-batch-delete-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
3913 (verilog-batch-execute-func `verilog-delete-auto))
3914
3915 (defun verilog-batch-inject-auto ()
3916 "For use with --batch, perform automatic injection as a stand-alone tool.
3917 This sets up the appropriate Verilog mode environment, injects new automatics
3918 with \\[verilog-inject-auto] on all command-line files, and saves the buffers.
3919 For proper results, multiple filenames need to be passed on the command
3920 line in bottom-up order."
3921 (unless noninteractive
3922 (error "Use verilog-batch-inject-auto only with --batch")) ;; Otherwise we'd mess up buffer modes
3923 (verilog-batch-execute-func `verilog-inject-auto))
3924
3925 (defun verilog-batch-indent ()
3926 "For use with --batch, reindent an a entire file as a stand-alone tool.
3927 This sets up the appropriate Verilog mode environment, calls
3928 \\[verilog-indent-buffer] on all command-line files, and saves the buffers."
3929 (unless noninteractive
3930 (error "Use verilog-batch-indent only with --batch")) ;; Otherwise we'd mess up buffer modes
3931 (verilog-batch-execute-func `verilog-indent-buffer))
3932 \f
3933
3934 ;;
3935 ;; Indentation
3936 ;;
3937 (defconst verilog-indent-alist
3938 '((block . (+ ind verilog-indent-level))
3939 (case . (+ ind verilog-case-indent))
3940 (cparenexp . (+ ind verilog-indent-level))
3941 (cexp . (+ ind verilog-cexp-indent))
3942 (defun . verilog-indent-level-module)
3943 (declaration . verilog-indent-level-declaration)
3944 (directive . (verilog-calculate-indent-directive))
3945 (tf . verilog-indent-level)
3946 (behavioral . (+ verilog-indent-level-behavioral verilog-indent-level-module))
3947 (statement . ind)
3948 (cpp . 0)
3949 (comment . (verilog-comment-indent))
3950 (unknown . 3)
3951 (string . 0)))
3952
3953 (defun verilog-continued-line-1 (lim)
3954 "Return true if this is a continued line.
3955 Set point to where line starts. Limit search to point LIM."
3956 (let ((continued 't))
3957 (if (eq 0 (forward-line -1))
3958 (progn
3959 (end-of-line)
3960 (verilog-backward-ws&directives lim)
3961 (if (bobp)
3962 (setq continued nil)
3963 (setq continued (verilog-backward-token))))
3964 (setq continued nil))
3965 continued))
3966
3967 (defun verilog-calculate-indent ()
3968 "Calculate the indent of the current Verilog line.
3969 Examine previous lines. Once a line is found that is definitive as to the
3970 type of the current line, return that lines' indent level and its type.
3971 Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
3972 (save-excursion
3973 (let* ((starting_position (point))
3974 (par 0)
3975 (begin (looking-at "[ \t]*begin\\>"))
3976 (lim (save-excursion (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)" nil t)))
3977 (type (catch 'nesting
3978 ;; Keep working backwards until we can figure out
3979 ;; what type of statement this is.
3980 ;; Basically we need to figure out
3981 ;; 1) if this is a continuation of the previous line;
3982 ;; 2) are we in a block scope (begin..end)
3983
3984 ;; if we are in a comment, done.
3985 (if (verilog-in-star-comment-p)
3986 (throw 'nesting 'comment))
3987
3988 ;; if we have a directive, done.
3989 (if (save-excursion (beginning-of-line) (looking-at verilog-directive-re-1))
3990 (throw 'nesting 'directive))
3991
3992 ;; unless we are in the newfangled coverpoint or constraint blocks
3993 ;; if we are in a parenthesized list, and the user likes to indent these, return.
3994 (if (and
3995 verilog-indent-lists
3996 (not (verilog-in-coverage))
3997 (verilog-in-paren))
3998 (progn (setq par 1)
3999 (throw 'nesting 'block)))
4000
4001 ;; See if we are continuing a previous line
4002 (while t
4003 ;; trap out if we crawl off the top of the buffer
4004 (if (bobp) (throw 'nesting 'cpp))
4005
4006 (if (verilog-continued-line-1 lim)
4007 (let ((sp (point)))
4008 (if (and
4009 (not (looking-at verilog-complete-reg))
4010 (verilog-continued-line-1 lim))
4011 (progn (goto-char sp)
4012 (throw 'nesting 'cexp))
4013
4014 (goto-char sp))
4015
4016 (if (and begin
4017 (not verilog-indent-begin-after-if)
4018 (looking-at verilog-no-indent-begin-re))
4019 (progn
4020 (beginning-of-line)
4021 (skip-chars-forward " \t")
4022 (throw 'nesting 'statement))
4023 (progn
4024 (throw 'nesting 'cexp))))
4025 ;; not a continued line
4026 (goto-char starting_position))
4027
4028 (if (looking-at "\\<else\\>")
4029 ;; search back for governing if, striding across begin..end pairs
4030 ;; appropriately
4031 (let ((elsec 1))
4032 (while (verilog-re-search-backward verilog-ends-re nil 'move)
4033 (cond
4034 ((match-end 1) ; else, we're in deep
4035 (setq elsec (1+ elsec)))
4036 ((match-end 2) ; if
4037 (setq elsec (1- elsec))
4038 (if (= 0 elsec)
4039 (if verilog-align-ifelse
4040 (throw 'nesting 'statement)
4041 (progn ;; back up to first word on this line
4042 (beginning-of-line)
4043 (verilog-forward-syntactic-ws)
4044 (throw 'nesting 'statement)))))
4045 (t ; endblock
4046 ; try to leap back to matching outward block by striding across
4047 ; indent level changing tokens then immediately
4048 ; previous line governs indentation.
4049 (let (( reg) (nest 1))
4050 ;; verilog-ends => else|if|end|join(_any|_none|)|endcase|endclass|endtable|endspecify|endfunction|endtask|endgenerate|endgroup
4051 (cond
4052 ((match-end 3) ; end
4053 ;; Search back for matching begin
4054 (setq reg "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)" ))
4055 ((match-end 4) ; endcase
4056 ;; Search back for matching case
4057 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4058 ((match-end 5) ; endfunction
4059 ;; Search back for matching function
4060 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4061 ((match-end 6) ; endtask
4062 ;; Search back for matching task
4063 (setq reg "\\(\\<task\\>\\)\\|\\(\\<endtask\\>\\)" ))
4064 ((match-end 7) ; endspecify
4065 ;; Search back for matching specify
4066 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4067 ((match-end 8) ; endtable
4068 ;; Search back for matching table
4069 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4070 ((match-end 9) ; endgenerate
4071 ;; Search back for matching generate
4072 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4073 ((match-end 10) ; joins
4074 ;; Search back for matching fork
4075 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|none\\)?\\>\\)" ))
4076 ((match-end 11) ; class
4077 ;; Search back for matching class
4078 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4079 ((match-end 12) ; covergroup
4080 ;; Search back for matching covergroup
4081 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" )))
4082 (catch 'skip
4083 (while (verilog-re-search-backward reg nil 'move)
4084 (cond
4085 ((match-end 1) ; begin
4086 (setq nest (1- nest))
4087 (if (= 0 nest)
4088 (throw 'skip 1)))
4089 ((match-end 2) ; end
4090 (setq nest (1+ nest)))))
4091 )))))))
4092 (throw 'nesting (verilog-calc-1)))
4093 );; catch nesting
4094 );; type
4095 )
4096 ;; Return type of block and indent level.
4097 (if (not type)
4098 (setq type 'cpp))
4099 (if (> par 0) ; Unclosed Parenthesis
4100 (list 'cparenexp par)
4101 (cond
4102 ((eq type 'case)
4103 (list type (verilog-case-indent-level)))
4104 ((eq type 'statement)
4105 (list type (current-column)))
4106 ((eq type 'defun)
4107 (list type 0))
4108 (t
4109 (list type (verilog-current-indent-level))))))))
4110
4111 (defun verilog-wai ()
4112 "Show matching nesting block for debugging."
4113 (interactive)
4114 (save-excursion
4115 (let* ((type (verilog-calc-1))
4116 depth)
4117 ;; Return type of block and indent level.
4118 (if (not type)
4119 (setq type 'cpp))
4120 (if (and
4121 verilog-indent-lists
4122 (not (verilog-in-coverage))
4123 (verilog-in-paren))
4124 (setq depth 1)
4125 (cond
4126 ((eq type 'case)
4127 (setq depth (verilog-case-indent-level)))
4128 ((eq type 'statement)
4129 (setq depth (current-column)))
4130 ((eq type 'defun)
4131 (setq depth 0))
4132 (t
4133 (setq depth (verilog-current-indent-level)))))
4134 (message "You are at nesting %s depth %d" type depth))))
4135
4136 (defun verilog-calc-1 ()
4137 (catch 'nesting
4138 (while (verilog-re-search-backward (concat "\\({\\|}\\|" verilog-indent-re "\\)") nil 'move)
4139 (cond
4140 ((equal (char-after) ?\{)
4141 (if (verilog-at-constraint-p)
4142 (throw 'nesting 'block)))
4143 ((equal (char-after) ?\})
4144
4145 (let ((there (verilog-at-close-constraint-p)))
4146 (if there (goto-char there))))
4147
4148 ((looking-at verilog-beg-block-re-ordered)
4149 (cond
4150 ((match-end 2) ; *sigh* could be "unique case" or "priority casex"
4151 (let ((here (point)))
4152 (verilog-beg-of-statement)
4153 (if (looking-at verilog-extended-case-re)
4154 (throw 'nesting 'case)
4155 (goto-char here)))
4156 (throw 'nesting 'case))
4157
4158 ((match-end 4) ; *sigh* could be "disable fork"
4159 (let ((here (point)))
4160 (verilog-beg-of-statement)
4161 (if (looking-at verilog-disable-fork-re)
4162 t ; is disable fork, this is a normal statement
4163 (progn ; or is fork, starts a new block
4164 (goto-char here)
4165 (throw 'nesting 'block)))))
4166
4167
4168 ;; need to consider typedef struct here...
4169 ((looking-at "\\<class\\|struct\\|function\\|task\\|property\\>")
4170 ; *sigh* These words have an optional prefix:
4171 ; extern {virtual|protected}? function a();
4172 ; assert property (p_1);
4173 ; typedef class foo;
4174 ; and we don't want to confuse this with
4175 ; function a();
4176 ; property
4177 ; ...
4178 ; endfunction
4179 (verilog-beg-of-statement)
4180 (if (looking-at verilog-beg-block-re-ordered)
4181 (throw 'nesting 'block)
4182 (throw 'nesting 'defun)))
4183
4184 (t (throw 'nesting 'block))))
4185
4186 ((looking-at verilog-end-block-re)
4187 (verilog-leap-to-head)
4188 (if (verilog-in-case-region-p)
4189 (progn
4190 (verilog-leap-to-case-head)
4191 (if (looking-at verilog-case-re)
4192 (throw 'nesting 'case)))))
4193
4194 ((looking-at (if (verilog-in-generate-region-p)
4195 verilog-defun-level-not-generate-re
4196 verilog-defun-level-re))
4197 (throw 'nesting 'defun))
4198
4199 ((looking-at verilog-cpp-level-re)
4200 (throw 'nesting 'cpp))
4201
4202 ((bobp)
4203 (throw 'nesting 'cpp))))
4204 (throw 'nesting 'cpp)))
4205
4206 (defun verilog-calculate-indent-directive ()
4207 "Return indentation level for directive.
4208 For speed, the searcher looks at the last directive, not the indent
4209 of the appropriate enclosing block."
4210 (let ((base -1) ;; Indent of the line that determines our indentation
4211 (ind 0)) ;; Relative offset caused by other directives (like `endif on same line as `else)
4212 ;; Start at current location, scan back for another directive
4213
4214 (save-excursion
4215 (beginning-of-line)
4216 (while (and (< base 0)
4217 (verilog-re-search-backward verilog-directive-re nil t))
4218 (cond ((save-excursion (skip-chars-backward " \t") (bolp))
4219 (setq base (current-indentation))))
4220 (cond ((and (looking-at verilog-directive-end) (< base 0)) ;; Only matters when not at BOL
4221 (setq ind (- ind verilog-indent-level-directive)))
4222 ((and (looking-at verilog-directive-middle) (>= base 0)) ;; Only matters when at BOL
4223 (setq ind (+ ind verilog-indent-level-directive)))
4224 ((looking-at verilog-directive-begin)
4225 (setq ind (+ ind verilog-indent-level-directive)))))
4226 ;; Adjust indent to starting indent of critical line
4227 (setq ind (max 0 (+ ind base))))
4228
4229 (save-excursion
4230 (beginning-of-line)
4231 (skip-chars-forward " \t")
4232 (cond ((or (looking-at verilog-directive-middle)
4233 (looking-at verilog-directive-end))
4234 (setq ind (max 0 (- ind verilog-indent-level-directive))))))
4235 ind))
4236
4237 (defun verilog-leap-to-case-head ()
4238 (let ((nest 1))
4239 (while (/= 0 nest)
4240 (verilog-re-search-backward "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" nil 'move)
4241 (cond
4242 ((match-end 1)
4243 (setq nest (1- nest)))
4244 ((match-end 2)
4245 (setq nest (1+ nest)))
4246 ((bobp)
4247 (ding 't)
4248 (setq nest 0))))))
4249
4250 (defun verilog-leap-to-head ()
4251 "Move point to the head of this block.
4252 Jump from end to matching begin, from endcase to matching case, and so on."
4253 (let ((reg nil)
4254 snest
4255 (nesting 'yes)
4256 (nest 1))
4257 (cond
4258 ((looking-at "\\<end\\>")
4259 ;; 1: Search back for matching begin
4260 (setq reg (concat "\\(\\<begin\\>\\)\\|\\(\\<end\\>\\)\\|"
4261 "\\(\\<endcase\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" )))
4262 ((looking-at "\\<endtask\\>")
4263 ;; 9: Search back for matching task
4264 (setq reg "\\(\\<task\\>\\)\\|\\(\\(\\(\\<virtual\\>\\s-+\\)\\|\\(\\<protected\\>\\s-+\\)\\)+\\<task\\>\\)")
4265 (setq nesting 'no))
4266 ((looking-at "\\<endcase\\>")
4267 ;; 2: Search back for matching case
4268 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>\\)\\|\\(\\<endcase\\>\\)" ))
4269 ((looking-at "\\<join\\(_any\\|_none\\)?\\>")
4270 ;; 3: Search back for matching fork
4271 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4272 ((looking-at "\\<endclass\\>")
4273 ;; 4: Search back for matching class
4274 (setq reg "\\(\\<class\\>\\)\\|\\(\\<endclass\\>\\)" ))
4275 ((looking-at "\\<endtable\\>")
4276 ;; 5: Search back for matching table
4277 (setq reg "\\(\\<table\\>\\)\\|\\(\\<endtable\\>\\)" ))
4278 ((looking-at "\\<endspecify\\>")
4279 ;; 6: Search back for matching specify
4280 (setq reg "\\(\\<specify\\>\\)\\|\\(\\<endspecify\\>\\)" ))
4281 ((looking-at "\\<endfunction\\>")
4282 ;; 7: Search back for matching function
4283 (setq reg "\\(\\<function\\>\\)\\|\\(\\<endfunction\\>\\)" ))
4284 ((looking-at "\\<endgenerate\\>")
4285 ;; 8: Search back for matching generate
4286 (setq reg "\\(\\<generate\\>\\)\\|\\(\\<endgenerate\\>\\)" ))
4287 ((looking-at "\\<endgroup\\>")
4288 ;; 10: Search back for matching covergroup
4289 (setq reg "\\(\\<covergroup\\>\\)\\|\\(\\<endgroup\\>\\)" ))
4290 ((looking-at "\\<endproperty\\>")
4291 ;; 11: Search back for matching property
4292 (setq reg "\\(\\<property\\>\\)\\|\\(\\<endproperty\\>\\)" ))
4293 ((looking-at "\\<endinterface\\>")
4294 ;; 12: Search back for matching interface
4295 (setq reg "\\(\\<interface\\>\\)\\|\\(\\<endinterface\\>\\)" ))
4296 ((looking-at "\\<endsequence\\>")
4297 ;; 12: Search back for matching sequence
4298 (setq reg "\\(\\<\\(rand\\)?sequence\\>\\)\\|\\(\\<endsequence\\>\\)" ))
4299 ((looking-at "\\<endclocking\\>")
4300 ;; 12: Search back for matching clocking
4301 (setq reg "\\(\\<clocking\\)\\|\\(\\<endclocking\\>\\)" )))
4302 (if reg
4303 (catch 'skip
4304 (if (eq nesting 'yes)
4305 (let (sreg)
4306 (while (verilog-re-search-backward reg nil 'move)
4307 (cond
4308 ((match-end 1) ; begin
4309 (setq nest (1- nest))
4310 (if (= 0 nest)
4311 ;; Now previous line describes syntax
4312 (throw 'skip 1))
4313 (if (and snest
4314 (= snest nest))
4315 (setq reg sreg)))
4316 ((match-end 2) ; end
4317 (setq nest (1+ nest)))
4318 ((match-end 3)
4319 ;; endcase, jump to case
4320 (setq snest nest)
4321 (setq nest (1+ nest))
4322 (setq sreg reg)
4323 (setq reg "\\(\\<randcase\\>\\|\\<case[xz]?\\>[^:]\\)\\|\\(\\<endcase\\>\\)" ))
4324 ((match-end 4)
4325 ;; join, jump to fork
4326 (setq snest nest)
4327 (setq nest (1+ nest))
4328 (setq sreg reg)
4329 (setq reg "\\(\\<fork\\>\\)\\|\\(\\<join\\(_any\\|_none\\)?\\>\\)" ))
4330 )))
4331 ;no nesting
4332 (if (and
4333 (verilog-re-search-backward reg nil 'move)
4334 (match-end 1)) ; task -> could be virtual and/or protected
4335 (progn
4336 (verilog-beg-of-statement)
4337 (throw 'skip 1))
4338 (throw 'skip 1)))))))
4339
4340 (defun verilog-continued-line ()
4341 "Return true if this is a continued line.
4342 Set point to where line starts."
4343 (let ((continued 't))
4344 (if (eq 0 (forward-line -1))
4345 (progn
4346 (end-of-line)
4347 (verilog-backward-ws&directives)
4348 (if (bobp)
4349 (setq continued nil)
4350 (while (and continued
4351 (save-excursion
4352 (skip-chars-backward " \t")
4353 (not (bolp))))
4354 (setq continued (verilog-backward-token)))))
4355 (setq continued nil))
4356 continued))
4357
4358 (defun verilog-backward-token ()
4359 "Step backward token, returning true if we are now at an end of line token."
4360 (interactive)
4361 (verilog-backward-syntactic-ws)
4362 (cond
4363 ((bolp)
4364 nil)
4365 (;-- Anything ending in a ; is complete
4366 (= (preceding-char) ?\;)
4367 nil)
4368 (; If a "}" is prefixed by a ";", then this is a complete statement
4369 ; i.e.: constraint foo { a = b; }
4370 (= (preceding-char) ?\})
4371 (progn
4372 (backward-char)
4373 (verilog-at-close-constraint-p)))
4374 (;-- constraint foo { a = b }
4375 ; is a complete statement. *sigh*
4376 (= (preceding-char) ?\{)
4377 (progn
4378 (backward-char)
4379 (not (verilog-at-constraint-p))))
4380 (;-- Could be 'case (foo)' or 'always @(bar)' which is complete
4381 ; also could be simply '@(foo)'
4382 ; or foo u1 #(a=8)
4383 ; (b, ... which ISN'T complete
4384 ;;;; Do we need this???
4385 (= (preceding-char) ?\))
4386 (progn
4387 (backward-char)
4388 (backward-up-list 1)
4389 (verilog-backward-syntactic-ws)
4390 (let ((back (point)))
4391 (forward-word -1)
4392 (cond
4393 ((looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|case\\(\\|[xz]\\)\\|for\\(\\|each\\|ever\\)\\|i\\(f\\|nitial\\)\\|repeat\\|while\\)\\>")
4394 (not (looking-at "\\<randcase\\>\\|\\<case[xz]?\\>[^:]")))
4395 (t
4396 (goto-char back)
4397 (cond
4398 ((= (preceding-char) ?\@)
4399 (backward-char)
4400 (save-excursion
4401 (verilog-backward-token)
4402 (not (looking-at "\\<\\(always\\(_latch\\|_ff\\|_comb\\)?\\|initial\\|while\\)\\>"))))
4403 ((= (preceding-char) ?\#)
4404 (backward-char))
4405 (t t)))))))
4406
4407 (;-- any of begin|initial|while are complete statements; 'begin : foo' is also complete
4408 t
4409 (forward-word -1)
4410 (cond
4411 ((looking-at "\\<else\\>")
4412 t)
4413 ((looking-at verilog-behavioral-block-beg-re)
4414 t)
4415 ((looking-at verilog-indent-re)
4416 nil)
4417 (t
4418 (let
4419 ((back (point)))
4420 (verilog-backward-syntactic-ws)
4421 (cond
4422 ((= (preceding-char) ?\:)
4423 (backward-char)
4424 (verilog-backward-syntactic-ws)
4425 (backward-sexp)
4426 (if (looking-at verilog-nameable-item-re )
4427 nil
4428 t))
4429 ((= (preceding-char) ?\#)
4430 (backward-char)
4431 t)
4432 ((= (preceding-char) ?\`)
4433 (backward-char)
4434 t)
4435
4436 (t
4437 (goto-char back)
4438 t))))))))
4439
4440 (defun verilog-backward-syntactic-ws (&optional bound)
4441 "Backward skip over syntactic whitespace for Emacs 19.
4442 Optional BOUND limits search."
4443 (save-restriction
4444 (let* ((bound (or bound (point-min))) (here bound) )
4445 (if (< bound (point))
4446 (progn
4447 (narrow-to-region bound (point))
4448 (while (/= here (point))
4449 (setq here (point))
4450 (verilog-skip-backward-comments))))))
4451 t)
4452
4453 (defun verilog-forward-syntactic-ws (&optional bound)
4454 "Forward skip over syntactic whitespace for Emacs 19.
4455 Optional BOUND limits search."
4456 (save-restriction
4457 (let* ((bound (or bound (point-max)))
4458 (here bound))
4459 (if (> bound (point))
4460 (progn
4461 (narrow-to-region (point) bound)
4462 (while (/= here (point))
4463 (setq here (point))
4464 (forward-comment (buffer-size))))))))
4465
4466 (defun verilog-backward-ws&directives (&optional bound)
4467 "Backward skip over syntactic whitespace and compiler directives for Emacs 19.
4468 Optional BOUND limits search."
4469 (save-restriction
4470 (let* ((bound (or bound (point-min)))
4471 (here bound)
4472 (p nil) )
4473 (if (< bound (point))
4474 (progn
4475 (let ((state (save-excursion (verilog-syntax-ppss))))
4476 (cond
4477 ((nth 7 state) ;; in // comment
4478 (verilog-re-search-backward "//" nil 'move)
4479 (skip-chars-backward "/"))
4480 ((nth 4 state) ;; in /* */ comment
4481 (verilog-re-search-backward "/\*" nil 'move))))
4482 (narrow-to-region bound (point))
4483 (while (/= here (point))
4484 (setq here (point))
4485 (verilog-skip-backward-comments)
4486 (setq p
4487 (save-excursion
4488 (beginning-of-line)
4489 (cond
4490 ((verilog-within-translate-off)
4491 (verilog-back-to-start-translate-off (point-min)))
4492 ((looking-at verilog-directive-re-1)
4493 (point))
4494 (t
4495 nil))))
4496 (if p (goto-char p))))))))
4497
4498 (defun verilog-forward-ws&directives (&optional bound)
4499 "Forward skip over syntactic whitespace and compiler directives for Emacs 19.
4500 Optional BOUND limits search."
4501 (save-restriction
4502 (let* ((bound (or bound (point-max)))
4503 (here bound)
4504 jump)
4505 (if (> bound (point))
4506 (progn
4507 (let ((state (save-excursion (verilog-syntax-ppss))))
4508 (cond
4509 ((nth 7 state) ;; in // comment
4510 (verilog-re-search-forward "//" nil 'move))
4511 ((nth 4 state) ;; in /* */ comment
4512 (verilog-re-search-forward "/\*" nil 'move))))
4513 (narrow-to-region (point) bound)
4514 (while (/= here (point))
4515 (setq here (point)
4516 jump nil)
4517 (forward-comment (buffer-size))
4518 (save-excursion
4519 (beginning-of-line)
4520 (if (looking-at verilog-directive-re-1)
4521 (setq jump t)))
4522 (if jump
4523 (beginning-of-line 2))))))))
4524
4525 (defun verilog-in-comment-p ()
4526 "Return true if in a star or // comment."
4527 (let ((state (save-excursion (verilog-syntax-ppss))))
4528 (or (nth 4 state) (nth 7 state))))
4529
4530 (defun verilog-in-star-comment-p ()
4531 "Return true if in a star comment."
4532 (let ((state (save-excursion (verilog-syntax-ppss))))
4533 (and
4534 (nth 4 state) ; t if in a comment of style a // or b /**/
4535 (not
4536 (nth 7 state) ; t if in a comment of style b /**/
4537 ))))
4538
4539 (defun verilog-in-slash-comment-p ()
4540 "Return true if in a slash comment."
4541 (let ((state (save-excursion (verilog-syntax-ppss))))
4542 (nth 7 state)))
4543
4544 (defun verilog-in-comment-or-string-p ()
4545 "Return true if in a string or comment."
4546 (let ((state (save-excursion (verilog-syntax-ppss))))
4547 (or (nth 3 state) (nth 4 state) (nth 7 state)))) ; Inside string or comment)
4548
4549 (defun verilog-in-escaped-name-p ()
4550 "Return true if in an escaped name."
4551 (save-excursion
4552 (backward-char)
4553 (skip-chars-backward "^ \t\n\f")
4554 (if (equal (char-after (point) ) ?\\ )
4555 t
4556 nil)))
4557
4558 (defun verilog-in-paren ()
4559 "Return true if in a parenthetical expression."
4560 (let ((state (save-excursion (verilog-syntax-ppss))))
4561 (> (nth 0 state) 0 )))
4562
4563 (defun verilog-in-coverage ()
4564 "Return true if in a constraint or coverpoint expression."
4565 (interactive)
4566 (save-excursion
4567 (if (verilog-in-paren)
4568 (progn
4569 (backward-up-list 1)
4570 (verilog-at-constraint-p)
4571 )
4572 nil)))
4573 (defun verilog-at-close-constraint-p ()
4574 "If at the } that closes a constraint or covergroup, return true."
4575 (if (and
4576 (equal (char-after) ?\})
4577 (verilog-in-paren))
4578
4579 (save-excursion
4580 (verilog-backward-ws&directives)
4581 (if (equal (char-before) ?\;)
4582 (point)
4583 nil))))
4584
4585 (defun verilog-at-constraint-p ()
4586 "If at the { of a constraint or coverpoint definition, return true, moving point to constraint."
4587 (if (save-excursion
4588 (and
4589 (equal (char-after) ?\{)
4590 (forward-list)
4591 (progn (backward-char 1)
4592 (verilog-backward-ws&directives)
4593 (equal (char-before) ?\;))))
4594 ;; maybe
4595 (verilog-re-search-backward "\\<constraint\\|coverpoint\\|cross\\>" nil 'move)
4596 ;; not
4597 nil))
4598
4599 (defun verilog-parenthesis-depth ()
4600 "Return non zero if in parenthetical-expression."
4601 (save-excursion (nth 1 (verilog-syntax-ppss))))
4602
4603
4604 (defun verilog-skip-forward-comment-or-string ()
4605 "Return true if in a string or comment."
4606 (let ((state (save-excursion (verilog-syntax-ppss))))
4607 (cond
4608 ((nth 3 state) ;Inside string
4609 (search-forward "\"")
4610 t)
4611 ((nth 7 state) ;Inside // comment
4612 (forward-line 1)
4613 t)
4614 ((nth 4 state) ;Inside any comment (hence /**/)
4615 (search-forward "*/"))
4616 (t
4617 nil))))
4618
4619 (defun verilog-skip-backward-comment-or-string ()
4620 "Return true if in a string or comment."
4621 (let ((state (save-excursion (verilog-syntax-ppss))))
4622 (cond
4623 ((nth 3 state) ;Inside string
4624 (search-backward "\"")
4625 t)
4626 ((nth 7 state) ;Inside // comment
4627 (search-backward "//")
4628 (skip-chars-backward "/")
4629 t)
4630 ((nth 4 state) ;Inside /* */ comment
4631 (search-backward "/*")
4632 t)
4633 (t
4634 nil))))
4635
4636 (defun verilog-skip-backward-comments ()
4637 "Return true if a comment was skipped."
4638 (let ((more t))
4639 (while more
4640 (setq more
4641 (let ((state (save-excursion (verilog-syntax-ppss))))
4642 (cond
4643 ((nth 7 state) ;Inside // comment
4644 (search-backward "//")
4645 (skip-chars-backward "/")
4646 (skip-chars-backward " \t\n\f")
4647 t)
4648 ((nth 4 state) ;Inside /* */ comment
4649 (search-backward "/*")
4650 (skip-chars-backward " \t\n\f")
4651 t)
4652 ((and (not (bobp))
4653 (= (char-before) ?\/)
4654 (= (char-before (1- (point))) ?\*))
4655 (goto-char (- (point) 2))
4656 t)
4657 (t
4658 (skip-chars-backward " \t\n\f")
4659 nil)))))))
4660
4661 (defun verilog-skip-forward-comment-p ()
4662 "If in comment, move to end and return true."
4663 (let (state)
4664 (progn
4665 (setq state (save-excursion (verilog-syntax-ppss)))
4666 (cond
4667 ((nth 3 state)
4668 t)
4669 ((nth 7 state) ;Inside // comment
4670 (end-of-line)
4671 (forward-char 1)
4672 t)
4673 ((nth 4 state) ;Inside any comment
4674 t)
4675 (t
4676 nil)))))
4677
4678 (defun verilog-indent-line-relative ()
4679 "Cheap version of indent line.
4680 Only look at a few lines to determine indent level."
4681 (interactive)
4682 (let ((indent-str)
4683 (sp (point)))
4684 (if (looking-at "^[ \t]*$")
4685 (cond ;- A blank line; No need to be too smart.
4686 ((bobp)
4687 (setq indent-str (list 'cpp 0)))
4688 ((verilog-continued-line)
4689 (let ((sp1 (point)))
4690 (if (verilog-continued-line)
4691 (progn
4692 (goto-char sp)
4693 (setq indent-str
4694 (list 'statement (verilog-current-indent-level))))
4695 (goto-char sp1)
4696 (setq indent-str (list 'block (verilog-current-indent-level)))))
4697 (goto-char sp))
4698 ((goto-char sp)
4699 (setq indent-str (verilog-calculate-indent))))
4700 (progn (skip-chars-forward " \t")
4701 (setq indent-str (verilog-calculate-indent))))
4702 (verilog-do-indent indent-str)))
4703
4704 (defun verilog-indent-line ()
4705 "Indent for special part of code."
4706 (verilog-do-indent (verilog-calculate-indent)))
4707
4708 (defun verilog-do-indent (indent-str)
4709 (let ((type (car indent-str))
4710 (ind (car (cdr indent-str))))
4711 (cond
4712 (; handle continued exp
4713 (eq type 'cexp)
4714 (let ((here (point)))
4715 (verilog-backward-syntactic-ws)
4716 (cond
4717 ((or
4718 (= (preceding-char) ?\,)
4719 (= (preceding-char) ?\])
4720 (save-excursion
4721 (verilog-beg-of-statement-1)
4722 (looking-at verilog-declaration-re)))
4723 (let* ( fst
4724 (val
4725 (save-excursion
4726 (backward-char 1)
4727 (verilog-beg-of-statement-1)
4728 (setq fst (point))
4729 (if (looking-at verilog-declaration-re)
4730 (progn ;; we have multiple words
4731 (goto-char (match-end 0))
4732 (skip-chars-forward " \t")
4733 (cond
4734 ((and verilog-indent-declaration-macros
4735 (= (following-char) ?\`))
4736 (progn
4737 (forward-char 1)
4738 (forward-word 1)
4739 (skip-chars-forward " \t")))
4740 ((= (following-char) ?\[)
4741 (progn
4742 (forward-char 1)
4743 (backward-up-list -1)
4744 (skip-chars-forward " \t"))))
4745 (current-column))
4746 (progn
4747 (goto-char fst)
4748 (+ (current-column) verilog-cexp-indent))))))
4749 (goto-char here)
4750 (indent-line-to val)))
4751 ((= (preceding-char) ?\) )
4752 (goto-char here)
4753 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4754 (indent-line-to val)))
4755 (t
4756 (goto-char here)
4757 (let ((val))
4758 (verilog-beg-of-statement-1)
4759 (if (and (< (point) here)
4760 (verilog-re-search-forward "=[ \\t]*" here 'move))
4761 (setq val (current-column))
4762 (setq val (eval (cdr (assoc type verilog-indent-alist)))))
4763 (goto-char here)
4764 (indent-line-to val))))))
4765
4766 (; handle inside parenthetical expressions
4767 (eq type 'cparenexp)
4768 (let ((val (save-excursion
4769 (backward-up-list 1)
4770 (forward-char 1)
4771 (skip-chars-forward " \t")
4772 (current-column))))
4773 (indent-line-to val)
4774 ))
4775
4776 (;-- Handle the ends
4777 (or
4778 (looking-at verilog-end-block-re )
4779 (verilog-at-close-constraint-p))
4780 (let ((val (if (eq type 'statement)
4781 (- ind verilog-indent-level)
4782 ind)))
4783 (indent-line-to val)))
4784
4785 (;-- Case -- maybe line 'em up
4786 (and (eq type 'case) (not (looking-at "^[ \t]*$")))
4787 (progn
4788 (cond
4789 ((looking-at "\\<endcase\\>")
4790 (indent-line-to ind))
4791 (t
4792 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4793 (indent-line-to val))))))
4794
4795 (;-- defun
4796 (and (eq type 'defun)
4797 (looking-at verilog-zero-indent-re))
4798 (indent-line-to 0))
4799
4800 (;-- declaration
4801 (and (or
4802 (eq type 'defun)
4803 (eq type 'block))
4804 (looking-at verilog-declaration-re))
4805 (verilog-indent-declaration ind))
4806
4807 (;-- Everything else
4808 t
4809 (let ((val (eval (cdr (assoc type verilog-indent-alist)))))
4810 (indent-line-to val))))
4811
4812 (if (looking-at "[ \t]+$")
4813 (skip-chars-forward " \t"))
4814 indent-str ; Return indent data
4815 ))
4816
4817 (defun verilog-current-indent-level ()
4818 "Return the indent-level of the current statement."
4819 (save-excursion
4820 (let (par-pos)
4821 (beginning-of-line)
4822 (setq par-pos (verilog-parenthesis-depth))
4823 (while par-pos
4824 (goto-char par-pos)
4825 (beginning-of-line)
4826 (setq par-pos (verilog-parenthesis-depth)))
4827 (skip-chars-forward " \t")
4828 (current-column))))
4829
4830 (defun verilog-case-indent-level ()
4831 "Return the indent-level of the current statement.
4832 Do not count named blocks or case-statements."
4833 (save-excursion
4834 (skip-chars-forward " \t")
4835 (cond
4836 ((looking-at verilog-named-block-re)
4837 (current-column))
4838 ((and (not (looking-at verilog-case-re))
4839 (looking-at "^[^:;]+[ \t]*:"))
4840 (verilog-re-search-forward ":" nil t)
4841 (skip-chars-forward " \t")
4842 (current-column))
4843 (t
4844 (current-column)))))
4845
4846 (defun verilog-indent-comment ()
4847 "Indent current line as comment."
4848 (let* ((stcol
4849 (cond
4850 ((verilog-in-star-comment-p)
4851 (save-excursion
4852 (re-search-backward "/\\*" nil t)
4853 (1+(current-column))))
4854 (comment-column
4855 comment-column )
4856 (t
4857 (save-excursion
4858 (re-search-backward "//" nil t)
4859 (current-column))))))
4860 (indent-line-to stcol)
4861 stcol))
4862
4863 (defun verilog-more-comment ()
4864 "Make more comment lines like the previous."
4865 (let* ((star 0)
4866 (stcol
4867 (cond
4868 ((verilog-in-star-comment-p)
4869 (save-excursion
4870 (setq star 1)
4871 (re-search-backward "/\\*" nil t)
4872 (1+(current-column))))
4873 (comment-column
4874 comment-column )
4875 (t
4876 (save-excursion
4877 (re-search-backward "//" nil t)
4878 (current-column))))))
4879 (progn
4880 (indent-to stcol)
4881 (if (and star
4882 (save-excursion
4883 (forward-line -1)
4884 (skip-chars-forward " \t")
4885 (looking-at "\*")))
4886 (insert "* ")))))
4887
4888 (defun verilog-comment-indent (&optional arg)
4889 "Return the column number the line should be indented to.
4890 ARG is ignored, for `comment-indent-function' compatibility."
4891 (cond
4892 ((verilog-in-star-comment-p)
4893 (save-excursion
4894 (re-search-backward "/\\*" nil t)
4895 (1+(current-column))))
4896 ( comment-column
4897 comment-column )
4898 (t
4899 (save-excursion
4900 (re-search-backward "//" nil t)
4901 (current-column)))))
4902
4903 ;;
4904
4905 (defun verilog-pretty-declarations (&optional quiet)
4906 "Line up declarations around point."
4907 (interactive)
4908 (save-excursion
4909 (if (progn
4910 (verilog-beg-of-statement-1)
4911 (looking-at verilog-declaration-re))
4912 (let* ((m1 (make-marker))
4913 (e) (r)
4914 (here (point))
4915 ;; Start of declaration range
4916 (start
4917 (progn
4918 (verilog-beg-of-statement-1)
4919 (while (looking-at verilog-declaration-re)
4920 (beginning-of-line)
4921 (setq e (point))
4922 (verilog-backward-syntactic-ws)
4923 (backward-char)
4924 (verilog-beg-of-statement-1)) ;Ack, need to grok `define
4925 e))
4926 ;; End of declaration range
4927 (end
4928 (progn
4929 (goto-char here)
4930 (verilog-end-of-statement)
4931 (setq e (point)) ;Might be on last line
4932 (verilog-forward-syntactic-ws)
4933 (while (looking-at verilog-declaration-re)
4934 (beginning-of-line)
4935 (verilog-end-of-statement)
4936 (setq e (point))
4937 (verilog-forward-syntactic-ws))
4938 e))
4939 (edpos (set-marker (make-marker) end))
4940 (ind)
4941 (base-ind
4942 (progn
4943 (goto-char start)
4944 (verilog-do-indent (verilog-calculate-indent))
4945 (verilog-forward-ws&directives)
4946 (current-column))))
4947 (goto-char end)
4948 (goto-char start)
4949 (if (and (not quiet)
4950 (> (- end start) 100))
4951 (message "Lining up declarations..(please stand by)"))
4952 ;; Get the beginning of line indent first
4953 (while (progn (setq e (marker-position edpos))
4954 (< (point) e))
4955 (cond
4956 ( (save-excursion (skip-chars-backward " \t")
4957 (bolp))
4958 (verilog-forward-ws&directives)
4959 (indent-line-to base-ind)
4960 (verilog-forward-ws&directives)
4961 (verilog-re-search-forward "[ \t\n\f]" e 'move))
4962 (t
4963 (just-one-space)
4964 (verilog-re-search-forward "[ \t\n\f]" e 'move)))
4965 ;;(forward-line)
4966 )
4967 ;; Now find biggest prefix
4968 (setq ind (verilog-get-lineup-indent start edpos))
4969 ;; Now indent each line.
4970 (goto-char start)
4971 (while (progn (setq e (marker-position edpos))
4972 (setq r (- e (point)))
4973 (> r 0))
4974 (setq e (point))
4975 (unless quiet (message "%d" r))
4976 (cond
4977 ((or (and verilog-indent-declaration-macros
4978 (looking-at verilog-declaration-re-1-macro))
4979 (looking-at verilog-declaration-re-1-no-macro))
4980 (let ((p (match-end 0)))
4981 (set-marker m1 p)
4982 (if (verilog-re-search-forward "[[#`]" p 'move)
4983 (progn
4984 (forward-char -1)
4985 (just-one-space)
4986 (goto-char (marker-position m1))
4987 (just-one-space)
4988 (indent-to ind))
4989 (progn
4990 (just-one-space)
4991 (indent-to ind)))))
4992 ((verilog-continued-line-1 start)
4993 (goto-char e)
4994 (indent-line-to ind))
4995 (t ; Must be comment or white space
4996 (goto-char e)
4997 (verilog-forward-ws&directives)
4998 (forward-line -1)))
4999 (forward-line 1))
5000 (unless quiet (message ""))))))
5001
5002 (defun verilog-pretty-expr (&optional quiet myre)
5003 "Line up expressions around point, or optional regexp MYRE."
5004 (interactive "sRegular Expression: ((<|:)?=) ")
5005 (save-excursion
5006 (if (or (eq myre nil)
5007 (string-equal myre ""))
5008 (setq myre "\\(<\\|:\\)?="))
5009 (setq myre (concat "\\(^[^;#<=>]*\\)\\(" myre "\\)"))
5010 (let ((rexp(concat "^\\s-*" verilog-complete-reg)))
5011 (beginning-of-line)
5012 (if (and (not (looking-at rexp ))
5013 (looking-at myre))
5014 (let* ((here (point))
5015 (e) (r)
5016 (start
5017 (progn
5018 (beginning-of-line)
5019 (setq e (point))
5020 (verilog-backward-syntactic-ws)
5021 (beginning-of-line)
5022 (while (and (not (looking-at rexp ))
5023 (looking-at myre)
5024 (not (bobp))
5025 )
5026 (setq e (point))
5027 (verilog-backward-syntactic-ws)
5028 (beginning-of-line)
5029 ) ;Ack, need to grok `define
5030 e))
5031 (end
5032 (progn
5033 (goto-char here)
5034 (end-of-line)
5035 (setq e (point)) ;Might be on last line
5036 (verilog-forward-syntactic-ws)
5037 (beginning-of-line)
5038 (while (and (not (looking-at rexp ))
5039 (looking-at myre))
5040 (end-of-line)
5041 (setq e (point))
5042 (verilog-forward-syntactic-ws)
5043 (beginning-of-line)
5044 )
5045 e))
5046 (edpos (set-marker (make-marker) end))
5047 (ind)
5048 )
5049 (goto-char start)
5050 (verilog-do-indent (verilog-calculate-indent))
5051 (if (and (not quiet)
5052 (> (- end start) 100))
5053 (message "Lining up expressions..(please stand by)"))
5054
5055 ;; Set indent to minimum throughout region
5056 (while (< (point) (marker-position edpos))
5057 (beginning-of-line)
5058 (verilog-just-one-space myre)
5059 (end-of-line)
5060 (verilog-forward-syntactic-ws)
5061 )
5062
5063 ;; Now find biggest prefix
5064 (setq ind (verilog-get-lineup-indent-2 myre start edpos))
5065
5066 ;; Now indent each line.
5067 (goto-char start)
5068 (while (progn (setq e (marker-position edpos))
5069 (setq r (- e (point)))
5070 (> r 0))
5071 (setq e (point))
5072 (if (not quiet) (message "%d" r))
5073 (cond
5074 ((looking-at myre)
5075 (goto-char (match-end 1))
5076 (if (not (verilog-parenthesis-depth)) ;; ignore parenthsized exprs
5077 (if (eq (char-after) ?=)
5078 (indent-to (1+ ind)) ; line up the = of the <= with surrounding =
5079 (indent-to ind)
5080 )))
5081 ((verilog-continued-line-1 start)
5082 (goto-char e)
5083 (indent-line-to ind))
5084 (t ; Must be comment or white space
5085 (goto-char e)
5086 (verilog-forward-ws&directives)
5087 (forward-line -1))
5088 )
5089 (forward-line 1))
5090 (unless quiet (message ""))
5091 )))))
5092
5093 (defun verilog-just-one-space (myre)
5094 "Remove extra spaces around regular expression MYRE."
5095 (interactive)
5096 (if (and (not(looking-at verilog-complete-reg))
5097 (looking-at myre))
5098 (let ((p1 (match-end 1))
5099 (p2 (match-end 2)))
5100 (progn
5101 (goto-char p2)
5102 (if (looking-at "\\s-") (just-one-space))
5103 (goto-char p1)
5104 (forward-char -1)
5105 (if (looking-at "\\s-") (just-one-space))
5106 ))))
5107
5108 (defun verilog-indent-declaration (baseind)
5109 "Indent current lines as declaration.
5110 Line up the variable names based on previous declaration's indentation.
5111 BASEIND is the base indent to offset everything."
5112 (interactive)
5113 (let ((pos (point-marker))
5114 (lim (save-excursion
5115 ;; (verilog-re-search-backward verilog-declaration-opener nil 'move)
5116 (verilog-re-search-backward "\\(\\<begin\\>\\)\\|\\(\\<module\\>\\)\\|\\(\\<task\\>\\)" nil 'move)
5117 (point)))
5118 (ind)
5119 (val)
5120 (m1 (make-marker)))
5121 (setq val
5122 (+ baseind (eval (cdr (assoc 'declaration verilog-indent-alist)))))
5123 (indent-line-to val)
5124
5125 ;; Use previous declaration (in this module) as template.
5126 (if (or (memq 'all verilog-auto-lineup)
5127 (memq 'declaration verilog-auto-lineup))
5128 (if (verilog-re-search-backward
5129 (or (and verilog-indent-declaration-macros
5130 verilog-declaration-re-1-macro)
5131 verilog-declaration-re-1-no-macro) lim t)
5132 (progn
5133 (goto-char (match-end 0))
5134 (skip-chars-forward " \t")
5135 (setq ind (current-column))
5136 (goto-char pos)
5137 (setq val
5138 (+ baseind
5139 (eval (cdr (assoc 'declaration verilog-indent-alist)))))
5140 (indent-line-to val)
5141 (if (and verilog-indent-declaration-macros
5142 (looking-at verilog-declaration-re-2-macro))
5143 (let ((p (match-end 0)))
5144 (set-marker m1 p)
5145 (if (verilog-re-search-forward "[[#`]" p 'move)
5146 (progn
5147 (forward-char -1)
5148 (just-one-space)
5149 (goto-char (marker-position m1))
5150 (just-one-space)
5151 (indent-to ind))
5152 (if (/= (current-column) ind)
5153 (progn
5154 (just-one-space)
5155 (indent-to ind)))))
5156 (if (looking-at verilog-declaration-re-2-no-macro)
5157 (let ((p (match-end 0)))
5158 (set-marker m1 p)
5159 (if (verilog-re-search-forward "[[`#]" p 'move)
5160 (progn
5161 (forward-char -1)
5162 (just-one-space)
5163 (goto-char (marker-position m1))
5164 (just-one-space)
5165 (indent-to ind))
5166 (if (/= (current-column) ind)
5167 (progn
5168 (just-one-space)
5169 (indent-to ind))))))))))
5170 (goto-char pos)))
5171
5172 (defun verilog-get-lineup-indent (b edpos)
5173 "Return the indent level that will line up several lines within the region.
5174 Region is defined by B and EDPOS."
5175 (save-excursion
5176 (let ((ind 0) e)
5177 (goto-char b)
5178 ;; Get rightmost position
5179 (while (progn (setq e (marker-position edpos))
5180 (< (point) e))
5181 (if (verilog-re-search-forward
5182 (or (and verilog-indent-declaration-macros
5183 verilog-declaration-re-1-macro)
5184 verilog-declaration-re-1-no-macro) e 'move)
5185 (progn
5186 (goto-char (match-end 0))
5187 (verilog-backward-syntactic-ws)
5188 (if (> (current-column) ind)
5189 (setq ind (current-column)))
5190 (goto-char (match-end 0)))))
5191 (if (> ind 0)
5192 (1+ ind)
5193 ;; No lineup-string found
5194 (goto-char b)
5195 (end-of-line)
5196 (skip-chars-backward " \t")
5197 (1+ (current-column))))))
5198
5199 (defun verilog-get-lineup-indent-2 (myre b edpos)
5200 "Return the indent level that will line up several lines within the region."
5201 (save-excursion
5202 (let ((ind 0) e)
5203 (goto-char b)
5204 ;; Get rightmost position
5205 (while (progn (setq e (marker-position edpos))
5206 (< (point) e))
5207 (if (and (verilog-re-search-forward myre e 'move)
5208 (not (verilog-parenthesis-depth))) ;; skip parenthsized exprs
5209 (progn
5210 (goto-char (match-beginning 2))
5211 (verilog-backward-syntactic-ws)
5212 (if (> (current-column) ind)
5213 (setq ind (current-column)))
5214 (goto-char (match-end 0)))
5215 ))
5216 (if (> ind 0)
5217 (1+ ind)
5218 ;; No lineup-string found
5219 (goto-char b)
5220 (end-of-line)
5221 (skip-chars-backward " \t")
5222 (1+ (current-column))))))
5223
5224 (defun verilog-comment-depth (type val)
5225 "A useful mode debugging aide. TYPE and VAL are comments for insertion."
5226 (save-excursion
5227 (let
5228 ((b (prog2
5229 (beginning-of-line)
5230 (point-marker)
5231 (end-of-line)))
5232 (e (point-marker)))
5233 (if (re-search-backward " /\\* \[#-\]# \[a-zA-Z\]+ \[0-9\]+ ## \\*/" b t)
5234 (progn
5235 (replace-match " /* -# ## */")
5236 (end-of-line))
5237 (progn
5238 (end-of-line)
5239 (insert " /* ## ## */"))))
5240 (backward-char 6)
5241 (insert
5242 (format "%s %d" type val))))
5243
5244 ;; \f
5245 ;;
5246 ;; Completion
5247 ;;
5248 (defvar verilog-str nil)
5249 (defvar verilog-all nil)
5250 (defvar verilog-pred nil)
5251 (defvar verilog-buffer-to-use nil)
5252 (defvar verilog-flag nil)
5253 (defvar verilog-toggle-completions nil
5254 "*True means \\<verilog-mode-map>\\[verilog-complete-word] should try all possible completions one by one.
5255 Repeated use of \\[verilog-complete-word] will show you all of them.
5256 Normally, when there is more than one possible completion,
5257 it displays a list of all possible completions.")
5258
5259
5260 (defvar verilog-type-keywords
5261 '(
5262 "and" "buf" "bufif0" "bufif1" "cmos" "defparam" "inout" "input"
5263 "integer" "localparam" "logic" "mailbox" "nand" "nmos" "nor" "not" "notif0"
5264 "notif1" "or" "output" "parameter" "pmos" "pull0" "pull1" "pullup"
5265 "rcmos" "real" "realtime" "reg" "rnmos" "rpmos" "rtran" "rtranif0"
5266 "rtranif1" "semaphore" "time" "tran" "tranif0" "tranif1" "tri" "tri0" "tri1"
5267 "triand" "trior" "trireg" "wand" "wire" "wor" "xnor" "xor"
5268 )
5269 "*Keywords for types used when completing a word in a declaration or parmlist.
5270 \(Eg. integer, real, reg...)")
5271
5272 (defvar verilog-cpp-keywords
5273 '("module" "macromodule" "primitive" "timescale" "define" "ifdef" "ifndef" "else"
5274 "endif")
5275 "*Keywords to complete when at first word of a line in declarative scope.
5276 \(Eg. initial, always, begin, assign.)
5277 The procedures and variables defined within the Verilog program
5278 will be completed at runtime and should not be added to this list.")
5279
5280 (defvar verilog-defun-keywords
5281 (append
5282 '(
5283 "always" "always_comb" "always_ff" "always_latch" "assign"
5284 "begin" "end" "generate" "endgenerate" "module" "endmodule"
5285 "specify" "endspecify" "function" "endfunction" "initial" "final"
5286 "task" "endtask" "primitive" "endprimitive"
5287 )
5288 verilog-type-keywords)
5289 "*Keywords to complete when at first word of a line in declarative scope.
5290 \(Eg. initial, always, begin, assign.)
5291 The procedures and variables defined within the Verilog program
5292 will be completed at runtime and should not be added to this list.")
5293
5294 (defvar verilog-block-keywords
5295 '(
5296 "begin" "break" "case" "continue" "else" "end" "endfunction"
5297 "endgenerate" "endinterface" "endpackage" "endspecify" "endtask"
5298 "for" "fork" "if" "join" "join_any" "join_none" "repeat" "return"
5299 "while")
5300 "*Keywords to complete when at first word of a line in behavioral scope.
5301 \(Eg. begin, if, then, else, for, fork.)
5302 The procedures and variables defined within the Verilog program
5303 will be completed at runtime and should not be added to this list.")
5304
5305 (defvar verilog-tf-keywords
5306 '("begin" "break" "fork" "join" "join_any" "join_none" "case" "end" "endtask" "endfunction" "if" "else" "for" "while" "repeat")
5307 "*Keywords to complete when at first word of a line in a task or function.
5308 \(Eg. begin, if, then, else, for, fork.)
5309 The procedures and variables defined within the Verilog program
5310 will be completed at runtime and should not be added to this list.")
5311
5312 (defvar verilog-case-keywords
5313 '("begin" "fork" "join" "join_any" "join_none" "case" "end" "endcase" "if" "else" "for" "repeat")
5314 "*Keywords to complete when at first word of a line in case scope.
5315 \(Eg. begin, if, then, else, for, fork.)
5316 The procedures and variables defined within the Verilog program
5317 will be completed at runtime and should not be added to this list.")
5318
5319 (defvar verilog-separator-keywords
5320 '("else" "then" "begin")
5321 "*Keywords to complete when NOT standing at the first word of a statement.
5322 \(Eg. else, then.)
5323 Variables and function names defined within the Verilog program
5324 will be completed at runtime and should not be added to this list.")
5325
5326 (defun verilog-string-diff (str1 str2)
5327 "Return index of first letter where STR1 and STR2 differs."
5328 (catch 'done
5329 (let ((diff 0))
5330 (while t
5331 (if (or (> (1+ diff) (length str1))
5332 (> (1+ diff) (length str2)))
5333 (throw 'done diff))
5334 (or (equal (aref str1 diff) (aref str2 diff))
5335 (throw 'done diff))
5336 (setq diff (1+ diff))))))
5337
5338 ;; Calculate all possible completions for functions if argument is `function',
5339 ;; completions for procedures if argument is `procedure' or both functions and
5340 ;; procedures otherwise.
5341
5342 (defun verilog-func-completion (type)
5343 "Build regular expression for module/task/function names.
5344 TYPE is 'module, 'tf for task or function, or t if unknown."
5345 (if (string= verilog-str "")
5346 (setq verilog-str "[a-zA-Z_]"))
5347 (let ((verilog-str (concat (cond
5348 ((eq type 'module) "\\<\\(module\\)\\s +")
5349 ((eq type 'tf) "\\<\\(task\\|function\\)\\s +")
5350 (t "\\<\\(task\\|function\\|module\\)\\s +"))
5351 "\\<\\(" verilog-str "[a-zA-Z0-9_.]*\\)\\>"))
5352 match)
5353
5354 (if (not (looking-at verilog-defun-re))
5355 (verilog-re-search-backward verilog-defun-re nil t))
5356 (forward-char 1)
5357
5358 ;; Search through all reachable functions
5359 (goto-char (point-min))
5360 (while (verilog-re-search-forward verilog-str (point-max) t)
5361 (progn (setq match (buffer-substring (match-beginning 2)
5362 (match-end 2)))
5363 (if (or (null verilog-pred)
5364 (funcall verilog-pred match))
5365 (setq verilog-all (cons match verilog-all)))))
5366 (if (match-beginning 0)
5367 (goto-char (match-beginning 0)))))
5368
5369 (defun verilog-get-completion-decl (end)
5370 "Macro for searching through current declaration (var, type or const)
5371 for matches of `str' and adding the occurrence tp `all' through point END."
5372 (let ((re (or (and verilog-indent-declaration-macros
5373 verilog-declaration-re-2-macro)
5374 verilog-declaration-re-2-no-macro))
5375 decl-end match)
5376 ;; Traverse lines
5377 (while (and (< (point) end)
5378 (verilog-re-search-forward re end t))
5379 ;; Traverse current line
5380 (setq decl-end (save-excursion (verilog-declaration-end)))
5381 (while (and (verilog-re-search-forward verilog-symbol-re decl-end t)
5382 (not (match-end 1)))
5383 (setq match (buffer-substring (match-beginning 0) (match-end 0)))
5384 (if (string-match (concat "\\<" verilog-str) match)
5385 (if (or (null verilog-pred)
5386 (funcall verilog-pred match))
5387 (setq verilog-all (cons match verilog-all)))))
5388 (forward-line 1)))
5389 verilog-all)
5390
5391 (defun verilog-type-completion ()
5392 "Calculate all possible completions for types."
5393 (let ((start (point))
5394 goon)
5395 ;; Search for all reachable type declarations
5396 (while (or (verilog-beg-of-defun)
5397 (setq goon (not goon)))
5398 (save-excursion
5399 (if (and (< start (prog1 (save-excursion (verilog-end-of-defun)
5400 (point))
5401 (forward-char 1)))
5402 (verilog-re-search-forward
5403 "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
5404 start t)
5405 (not (match-end 1)))
5406 ;; Check current type declaration
5407 (verilog-get-completion-decl start))))))
5408
5409 (defun verilog-var-completion ()
5410 "Calculate all possible completions for variables (or constants)."
5411 (let ((start (point)))
5412 ;; Search for all reachable var declarations
5413 (verilog-beg-of-defun)
5414 (save-excursion
5415 ;; Check var declarations
5416 (verilog-get-completion-decl start))))
5417
5418 (defun verilog-keyword-completion (keyword-list)
5419 "Give list of all possible completions of keywords in KEYWORD-LIST."
5420 (mapcar '(lambda (s)
5421 (if (string-match (concat "\\<" verilog-str) s)
5422 (if (or (null verilog-pred)
5423 (funcall verilog-pred s))
5424 (setq verilog-all (cons s verilog-all)))))
5425 keyword-list))
5426
5427
5428 (defun verilog-completion (verilog-str verilog-pred verilog-flag)
5429 "Function passed to `completing-read', `try-completion' or `all-completions'.
5430 Called to get completion on VERILOG-STR. If VERILOG-PRED is non-nil, it
5431 must be a function to be called for every match to check if this should
5432 really be a match. If VERILOG-FLAG is t, the function returns a list of
5433 all possible completions. If VERILOG-FLAG is nil it returns a string,
5434 the longest possible completion, or t if VERILOG-STR is an exact match.
5435 If VERILOG-FLAG is 'lambda, the function returns t if VERILOG-STR is an
5436 exact match, nil otherwise."
5437 (save-excursion
5438 (let ((verilog-all nil))
5439 ;; Set buffer to use for searching labels. This should be set
5440 ;; within functions which use verilog-completions
5441 (set-buffer verilog-buffer-to-use)
5442
5443 ;; Determine what should be completed
5444 (let ((state (car (verilog-calculate-indent))))
5445 (cond ((eq state 'defun)
5446 (save-excursion (verilog-var-completion))
5447 (verilog-func-completion 'module)
5448 (verilog-keyword-completion verilog-defun-keywords))
5449
5450 ((eq state 'behavioral)
5451 (save-excursion (verilog-var-completion))
5452 (verilog-func-completion 'module)
5453 (verilog-keyword-completion verilog-defun-keywords))
5454
5455 ((eq state 'block)
5456 (save-excursion (verilog-var-completion))
5457 (verilog-func-completion 'tf)
5458 (verilog-keyword-completion verilog-block-keywords))
5459
5460 ((eq state 'case)
5461 (save-excursion (verilog-var-completion))
5462 (verilog-func-completion 'tf)
5463 (verilog-keyword-completion verilog-case-keywords))
5464
5465 ((eq state 'tf)
5466 (save-excursion (verilog-var-completion))
5467 (verilog-func-completion 'tf)
5468 (verilog-keyword-completion verilog-tf-keywords))
5469
5470 ((eq state 'cpp)
5471 (save-excursion (verilog-var-completion))
5472 (verilog-keyword-completion verilog-cpp-keywords))
5473
5474 ((eq state 'cparenexp)
5475 (save-excursion (verilog-var-completion)))
5476
5477 (t;--Anywhere else
5478 (save-excursion (verilog-var-completion))
5479 (verilog-func-completion 'both)
5480 (verilog-keyword-completion verilog-separator-keywords))))
5481
5482 ;; Now we have built a list of all matches. Give response to caller
5483 (verilog-completion-response))))
5484
5485 (defun verilog-completion-response ()
5486 (cond ((or (equal verilog-flag 'lambda) (null verilog-flag))
5487 ;; This was not called by all-completions
5488 (if (null verilog-all)
5489 ;; Return nil if there was no matching label
5490 nil
5491 ;; Get longest string common in the labels
5492 (let* ((elm (cdr verilog-all))
5493 (match (car verilog-all))
5494 (min (length match))
5495 tmp)
5496 (if (string= match verilog-str)
5497 ;; Return t if first match was an exact match
5498 (setq match t)
5499 (while (not (null elm))
5500 ;; Find longest common string
5501 (if (< (setq tmp (verilog-string-diff match (car elm))) min)
5502 (progn
5503 (setq min tmp)
5504 (setq match (substring match 0 min))))
5505 ;; Terminate with match=t if this is an exact match
5506 (if (string= (car elm) verilog-str)
5507 (progn
5508 (setq match t)
5509 (setq elm nil))
5510 (setq elm (cdr elm)))))
5511 ;; If this is a test just for exact match, return nil ot t
5512 (if (and (equal verilog-flag 'lambda) (not (equal match 't)))
5513 nil
5514 match))))
5515 ;; If flag is t, this was called by all-completions. Return
5516 ;; list of all possible completions
5517 (verilog-flag
5518 verilog-all)))
5519
5520 (defvar verilog-last-word-numb 0)
5521 (defvar verilog-last-word-shown nil)
5522 (defvar verilog-last-completions nil)
5523
5524 (defun verilog-complete-word ()
5525 "Complete word at current point.
5526 \(See also `verilog-toggle-completions', `verilog-type-keywords',
5527 and `verilog-separator-keywords'.)"
5528 (interactive)
5529 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5530 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5531 (verilog-str (buffer-substring b e))
5532 ;; The following variable is used in verilog-completion
5533 (verilog-buffer-to-use (current-buffer))
5534 (allcomp (if (and verilog-toggle-completions
5535 (string= verilog-last-word-shown verilog-str))
5536 verilog-last-completions
5537 (all-completions verilog-str 'verilog-completion)))
5538 (match (if verilog-toggle-completions
5539 "" (try-completion
5540 verilog-str (mapcar '(lambda (elm)
5541 (cons elm 0)) allcomp)))))
5542 ;; Delete old string
5543 (delete-region b e)
5544
5545 ;; Toggle-completions inserts whole labels
5546 (if verilog-toggle-completions
5547 (progn
5548 ;; Update entry number in list
5549 (setq verilog-last-completions allcomp
5550 verilog-last-word-numb
5551 (if (>= verilog-last-word-numb (1- (length allcomp)))
5552 0
5553 (1+ verilog-last-word-numb)))
5554 (setq verilog-last-word-shown (elt allcomp verilog-last-word-numb))
5555 ;; Display next match or same string if no match was found
5556 (if (not (null allcomp))
5557 (insert "" verilog-last-word-shown)
5558 (insert "" verilog-str)
5559 (message "(No match)")))
5560 ;; The other form of completion does not necessarily do that.
5561
5562 ;; Insert match if found, or the original string if no match
5563 (if (or (null match) (equal match 't))
5564 (progn (insert "" verilog-str)
5565 (message "(No match)"))
5566 (insert "" match))
5567 ;; Give message about current status of completion
5568 (cond ((equal match 't)
5569 (if (not (null (cdr allcomp)))
5570 (message "(Complete but not unique)")
5571 (message "(Sole completion)")))
5572 ;; Display buffer if the current completion didn't help
5573 ;; on completing the label.
5574 ((and (not (null (cdr allcomp))) (= (length verilog-str)
5575 (length match)))
5576 (with-output-to-temp-buffer "*Completions*"
5577 (display-completion-list allcomp))
5578 ;; Wait for a key press. Then delete *Completion* window
5579 (momentary-string-display "" (point))
5580 (delete-window (get-buffer-window (get-buffer "*Completions*")))
5581 )))))
5582
5583 (defun verilog-show-completions ()
5584 "Show all possible completions at current point."
5585 (interactive)
5586 (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
5587 (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
5588 (verilog-str (buffer-substring b e))
5589 ;; The following variable is used in verilog-completion
5590 (verilog-buffer-to-use (current-buffer))
5591 (allcomp (if (and verilog-toggle-completions
5592 (string= verilog-last-word-shown verilog-str))
5593 verilog-last-completions
5594 (all-completions verilog-str 'verilog-completion))))
5595 ;; Show possible completions in a temporary buffer.
5596 (with-output-to-temp-buffer "*Completions*"
5597 (display-completion-list allcomp))
5598 ;; Wait for a key press. Then delete *Completion* window
5599 (momentary-string-display "" (point))
5600 (delete-window (get-buffer-window (get-buffer "*Completions*")))))
5601
5602
5603 (defun verilog-get-default-symbol ()
5604 "Return symbol around current point as a string."
5605 (save-excursion
5606 (buffer-substring (progn
5607 (skip-chars-backward " \t")
5608 (skip-chars-backward "a-zA-Z0-9_")
5609 (point))
5610 (progn
5611 (skip-chars-forward "a-zA-Z0-9_")
5612 (point)))))
5613
5614 (defun verilog-build-defun-re (str &optional arg)
5615 "Return function/task/module starting with STR as regular expression.
5616 With optional second ARG non-nil, STR is the complete name of the instruction."
5617 (if arg
5618 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "\\)\\>")
5619 (concat "^\\(function\\|task\\|module\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
5620
5621 (defun verilog-comp-defun (verilog-str verilog-pred verilog-flag)
5622 "Function passed to `completing-read', `try-completion' or `all-completions'.
5623 Returns a completion on any function name based on VERILOG-STR prefix. If
5624 VERILOG-PRED is non-nil, it must be a function to be called for every match
5625 to check if this should really be a match. If VERILOG-FLAG is t, the
5626 function returns a list of all possible completions. If it is nil it
5627 returns a string, the longest possible completion, or t if VERILOG-STR is
5628 an exact match. If VERILOG-FLAG is 'lambda, the function returns t if
5629 VERILOG-STR is an exact match, nil otherwise."
5630 (save-excursion
5631 (let ((verilog-all nil)
5632 match)
5633
5634 ;; Set buffer to use for searching labels. This should be set
5635 ;; within functions which use verilog-completions
5636 (set-buffer verilog-buffer-to-use)
5637
5638 (let ((verilog-str verilog-str))
5639 ;; Build regular expression for functions
5640 (if (string= verilog-str "")
5641 (setq verilog-str (verilog-build-defun-re "[a-zA-Z_]"))
5642 (setq verilog-str (verilog-build-defun-re verilog-str)))
5643 (goto-char (point-min))
5644
5645 ;; Build a list of all possible completions
5646 (while (verilog-re-search-forward verilog-str nil t)
5647 (setq match (buffer-substring (match-beginning 2) (match-end 2)))
5648 (if (or (null verilog-pred)
5649 (funcall verilog-pred match))
5650 (setq verilog-all (cons match verilog-all)))))
5651
5652 ;; Now we have built a list of all matches. Give response to caller
5653 (verilog-completion-response))))
5654
5655 (defun verilog-goto-defun ()
5656 "Move to specified Verilog module/task/function.
5657 The default is a name found in the buffer around point.
5658 If search fails, other files are checked based on
5659 `verilog-library-flags'."
5660 (interactive)
5661 (let* ((default (verilog-get-default-symbol))
5662 ;; The following variable is used in verilog-comp-function
5663 (verilog-buffer-to-use (current-buffer))
5664 (label (if (not (string= default ""))
5665 ;; Do completion with default
5666 (completing-read (concat "Label: (default " default ") ")
5667 'verilog-comp-defun nil nil "")
5668 ;; There is no default value. Complete without it
5669 (completing-read "Label: "
5670 'verilog-comp-defun nil nil "")))
5671 pt)
5672 ;; If there was no response on prompt, use default value
5673 (if (string= label "")
5674 (setq label default))
5675 ;; Goto right place in buffer if label is not an empty string
5676 (or (string= label "")
5677 (progn
5678 (save-excursion
5679 (goto-char (point-min))
5680 (setq pt
5681 (re-search-forward (verilog-build-defun-re label t) nil t)))
5682 (when pt
5683 (goto-char pt)
5684 (beginning-of-line))
5685 pt)
5686 (verilog-goto-defun-file label))))
5687
5688 ;; Eliminate compile warning
5689 (defvar occur-pos-list)
5690
5691 (defun verilog-showscopes ()
5692 "List all scopes in this module."
5693 (interactive)
5694 (let ((buffer (current-buffer))
5695 (linenum 1)
5696 (nlines 0)
5697 (first 1)
5698 (prevpos (point-min))
5699 (final-context-start (make-marker))
5700 (regexp "\\(module\\s-+\\w+\\s-*(\\)\\|\\(\\w+\\s-+\\w+\\s-*(\\)"))
5701 (with-output-to-temp-buffer "*Occur*"
5702 (save-excursion
5703 (message (format "Searching for %s ..." regexp))
5704 ;; Find next match, but give up if prev match was at end of buffer.
5705 (while (and (not (= prevpos (point-max)))
5706 (verilog-re-search-forward regexp nil t))
5707 (goto-char (match-beginning 0))
5708 (beginning-of-line)
5709 (save-match-data
5710 (setq linenum (+ linenum (count-lines prevpos (point)))))
5711 (setq prevpos (point))
5712 (goto-char (match-end 0))
5713 (let* ((start (save-excursion
5714 (goto-char (match-beginning 0))
5715 (forward-line (if (< nlines 0) nlines (- nlines)))
5716 (point)))
5717 (end (save-excursion
5718 (goto-char (match-end 0))
5719 (if (> nlines 0)
5720 (forward-line (1+ nlines))
5721 (forward-line 1))
5722 (point)))
5723 (tag (format "%3d" linenum))
5724 (empty (make-string (length tag) ?\ ))
5725 tem)
5726 (save-excursion
5727 (setq tem (make-marker))
5728 (set-marker tem (point))
5729 (set-buffer standard-output)
5730 (setq occur-pos-list (cons tem occur-pos-list))
5731 (or first (zerop nlines)
5732 (insert "--------\n"))
5733 (setq first nil)
5734 (insert-buffer-substring buffer start end)
5735 (backward-char (- end start))
5736 (setq tem (if (< nlines 0) (- nlines) nlines))
5737 (while (> tem 0)
5738 (insert empty ?:)
5739 (forward-line 1)
5740 (setq tem (1- tem)))
5741 (let ((this-linenum linenum))
5742 (set-marker final-context-start
5743 (+ (point) (- (match-end 0) (match-beginning 0))))
5744 (while (< (point) final-context-start)
5745 (if (null tag)
5746 (setq tag (format "%3d" this-linenum)))
5747 (insert tag ?:)))))))
5748 (set-buffer-modified-p nil))))
5749
5750
5751 ;; Highlight helper functions
5752 (defconst verilog-directive-regexp "\\(translate\\|coverage\\|lint\\)_")
5753 (defun verilog-within-translate-off ()
5754 "Return point if within translate-off region, else nil."
5755 (and (save-excursion
5756 (re-search-backward
5757 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "\\(on\\|off\\)\\>")
5758 nil t))
5759 (equal "off" (match-string 2))
5760 (point)))
5761
5762 (defun verilog-start-translate-off (limit)
5763 "Return point before translate-off directive if before LIMIT, else nil."
5764 (when (re-search-forward
5765 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
5766 limit t)
5767 (match-beginning 0)))
5768
5769 (defun verilog-back-to-start-translate-off (limit)
5770 "Return point before translate-off directive if before LIMIT, else nil."
5771 (when (re-search-backward
5772 (concat "//\\s-*.*\\s-*" verilog-directive-regexp "off\\>")
5773 limit t)
5774 (match-beginning 0)))
5775
5776 (defun verilog-end-translate-off (limit)
5777 "Return point after translate-on directive if before LIMIT, else nil."
5778
5779 (re-search-forward (concat
5780 "//\\s-*.*\\s-*" verilog-directive-regexp "on\\>") limit t))
5781
5782 (defun verilog-match-translate-off (limit)
5783 "Match a translate-off block, setting `match-data' and returning t, else nil.
5784 Bound search by LIMIT."
5785 (when (< (point) limit)
5786 (let ((start (or (verilog-within-translate-off)
5787 (verilog-start-translate-off limit)))
5788 (case-fold-search t))
5789 (when start
5790 (let ((end (or (verilog-end-translate-off limit) limit)))
5791 (set-match-data (list start end))
5792 (goto-char end))))))
5793
5794 (defun verilog-font-lock-match-item (limit)
5795 "Match, and move over, any declaration item after point.
5796 Bound search by LIMIT. Adapted from
5797 `font-lock-match-c-style-declaration-item-and-skip-to-next'."
5798 (condition-case nil
5799 (save-restriction
5800 (narrow-to-region (point-min) limit)
5801 ;; match item
5802 (when (looking-at "\\s-*\\([a-zA-Z]\\w*\\)")
5803 (save-match-data
5804 (goto-char (match-end 1))
5805 ;; move to next item
5806 (if (looking-at "\\(\\s-*,\\)")
5807 (goto-char (match-end 1))
5808 (end-of-line) t))))
5809 (error nil)))
5810
5811
5812 ;; Added by Subbu Meiyappan for Header
5813
5814 (defun verilog-header ()
5815 "Insert a standard Verilog file header."
5816 (interactive)
5817 (let ((start (point)))
5818 (insert "\
5819 //-----------------------------------------------------------------------------
5820 // Title : <title>
5821 // Project : <project>
5822 //-----------------------------------------------------------------------------
5823 // File : <filename>
5824 // Author : <author>
5825 // Created : <credate>
5826 // Last modified : <moddate>
5827 //-----------------------------------------------------------------------------
5828 // Description :
5829 // <description>
5830 //-----------------------------------------------------------------------------
5831 // Copyright (c) <copydate> by <company> This model is the confidential and
5832 // proprietary property of <company> and the possession or use of this
5833 // file requires a written license from <company>.
5834 //------------------------------------------------------------------------------
5835 // Modification history :
5836 // <modhist>
5837 //-----------------------------------------------------------------------------
5838
5839 ")
5840 (goto-char start)
5841 (search-forward "<filename>")
5842 (replace-match (buffer-name) t t)
5843 (search-forward "<author>") (replace-match "" t t)
5844 (insert (user-full-name))
5845 (insert " <" (user-login-name) "@" (system-name) ">")
5846 (search-forward "<credate>") (replace-match "" t t)
5847 (verilog-insert-date)
5848 (search-forward "<moddate>") (replace-match "" t t)
5849 (verilog-insert-date)
5850 (search-forward "<copydate>") (replace-match "" t t)
5851 (verilog-insert-year)
5852 (search-forward "<modhist>") (replace-match "" t t)
5853 (verilog-insert-date)
5854 (insert " : created")
5855 (goto-char start)
5856 (let (string)
5857 (setq string (read-string "title: "))
5858 (search-forward "<title>")
5859 (replace-match string t t)
5860 (setq string (read-string "project: " verilog-project))
5861 (setq verilog-project string)
5862 (search-forward "<project>")
5863 (replace-match string t t)
5864 (setq string (read-string "Company: " verilog-company))
5865 (setq verilog-company string)
5866 (search-forward "<company>")
5867 (replace-match string t t)
5868 (search-forward "<company>")
5869 (replace-match string t t)
5870 (search-forward "<company>")
5871 (replace-match string t t)
5872 (search-backward "<description>")
5873 (replace-match "" t t))))
5874
5875 ;; verilog-header Uses the verilog-insert-date function
5876
5877 (defun verilog-insert-date ()
5878 "Insert date from the system."
5879 (interactive)
5880 (let ((timpos))
5881 (setq timpos (point))
5882 (if verilog-date-scientific-format
5883 (shell-command "date \"+@%Y/%m/%d\"" t)
5884 (shell-command "date \"+@%d.%m.%Y\"" t))
5885 (search-forward "@")
5886 (delete-region timpos (point))
5887 (end-of-line))
5888 (delete-char 1))
5889
5890 (defun verilog-insert-year ()
5891 "Insert year from the system."
5892 (interactive)
5893 (let ((timpos))
5894 (setq timpos (point))
5895 (shell-command "date \"+@%Y\"" t)
5896 (search-forward "@")
5897 (delete-region timpos (point))
5898 (end-of-line))
5899 (delete-char 1))
5900
5901 \f
5902 ;;
5903 ;; Signal list parsing
5904 ;;
5905
5906 ;; Elements of a signal list
5907 (defsubst verilog-sig-name (sig)
5908 (car sig))
5909 (defsubst verilog-sig-bits (sig)
5910 (nth 1 sig))
5911 (defsubst verilog-sig-comment (sig)
5912 (nth 2 sig))
5913 (defsubst verilog-sig-memory (sig)
5914 (nth 3 sig))
5915 (defsubst verilog-sig-enum (sig)
5916 (nth 4 sig))
5917 (defsubst verilog-sig-signed (sig)
5918 (nth 5 sig))
5919 (defsubst verilog-sig-type (sig)
5920 (nth 6 sig))
5921 (defsubst verilog-sig-multidim (sig)
5922 (nth 7 sig))
5923 (defsubst verilog-sig-multidim-string (sig)
5924 (if (verilog-sig-multidim sig)
5925 (let ((str "") (args (verilog-sig-multidim sig)))
5926 (while args
5927 (setq str (concat str (car args)))
5928 (setq args (cdr args)))
5929 str)))
5930 (defsubst verilog-sig-width (sig)
5931 (verilog-make-width-expression (verilog-sig-bits sig)))
5932
5933 (defsubst verilog-alw-get-inputs (sigs)
5934 (nth 2 sigs))
5935 (defsubst verilog-alw-get-outputs (sigs)
5936 (nth 0 sigs))
5937 (defsubst verilog-alw-get-uses-delayed (sigs)
5938 (nth 3 sigs))
5939
5940 (defun verilog-signals-not-in (in-list not-list)
5941 "Return list of signals in IN-LIST that aren't also in NOT-LIST.
5942 Also remove any duplicates in IN-LIST.
5943 Signals must be in standard (base vector) form."
5944 (let (out-list)
5945 (while in-list
5946 (if (not (or (assoc (car (car in-list)) not-list)
5947 (assoc (car (car in-list)) out-list)))
5948 (setq out-list (cons (car in-list) out-list)))
5949 (setq in-list (cdr in-list)))
5950 (nreverse out-list)))
5951 ;;(verilog-signals-not-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
5952
5953 (defun verilog-signals-in (in-list other-list)
5954 "Return list of signals in IN-LIST that are also in OTHER-LIST.
5955 Signals must be in standard (base vector) form."
5956 (let (out-list)
5957 (while in-list
5958 (if (assoc (car (car in-list)) other-list)
5959 (setq out-list (cons (car in-list) out-list)))
5960 (setq in-list (cdr in-list)))
5961 (nreverse out-list)))
5962 ;;(verilog-signals-in '(("A" "") ("B" "") ("DEL" "[2:3]")) '(("DEL" "") ("EXT" "")))
5963
5964 (defun verilog-signals-memory (in-list)
5965 "Return list of signals in IN-LIST that are memoried (multidimensional)."
5966 (let (out-list)
5967 (while in-list
5968 (if (nth 3 (car in-list))
5969 (setq out-list (cons (car in-list) out-list)))
5970 (setq in-list (cdr in-list)))
5971 out-list))
5972 ;;(verilog-signals-memory '(("A" nil nil "[3:0]")) '(("B" nil nil nil)))
5973
5974 (defun verilog-signals-sort-compare (a b)
5975 "Compare signal A and B for sorting."
5976 (string< (car a) (car b)))
5977
5978 (defun verilog-signals-not-params (in-list)
5979 "Return list of signals in IN-LIST that aren't parameters or numeric constants."
5980 (let (out-list)
5981 (while in-list
5982 (unless (boundp (intern (concat "vh-" (car (car in-list)))))
5983 (setq out-list (cons (car in-list) out-list)))
5984 (setq in-list (cdr in-list)))
5985 (nreverse out-list)))
5986
5987 (defun verilog-signals-combine-bus (in-list)
5988 "Return a list of signals in IN-LIST, with busses combined.
5989 Duplicate signals are also removed. For example A[2] and A[1] become A[2:1]."
5990 (let (combo buswarn
5991 out-list
5992 sig highbit lowbit ; Temp information about current signal
5993 sv-name sv-highbit sv-lowbit ; Details about signal we are forming
5994 sv-comment sv-memory sv-enum sv-signed sv-type sv-multidim sv-busstring
5995 bus)
5996 ;; Shove signals so duplicated signals will be adjacent
5997 (setq in-list (sort in-list `verilog-signals-sort-compare))
5998 (while in-list
5999 (setq sig (car in-list))
6000 ;; No current signal; form from existing details
6001 (unless sv-name
6002 (setq sv-name (verilog-sig-name sig)
6003 sv-highbit nil
6004 sv-busstring nil
6005 sv-comment (verilog-sig-comment sig)
6006 sv-memory (verilog-sig-memory sig)
6007 sv-enum (verilog-sig-enum sig)
6008 sv-signed (verilog-sig-signed sig)
6009 sv-type (verilog-sig-type sig)
6010 sv-multidim (verilog-sig-multidim sig)
6011 combo ""
6012 buswarn ""))
6013 ;; Extract bus details
6014 (setq bus (verilog-sig-bits sig))
6015 (cond ((and bus
6016 (or (and (string-match "\\[\\([0-9]+\\):\\([0-9]+\\)\\]" bus)
6017 (setq highbit (string-to-number (match-string 1 bus))
6018 lowbit (string-to-number
6019 (match-string 2 bus))))
6020 (and (string-match "\\[\\([0-9]+\\)\\]" bus)
6021 (setq highbit (string-to-number (match-string 1 bus))
6022 lowbit highbit))))
6023 ;; Combine bits in bus
6024 (if sv-highbit
6025 (setq sv-highbit (max highbit sv-highbit)
6026 sv-lowbit (min lowbit sv-lowbit))
6027 (setq sv-highbit highbit
6028 sv-lowbit lowbit)))
6029 (bus
6030 ;; String, probably something like `preproc:0
6031 (setq sv-busstring bus)))
6032 ;; Peek ahead to next signal
6033 (setq in-list (cdr in-list))
6034 (setq sig (car in-list))
6035 (cond ((and sig (equal sv-name (verilog-sig-name sig)))
6036 ;; Combine with this signal
6037 (when (and sv-busstring
6038 (not (equal sv-busstring (verilog-sig-bits sig))))
6039 (when nil ;; Debugging
6040 (message (concat "Warning, can't merge into single bus "
6041 sv-name bus
6042 ", the AUTOs may be wrong")))
6043 (setq buswarn ", Couldn't Merge"))
6044 (if (verilog-sig-comment sig) (setq combo ", ..."))
6045 (setq sv-memory (or sv-memory (verilog-sig-memory sig))
6046 sv-enum (or sv-enum (verilog-sig-enum sig))
6047 sv-signed (or sv-signed (verilog-sig-signed sig))
6048 sv-type (or sv-type (verilog-sig-type sig))
6049 sv-multidim (or sv-multidim (verilog-sig-multidim sig))))
6050 ;; Doesn't match next signal, add to queue, zero in prep for next
6051 ;; Note sig may also be nil for the last signal in the list
6052 (t
6053 (setq out-list
6054 (cons
6055 (list sv-name
6056 (or sv-busstring
6057 (if sv-highbit
6058 (concat "[" (int-to-string sv-highbit) ":"
6059 (int-to-string sv-lowbit) "]")))
6060 (concat sv-comment combo buswarn)
6061 sv-memory sv-enum sv-signed sv-type sv-multidim)
6062 out-list)
6063 sv-name nil))))
6064 ;;
6065 out-list))
6066
6067 (defun verilog-sig-tieoff (sig &optional no-width)
6068 "Return tieoff expression for given SIG, with appropriate width.
6069 Ignore width if optional NO-WIDTH is set."
6070 (let* ((width (if no-width nil (verilog-sig-width sig))))
6071 (concat
6072 (if (and verilog-active-low-regexp
6073 (string-match verilog-active-low-regexp (verilog-sig-name sig)))
6074 "~" "")
6075 (cond ((not width)
6076 "0")
6077 ((string-match "^[0-9]+$" width)
6078 (concat width (if (verilog-sig-signed sig) "'sh0" "'h0")))
6079 (t
6080 (concat "{" width "{1'b0}}"))))))
6081
6082 ;;
6083 ;; Port/Wire/Etc Reading
6084 ;;
6085
6086 (defun verilog-read-inst-backward-name ()
6087 "Internal. Move point back to beginning of inst-name."
6088 (verilog-backward-open-paren)
6089 (let (done)
6090 (while (not done)
6091 (verilog-re-search-backward-quick "\\()\\|\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil) ; ] isn't word boundary
6092 (cond ((looking-at ")")
6093 (verilog-backward-open-paren))
6094 (t (setq done t)))))
6095 (while (looking-at "\\]")
6096 (verilog-backward-open-bracket)
6097 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|\\]\\)" nil nil))
6098 (skip-chars-backward "a-zA-Z0-9`_$"))
6099
6100 (defun verilog-read-inst-module ()
6101 "Return module_name when point is inside instantiation."
6102 (save-excursion
6103 (verilog-read-inst-backward-name)
6104 ;; Skip over instantiation name
6105 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
6106 ;; Check for parameterized instantiations
6107 (when (looking-at ")")
6108 (verilog-backward-open-paren)
6109 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil))
6110 (skip-chars-backward "a-zA-Z0-9'_$")
6111 (looking-at "[a-zA-Z0-9`_\$]+")
6112 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6113 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
6114
6115 (defun verilog-read-inst-name ()
6116 "Return instance_name when point is inside instantiation."
6117 (save-excursion
6118 (verilog-read-inst-backward-name)
6119 (looking-at "[a-zA-Z0-9`_\$]+")
6120 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6121 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
6122
6123 (defun verilog-read-module-name ()
6124 "Return module name when after its ( or ;."
6125 (save-excursion
6126 (re-search-backward "[(;]")
6127 (verilog-re-search-backward-quick "\\b[a-zA-Z0-9`_\$]" nil nil)
6128 (skip-chars-backward "a-zA-Z0-9`_$")
6129 (looking-at "[a-zA-Z0-9`_\$]+")
6130 ;; Important: don't use match string, this must work with Emacs 19 font-lock on
6131 (buffer-substring-no-properties (match-beginning 0) (match-end 0))))
6132
6133 (defun verilog-read-inst-param-value ()
6134 "Return list of parameters and values when point is inside instantiation."
6135 (save-excursion
6136 (verilog-read-inst-backward-name)
6137 ;; Skip over instantiation name
6138 (verilog-re-search-backward-quick "\\(\\b[a-zA-Z0-9`_\$]\\|)\\)" nil nil) ; ) isn't word boundary
6139 ;; If there are parameterized instantiations
6140 (when (looking-at ")")
6141 (let ((end-pt (point))
6142 params
6143 param-name paren-beg-pt param-value)
6144 (verilog-backward-open-paren)
6145 (while (verilog-re-search-forward-quick "\\." end-pt t)
6146 (verilog-re-search-forward-quick "\\([a-zA-Z0-9`_\$]\\)" nil nil)
6147 (skip-chars-backward "a-zA-Z0-9'_$")
6148 (looking-at "[a-zA-Z0-9`_\$]+")
6149 (setq param-name (buffer-substring-no-properties
6150 (match-beginning 0) (match-end 0)))
6151 (verilog-re-search-forward-quick "(" nil nil)
6152 (setq paren-beg-pt (point))
6153 (verilog-forward-close-paren)
6154 (setq param-value (verilog-string-remove-spaces
6155 (buffer-substring-no-properties
6156 paren-beg-pt (1- (point)))))
6157 (setq params (cons (list param-name param-value) params)))
6158 params))))
6159
6160 (defun verilog-read-auto-params (num-param &optional max-param)
6161 "Return parameter list inside auto.
6162 Optional NUM-PARAM and MAX-PARAM check for a specific number of parameters."
6163 (let ((olist))
6164 (save-excursion
6165 ;; /*AUTOPUNT("parameter", "parameter")*/
6166 (search-backward "(")
6167 (while (looking-at "(?\\s *\"\\([^\"]*\\)\"\\s *,?")
6168 (setq olist (cons (match-string 1) olist))
6169 (goto-char (match-end 0))))
6170 (or (eq nil num-param)
6171 (<= num-param (length olist))
6172 (error "%s: Expected %d parameters" (verilog-point-text) num-param))
6173 (if (eq max-param nil) (setq max-param num-param))
6174 (or (eq nil max-param)
6175 (>= max-param (length olist))
6176 (error "%s: Expected <= %d parameters" (verilog-point-text) max-param))
6177 (nreverse olist)))
6178
6179 (defun verilog-read-decls ()
6180 "Compute signal declaration information for the current module at point.
6181 Return a array of [outputs inouts inputs wire reg assign const]."
6182 (let ((end-mod-point (or (verilog-get-end-of-defun t) (point-max)))
6183 (functask 0) (paren 0) (sig-paren 0)
6184 sigs-in sigs-out sigs-inout sigs-wire sigs-reg sigs-assign sigs-const sigs-gparam
6185 vec expect-signal keywd newsig rvalue enum io signed typedefed multidim)
6186 (save-excursion
6187 (verilog-beg-of-defun)
6188 (setq sigs-const (verilog-read-auto-constants (point) end-mod-point))
6189 (while (< (point) end-mod-point)
6190 ;;(if dbg (setq dbg (cons (format "Pt %s Vec %s Kwd'%s'\n" (point) vec keywd) dbg)))
6191 (cond
6192 ((looking-at "//")
6193 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6194 (setq enum (match-string 1)))
6195 (search-forward "\n"))
6196 ((looking-at "/\\*")
6197 (forward-char 2)
6198 (if (looking-at "[^*]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6199 (setq enum (match-string 1)))
6200 (or (search-forward "*/")
6201 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6202 ((looking-at "(\\*")
6203 (forward-char 2)
6204 (or (looking-at "\\s-*)") ; It's a "always @ (*)"
6205 (search-forward "*)")
6206 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
6207 ((eq ?\" (following-char))
6208 (or (re-search-forward "[^\\]\"" nil t) ;; don't forward-char first, since we look for a non backslash first
6209 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
6210 ((eq ?\; (following-char))
6211 (setq vec nil io nil expect-signal nil newsig nil paren 0 rvalue nil)
6212 (forward-char 1))
6213 ((eq ?= (following-char))
6214 (setq rvalue t newsig nil)
6215 (forward-char 1))
6216 ((and (or rvalue sig-paren)
6217 (cond ((and (eq ?, (following-char))
6218 (eq paren sig-paren))
6219 (setq rvalue nil)
6220 (forward-char 1)
6221 t)
6222 ;; ,'s can occur inside {} & funcs
6223 ((looking-at "[{(]")
6224 (setq paren (1+ paren))
6225 (forward-char 1)
6226 t)
6227 ((looking-at "[})]")
6228 (setq paren (1- paren))
6229 (forward-char 1)
6230 (when (< paren sig-paren)
6231 (setq expect-signal nil)) ; ) that ends variables inside v2k arg list
6232 t))))
6233 ((looking-at "\\s-*\\(\\[[^]]+\\]\\)")
6234 (goto-char (match-end 0))
6235 (cond (newsig ; Memory, not just width. Patch last signal added's memory (nth 3)
6236 (setcar (cdr (cdr (cdr newsig))) (match-string 1)))
6237 (vec ;; Multidimensional
6238 (setq multidim (cons vec multidim))
6239 (setq vec (verilog-string-replace-matches
6240 "\\s-+" "" nil nil (match-string 1))))
6241 (t ;; Bit width
6242 (setq vec (verilog-string-replace-matches
6243 "\\s-+" "" nil nil (match-string 1))))))
6244 ;; Normal or escaped identifier -- note we remember the \ if escaped
6245 ((looking-at "\\s-*\\([a-zA-Z0-9`_$]+\\|\\\\[^ \t\n\f]+\\)")
6246 (goto-char (match-end 0))
6247 (setq keywd (match-string 1))
6248 (when (string-match "^\\\\" keywd)
6249 (setq keywd (concat keywd " "))) ;; Escaped ID needs space at end
6250 (cond ((equal keywd "input")
6251 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
6252 expect-signal 'sigs-in io t))
6253 ((equal keywd "output")
6254 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
6255 expect-signal 'sigs-out io t))
6256 ((equal keywd "inout")
6257 (setq vec nil enum nil rvalue nil newsig nil signed nil typedefed nil multidim nil sig-paren paren
6258 expect-signal 'sigs-inout io t))
6259 ((or (equal keywd "wire")
6260 (equal keywd "tri")
6261 (equal keywd "tri0")
6262 (equal keywd "tri1"))
6263 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6264 expect-signal 'sigs-wire)))
6265 ((member keywd (list "reg" "trireg"
6266 "byte" "shortint" "int" "longint" "integer" "time"
6267 "bit" "logic"))
6268 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6269 expect-signal 'sigs-reg)))
6270 ((equal keywd "assign")
6271 (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6272 expect-signal 'sigs-assign))
6273 ((or (equal keywd "supply0")
6274 (equal keywd "supply1")
6275 (equal keywd "supply")
6276 (equal keywd "localparam")
6277 (equal keywd "genvar"))
6278 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6279 expect-signal 'sigs-const)))
6280 ((or (equal keywd "parameter"))
6281 (unless io (setq vec nil enum nil rvalue nil signed nil typedefed nil multidim nil sig-paren paren
6282 expect-signal 'sigs-gparam)))
6283 ((equal keywd "signed")
6284 (setq signed "signed"))
6285 ((or (equal keywd "function")
6286 (equal keywd "task"))
6287 (setq functask (1+ functask)))
6288 ((or (equal keywd "endfunction")
6289 (equal keywd "endtask"))
6290 (setq functask (1- functask)))
6291 ((or (equal keywd "`ifdef")
6292 (equal keywd "`ifndef"))
6293 (setq rvalue t))
6294 ((verilog-typedef-name-p keywd)
6295 (setq typedefed keywd))
6296 ((and expect-signal
6297 (eq functask 0)
6298 (not rvalue)
6299 (eq paren sig-paren)
6300 (not (member keywd verilog-keywords)))
6301 ;; Add new signal to expect-signal's variable
6302 (setq newsig (list keywd vec nil nil enum signed typedefed multidim))
6303 (set expect-signal (cons newsig
6304 (symbol-value expect-signal))))))
6305 (t
6306 (forward-char 1)))
6307 (skip-syntax-forward " "))
6308 ;; Return arguments
6309 (vector (nreverse sigs-out)
6310 (nreverse sigs-inout)
6311 (nreverse sigs-in)
6312 (nreverse sigs-wire)
6313 (nreverse sigs-reg)
6314 (nreverse sigs-assign)
6315 (nreverse sigs-const)
6316 (nreverse sigs-gparam)))))
6317
6318 (eval-when-compile
6319 ;; Prevent compile warnings; these are let's, not globals
6320 ;; Do not remove the eval-when-compile
6321 ;; - we want a error when we are debugging this code if they are refed.
6322 (defvar sigs-in)
6323 (defvar sigs-inout)
6324 (defvar sigs-out))
6325
6326
6327 (defsubst verilog-modi-get-decls (modi)
6328 (verilog-modi-cache-results modi 'verilog-read-decls))
6329
6330 (defsubst verilog-modi-get-sub-decls (modi)
6331 (verilog-modi-cache-results modi 'verilog-read-sub-decls))
6332
6333
6334 ;; Signal reading for given module
6335 ;; Note these all take modi's - as returned from the
6336 ;; verilog-modi-current function.
6337 (defsubst verilog-decls-get-outputs (decls)
6338 (aref decls 0))
6339 (defsubst verilog-decls-get-inouts (decls)
6340 (aref decls 1))
6341 (defsubst verilog-decls-get-inputs (decls)
6342 (aref decls 2))
6343 (defsubst verilog-decls-get-wires (decls)
6344 (aref decls 3))
6345 (defsubst verilog-decls-get-regs (decls)
6346 (aref decls 4))
6347 (defsubst verilog-decls-get-assigns (decls)
6348 (aref decls 5))
6349 (defsubst verilog-decls-get-consts (decls)
6350 (aref decls 6))
6351 (defsubst verilog-decls-get-gparams (decls)
6352 (aref decls 7))
6353 (defsubst verilog-subdecls-get-outputs (subdecls)
6354 (aref subdecls 0))
6355 (defsubst verilog-subdecls-get-inouts (subdecls)
6356 (aref subdecls 1))
6357 (defsubst verilog-subdecls-get-inputs (subdecls)
6358 (aref subdecls 2))
6359
6360
6361 (defun verilog-read-sub-decls-sig (submoddecls comment port sig vec multidim)
6362 "For `verilog-read-sub-decls-line', add a signal."
6363 (let (portdata)
6364 (when sig
6365 (setq port (verilog-symbol-detick-denumber port))
6366 (setq sig (verilog-symbol-detick-denumber sig))
6367 (if sig (setq sig (verilog-string-replace-matches "^[---+~!|&]+" "" nil nil sig)))
6368 (if vec (setq vec (verilog-symbol-detick-denumber vec)))
6369 (if multidim (setq multidim (mapcar `verilog-symbol-detick-denumber multidim)))
6370 (unless (or (not sig)
6371 (equal sig "")) ;; Ignore .foo(1'b1) assignments
6372 (cond ((setq portdata (assoc port (verilog-decls-get-inouts submoddecls)))
6373 (setq sigs-inout (cons (list sig vec (concat "To/From " comment) nil nil
6374 (verilog-sig-signed portdata)
6375 (verilog-sig-type portdata)
6376 multidim)
6377 sigs-inout)))
6378 ((setq portdata (assoc port (verilog-decls-get-outputs submoddecls)))
6379 (setq sigs-out (cons (list sig vec (concat "From " comment) nil nil
6380 (verilog-sig-signed portdata)
6381 (verilog-sig-type portdata)
6382 multidim)
6383 sigs-out)))
6384 ((setq portdata (assoc port (verilog-decls-get-inputs submoddecls)))
6385 (setq sigs-in (cons (list sig vec (concat "To " comment) nil nil
6386 (verilog-sig-signed portdata)
6387 (verilog-sig-type portdata)
6388 multidim)
6389 sigs-in)))
6390 ;; (t -- warning pin isn't defined.) ; Leave for lint tool
6391 )))))
6392
6393 (defun verilog-read-sub-decls-line (submoddecls comment)
6394 "For `verilog-read-sub-decls', read lines of port defs until none match anymore.
6395 Return the list of signals found, using submodi to look up each port."
6396 (let (done port sig vec multidim)
6397 (save-excursion
6398 (forward-line 1)
6399 (while (not done)
6400 ;; Get port name
6401 (cond ((looking-at "\\s-*\\.\\s-*\\([a-zA-Z0-9`_$]*\\)\\s-*(\\s-*")
6402 (setq port (match-string 1))
6403 (goto-char (match-end 0)))
6404 ((looking-at "\\s-*\\.\\s-*\\(\\\\[^ \t\n\f]*\\)\\s-*(\\s-*")
6405 (setq port (concat (match-string 1) " ")) ;; escaped id's need trailing space
6406 (goto-char (match-end 0)))
6407 ((looking-at "\\s-*\\.[^(]*(")
6408 (setq port nil) ;; skip this line
6409 (goto-char (match-end 0)))
6410 (t
6411 (setq port nil done t))) ;; Unknown, ignore rest of line
6412 ;; Get signal name
6413 (when port
6414 (setq multidim nil)
6415 (cond ((looking-at "\\(\\\\[^ \t\n\f]*\\)\\s-*)")
6416 (setq sig (concat (match-string 1) " ") ;; escaped id's need trailing space
6417 vec nil))
6418 ; We intentionally ignore (non-escaped) signals with .s in them
6419 ; this prevents AUTOWIRE etc from noticing hierarchical sigs.
6420 ((looking-at "\\([^[({).]*\\)\\s-*)")
6421 (setq sig (verilog-string-remove-spaces (match-string 1))
6422 vec nil))
6423 ((looking-at "\\([^[({).]*\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*)")
6424 (setq sig (verilog-string-remove-spaces (match-string 1))
6425 vec (match-string 2)))
6426 ((looking-at "\\([^[({).]*\\)\\s-*/\\*\\(\\[[^*]+\\]\\)\\*/\\s-*)")
6427 (setq sig (verilog-string-remove-spaces (match-string 1))
6428 vec nil)
6429 (let ((parse (match-string 2)))
6430 (while (string-match "^\\(\\[[^]]+\\]\\)\\(.*\\)$" parse)
6431 (when vec (setq multidim (cons vec multidim)))
6432 (setq vec (match-string 1 parse))
6433 (setq parse (match-string 2 parse)))))
6434 ((looking-at "{\\(.*\\)}.*\\s-*)")
6435 (let ((mlst (split-string (match-string 1) ","))
6436 mstr)
6437 (while (setq mstr (pop mlst))
6438 ;;(unless noninteractive (message "sig: %s " mstr))
6439 (cond
6440 ((string-match "\\(['`a-zA-Z0-9_$]+\\)\\s-*$" mstr)
6441 (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
6442 vec nil)
6443 ;;(unless noninteractive (message "concat sig1: %s %s" mstr (match-string 1 mstr)))
6444 )
6445 ((string-match "\\([^[({).]+\\)\\s-*\\(\\[[^]]+\\]\\)\\s-*" mstr)
6446 (setq sig (verilog-string-remove-spaces (match-string 1 mstr))
6447 vec (match-string 2 mstr))
6448 ;;(unless noninteractive (message "concat sig2: '%s' '%s' '%s'" mstr (match-string 1 mstr) (match-string 2 mstr)))
6449 )
6450 (t
6451 (setq sig nil)))
6452 ;; Process signals
6453 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))))
6454 (t
6455 (setq sig nil)))
6456 ;; Process signals
6457 (verilog-read-sub-decls-sig submoddecls comment port sig vec multidim))
6458 ;;
6459 (forward-line 1)))))
6460
6461 (defun verilog-read-sub-decls ()
6462 "Internally parse signals going to modules under this module.
6463 Return a array of [ outputs inouts inputs ] signals for modules that are
6464 instantiated in this module. For example if declare A A (.B(SIG)) and SIG
6465 is a output, then SIG will be included in the list.
6466
6467 This only works on instantiations created with /*AUTOINST*/ converted by
6468 \\[verilog-auto-inst]. Otherwise, it would have to read in the whole
6469 component library to determine connectivity of the design.
6470
6471 One work around for this problem is to manually create // Inputs and //
6472 Outputs comments above subcell signals, for example:
6473
6474 module ModuleName (
6475 // Outputs
6476 .out (out),
6477 // Inputs
6478 .in (in));"
6479 (save-excursion
6480 (let ((end-mod-point (verilog-get-end-of-defun t))
6481 st-point end-inst-point
6482 ;; below 3 modified by verilog-read-sub-decls-line
6483 sigs-out sigs-inout sigs-in)
6484 (verilog-beg-of-defun)
6485 (while (verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-mod-point t)
6486 (save-excursion
6487 (goto-char (match-beginning 0))
6488 (unless (verilog-inside-comment-p)
6489 ;; Attempt to snarf a comment
6490 (let* ((submod (verilog-read-inst-module))
6491 (inst (verilog-read-inst-name))
6492 (comment (concat inst " of " submod ".v"))
6493 submodi submoddecls)
6494 (when (setq submodi (verilog-modi-lookup submod t))
6495 (setq submoddecls (verilog-modi-get-decls submodi))
6496 ;; This could have used a list created by verilog-auto-inst
6497 ;; However I want it to be runnable even on user's manually added signals
6498 (verilog-backward-open-paren)
6499 (setq end-inst-point (save-excursion (forward-sexp 1) (point))
6500 st-point (point))
6501 (while (re-search-forward "\\s *(?\\s *// Outputs" end-inst-point t)
6502 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-out
6503 (goto-char st-point)
6504 (while (re-search-forward "\\s *// Inouts" end-inst-point t)
6505 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-inout
6506 (goto-char st-point)
6507 (while (re-search-forward "\\s *// Inputs" end-inst-point t)
6508 (verilog-read-sub-decls-line submoddecls comment)) ;; Modifies sigs-in
6509 )))))
6510 ;; Combine duplicate bits
6511 ;;(setq rr (vector sigs-out sigs-inout sigs-in))
6512 (vector (verilog-signals-combine-bus (nreverse sigs-out))
6513 (verilog-signals-combine-bus (nreverse sigs-inout))
6514 (verilog-signals-combine-bus (nreverse sigs-in))))))
6515
6516 (defun verilog-read-inst-pins ()
6517 "Return an array of [ pins ] for the current instantiation at point.
6518 For example if declare A A (.B(SIG)) then B will be included in the list."
6519 (save-excursion
6520 (let ((end-mod-point (point)) ;; presume at /*AUTOINST*/ point
6521 pins pin)
6522 (verilog-backward-open-paren)
6523 (while (re-search-forward "\\.\\([^(,) \t\n\f]*\\)\\s-*" end-mod-point t)
6524 (setq pin (match-string 1))
6525 (unless (verilog-inside-comment-p)
6526 (setq pins (cons (list pin) pins))
6527 (when (looking-at "(")
6528 (forward-sexp 1))))
6529 (vector pins))))
6530
6531 (defun verilog-read-arg-pins ()
6532 "Return an array of [ pins ] for the current argument declaration at point."
6533 (save-excursion
6534 (let ((end-mod-point (point)) ;; presume at /*AUTOARG*/ point
6535 pins pin)
6536 (verilog-backward-open-paren)
6537 (while (re-search-forward "\\([a-zA-Z0-9$_.%`]+\\)" end-mod-point t)
6538 (setq pin (match-string 1))
6539 (unless (verilog-inside-comment-p)
6540 (setq pins (cons (list pin) pins))))
6541 (vector pins))))
6542
6543 (defun verilog-read-auto-constants (beg end-mod-point)
6544 "Return a list of AUTO_CONSTANTs used in the region from BEG to END-MOD-POINT."
6545 ;; Insert new
6546 (save-excursion
6547 (let (sig-list tpl-end-pt)
6548 (goto-char beg)
6549 (while (re-search-forward "\\<AUTO_CONSTANT" end-mod-point t)
6550 (if (not (looking-at "\\s *("))
6551 (error "%s: Missing () after AUTO_CONSTANT" (verilog-point-text)))
6552 (search-forward "(" end-mod-point)
6553 (setq tpl-end-pt (save-excursion
6554 (backward-char 1)
6555 (forward-sexp 1) ;; Moves to paren that closes argdecl's
6556 (backward-char 1)
6557 (point)))
6558 (while (re-search-forward "\\s-*\\([\"a-zA-Z0-9$_.%`]+\\)\\s-*,*" tpl-end-pt t)
6559 (setq sig-list (cons (list (match-string 1) nil nil) sig-list))))
6560 sig-list)))
6561
6562 (defun verilog-read-auto-lisp (start end)
6563 "Look for and evaluate a AUTO_LISP between START and END."
6564 (save-excursion
6565 (goto-char start)
6566 (while (re-search-forward "\\<AUTO_LISP(" end t)
6567 (backward-char)
6568 (let* ((beg-pt (prog1 (point)
6569 (forward-sexp 1))) ;; Closing paren
6570 (end-pt (point)))
6571 (eval-region beg-pt end-pt nil)))))
6572
6573 (eval-when-compile
6574 ;; Prevent compile warnings; these are let's, not globals
6575 ;; Do not remove the eval-when-compile
6576 ;; - we want a error when we are debugging this code if they are refed.
6577 (defvar sigs-in)
6578 (defvar sigs-out)
6579 (defvar got-sig)
6580 (defvar got-rvalue)
6581 (defvar uses-delayed)
6582 (defvar vector-skip-list))
6583
6584 (defun verilog-read-always-signals-recurse
6585 (exit-keywd rvalue ignore-next)
6586 "Recursive routine for parentheses/bracket matching.
6587 EXIT-KEYWD is expression to stop at, nil if top level.
6588 RVALUE is true if at right hand side of equal.
6589 IGNORE-NEXT is true to ignore next token, fake from inside case statement."
6590 (let* ((semi-rvalue (equal "endcase" exit-keywd)) ;; true if after a ; we are looking for rvalue
6591 keywd last-keywd sig-tolk sig-last-tolk gotend got-sig got-rvalue end-else-check)
6592 ;;(if dbg (setq dbg (concat dbg (format "Recursion %S %S %S\n" exit-keywd rvalue ignore-next))))
6593 (while (not (or (eobp) gotend))
6594 (cond
6595 ((looking-at "//")
6596 (search-forward "\n"))
6597 ((looking-at "/\\*")
6598 (or (search-forward "*/")
6599 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6600 ((looking-at "(\\*")
6601 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
6602 (search-forward "*)")
6603 (error "%s: Unmatched (* *), at char %d" (verilog-point-text) (point))))
6604 (t (setq keywd (buffer-substring-no-properties
6605 (point)
6606 (save-excursion (when (eq 0 (skip-chars-forward "a-zA-Z0-9$_.%`"))
6607 (forward-char 1))
6608 (point)))
6609 sig-last-tolk sig-tolk
6610 sig-tolk nil)
6611 ;;(if dbg (setq dbg (concat dbg (format "\tPt=%S %S\trv=%S in=%S ee=%S\n" (point) keywd rvalue ignore-next end-else-check))))
6612 (cond
6613 ((equal keywd "\"")
6614 (or (re-search-forward "[^\\]\"" nil t)
6615 (error "%s: Unmatched quotes, at char %d" (verilog-point-text) (point))))
6616 ;; else at top level loop, keep parsing
6617 ((and end-else-check (equal keywd "else"))
6618 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else %s\n" keywd))))
6619 ;; no forward movement, want to see else in lower loop
6620 (setq end-else-check nil))
6621 ;; End at top level loop
6622 ((and end-else-check (looking-at "[^ \t\n\f]"))
6623 ;;(if dbg (setq dbg (concat dbg (format "\tif-check-else-other %s\n" keywd))))
6624 (setq gotend t))
6625 ;; Final statement?
6626 ((and exit-keywd (equal keywd exit-keywd))
6627 (setq gotend t)
6628 (forward-char (length keywd)))
6629 ;; Standard tokens...
6630 ((equal keywd ";")
6631 (setq ignore-next nil rvalue semi-rvalue)
6632 ;; Final statement at top level loop?
6633 (when (not exit-keywd)
6634 ;;(if dbg (setq dbg (concat dbg (format "\ttop-end-check %s\n" keywd))))
6635 (setq end-else-check t))
6636 (forward-char 1))
6637 ((equal keywd "'")
6638 (if (looking-at "'s?[hdxbo][0-9a-fA-F_xz? \t]*")
6639 (goto-char (match-end 0))
6640 (forward-char 1)))
6641 ((equal keywd ":") ;; Case statement, begin/end label, x?y:z
6642 (cond ((equal "endcase" exit-keywd) ;; case x: y=z; statement next
6643 (setq ignore-next nil rvalue nil))
6644 ((equal "?" exit-keywd) ;; x?y:z rvalue
6645 ) ;; NOP
6646 (got-sig ;; label: statement
6647 (setq ignore-next nil rvalue semi-rvalue got-sig nil))
6648 ((not rvalue) ;; begin label
6649 (setq ignore-next t rvalue nil)))
6650 (forward-char 1))
6651 ((equal keywd "=")
6652 (if (eq (char-before) ?< )
6653 (setq uses-delayed 1))
6654 (setq ignore-next nil rvalue t)
6655 (forward-char 1))
6656 ((equal keywd "?")
6657 (forward-char 1)
6658 (verilog-read-always-signals-recurse ":" rvalue nil))
6659 ((equal keywd "[")
6660 (forward-char 1)
6661 (verilog-read-always-signals-recurse "]" t nil))
6662 ((equal keywd "(")
6663 (forward-char 1)
6664 (cond (sig-last-tolk ;; Function call; zap last signal
6665 (setq got-sig nil)))
6666 (cond ((equal last-keywd "for")
6667 (verilog-read-always-signals-recurse ";" nil nil)
6668 (verilog-read-always-signals-recurse ";" t nil)
6669 (verilog-read-always-signals-recurse ")" nil nil))
6670 (t (verilog-read-always-signals-recurse ")" t nil))))
6671 ((equal keywd "begin")
6672 (skip-syntax-forward "w_")
6673 (verilog-read-always-signals-recurse "end" nil nil)
6674 ;;(if dbg (setq dbg (concat dbg (format "\tgot-end %s\n" exit-keywd))))
6675 (setq ignore-next nil rvalue semi-rvalue)
6676 (if (not exit-keywd) (setq end-else-check t)))
6677 ((or (equal keywd "case")
6678 (equal keywd "casex")
6679 (equal keywd "casez"))
6680 (skip-syntax-forward "w_")
6681 (verilog-read-always-signals-recurse "endcase" t nil)
6682 (setq ignore-next nil rvalue semi-rvalue)
6683 (if (not exit-keywd) (setq gotend t))) ;; top level begin/end
6684 ((string-match "^[$`a-zA-Z_]" keywd) ;; not exactly word constituent
6685 (cond ((or (equal keywd "`ifdef")
6686 (equal keywd "`ifndef"))
6687 (setq ignore-next t))
6688 ((or ignore-next
6689 (member keywd verilog-keywords)
6690 (string-match "^\\$" keywd)) ;; PLI task
6691 (setq ignore-next nil))
6692 (t
6693 (setq keywd (verilog-symbol-detick-denumber keywd))
6694 (when got-sig
6695 (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
6696 (setq sigs-out (cons got-sig sigs-out)))
6697 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
6698 )
6699 (setq got-rvalue rvalue
6700 got-sig (if (or (not keywd)
6701 (assoc keywd (if got-rvalue sigs-in sigs-out)))
6702 nil (list keywd nil nil))
6703 sig-tolk t)))
6704 (skip-chars-forward "a-zA-Z0-9$_.%`"))
6705 (t
6706 (forward-char 1)))
6707 ;; End of non-comment token
6708 (setq last-keywd keywd)))
6709 (skip-syntax-forward " "))
6710 ;; Append the final pending signal
6711 (when got-sig
6712 (if got-rvalue (setq sigs-in (cons got-sig sigs-in))
6713 (setq sigs-out (cons got-sig sigs-out)))
6714 ;;(if dbg (setq dbg (concat dbg (format "\t\tgot-sig=%S rv=%S\n" got-sig got-rvalue))))
6715 (setq got-sig nil))
6716 ;;(if dbg (setq dbg (concat dbg (format "ENDRecursion %s\n" exit-keywd))))
6717 ))
6718
6719 (defun verilog-read-always-signals ()
6720 "Parse always block at point and return list of (outputs inout inputs)."
6721 ;; Insert new
6722 (save-excursion
6723 (let* (;;(dbg "")
6724 sigs-in sigs-out
6725 uses-delayed) ;; Found signal/rvalue; push if not function
6726 (search-forward ")")
6727 (verilog-read-always-signals-recurse nil nil nil)
6728 ;;(if dbg (save-excursion (set-buffer (get-buffer-create "*vl-dbg*")) (delete-region (point-min) (point-max)) (insert dbg) (setq dbg "")))
6729 ;; Return what was found
6730 (list sigs-out nil sigs-in uses-delayed))))
6731
6732 (defun verilog-read-instants ()
6733 "Parse module at point and return list of ( ( file instance ) ... )."
6734 (verilog-beg-of-defun)
6735 (let* ((end-mod-point (verilog-get-end-of-defun t))
6736 (state nil)
6737 (instants-list nil))
6738 (save-excursion
6739 (while (< (point) end-mod-point)
6740 ;; Stay at level 0, no comments
6741 (while (progn
6742 (setq state (parse-partial-sexp (point) end-mod-point 0 t nil))
6743 (or (> (car state) 0) ; in parens
6744 (nth 5 state) ; comment
6745 ))
6746 (forward-line 1))
6747 (beginning-of-line)
6748 (if (looking-at "^\\s-*\\([a-zA-Z0-9`_$]+\\)\\s-+\\([a-zA-Z0-9`_$]+\\)\\s-*(")
6749 ;;(if (looking-at "^\\(.+\\)$")
6750 (let ((module (match-string 1))
6751 (instant (match-string 2)))
6752 (if (not (member module verilog-keywords))
6753 (setq instants-list (cons (list module instant) instants-list)))))
6754 (forward-line 1)))
6755 instants-list))
6756
6757
6758 (defun verilog-read-auto-template (module)
6759 "Look for a auto_template for the instantiation of the given MODULE.
6760 If found returns the signal name connections. Return REGEXP and
6761 list of ( (signal_name connection_name)... )."
6762 (save-excursion
6763 ;; Find beginning
6764 (let ((tpl-regexp "\\([0-9]+\\)")
6765 (lineno 0)
6766 (templateno 0)
6767 tpl-sig-list tpl-wild-list tpl-end-pt rep)
6768 (cond ((or
6769 (re-search-backward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)
6770 (progn
6771 (goto-char (point-min))
6772 (re-search-forward (concat "^\\s-*/?\\*?\\s-*" module "\\s-+AUTO_TEMPLATE") nil t)))
6773 (goto-char (match-end 0))
6774 ;; Parse "REGEXP"
6775 ;; We reserve @"..." for future lisp expressions that evaluate once-per-AUTOINST
6776 (when (looking-at "\\s-*\"\\([^\"]*)\\)\"")
6777 (setq tpl-regexp (match-string 1))
6778 (goto-char (match-end 0)))
6779 (search-forward "(")
6780 ;; Parse lines in the template
6781 (when verilog-auto-inst-template-numbers
6782 (save-excursion
6783 (goto-char (point-min))
6784 (while (search-forward "AUTO_TEMPLATE" nil t)
6785 (setq templateno (1+ templateno)))))
6786 (setq tpl-end-pt (save-excursion
6787 (backward-char 1)
6788 (forward-sexp 1) ;; Moves to paren that closes argdecl's
6789 (backward-char 1)
6790 (point)))
6791 ;;
6792 (while (< (point) tpl-end-pt)
6793 (cond ((looking-at "\\s-*\\.\\([a-zA-Z0-9`_$]+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
6794 (setq tpl-sig-list (cons (list
6795 (match-string-no-properties 1)
6796 (match-string-no-properties 2)
6797 templateno lineno)
6798 tpl-sig-list))
6799 (goto-char (match-end 0)))
6800 ;; Regexp form??
6801 ((looking-at
6802 ;; Regexp bug in XEmacs disallows ][ inside [], and wants + last
6803 "\\s-*\\.\\(\\([a-zA-Z0-9`_$+@^.*?|---]+\\|[][]\\|\\\\[()|]\\)+\\)\\s-*(\\(.*\\))\\s-*\\(,\\|)\\s-*;\\)")
6804 (setq rep (match-string-no-properties 3))
6805 (goto-char (match-end 0))
6806 (setq tpl-wild-list
6807 (cons (list
6808 (concat "^"
6809 (verilog-string-replace-matches "@" "\\\\([0-9]+\\\\)" nil nil
6810 (match-string 1))
6811 "$")
6812 rep
6813 templateno lineno)
6814 tpl-wild-list)))
6815 ((looking-at "[ \t\f]+")
6816 (goto-char (match-end 0)))
6817 ((looking-at "\n")
6818 (setq lineno (1+ lineno))
6819 (goto-char (match-end 0)))
6820 ((looking-at "//")
6821 (search-forward "\n"))
6822 ((looking-at "/\\*")
6823 (forward-char 2)
6824 (or (search-forward "*/")
6825 (error "%s: Unmatched /* */, at char %d" (verilog-point-text) (point))))
6826 (t
6827 (error "%s: AUTO_TEMPLATE parsing error: %s"
6828 (verilog-point-text)
6829 (progn (looking-at ".*$") (match-string 0))))))
6830 ;; Return
6831 (vector tpl-regexp
6832 (list tpl-sig-list tpl-wild-list)))
6833 ;; If no template found
6834 (t (vector tpl-regexp nil))))))
6835 ;;(progn (find-file "auto-template.v") (verilog-read-auto-template "ptl_entry"))
6836
6837 (defun verilog-set-define (defname defvalue &optional buffer enumname)
6838 "Set the definition DEFNAME to the DEFVALUE in the given BUFFER.
6839 Optionally associate it with the specified enumeration ENUMNAME."
6840 (save-excursion
6841 (set-buffer (or buffer (current-buffer)))
6842 (let ((mac (intern (concat "vh-" defname))))
6843 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
6844 ;; Need to define to a constant if no value given
6845 (set (make-variable-buffer-local mac)
6846 (if (equal defvalue "") "1" defvalue)))
6847 (if enumname
6848 (let ((enumvar (intern (concat "venum-" enumname))))
6849 ;;(message "Define %s=%s" defname defvalue) (sleep-for 1)
6850 (make-variable-buffer-local enumvar)
6851 (add-to-list enumvar defname)))))
6852
6853 (defun verilog-read-defines (&optional filename recurse subcall)
6854 "Read `defines and parameters for the current file, or optional FILENAME.
6855 If the filename is provided, `verilog-library-flags' will be used to
6856 resolve it. If optional RECURSE is non-nil, recurse through `includes.
6857
6858 Parameters must be simple assignments to constants, or have their own
6859 \"parameter\" label rather than a list of parameters. Thus:
6860
6861 parameter X = 5, Y = 10; // Ok
6862 parameter X = {1'b1, 2'h2}; // Ok
6863 parameter X = {1'b1, 2'h2}, Y = 10; // Bad, make into 2 parameter lines
6864
6865 Defines must be simple text substitutions, one on a line, starting
6866 at the beginning of the line. Any ifdefs or multiline comments around the
6867 define are ignored.
6868
6869 Defines are stored inside Emacs variables using the name vh-{definename}.
6870
6871 This function is useful for setting vh-* variables. The file variables
6872 feature can be used to set defines that `verilog-mode' can see; put at the
6873 *END* of your file something like:
6874
6875 // Local Variables:
6876 // vh-macro:\"macro_definition\"
6877 // End:
6878
6879 If macros are defined earlier in the same file and you want their values,
6880 you can read them automatically (provided `enable-local-eval' is on):
6881
6882 // Local Variables:
6883 // eval:(verilog-read-defines)
6884 // eval:(verilog-read-defines \"group_standard_includes.v\")
6885 // End:
6886
6887 Note these are only read when the file is first visited, you must use
6888 \\[find-alternate-file] RET to have these take effect after editing them!
6889
6890 If you want to disable the \"Process `eval' or hook local variables\"
6891 warning message, you need to add to your .emacs file:
6892
6893 (setq enable-local-eval t)"
6894 (let ((origbuf (current-buffer)))
6895 (save-excursion
6896 (unless subcall (verilog-getopt-flags))
6897 (when filename
6898 (let ((fns (verilog-library-filenames filename (buffer-file-name))))
6899 (if fns
6900 (set-buffer (find-file-noselect (car fns)))
6901 (error (concat (verilog-point-text)
6902 ": Can't find verilog-read-defines file: " filename)))))
6903 (when recurse
6904 (goto-char (point-min))
6905 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
6906 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string-no-properties 1))))
6907 (unless (verilog-inside-comment-p)
6908 (verilog-read-defines inc recurse t)))))
6909 ;; Read `defines
6910 ;; note we don't use verilog-re... it's faster this way, and that
6911 ;; function has problems when comments are at the end of the define
6912 (goto-char (point-min))
6913 (while (re-search-forward "^\\s-*`define\\s-+\\([a-zA-Z0-9_$]+\\)\\s-+\\(.*\\)$" nil t)
6914 (let ((defname (match-string-no-properties 1))
6915 (defvalue (match-string-no-properties 2)))
6916 (setq defvalue (verilog-string-replace-matches "\\s-*/[/*].*$" "" nil nil defvalue))
6917 (verilog-set-define defname defvalue origbuf)))
6918 ;; Hack: Read parameters
6919 (goto-char (point-min))
6920 (while (re-search-forward
6921 "^\\s-*\\(parameter\\|localparam\\)\\(\\(\\s-*\\[[^]]*\\]\\|\\)\\s-+\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\|\\)\\s-*" nil t)
6922 (let ((var (match-string-no-properties 4))
6923 (val (match-string-no-properties 5))
6924 enumname)
6925 ;; The primary way of getting defines is verilog-read-decls
6926 ;; However, that isn't called yet for included files, so we'll add another scheme
6927 (if (looking-at "[^\n]*synopsys\\s +enum\\s +\\([a-zA-Z0-9_]+\\)")
6928 (setq enumname (match-string-no-properties 1)))
6929 (if var
6930 (verilog-set-define var val origbuf enumname))
6931 (forward-comment 999)
6932 (while (looking-at "\\s-*,?\\s-*\\([a-zA-Z0-9_$]+\\)\\s-*=\\s-*\\([^;,]*\\),?\\s-*")
6933 (verilog-set-define (match-string-no-properties 1) (match-string-no-properties 2) origbuf enumname)
6934 (goto-char (match-end 0))
6935 (forward-comment 999)))))))
6936
6937 (defun verilog-read-includes ()
6938 "Read `includes for the current file.
6939 This will find all of the `includes which are at the beginning of lines,
6940 ignoring any ifdefs or multiline comments around them.
6941 `verilog-read-defines' is then performed on the current and each included
6942 file.
6943
6944 It is often useful put at the *END* of your file something like:
6945
6946 // Local Variables:
6947 // eval:(verilog-read-defines)
6948 // eval:(verilog-read-includes)
6949 // End:
6950
6951 Note includes are only read when the file is first visited, you must use
6952 \\[find-alternate-file] RET to have these take effect after editing them!
6953
6954 It is good to get in the habit of including all needed files in each .v
6955 file that needs it, rather than waiting for compile time. This will aid
6956 this process, Verilint, and readability. To prevent defining the same
6957 variable over and over when many modules are compiled together, put a test
6958 around the inside each include file:
6959
6960 foo.v (a include):
6961 `ifdef _FOO_V // include if not already included
6962 `else
6963 `define _FOO_V
6964 ... contents of file
6965 `endif // _FOO_V"
6966 ;;slow: (verilog-read-defines nil t))
6967 (save-excursion
6968 (verilog-getopt-flags)
6969 (goto-char (point-min))
6970 (while (re-search-forward "^\\s-*`include\\s-+\\([^ \t\n\f]+\\)" nil t)
6971 (let ((inc (verilog-string-replace-matches "\"" "" nil nil (match-string 1))))
6972 (verilog-read-defines inc nil t)))))
6973
6974 (defun verilog-read-signals (&optional start end)
6975 "Return a simple list of all possible signals in the file.
6976 Bounded by optional region from START to END. Overly aggressive but fast.
6977 Some macros and such are also found and included. For dinotrace.el."
6978 (let (sigs-all keywd)
6979 (progn;save-excursion
6980 (goto-char (or start (point-min)))
6981 (setq end (or end (point-max)))
6982 (while (re-search-forward "[\"/a-zA-Z_.%`]" end t)
6983 (forward-char -1)
6984 (cond
6985 ((looking-at "//")
6986 (search-forward "\n"))
6987 ((looking-at "/\\*")
6988 (search-forward "*/"))
6989 ((looking-at "(\\*")
6990 (or (looking-at "(\\*\\s-*)") ; It's a "always @ (*)"
6991 (search-forward "*)")))
6992 ((eq ?\" (following-char))
6993 (re-search-forward "[^\\]\"")) ;; don't forward-char first, since we look for a non backslash first
6994 ((looking-at "\\s-*\\([a-zA-Z0-9$_.%`]+\\)")
6995 (goto-char (match-end 0))
6996 (setq keywd (match-string-no-properties 1))
6997 (or (member keywd verilog-keywords)
6998 (member keywd sigs-all)
6999 (setq sigs-all (cons keywd sigs-all))))
7000 (t (forward-char 1))))
7001 ;; Return list
7002 sigs-all)))
7003
7004 ;;
7005 ;; Argument file parsing
7006 ;;
7007
7008 (defun verilog-getopt (arglist)
7009 "Parse -f, -v etc arguments in ARGLIST list or string."
7010 (unless (listp arglist) (setq arglist (list arglist)))
7011 (let ((space-args '())
7012 arg next-param)
7013 ;; Split on spaces, so users can pass whole command lines
7014 (while arglist
7015 (setq arg (car arglist)
7016 arglist (cdr arglist))
7017 (while (string-match "^\\([^ \t\n\f]+\\)[ \t\n\f]*\\(.*$\\)" arg)
7018 (setq space-args (append space-args
7019 (list (match-string-no-properties 1 arg))))
7020 (setq arg (match-string 2 arg))))
7021 ;; Parse arguments
7022 (while space-args
7023 (setq arg (car space-args)
7024 space-args (cdr space-args))
7025 (cond
7026 ;; Need another arg
7027 ((equal arg "-f")
7028 (setq next-param arg))
7029 ((equal arg "-v")
7030 (setq next-param arg))
7031 ((equal arg "-y")
7032 (setq next-param arg))
7033 ;; +libext+(ext1)+(ext2)...
7034 ((string-match "^\\+libext\\+\\(.*\\)" arg)
7035 (setq arg (match-string 1 arg))
7036 (while (string-match "\\([^+]+\\)\\+?\\(.*\\)" arg)
7037 (verilog-add-list-unique `verilog-library-extensions
7038 (match-string 1 arg))
7039 (setq arg (match-string 2 arg))))
7040 ;;
7041 ((or (string-match "^-D\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; -Ddefine=val
7042 (string-match "^-D\\([^+=]*\\)\\(\\)" arg) ;; -Ddefine
7043 (string-match "^\\+define\\([^+=]*\\)[+=]\\(.*\\)" arg) ;; +define+val
7044 (string-match "^\\+define\\([^+=]*\\)\\(\\)" arg)) ;; +define+define
7045 (verilog-set-define (match-string 1 arg) (match-string 2 arg)))
7046 ;;
7047 ((or (string-match "^\\+incdir\\+\\(.*\\)" arg) ;; +incdir+dir
7048 (string-match "^-I\\(.*\\)" arg)) ;; -Idir
7049 (verilog-add-list-unique `verilog-library-directories
7050 (match-string 1 arg)))
7051 ;; Ignore
7052 ((equal "+librescan" arg))
7053 ((string-match "^-U\\(.*\\)" arg)) ;; -Udefine
7054 ;; Second parameters
7055 ((equal next-param "-f")
7056 (setq next-param nil)
7057 (verilog-getopt-file arg))
7058 ((equal next-param "-v")
7059 (setq next-param nil)
7060 (verilog-add-list-unique `verilog-library-files arg))
7061 ((equal next-param "-y")
7062 (setq next-param nil)
7063 (verilog-add-list-unique `verilog-library-directories arg))
7064 ;; Filename
7065 ((string-match "^[^-+]" arg)
7066 (verilog-add-list-unique `verilog-library-files arg))
7067 ;; Default - ignore; no warning
7068 ))))
7069 ;;(verilog-getopt (list "+libext+.a+.b" "+incdir+foodir" "+define+a+aval" "-f" "otherf" "-v" "library" "-y" "dir"))
7070
7071 (defun verilog-getopt-file (filename)
7072 "Read Verilog options from the specified FILENAME."
7073 (save-excursion
7074 (let ((fns (verilog-library-filenames filename (buffer-file-name)))
7075 (orig-buffer (current-buffer))
7076 line)
7077 (if fns
7078 (set-buffer (find-file-noselect (car fns)))
7079 (error (concat (verilog-point-text)
7080 ": Can't find verilog-getopt-file -f file: " filename)))
7081 (goto-char (point-min))
7082 (while (not (eobp))
7083 (setq line (buffer-substring (point)
7084 (save-excursion (end-of-line) (point))))
7085 (forward-line 1)
7086 (when (string-match "//" line)
7087 (setq line (substring line 0 (match-beginning 0))))
7088 (save-excursion
7089 (set-buffer orig-buffer) ; Variables are buffer-local, so need right context.
7090 (verilog-getopt line))))))
7091
7092 (defun verilog-getopt-flags ()
7093 "Convert `verilog-library-flags' into standard library variables."
7094 ;; If the flags are local, then all the outputs should be local also
7095 (when (local-variable-p `verilog-library-flags (current-buffer))
7096 (mapc 'make-local-variable '(verilog-library-extensions
7097 verilog-library-directories
7098 verilog-library-files
7099 verilog-library-flags)))
7100 ;; Allow user to customize
7101 (run-hooks 'verilog-before-getopt-flags-hook)
7102 ;; Process arguments
7103 (verilog-getopt verilog-library-flags)
7104 ;; Allow user to customize
7105 (run-hooks 'verilog-getopt-flags-hook))
7106
7107 (defun verilog-add-list-unique (varref object)
7108 "Append to VARREF list the given OBJECT,
7109 unless it is already a member of the variable's list."
7110 (unless (member object (symbol-value varref))
7111 (set varref (append (symbol-value varref) (list object))))
7112 varref)
7113 ;;(progn (setq l '()) (verilog-add-list-unique `l "a") (verilog-add-list-unique `l "a") l)
7114
7115 \f
7116 ;;
7117 ;; Cached directory support
7118 ;;
7119
7120 (defvar verilog-dir-cache-preserving nil
7121 "If set, the directory cache is enabled, and file system changes are ignored.
7122 See `verilog-dir-exists-p' and `verilog-dir-files'.")
7123
7124 ;; If adding new cached variable, add also to verilog-preserve-dir-cache
7125 (defvar verilog-dir-cache-list nil
7126 "Alist of (((Cwd Dirname) Results)...) for caching `verilog-dir-files'.")
7127 (defvar verilog-dir-cache-lib-filenames nil
7128 "Cached data for `verilog-library-filenames'.")
7129
7130 (defmacro verilog-preserve-dir-cache (&rest body)
7131 "Execute the BODY forms, allowing directory cache preservation within BODY.
7132 This means that changes inside BODY made to the file system will not be
7133 seen by the `verilog-dir-files' and related functions."
7134 `(let ((verilog-dir-cache-preserving t)
7135 verilog-dir-cache-list
7136 verilog-dir-cache-lib-filenames)
7137 (progn ,@body)))
7138
7139 (defun verilog-dir-files (dirname)
7140 "Return all filenames in the DIRNAME directory.
7141 Relative paths depend on the `default-directory'.
7142 Results are cached if inside `verilog-preserve-dir-cache'."
7143 (unless verilog-dir-cache-preserving
7144 (setq verilog-dir-cache-list nil)) ;; Cache disabled
7145 ;; We don't use expand-file-name on the dirname to make key, as it's slow
7146 (let* ((cache-key (list dirname default-directory))
7147 (fass (assoc cache-key verilog-dir-cache-list))
7148 exp-dirname data)
7149 (cond (fass ;; Return data from cache hit
7150 (nth 1 fass))
7151 (t
7152 (setq exp-dirname (expand-file-name dirname)
7153 data (and (file-directory-p exp-dirname)
7154 (directory-files exp-dirname nil nil nil)))
7155 ;; Note we also encache nil for non-existing dirs.
7156 (setq verilog-dir-cache-list (cons (list cache-key data)
7157 verilog-dir-cache-list))
7158 data))))
7159 ;; Miss-and-hit test:
7160 ;;(verilog-preserve-dir-cache (prin1 (verilog-dir-files "."))
7161 ;; (prin1 (verilog-dir-files ".")) nil)
7162
7163 (defun verilog-dir-file-exists-p (filename)
7164 "Return true if FILENAME exists.
7165 Like `file-exists-p' but results are cached if inside
7166 `verilog-preserve-dir-cache'."
7167 (let* ((dirname (file-name-directory filename))
7168 ;; Correct for file-name-nondirectory returning same if no slash.
7169 (dirnamed (if (or (not dirname) (equal dirname filename))
7170 default-directory dirname))
7171 (flist (verilog-dir-files dirnamed)))
7172 (and flist
7173 (member (file-name-nondirectory filename) flist)
7174 t)))
7175 ;;(verilog-dir-file-exists-p "verilog-mode.el")
7176 ;;(verilog-dir-file-exists-p "../verilog-mode/verilog-mode.el")
7177
7178 \f
7179 ;;
7180 ;; Module name lookup
7181 ;;
7182
7183 (defun verilog-module-inside-filename-p (module filename)
7184 "Return point if MODULE is specified inside FILENAME, else nil.
7185 Allows version control to check out the file if need be."
7186 (and (or (file-exists-p filename)
7187 (and (fboundp 'vc-backend)
7188 (vc-backend filename)))
7189 (let (pt)
7190 (save-excursion
7191 (set-buffer (find-file-noselect filename))
7192 (goto-char (point-min))
7193 (while (and
7194 ;; It may be tempting to look for verilog-defun-re, don't, it slows things down a lot!
7195 (verilog-re-search-forward-quick "\\<module\\>" nil t)
7196 (verilog-re-search-forward-quick "[(;]" nil t))
7197 (if (equal module (verilog-read-module-name))
7198 (setq pt (point))))
7199 pt))))
7200
7201 (defun verilog-is-number (symbol)
7202 "Return true if SYMBOL is number-like."
7203 (or (string-match "^[0-9 \t:]+$" symbol)
7204 (string-match "^[---]*[0-9]+$" symbol)
7205 (string-match "^[0-9 \t]+'s?[hdxbo][0-9a-fA-F_xz? \t]*$" symbol)))
7206
7207 (defun verilog-symbol-detick (symbol wing-it)
7208 "Return an expanded SYMBOL name without any defines.
7209 If the variable vh-{symbol} is defined, return that value.
7210 If undefined, and WING-IT, return just SYMBOL without the tick, else nil."
7211 (while (and symbol (string-match "^`" symbol))
7212 (setq symbol (substring symbol 1))
7213 (setq symbol
7214 (if (boundp (intern (concat "vh-" symbol)))
7215 ;; Emacs has a bug where boundp on a buffer-local
7216 ;; variable in only one buffer returns t in another.
7217 ;; This can confuse, so check for nil.
7218 (let ((val (eval (intern (concat "vh-" symbol)))))
7219 (if (eq val nil)
7220 (if wing-it symbol nil)
7221 val))
7222 (if wing-it symbol nil))))
7223 symbol)
7224 ;;(verilog-symbol-detick "`mod" nil)
7225
7226 (defun verilog-symbol-detick-denumber (symbol)
7227 "Return SYMBOL with defines converted and any numbers dropped to nil."
7228 (when (string-match "^`" symbol)
7229 ;; This only will work if the define is a simple signal, not
7230 ;; something like a[b]. Sorry, it should be substituted into the parser
7231 (setq symbol
7232 (verilog-string-replace-matches
7233 "\[[^0-9: \t]+\]" "" nil nil
7234 (or (verilog-symbol-detick symbol nil)
7235 (if verilog-auto-sense-defines-constant
7236 "0"
7237 symbol)))))
7238 (if (verilog-is-number symbol)
7239 nil
7240 symbol))
7241
7242 (defun verilog-symbol-detick-text (text)
7243 "Return TEXT without any known defines.
7244 If the variable vh-{symbol} is defined, substitute that value."
7245 (let ((ok t) symbol val)
7246 (while (and ok (string-match "`\\([a-zA-Z0-9_]+\\)" text))
7247 (setq symbol (match-string 1 text))
7248 (message symbol)
7249 (cond ((and
7250 (boundp (intern (concat "vh-" symbol)))
7251 ;; Emacs has a bug where boundp on a buffer-local
7252 ;; variable in only one buffer returns t in another.
7253 ;; This can confuse, so check for nil.
7254 (setq val (eval (intern (concat "vh-" symbol)))))
7255 (setq text (replace-match val nil nil text)))
7256 (t (setq ok nil)))))
7257 text)
7258 ;;(progn (setq vh-mod "`foo" vh-foo "bar") (verilog-symbol-detick-text "bar `mod `undefed"))
7259
7260 (defun verilog-expand-dirnames (&optional dirnames)
7261 "Return a list of existing directories given a list of wildcarded DIRNAMES.
7262 Or, just the existing dirnames themselves if there are no wildcards."
7263 ;; Note this function is performance critical.
7264 ;; Do not call anything that requires disk access that cannot be cached.
7265 (interactive)
7266 (unless dirnames (error "`verilog-library-directories' should include at least '.'"))
7267 (setq dirnames (reverse dirnames)) ; not nreverse
7268 (let ((dirlist nil)
7269 pattern dirfile dirfiles dirname root filename rest basefile)
7270 (while dirnames
7271 (setq dirname (substitute-in-file-name (car dirnames))
7272 dirnames (cdr dirnames))
7273 (cond ((string-match (concat "^\\(\\|[/\\]*[^*?]*[/\\]\\)" ;; root
7274 "\\([^/\\]*[*?][^/\\]*\\)" ;; filename with *?
7275 "\\(.*\\)") ;; rest
7276 dirname)
7277 (setq root (match-string 1 dirname)
7278 filename (match-string 2 dirname)
7279 rest (match-string 3 dirname)
7280 pattern filename)
7281 ;; now replace those * and ? with .+ and .
7282 ;; use ^ and /> to get only whole file names
7283 (setq pattern (verilog-string-replace-matches "[*]" ".+" nil nil pattern)
7284 pattern (verilog-string-replace-matches "[?]" "." nil nil pattern)
7285 pattern (concat "^" pattern "$")
7286 dirfiles (verilog-dir-files root))
7287 (while dirfiles
7288 (setq basefile (car dirfiles)
7289 dirfile (expand-file-name (concat root basefile rest))
7290 dirfiles (cdr dirfiles))
7291 (if (and (string-match pattern basefile)
7292 ;; Don't allow abc/*/rtl to match abc/rtl via ..
7293 (not (equal basefile "."))
7294 (not (equal basefile ".."))
7295 (file-directory-p dirfile))
7296 (setq dirlist (cons dirfile dirlist)))))
7297 ;; Defaults
7298 (t
7299 (if (file-directory-p dirname)
7300 (setq dirlist (cons dirname dirlist))))))
7301 dirlist))
7302 ;;(verilog-expand-dirnames (list "." ".." "nonexist" "../*" "/home/wsnyder/*/v"))
7303
7304 (defun verilog-library-filenames (filename current &optional check-ext)
7305 "Return a search path to find the given FILENAME or module name.
7306 Uses the CURRENT filename, `verilog-library-directories' and
7307 `verilog-library-extensions' variables to build the path.
7308 With optional CHECK-EXT also check `verilog-library-extensions'."
7309 (unless verilog-dir-cache-preserving
7310 (setq verilog-dir-cache-lib-filenames nil))
7311 (let* ((cache-key (list filename current check-ext))
7312 (fass (assoc cache-key verilog-dir-cache-lib-filenames))
7313 chkdirs chkdir chkexts fn outlist)
7314 (cond (fass ;; Return data from cache hit
7315 (nth 1 fass))
7316 (t
7317 ;; Note this expand can't be easily cached, as we need to
7318 ;; pick up buffer-local variables for newly read sub-module files
7319 (setq chkdirs (verilog-expand-dirnames verilog-library-directories))
7320 (while chkdirs
7321 (setq chkdir (expand-file-name (car chkdirs)
7322 (file-name-directory current))
7323 chkexts (if check-ext verilog-library-extensions `("")))
7324 (while chkexts
7325 (setq fn (expand-file-name (concat filename (car chkexts))
7326 chkdir))
7327 ;;(message "Check for %s" fn)
7328 (if (verilog-dir-file-exists-p fn)
7329 (setq outlist (cons (expand-file-name
7330 fn (file-name-directory current))
7331 outlist)))
7332 (setq chkexts (cdr chkexts)))
7333 (setq chkdirs (cdr chkdirs)))
7334 (setq outlist (nreverse outlist))
7335 (setq verilog-dir-cache-lib-filenames
7336 (cons (list cache-key outlist)
7337 verilog-dir-cache-lib-filenames))
7338 outlist))))
7339
7340 (defun verilog-module-filenames (module current)
7341 "Return a search path to find the given MODULE name.
7342 Uses the CURRENT filename, `verilog-library-extensions',
7343 `verilog-library-directories' and `verilog-library-files'
7344 variables to build the path."
7345 ;; Return search locations for it
7346 (append (list current) ; first, current buffer
7347 (verilog-library-filenames module current t)
7348 verilog-library-files)) ; finally, any libraries
7349
7350 ;;
7351 ;; Module Information
7352 ;;
7353 ;; Many of these functions work on "modi" a module information structure
7354 ;; A modi is: [module-name-string file-name begin-point]
7355
7356 (defvar verilog-cache-enabled t
7357 "If true, enable caching of signals, etc. Set to nil for debugging to make things SLOW!")
7358
7359 (defvar verilog-modi-cache-list nil
7360 "Cache of ((Module Function) Buf-Tick Buf-Modtime Func-Returns)...
7361 For speeding up verilog-modi-get-* commands.
7362 Buffer-local.")
7363
7364 (make-variable-buffer-local 'verilog-modi-cache-list)
7365
7366 (defvar verilog-modi-cache-preserve-tick nil
7367 "Modification tick after which the cache is still considered valid.
7368 Use `verilog-preserve-modi-cache' to set it.")
7369 (defvar verilog-modi-cache-preserve-buffer nil
7370 "Modification tick after which the cache is still considered valid.
7371 Use `verilog-preserve-modi-cache' to set it.")
7372
7373 (defun verilog-modi-current ()
7374 "Return the modi structure for the module currently at point."
7375 (let* (name pt)
7376 ;; read current module's name
7377 (save-excursion
7378 (verilog-re-search-backward-quick verilog-defun-re nil nil)
7379 (verilog-re-search-forward-quick "(" nil nil)
7380 (setq name (verilog-read-module-name))
7381 (setq pt (point)))
7382 ;; return
7383 (vector name (or (buffer-file-name) (current-buffer)) pt)))
7384
7385 (defvar verilog-modi-lookup-last-mod nil "Cache of last module looked up.")
7386 (defvar verilog-modi-lookup-last-modi nil "Cache of last modi returned.")
7387 (defvar verilog-modi-lookup-last-current nil "Cache of last `current-buffer' looked up.")
7388 (defvar verilog-modi-lookup-last-tick nil "Cache of last `buffer-modified-tick' looked up.")
7389
7390 (defun verilog-modi-lookup (module allow-cache &optional ignore-error)
7391 "Find the file and point at which MODULE is defined.
7392 If ALLOW-CACHE is set, check and remember cache of previous lookups.
7393 Return modi if successful, else print message unless IGNORE-ERROR is true."
7394 (let* ((current (or (buffer-file-name) (current-buffer))))
7395 (cond ((and verilog-modi-lookup-last-modi
7396 verilog-cache-enabled
7397 allow-cache
7398 (equal verilog-modi-lookup-last-mod module)
7399 (equal verilog-modi-lookup-last-current current)
7400 (equal verilog-modi-lookup-last-tick (buffer-modified-tick)))
7401 ;; ok as is
7402 )
7403 (t (let* ((realmod (verilog-symbol-detick module t))
7404 (orig-filenames (verilog-module-filenames realmod current))
7405 (filenames orig-filenames)
7406 pt)
7407 (while (and filenames (not pt))
7408 (if (not (setq pt (verilog-module-inside-filename-p realmod (car filenames))))
7409 (setq filenames (cdr filenames))))
7410 (cond (pt (setq verilog-modi-lookup-last-modi
7411 (vector realmod (car filenames) pt)))
7412 (t (setq verilog-modi-lookup-last-modi nil)
7413 (or ignore-error
7414 (error (concat (verilog-point-text)
7415 ": Can't locate " module " module definition"
7416 (if (not (equal module realmod))
7417 (concat " (Expanded macro to " realmod ")")
7418 "")
7419 "\n Check the verilog-library-directories variable."
7420 "\n I looked in (if not listed, doesn't exist):\n\t"
7421 (mapconcat 'concat orig-filenames "\n\t"))))))
7422 (setq verilog-modi-lookup-last-mod module
7423 verilog-modi-lookup-last-current current
7424 verilog-modi-lookup-last-tick (buffer-modified-tick)))))
7425 verilog-modi-lookup-last-modi))
7426
7427 (defsubst verilog-modi-name (modi)
7428 (aref modi 0))
7429 (defsubst verilog-modi-file-or-buffer (modi)
7430 (aref modi 1))
7431 (defsubst verilog-modi-point (modi)
7432 (aref modi 2))
7433
7434 (defun verilog-modi-filename (modi)
7435 "Filename of MODI, or name of buffer if it's never been saved."
7436 (if (bufferp (verilog-modi-file-or-buffer modi))
7437 (or (buffer-file-name (verilog-modi-file-or-buffer modi))
7438 (buffer-name (verilog-modi-file-or-buffer modi)))
7439 (verilog-modi-file-or-buffer modi)))
7440
7441 (defun verilog-modi-goto (modi)
7442 "Move point/buffer to specified MODI."
7443 (or modi (error "Passed unfound modi to goto, check earlier"))
7444 (set-buffer (if (bufferp (verilog-modi-file-or-buffer modi))
7445 (verilog-modi-file-or-buffer modi)
7446 (find-file-noselect (verilog-modi-file-or-buffer modi))))
7447 (or (equal major-mode `verilog-mode) ;; Put into Verilog mode to get syntax
7448 (verilog-mode))
7449 (goto-char (verilog-modi-point modi)))
7450
7451 (defun verilog-goto-defun-file (module)
7452 "Move point to the file at which a given MODULE is defined."
7453 (interactive "sGoto File for Module: ")
7454 (let* ((modi (verilog-modi-lookup module nil)))
7455 (when modi
7456 (verilog-modi-goto modi)
7457 (switch-to-buffer (current-buffer)))))
7458
7459 (defun verilog-modi-cache-results (modi function)
7460 "Run on MODI the given FUNCTION. Locate the module in a file.
7461 Cache the output of function so next call may have faster access."
7462 (let (fass)
7463 (save-excursion ;; Cache is buffer-local so can't avoid this.
7464 (verilog-modi-goto modi)
7465 (if (and (setq fass (assoc (list modi function)
7466 verilog-modi-cache-list))
7467 ;; Destroy caching when incorrect; Modified or file changed
7468 (not (and verilog-cache-enabled
7469 (or (equal (buffer-modified-tick) (nth 1 fass))
7470 (and verilog-modi-cache-preserve-tick
7471 (<= verilog-modi-cache-preserve-tick (nth 1 fass))
7472 (equal verilog-modi-cache-preserve-buffer (current-buffer))))
7473 (equal (visited-file-modtime) (nth 2 fass)))))
7474 (setq verilog-modi-cache-list nil
7475 fass nil))
7476 (cond (fass
7477 ;; Return data from cache hit
7478 (nth 3 fass))
7479 (t
7480 ;; Read from file
7481 ;; Clear then restore any hilighting to make emacs19 happy
7482 (let ((fontlocked (when (and (boundp 'font-lock-mode)
7483 font-lock-mode)
7484 (font-lock-mode nil)
7485 t))
7486 func-returns)
7487 (setq func-returns (funcall function))
7488 (when fontlocked (font-lock-mode t))
7489 ;; Cache for next time
7490 (setq verilog-modi-cache-list
7491 (cons (list (list modi function)
7492 (buffer-modified-tick)
7493 (visited-file-modtime)
7494 func-returns)
7495 verilog-modi-cache-list))
7496 func-returns))))))
7497
7498 (defun verilog-modi-cache-add (modi function element sig-list)
7499 "Add function return results to the module cache.
7500 Update MODI's cache for given FUNCTION so that the return ELEMENT of that
7501 function now contains the additional SIG-LIST parameters."
7502 (let (fass)
7503 (save-excursion
7504 (verilog-modi-goto modi)
7505 (if (setq fass (assoc (list modi function)
7506 verilog-modi-cache-list))
7507 (let ((func-returns (nth 3 fass)))
7508 (aset func-returns element
7509 (append sig-list (aref func-returns element))))))))
7510
7511 (defmacro verilog-preserve-modi-cache (&rest body)
7512 "Execute the BODY forms, allowing cache preservation within BODY.
7513 This means that changes to the buffer will not result in the cache being
7514 flushed. If the changes affect the modsig state, they must call the
7515 modsig-cache-add-* function, else the results of later calls may be
7516 incorrect. Without this, changes are assumed to be adding/removing signals
7517 and invalidating the cache."
7518 `(let ((verilog-modi-cache-preserve-tick (buffer-modified-tick))
7519 (verilog-modi-cache-preserve-buffer (current-buffer)))
7520 (progn ,@body)))
7521
7522
7523 (defun verilog-signals-matching-enum (in-list enum)
7524 "Return all signals in IN-LIST matching the given ENUM."
7525 (let (out-list)
7526 (while in-list
7527 (if (equal (verilog-sig-enum (car in-list)) enum)
7528 (setq out-list (cons (car in-list) out-list)))
7529 (setq in-list (cdr in-list)))
7530 ;; New scheme
7531 (let* ((enumvar (intern (concat "venum-" enum)))
7532 (enumlist (and (boundp enumvar) (eval enumvar))))
7533 (while enumlist
7534 (add-to-list 'out-list (list (car enumlist)))
7535 (setq enumlist (cdr enumlist))))
7536 (nreverse out-list)))
7537
7538 (defun verilog-signals-matching-regexp (in-list regexp)
7539 "Return all signals in IN-LIST matching the given REGEXP, if non-nil."
7540 (if (not regexp)
7541 in-list
7542 (let (out-list)
7543 (while in-list
7544 (if (string-match regexp (verilog-sig-name (car in-list)))
7545 (setq out-list (cons (car in-list) out-list)))
7546 (setq in-list (cdr in-list)))
7547 (nreverse out-list))))
7548
7549 (defun verilog-signals-not-matching-regexp (in-list regexp)
7550 "Return all signals in IN-LIST not matching the given REGEXP, if non-nil."
7551 (if (not regexp)
7552 in-list
7553 (let (out-list)
7554 (while in-list
7555 (if (not (string-match regexp (verilog-sig-name (car in-list))))
7556 (setq out-list (cons (car in-list) out-list)))
7557 (setq in-list (cdr in-list)))
7558 (nreverse out-list))))
7559
7560 ;; Combined
7561 (defun verilog-decls-get-signals (decls)
7562 (append
7563 (verilog-decls-get-outputs decls)
7564 (verilog-decls-get-inouts decls)
7565 (verilog-decls-get-inputs decls)
7566 (verilog-decls-get-wires decls)
7567 (verilog-decls-get-regs decls)
7568 (verilog-decls-get-assigns decls)
7569 (verilog-decls-get-consts decls)
7570 (verilog-decls-get-gparams decls)))
7571
7572 (defun verilog-decls-get-ports (decls)
7573 (append
7574 (verilog-decls-get-outputs decls)
7575 (verilog-decls-get-inouts decls)
7576 (verilog-decls-get-inputs decls)))
7577
7578 (defsubst verilog-modi-cache-add-outputs (modi sig-list)
7579 (verilog-modi-cache-add modi 'verilog-read-decls 0 sig-list))
7580 (defsubst verilog-modi-cache-add-inouts (modi sig-list)
7581 (verilog-modi-cache-add modi 'verilog-read-decls 1 sig-list))
7582 (defsubst verilog-modi-cache-add-inputs (modi sig-list)
7583 (verilog-modi-cache-add modi 'verilog-read-decls 2 sig-list))
7584 (defsubst verilog-modi-cache-add-wires (modi sig-list)
7585 (verilog-modi-cache-add modi 'verilog-read-decls 3 sig-list))
7586 (defsubst verilog-modi-cache-add-regs (modi sig-list)
7587 (verilog-modi-cache-add modi 'verilog-read-decls 4 sig-list))
7588
7589 (defun verilog-signals-from-signame (signame-list)
7590 "Return signals in standard form from SIGNAME-LIST, a simple list of signal names."
7591 (mapcar (function (lambda (name) (list name nil nil)))
7592 signame-list))
7593 \f
7594 ;;
7595 ;; Auto creation utilities
7596 ;;
7597
7598 (defun verilog-auto-re-search-do (search-for func)
7599 "Search for the given auto text regexp SEARCH-FOR, and perform FUNC where it occurs."
7600 (goto-char (point-min))
7601 (while (verilog-re-search-forward search-for nil t)
7602 (funcall func)))
7603
7604 (defun verilog-insert-one-definition (sig type indent-pt)
7605 "Print out a definition for SIG of the given TYPE,
7606 with appropriate INDENT-PT indentation."
7607 (indent-to indent-pt)
7608 (insert type)
7609 (when (verilog-sig-signed sig)
7610 (insert " " (verilog-sig-signed sig)))
7611 (when (verilog-sig-multidim sig)
7612 (insert " " (verilog-sig-multidim-string sig)))
7613 (when (verilog-sig-bits sig)
7614 (insert " " (verilog-sig-bits sig)))
7615 (indent-to (max 24 (+ indent-pt 16)))
7616 (unless (= (char-syntax (preceding-char)) ?\ )
7617 (insert " ")) ; Need space between "]name" if indent-to did nothing
7618 (insert (verilog-sig-name sig)))
7619
7620 (defun verilog-insert-definition (sigs direction indent-pt v2k &optional dont-sort)
7621 "Print out a definition for a list of SIGS of the given DIRECTION,
7622 with appropriate INDENT-PT indentation. If V2K, use Verilog 2001 I/O
7623 format. Sort unless DONT-SORT. DIRECTION is normally wire/reg/output."
7624 (or dont-sort
7625 (setq sigs (sort (copy-alist sigs) `verilog-signals-sort-compare)))
7626 (while sigs
7627 (let ((sig (car sigs)))
7628 (verilog-insert-one-definition
7629 sig
7630 ;; Want "type x" or "output type x", not "wire type x"
7631 (cond ((verilog-sig-type sig)
7632 (concat
7633 (if (not (equal direction "wire"))
7634 (concat direction " "))
7635 (verilog-sig-type sig)))
7636 (t direction))
7637 indent-pt)
7638 (insert (if v2k "," ";"))
7639 (if (or (not (verilog-sig-comment sig))
7640 (equal "" (verilog-sig-comment sig)))
7641 (insert "\n")
7642 (indent-to (max 48 (+ indent-pt 40)))
7643 (insert (concat "// " (verilog-sig-comment sig) "\n")))
7644 (setq sigs (cdr sigs)))))
7645
7646 (eval-when-compile
7647 (if (not (boundp 'indent-pt))
7648 (defvar indent-pt nil "Local used by insert-indent")))
7649
7650 (defun verilog-insert-indent (&rest stuff)
7651 "Indent to position stored in local `indent-pt' variable, then insert STUFF.
7652 Presumes that any newlines end a list element."
7653 (let ((need-indent t))
7654 (while stuff
7655 (if need-indent (indent-to indent-pt))
7656 (setq need-indent nil)
7657 (insert (car stuff))
7658 (setq need-indent (string-match "\n$" (car stuff))
7659 stuff (cdr stuff)))))
7660 ;;(let ((indent-pt 10)) (verilog-insert-indent "hello\n" "addon" "there\n"))
7661
7662 (defun verilog-repair-open-comma ()
7663 "If backwards-from-point is other than a open parenthesis insert comma."
7664 (save-excursion
7665 (verilog-backward-syntactic-ws)
7666 (when (save-excursion
7667 (backward-char 1)
7668 (and (not (looking-at "[(,]"))
7669 (progn
7670 (verilog-re-search-backward "[(`]" nil t)
7671 (looking-at "("))))
7672 (insert ","))))
7673
7674 (defun verilog-repair-close-comma ()
7675 "If point is at a comma followed by a close parenthesis, fix it.
7676 This repairs those mis-inserted by a AUTOARG."
7677 ;; It would be much nicer if Verilog allowed extra commas like Perl does!
7678 (save-excursion
7679 (verilog-forward-close-paren)
7680 (backward-char 1)
7681 (verilog-backward-syntactic-ws)
7682 (backward-char 1)
7683 (when (looking-at ",")
7684 (delete-char 1))))
7685
7686 (defun verilog-get-list (start end)
7687 "Return the elements of a comma separated list between START and END."
7688 (interactive)
7689 (let ((my-list (list))
7690 my-string)
7691 (save-excursion
7692 (while (< (point) end)
7693 (when (re-search-forward "\\([^,{]+\\)" end t)
7694 (setq my-string (verilog-string-remove-spaces (match-string 1)))
7695 (setq my-list (nconc my-list (list my-string) ))
7696 (goto-char (match-end 0))))
7697 my-list)))
7698
7699 (defun verilog-make-width-expression (range-exp)
7700 "Return an expression calculating the length of a range [x:y] in RANGE-EXP."
7701 ;; strip off the []
7702 (cond ((not range-exp)
7703 "1")
7704 (t
7705 (if (string-match "^\\[\\(.*\\)\\]$" range-exp)
7706 (setq range-exp (match-string 1 range-exp)))
7707 (cond ((not range-exp)
7708 "1")
7709 ((string-match "^\\s *\\([0-9]+\\)\\s *:\\s *\\([0-9]+\\)\\s *$"
7710 range-exp)
7711 (int-to-string
7712 (1+ (abs (- (string-to-number (match-string 1 range-exp))
7713 (string-to-number (match-string 2 range-exp)))))))
7714 ((string-match "^\\(.*\\)\\s *:\\s *\\(.*\\)\\s *$" range-exp)
7715 (concat "(1+(" (match-string 1 range-exp) ")"
7716 (if (equal "0" (match-string 2 range-exp))
7717 "" ;; Don't bother with -(0)
7718 (concat "-(" (match-string 2 range-exp) ")"))
7719 ")"))
7720 (t nil)))))
7721 ;;(verilog-make-width-expression "`A:`B")
7722
7723 (defun verilog-simplify-range-expression (range-exp)
7724 "Return a simplified range expression with constants eliminated from RANGE-EXP."
7725 (let ((out range-exp)
7726 (last-pass ""))
7727 (while (not (equal last-pass out))
7728 (setq last-pass out)
7729 (while (string-match "(\\<\\([0-9]+\\)\\>)" out)
7730 (setq out (replace-match "\\1" nil nil out)))
7731 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\+\\s *\\<\\([0-9]+\\)\\>" out)
7732 (setq out (replace-match
7733 (int-to-string (+ (string-to-number (match-string 1 out))
7734 (string-to-number (match-string 2 out))))
7735 nil nil out)))
7736 (while (string-match "\\<\\([0-9]+\\)\\>\\s *\\-\\s *\\<\\([0-9]+\\)\\>" out)
7737 (setq out (replace-match
7738 (int-to-string (- (string-to-number (match-string 1 out))
7739 (string-to-number (match-string 2 out))))
7740 nil nil out))))
7741 out))
7742 ;;(verilog-simplify-range-expression "1")
7743 ;;(verilog-simplify-range-expression "(((16)+1)-3)")
7744
7745 (defun verilog-typedef-name-p (variable-name)
7746 "Return true if the VARIABLE-NAME is a type definition."
7747 (when verilog-typedef-regexp
7748 (string-match verilog-typedef-regexp variable-name)))
7749 \f
7750 ;;
7751 ;; Auto deletion
7752 ;;
7753
7754 (defun verilog-delete-autos-lined ()
7755 "Delete autos that occupy multiple lines, between begin and end comments."
7756 (let ((pt (point)))
7757 (forward-line 1)
7758 (when (and
7759 (looking-at "\\s-*// Beginning")
7760 (search-forward "// End of automatic" nil t))
7761 ;; End exists
7762 (end-of-line)
7763 (delete-region pt (point))
7764 (forward-line 1))))
7765
7766 (defun verilog-forward-close-paren ()
7767 "Find the close parenthesis that match the current point.
7768 Ignore other close parenthesis with matching open parens."
7769 (let ((parens 1))
7770 (while (> parens 0)
7771 (unless (verilog-re-search-forward-quick "[()]" nil t)
7772 (error "%s: Mismatching ()" (verilog-point-text)))
7773 (cond ((= (preceding-char) ?\( )
7774 (setq parens (1+ parens)))
7775 ((= (preceding-char) ?\) )
7776 (setq parens (1- parens)))))))
7777
7778 (defun verilog-backward-open-paren ()
7779 "Find the open parenthesis that match the current point.
7780 Ignore other open parenthesis with matching close parens."
7781 (let ((parens 1))
7782 (while (> parens 0)
7783 (unless (verilog-re-search-backward-quick "[()]" nil t)
7784 (error "%s: Mismatching ()" (verilog-point-text)))
7785 (cond ((= (following-char) ?\) )
7786 (setq parens (1+ parens)))
7787 ((= (following-char) ?\( )
7788 (setq parens (1- parens)))))))
7789
7790 (defun verilog-backward-open-bracket ()
7791 "Find the open bracket that match the current point.
7792 Ignore other open bracket with matching close bracket."
7793 (let ((parens 1))
7794 (while (> parens 0)
7795 (unless (verilog-re-search-backward-quick "[][]" nil t)
7796 (error "%s: Mismatching []" (verilog-point-text)))
7797 (cond ((= (following-char) ?\] )
7798 (setq parens (1+ parens)))
7799 ((= (following-char) ?\[ )
7800 (setq parens (1- parens)))))))
7801
7802 (defun verilog-delete-to-paren ()
7803 "Delete the automatic inst/sense/arg created by autos.
7804 Deletion stops at the matching end parenthesis."
7805 (delete-region (point)
7806 (save-excursion
7807 (verilog-backward-open-paren)
7808 (forward-sexp 1) ;; Moves to paren that closes argdecl's
7809 (backward-char 1)
7810 (point))))
7811
7812 (defun verilog-auto-star-safe ()
7813 "Return if a .* AUTOINST is safe to delete or expand.
7814 It was created by the AUTOS themselves, or by the user."
7815 (and verilog-auto-star-expand
7816 (looking-at "[ \t\n\f,]*\\([)]\\|// \\(Outputs\\|Inouts\\|Inputs\\)\\)")))
7817
7818 (defun verilog-delete-auto-star-all ()
7819 "Delete a .* AUTOINST, if it is safe."
7820 (when (verilog-auto-star-safe)
7821 (verilog-delete-to-paren)))
7822
7823 (defun verilog-delete-auto-star-implicit ()
7824 "Delete all .* implicit connections created by `verilog-auto-star'.
7825 This function will be called automatically at save unless
7826 `verilog-auto-star-save' is set, any non-templated expanded pins will be
7827 removed."
7828 (interactive)
7829 (let (paren-pt indent have-close-paren)
7830 (save-excursion
7831 (goto-char (point-min))
7832 ;; We need to match these even outside of comments.
7833 ;; For reasonable performance, we don't check if inside comments, sorry.
7834 (while (re-search-forward "// Implicit \\.\\*" nil t)
7835 (setq paren-pt (point))
7836 (beginning-of-line)
7837 (setq have-close-paren
7838 (save-excursion
7839 (when (search-forward ");" paren-pt t)
7840 (setq indent (current-indentation))
7841 t)))
7842 (delete-region (point) (+ 1 paren-pt)) ; Nuke line incl CR
7843 (when have-close-paren
7844 ;; Delete extra commentary
7845 (save-excursion
7846 (while (progn
7847 (forward-line -1)
7848 (looking-at "\\s *//\\s *\\(Outputs\\|Inouts\\|Inputs\\)\n"))
7849 (delete-region (match-beginning 0) (match-end 0))))
7850 ;; If it is simple, we can put the ); on the same line as the last text
7851 (let ((rtn-pt (point)))
7852 (save-excursion
7853 (while (progn (backward-char 1)
7854 (looking-at "[ \t\n\f]")))
7855 (when (looking-at ",")
7856 (delete-region (+ 1 (point)) rtn-pt))))
7857 (when (bolp)
7858 (indent-to indent))
7859 (insert ");\n")
7860 ;; Still need to kill final comma - always is one as we put one after the .*
7861 (re-search-backward ",")
7862 (delete-char 1))))))
7863
7864 (defun verilog-delete-auto ()
7865 "Delete the automatic outputs, regs, and wires created by \\[verilog-auto].
7866 Use \\[verilog-auto] to re-insert the updated AUTOs.
7867
7868 The hooks `verilog-before-delete-auto-hook' and `verilog-delete-auto-hook' are
7869 called before and after this function, respectively."
7870 (interactive)
7871 (save-excursion
7872 (if (buffer-file-name)
7873 (find-file-noselect (buffer-file-name))) ;; To check we have latest version
7874 ;; Allow user to customize
7875 (run-hooks 'verilog-before-delete-auto-hook)
7876
7877 ;; Remove those that have multi-line insertions, possibly with parameters
7878 (verilog-auto-re-search-do
7879 (concat "/\\*"
7880 (eval-when-compile
7881 (verilog-regexp-words
7882 `("AUTOASCIIENUM" "AUTOCONCATCOMMENT" "AUTODEFINEVALUE"
7883 "AUTOINOUT" "AUTOINOUTMODULE" "AUTOINPUT" "AUTOOUTPUT"
7884 "AUTOOUTPUTEVERY"
7885 "AUTOREG" "AUTOREGINPUT" "AUTORESET" "AUTOTIEOFF"
7886 "AUTOUNUSED" "AUTOWIRE")))
7887 "\\(\\|([^)]*)\\|(\"[^\"]*\")\\)" ; Optional parens or quoted parameter
7888 "\\*/")
7889 'verilog-delete-autos-lined)
7890 ;; Remove those that are in parenthesis
7891 (verilog-auto-re-search-do
7892 (concat "/\\*"
7893 (eval-when-compile
7894 (verilog-regexp-words
7895 `("AS" "AUTOARG" "AUTOCONCATWIDTH" "AUTOINST" "AUTOINSTPARAM"
7896 "AUTOSENSE")))
7897 "\\*/")
7898 'verilog-delete-to-paren)
7899 ;; Do .* instantiations, but avoid removing any user pins by looking for our magic comments
7900 (verilog-auto-re-search-do "\\.\\*"
7901 'verilog-delete-auto-star-all)
7902 ;; Remove template comments ... anywhere in case was pasted after AUTOINST removed
7903 (goto-char (point-min))
7904 (while (re-search-forward "\\s-*// \\(Templated\\|Implicit \\.\\*\\)[ \tLT0-9]*$" nil t)
7905 (replace-match ""))
7906
7907 ;; Final customize
7908 (run-hooks 'verilog-delete-auto-hook)))
7909 \f
7910 ;;
7911 ;; Auto inject
7912 ;;
7913
7914 (defun verilog-inject-auto ()
7915 "Examine legacy non-AUTO code and insert AUTOs in appropriate places.
7916
7917 Any always @ blocks with sensitivity lists that match computed lists will
7918 be replaced with /*AS*/ comments.
7919
7920 Any cells will get /*AUTOINST*/ added to the end of the pin list.
7921 Pins with have identical names will be deleted.
7922
7923 Argument lists will not be deleted, /*AUTOARG*/ will only be inserted to
7924 support adding new ports. You may wish to delete older ports yourself.
7925
7926 For example:
7927
7928 module ExampInject (i, o);
7929 input i;
7930 input j;
7931 output o;
7932 always @ (i or j)
7933 o = i | j;
7934 InstModule instName
7935 (.foobar(baz),
7936 j(j));
7937 endmodule
7938
7939 Typing \\[verilog-inject-auto] will make this into:
7940
7941 module ExampInject (i, o/*AUTOARG*/
7942 // Inputs
7943 j);
7944 input i;
7945 output o;
7946 always @ (/*AS*/i or j)
7947 o = i | j;
7948 InstModule instName
7949 (.foobar(baz),
7950 /*AUTOINST*/
7951 // Outputs
7952 j(j));
7953 endmodule"
7954 (interactive)
7955 (verilog-auto t))
7956
7957 (defun verilog-inject-arg ()
7958 "Inject AUTOARG into new code. See `verilog-inject-auto'."
7959 ;; Presume one module per file.
7960 (save-excursion
7961 (goto-char (point-min))
7962 (while (verilog-re-search-forward-quick "\\<module\\>" nil t)
7963 (let ((endmodp (save-excursion
7964 (verilog-re-search-forward-quick "\\<endmodule\\>" nil t)
7965 (point))))
7966 ;; See if there's already a comment .. inside a comment so not verilog-re-search
7967 (when (not (re-search-forward "/\\*AUTOARG\\*/" endmodp t))
7968 (verilog-re-search-forward-quick ";" nil t)
7969 (backward-char 1)
7970 (verilog-backward-syntactic-ws)
7971 (backward-char 1) ; Moves to paren that closes argdecl's
7972 (when (looking-at ")")
7973 (insert "/*AUTOARG*/")))))))
7974
7975 (defun verilog-inject-sense ()
7976 "Inject AUTOSENSE into new code. See `verilog-inject-auto'."
7977 (save-excursion
7978 (goto-char (point-min))
7979 (while (verilog-re-search-forward-quick "\\<always\\s *@\\s *(" nil t)
7980 (let* ((start-pt (point))
7981 (modi (verilog-modi-current))
7982 (moddecls (verilog-modi-get-decls modi))
7983 pre-sigs
7984 got-sigs)
7985 (backward-char 1)
7986 (forward-sexp 1)
7987 (backward-char 1) ;; End )
7988 (when (not (verilog-re-search-backward "/\\*\\(AUTOSENSE\\|AS\\)\\*/" start-pt t))
7989 (setq pre-sigs (verilog-signals-from-signame
7990 (verilog-read-signals start-pt (point)))
7991 got-sigs (verilog-auto-sense-sigs moddecls nil))
7992 (when (not (or (verilog-signals-not-in pre-sigs got-sigs) ; Both are equal?
7993 (verilog-signals-not-in got-sigs pre-sigs)))
7994 (delete-region start-pt (point))
7995 (insert "/*AS*/")))))))
7996
7997 (defun verilog-inject-inst ()
7998 "Inject AUTOINST into new code. See `verilog-inject-auto'."
7999 (save-excursion
8000 (goto-char (point-min))
8001 ;; It's hard to distinguish modules; we'll instead search for pins.
8002 (while (verilog-re-search-forward-quick "\\.\\s *[a-zA-Z0-9`_\$]+\\s *(\\s *[a-zA-Z0-9`_\$]+\\s *)" nil t)
8003 (verilog-backward-open-paren) ;; Inst start
8004 (cond
8005 ((= (preceding-char) ?\#) ;; #(...) parameter section, not pin. Skip.
8006 (forward-char 1)
8007 (verilog-forward-close-paren)) ;; Parameters done
8008 (t
8009 (forward-char 1)
8010 (let ((indent-pt (+ (current-column)))
8011 (end-pt (save-excursion (verilog-forward-close-paren) (point))))
8012 (cond ((verilog-re-search-forward "\\(/\\*AUTOINST\\*/\\|\\.\\*\\)" end-pt t)
8013 (goto-char end-pt)) ;; Already there, continue search with next instance
8014 (t
8015 ;; Delete identical interconnect
8016 (let ((case-fold-search nil)) ;; So we don't convert upper-to-lower, etc
8017 (while (verilog-re-search-forward "\\.\\s *\\([a-zA-Z0-9`_\$]+\\)*\\s *(\\s *\\1\\s *)\\s *" end-pt t)
8018 (delete-region (match-beginning 0) (match-end 0))
8019 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))) ;; Keep it correct
8020 (while (or (looking-at "[ \t\n\f,]+")
8021 (looking-at "//[^\n]*"))
8022 (delete-region (match-beginning 0) (match-end 0))
8023 (setq end-pt (- end-pt (- (match-end 0) (match-beginning 0)))))))
8024 (verilog-forward-close-paren)
8025 (backward-char 1)
8026 ;; Not verilog-re-search, as we don't want to strip comments
8027 (while (re-search-backward "[ \t\n\f]+" (- (point) 1) t)
8028 (delete-region (match-beginning 0) (match-end 0)))
8029 (insert "\n")
8030 (indent-to indent-pt)
8031 (insert "/*AUTOINST*/")))))))))
8032 \f
8033 ;;
8034 ;; Auto save
8035 ;;
8036
8037 (defun verilog-auto-save-check ()
8038 "On saving see if we need auto update."
8039 (cond ((not verilog-auto-save-policy)) ; disabled
8040 ((not (save-excursion
8041 (save-match-data
8042 (let ((case-fold-search nil))
8043 (goto-char (point-min))
8044 (re-search-forward "AUTO" nil t))))))
8045 ((eq verilog-auto-save-policy 'force)
8046 (verilog-auto))
8047 ((not (buffer-modified-p)))
8048 ((eq verilog-auto-update-tick (buffer-modified-tick))) ; up-to-date
8049 ((eq verilog-auto-save-policy 'detect)
8050 (verilog-auto))
8051 (t
8052 (when (yes-or-no-p "AUTO statements not recomputed, do it now? ")
8053 (verilog-auto))
8054 ;; Don't ask again if didn't update
8055 (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))))
8056 (when (not verilog-auto-star-save)
8057 (verilog-delete-auto-star-implicit))
8058 nil) ;; Always return nil -- we don't write the file ourselves
8059
8060 (defun verilog-auto-read-locals ()
8061 "Return file local variable segment at bottom of file."
8062 (save-excursion
8063 (goto-char (point-max))
8064 (if (re-search-backward "Local Variables:" nil t)
8065 (buffer-substring-no-properties (point) (point-max))
8066 "")))
8067
8068 (defun verilog-auto-reeval-locals (&optional force)
8069 "Read file local variable segment at bottom of file if it has changed.
8070 If FORCE, always reread it."
8071 (make-local-variable 'verilog-auto-last-file-locals)
8072 (let ((curlocal (verilog-auto-read-locals)))
8073 (when (or force (not (equal verilog-auto-last-file-locals curlocal)))
8074 (setq verilog-auto-last-file-locals curlocal)
8075 ;; Note this may cause this function to be recursively invoked.
8076 ;; The above when statement will prevent it from recursing forever.
8077 (hack-local-variables)
8078 t)))
8079 \f
8080 ;;
8081 ;; Auto creation
8082 ;;
8083
8084 (defun verilog-auto-arg-ports (sigs message indent-pt)
8085 "Print a list of ports for a AUTOINST.
8086 Takes SIGS list, adds MESSAGE to front and inserts each at INDENT-PT."
8087 (when sigs
8088 (insert "\n")
8089 (indent-to indent-pt)
8090 (insert message)
8091 (insert "\n")
8092 (let ((space ""))
8093 (indent-to indent-pt)
8094 (while sigs
8095 (cond ((> (+ 2 (current-column) (length (verilog-sig-name (car sigs)))) fill-column)
8096 (insert "\n")
8097 (indent-to indent-pt))
8098 (t (insert space)))
8099 (insert (verilog-sig-name (car sigs)) ",")
8100 (setq sigs (cdr sigs)
8101 space " ")))))
8102
8103 (defun verilog-auto-arg ()
8104 "Expand AUTOARG statements.
8105 Replace the argument declarations at the beginning of the
8106 module with ones automatically derived from input and output
8107 statements. This can be dangerous if the module is instantiated
8108 using position-based connections, so use only name-based when
8109 instantiating the resulting module. Long lines are split based
8110 on the `fill-column', see \\[set-fill-column].
8111
8112 Limitations:
8113 Concatenation and outputting partial busses is not supported.
8114
8115 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8116
8117 For example:
8118
8119 module ExampArg (/*AUTOARG*/);
8120 input i;
8121 output o;
8122 endmodule
8123
8124 Typing \\[verilog-auto] will make this into:
8125
8126 module ExampArg (/*AUTOARG*/
8127 // Outputs
8128 o,
8129 // Inputs
8130 i
8131 );
8132 input i;
8133 output o;
8134 endmodule
8135
8136 Any ports declared between the ( and /*AUTOARG*/ are presumed to be
8137 predeclared and are not redeclared by AUTOARG. AUTOARG will make a
8138 conservative guess on adding a comma for the first signal, if you have
8139 any ifdefs or complicated expressions before the AUTOARG you will need
8140 to choose the comma yourself.
8141
8142 Avoid declaring ports manually, as it makes code harder to maintain."
8143 (save-excursion
8144 (let* ((modi (verilog-modi-current))
8145 (moddecls (verilog-modi-get-decls modi))
8146 (skip-pins (aref (verilog-read-arg-pins) 0)))
8147 (verilog-repair-open-comma)
8148 (verilog-auto-arg-ports (verilog-signals-not-in
8149 (verilog-decls-get-outputs moddecls)
8150 skip-pins)
8151 "// Outputs"
8152 verilog-indent-level-declaration)
8153 (verilog-auto-arg-ports (verilog-signals-not-in
8154 (verilog-decls-get-inouts moddecls)
8155 skip-pins)
8156 "// Inouts"
8157 verilog-indent-level-declaration)
8158 (verilog-auto-arg-ports (verilog-signals-not-in
8159 (verilog-decls-get-inputs moddecls)
8160 skip-pins)
8161 "// Inputs"
8162 verilog-indent-level-declaration)
8163 (verilog-repair-close-comma)
8164 (unless (eq (char-before) ?/ )
8165 (insert "\n"))
8166 (indent-to verilog-indent-level-declaration))))
8167
8168 (defun verilog-auto-inst-port-map (port-st)
8169 nil)
8170
8171 (defvar vl-cell-type nil "See `verilog-auto-inst'.") ; Prevent compile warning
8172 (defvar vl-cell-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
8173 (defvar vl-name nil "See `verilog-auto-inst'.") ; Prevent compile warning
8174 (defvar vl-width nil "See `verilog-auto-inst'.") ; Prevent compile warning
8175 (defvar vl-dir nil "See `verilog-auto-inst'.") ; Prevent compile warning
8176
8177 (defun verilog-auto-inst-port (port-st indent-pt tpl-list tpl-num for-star par-values)
8178 "Print out a instantiation connection for this PORT-ST.
8179 Insert to INDENT-PT, use template TPL-LIST.
8180 @ are instantiation numbers, replaced with TPL-NUM.
8181 @\"(expression @)\" are evaluated, with @ as a variable.
8182 If FOR-STAR add comment it is a .* expansion.
8183 If PAR-VALUES replace final strings with these parameter values."
8184 (let* ((port (verilog-sig-name port-st))
8185 (tpl-ass (or (assoc port (car tpl-list))
8186 (verilog-auto-inst-port-map port-st)))
8187 ;; vl-* are documented for user use
8188 (vl-name (verilog-sig-name port-st))
8189 (vl-width (verilog-sig-width port-st))
8190 (vl-bits (if (or verilog-auto-inst-vector
8191 (not (assoc port vector-skip-list))
8192 (not (equal (verilog-sig-bits port-st)
8193 (verilog-sig-bits (assoc port vector-skip-list)))))
8194 (or (verilog-sig-bits port-st) "")
8195 ""))
8196 ;; Default if not found
8197 (tpl-net (if (verilog-sig-multidim port-st)
8198 (concat port "/*" (verilog-sig-multidim-string port-st)
8199 vl-bits "*/")
8200 (concat port vl-bits)))
8201 (case-fold-search nil)
8202 (check-values par-values))
8203 ;; Replace parameters in bit-width
8204 (when (and check-values
8205 (not (equal vl-bits "")))
8206 (while check-values
8207 (setq vl-bits (verilog-string-replace-matches
8208 (concat "\\<" (nth 0 (car check-values)) "\\>")
8209 (concat "(" (nth 1 (car check-values)) ")")
8210 t t vl-bits)
8211 check-values (cdr check-values)))
8212 (setq vl-bits (verilog-simplify-range-expression vl-bits))) ; Not in the loop for speed
8213 ;; Find template
8214 (cond (tpl-ass ; Template of exact port name
8215 (setq tpl-net (nth 1 tpl-ass)))
8216 ((nth 1 tpl-list) ; Wildcards in template, search them
8217 (let ((wildcards (nth 1 tpl-list)))
8218 (while wildcards
8219 (when (string-match (nth 0 (car wildcards)) port)
8220 (setq tpl-ass (car wildcards) ; so allow @ parsing
8221 tpl-net (replace-match (nth 1 (car wildcards))
8222 t nil port)))
8223 (setq wildcards (cdr wildcards))))))
8224 ;; Parse Templated variable
8225 (when tpl-ass
8226 ;; Evaluate @"(lispcode)"
8227 (when (string-match "@\".*[^\\]\"" tpl-net)
8228 (while (string-match "@\"\\(\\([^\\\"]*\\(\\\\.\\)*\\)*\\)\"" tpl-net)
8229 (setq tpl-net
8230 (concat
8231 (substring tpl-net 0 (match-beginning 0))
8232 (save-match-data
8233 (let* ((expr (match-string 1 tpl-net))
8234 (value
8235 (progn
8236 (setq expr (verilog-string-replace-matches "\\\\\"" "\"" nil nil expr))
8237 (setq expr (verilog-string-replace-matches "@" tpl-num nil nil expr))
8238 (prin1 (eval (car (read-from-string expr)))
8239 (lambda (ch) ())))))
8240 (if (numberp value) (setq value (number-to-string value)))
8241 value))
8242 (substring tpl-net (match-end 0))))))
8243 ;; Replace @ and [] magic variables in final output
8244 (setq tpl-net (verilog-string-replace-matches "@" tpl-num nil nil tpl-net))
8245 (setq tpl-net (verilog-string-replace-matches "\\[\\]" vl-bits nil nil tpl-net)))
8246 ;; Insert it
8247 (indent-to indent-pt)
8248 (insert "." port)
8249 (indent-to verilog-auto-inst-column)
8250 (insert "(" tpl-net "),")
8251 (cond (tpl-ass
8252 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
8253 verilog-auto-inst-column))
8254 (insert " // Templated")
8255 (when verilog-auto-inst-template-numbers
8256 (insert " T" (int-to-string (nth 2 tpl-ass))
8257 " L" (int-to-string (nth 3 tpl-ass)))))
8258 (for-star
8259 (indent-to (+ (if (< verilog-auto-inst-column 48) 24 16)
8260 verilog-auto-inst-column))
8261 (insert " // Implicit .\*"))) ;For some reason the . or * must be escaped...
8262 (insert "\n")))
8263 ;;(verilog-auto-inst-port (list "foo" "[5:0]") 10 (list (list "foo" "a@\"(% (+ @ 1) 4)\"a")) "3")
8264 ;;(x "incom[@\"(+ (* 8 @) 7)\":@\"(* 8 @)\"]")
8265 ;;(x ".out (outgo[@\"(concat (+ (* 8 @) 7) \\\":\\\" ( * 8 @))\"]));")
8266
8267 (defun verilog-auto-inst-first ()
8268 "Insert , etc before first ever port in this instant, as part of \\[verilog-auto-inst]."
8269 ;; Do we need a trailing comma?
8270 ;; There maybe a ifdef or something similar before us. What a mess. Thus
8271 ;; to avoid trouble we only insert on preceeding ) or *.
8272 ;; Insert first port on new line
8273 (insert "\n") ;; Must insert before search, so point will move forward if insert comma
8274 (save-excursion
8275 (verilog-re-search-backward "[^ \t\n\f]" nil nil)
8276 (when (looking-at ")\\|\\*") ;; Generally don't insert, unless we are fairly sure
8277 (forward-char 1)
8278 (insert ","))))
8279
8280 (defun verilog-auto-star ()
8281 "Expand SystemVerilog .* pins, as part of \\[verilog-auto].
8282
8283 If `verilog-auto-star-expand' is set, .* pins are treated if they were
8284 AUTOINST statements, otherwise they are ignored. For safety, Verilog mode
8285 will also ignore any .* that are not last in your pin list (this prevents
8286 it from deleting pins following the .* when it expands the AUTOINST.)
8287
8288 On writing your file, unless `verilog-auto-star-save' is set, any
8289 non-templated expanded pins will be removed. You may do this at any time
8290 with \\[verilog-delete-auto-star-implicit].
8291
8292 If you are converting a module to use .* for the first time, you may wish
8293 to use \\[verilog-inject-auto] and then replace the created AUTOINST with .*.
8294
8295 See `verilog-auto-inst' for examples, templates, and more information."
8296 (when (verilog-auto-star-safe)
8297 (verilog-auto-inst)))
8298
8299 (defun verilog-auto-inst ()
8300 "Expand AUTOINST statements, as part of \\[verilog-auto].
8301 Replace the pin connections to an instantiation with ones
8302 automatically derived from the module header of the instantiated netlist.
8303
8304 If `verilog-auto-star-expand' is set, also expand SystemVerilog .* ports,
8305 and delete them before saving unless `verilog-auto-star-save' is set.
8306 See `verilog-auto-star' for more information.
8307
8308 Limitations:
8309 Module names must be resolvable to filenames by adding a
8310 `verilog-library-extensions', and being found in the same directory, or
8311 by changing the variable `verilog-library-flags' or
8312 `verilog-library-directories'. Macros `modname are translated through the
8313 vh-{name} Emacs variable, if that is not found, it just ignores the `.
8314
8315 In templates you must have one signal per line, ending in a ), or ));,
8316 and have proper () nesting, including a final ); to end the template.
8317
8318 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8319
8320 SystemVerilog multidimensional input/output has only experimental support.
8321
8322 Parameters referenced by the instantiation will remain symbolic, unless
8323 `verilog-auto-inst-param-value' is set.
8324
8325 For example, first take the submodule InstModule.v:
8326
8327 module InstModule (o,i)
8328 output [31:0] o;
8329 input i;
8330 wire [31:0] o = {32{i}};
8331 endmodule
8332
8333 This is then used in a upper level module:
8334
8335 module ExampInst (o,i)
8336 output o;
8337 input i;
8338 InstModule instName
8339 (/*AUTOINST*/);
8340 endmodule
8341
8342 Typing \\[verilog-auto] will make this into:
8343
8344 module ExampInst (o,i)
8345 output o;
8346 input i;
8347 InstModule instName
8348 (/*AUTOINST*/
8349 // Outputs
8350 .ov (ov[31:0]),
8351 // Inputs
8352 .i (i));
8353 endmodule
8354
8355 Where the list of inputs and outputs came from the inst module.
8356 \f
8357 Exceptions:
8358
8359 Unless you are instantiating a module multiple times, or the module is
8360 something trivial like an adder, DO NOT CHANGE SIGNAL NAMES ACROSS HIERARCHY.
8361 It just makes for unmaintainable code. To sanitize signal names, try
8362 vrename from http://www.veripool.com.
8363
8364 When you need to violate this suggestion there are two ways to list
8365 exceptions, placing them before the AUTOINST, or using templates.
8366
8367 Any ports defined before the /*AUTOINST*/ are not included in the list of
8368 automatics. This is similar to making a template as described below, but
8369 is restricted to simple connections just like you normally make. Also note
8370 that any signals before the AUTOINST will only be picked up by AUTOWIRE if
8371 you have the appropriate // Input or // Output comment, and exactly the
8372 same line formatting as AUTOINST itself uses.
8373
8374 InstModule instName
8375 (// Inputs
8376 .i (my_i_dont_mess_with_it),
8377 /*AUTOINST*/
8378 // Outputs
8379 .ov (ov[31:0]));
8380
8381 \f
8382 Templates:
8383
8384 For multiple instantiations based upon a single template, create a
8385 commented out template:
8386
8387 /* InstModule AUTO_TEMPLATE (
8388 .sig3 (sigz[]),
8389 );
8390 */
8391
8392 Templates go ABOVE the instantiation(s). When an instantiation is
8393 expanded `verilog-mode' simply searches up for the closest template.
8394 Thus you can have multiple templates for the same module, just alternate
8395 between the template for an instantiation and the instantiation itself.
8396
8397 The module name must be the same as the name of the module in the
8398 instantiation name, and the code \"AUTO_TEMPLATE\" must be in these exact
8399 words and capitalized. Only signals that must be different for each
8400 instantiation need to be listed.
8401
8402 Inside a template, a [] in a connection name (with nothing else inside
8403 the brackets) will be replaced by the same bus subscript as it is being
8404 connected to, or the [] will be removed if it is a single bit signal.
8405 Generally it is a good idea to do this for all connections in a template,
8406 as then they will work for any width signal, and with AUTOWIRE. See
8407 PTL_BUS becoming PTL_BUSNEW below.
8408
8409 If you have a complicated template, set `verilog-auto-inst-template-numbers'
8410 to see which regexps are matching. Don't leave that mode set after
8411 debugging is completed though, it will result in lots of extra differences
8412 and merge conflicts.
8413
8414 For example:
8415
8416 /* InstModule AUTO_TEMPLATE (
8417 .ptl_bus (ptl_busnew[]),
8418 );
8419 */
8420 InstModule ms2m (/*AUTOINST*/);
8421
8422 Typing \\[verilog-auto] will make this into:
8423
8424 InstModule ms2m (/*AUTOINST*/
8425 // Outputs
8426 .NotInTemplate (NotInTemplate),
8427 .ptl_bus (ptl_busnew[3:0]), // Templated
8428 ....
8429 \f
8430 @ Templates:
8431
8432 It is common to instantiate a cell multiple times, so templates make it
8433 trivial to substitute part of the cell name into the connection name.
8434
8435 /* InstName AUTO_TEMPLATE <optional \"REGEXP\"> (
8436 .sig1 (sigx[@]),
8437 .sig2 (sigy[@\"(% (+ 1 @) 4)\"]),
8438 );
8439 */
8440
8441 If no regular expression is provided immediately after the AUTO_TEMPLATE
8442 keyword, then the @ character in any connection names will be replaced
8443 with the instantiation number; the first digits found in the cell's
8444 instantiation name.
8445
8446 If a regular expression is provided, the @ character will be replaced
8447 with the first \(\) grouping that matches against the cell name. Using a
8448 regexp of \"\\([0-9]+\\)\" provides identical values for @ as when no
8449 regexp is provided. If you use multiple layers of parenthesis,
8450 \"test\\([^0-9]+\\)_\\([0-9]+\\)\" would replace @ with non-number
8451 characters after test and before _, whereas
8452 \"\\(test\\([a-z]+\\)_\\([0-9]+\\)\\)\" would replace @ with the entire
8453 match.
8454
8455 For example:
8456
8457 /* InstModule AUTO_TEMPLATE (
8458 .ptl_mapvalidx (ptl_mapvalid[@]),
8459 .ptl_mapvalidp1x (ptl_mapvalid[@\"(% (+ 1 @) 4)\"]),
8460 );
8461 */
8462 InstModule ms2m (/*AUTOINST*/);
8463
8464 Typing \\[verilog-auto] will make this into:
8465
8466 InstModule ms2m (/*AUTOINST*/
8467 // Outputs
8468 .ptl_mapvalidx (ptl_mapvalid[2]),
8469 .ptl_mapvalidp1x (ptl_mapvalid[3]));
8470
8471 Note the @ character was replaced with the 2 from \"ms2m\".
8472
8473 Alternatively, using a regular expression for @:
8474
8475 /* InstModule AUTO_TEMPLATE \"_\\([a-z]+\\)\" (
8476 .ptl_mapvalidx (@_ptl_mapvalid),
8477 .ptl_mapvalidp1x (ptl_mapvalid_@),
8478 );
8479 */
8480 InstModule ms2_FOO (/*AUTOINST*/);
8481 InstModule ms2_BAR (/*AUTOINST*/);
8482
8483 Typing \\[verilog-auto] will make this into:
8484
8485 InstModule ms2_FOO (/*AUTOINST*/
8486 // Outputs
8487 .ptl_mapvalidx (FOO_ptl_mapvalid),
8488 .ptl_mapvalidp1x (ptl_mapvalid_FOO));
8489 InstModule ms2_BAR (/*AUTOINST*/
8490 // Outputs
8491 .ptl_mapvalidx (BAR_ptl_mapvalid),
8492 .ptl_mapvalidp1x (ptl_mapvalid_BAR));
8493
8494 \f
8495 Regexp Templates:
8496
8497 A template entry of the form
8498
8499 .pci_req\\([0-9]+\\)_l (pci_req_jtag_[\\1]),
8500
8501 will apply an Emacs style regular expression search for any port beginning
8502 in pci_req followed by numbers and ending in _l and connecting that to
8503 the pci_req_jtag_[] net, with the bus subscript coming from what matches
8504 inside the first set of \\( \\). Thus pci_req2_l becomes pci_req_jtag_[2].
8505
8506 Since \\([0-9]+\\) is so common and ugly to read, a @ in the port name
8507 does the same thing. (Note a @ in the connection/replacement text is
8508 completely different -- still use \\1 there!) Thus this is the same as
8509 the above template:
8510
8511 .pci_req@_l (pci_req_jtag_[\\1]),
8512
8513 Here's another example to remove the _l, useful when naming conventions
8514 specify _ alone to mean active low. Note the use of [] to keep the bus
8515 subscript:
8516
8517 .\\(.*\\)_l (\\1_[]),
8518 \f
8519 Lisp Templates:
8520
8521 First any regular expression template is expanded.
8522
8523 If the syntax @\"( ... )\" is found in a connection, the expression in
8524 quotes will be evaluated as a Lisp expression, with @ replaced by the
8525 instantiation number. The MAPVALIDP1X example above would put @+1 modulo
8526 4 into the brackets. Quote all double-quotes inside the expression with
8527 a leading backslash (\\\"). There are special variables defined that are
8528 useful in these Lisp functions:
8529
8530 vl-name Name portion of the input/output port.
8531 vl-bits Bus bits portion of the input/output port ('[2:0]').
8532 vl-width Width of the input/output port ('3' for [2:0]).
8533 May be a (...) expression if bits isn't a constant.
8534 vl-dir Direction of the pin input/output/inout.
8535 vl-cell-type Module name/type of the cell ('InstModule').
8536 vl-cell-name Instance name of the cell ('instName').
8537
8538 Normal Lisp variables may be used in expressions. See
8539 `verilog-read-defines' which can set vh-{definename} variables for use
8540 here. Also, any comments of the form:
8541
8542 /*AUTO_LISP(setq foo 1)*/
8543
8544 will evaluate any Lisp expression inside the parenthesis between the
8545 beginning of the buffer and the point of the AUTOINST. This allows
8546 functions to be defined or variables to be changed between instantiations.
8547
8548 Note that when using lisp expressions errors may occur when @ is not a
8549 number; you may need to use the standard Emacs Lisp functions
8550 `number-to-string' and `string-to-number'.
8551
8552 After the evaluation is completed, @ substitution and [] substitution
8553 occur."
8554 (save-excursion
8555 ;; Find beginning
8556 (let* ((pt (point))
8557 (for-star (save-excursion (backward-char 2) (looking-at "\\.\\*")))
8558 (indent-pt (save-excursion (verilog-backward-open-paren)
8559 (1+ (current-column))))
8560 (verilog-auto-inst-column (max verilog-auto-inst-column
8561 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
8562 (modi (verilog-modi-current))
8563 (moddecls (verilog-modi-get-decls modi))
8564 (vector-skip-list (unless verilog-auto-inst-vector
8565 (verilog-decls-get-signals moddecls)))
8566 submod submodi submoddecls
8567 inst skip-pins tpl-list tpl-num did-first par-values)
8568
8569 ;; Find module name that is instantiated
8570 (setq submod (verilog-read-inst-module)
8571 inst (verilog-read-inst-name)
8572 vl-cell-type submod
8573 vl-cell-name inst
8574 skip-pins (aref (verilog-read-inst-pins) 0))
8575
8576 ;; Parse any AUTO_LISP() before here
8577 (verilog-read-auto-lisp (point-min) pt)
8578
8579 ;; Read parameters (after AUTO_LISP)
8580 (setq par-values (and verilog-auto-inst-param-value
8581 (verilog-read-inst-param-value)))
8582
8583 ;; Lookup position, etc of submodule
8584 ;; Note this may raise an error
8585 (when (setq submodi (verilog-modi-lookup submod t))
8586 (setq submoddecls (verilog-modi-get-decls submodi))
8587 ;; If there's a number in the instantiation, it may be a argument to the
8588 ;; automatic variable instantiation program.
8589 (let* ((tpl-info (verilog-read-auto-template submod))
8590 (tpl-regexp (aref tpl-info 0)))
8591 (setq tpl-num (if (string-match tpl-regexp inst)
8592 (match-string 1 inst)
8593 "")
8594 tpl-list (aref tpl-info 1)))
8595 ;; Find submodule's signals and dump
8596 (let ((sig-list (verilog-signals-not-in
8597 (verilog-decls-get-outputs submoddecls)
8598 skip-pins))
8599 (vl-dir "output"))
8600 (when sig-list
8601 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8602 (indent-to indent-pt)
8603 ;; Note these are searched for in verilog-read-sub-decls.
8604 (insert "// Outputs\n")
8605 (mapc (lambda (port)
8606 (verilog-auto-inst-port port indent-pt
8607 tpl-list tpl-num for-star par-values))
8608 sig-list)))
8609 (let ((sig-list (verilog-signals-not-in
8610 (verilog-decls-get-inouts submoddecls)
8611 skip-pins))
8612 (vl-dir "inout"))
8613 (when sig-list
8614 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8615 (indent-to indent-pt)
8616 (insert "// Inouts\n")
8617 (mapc (lambda (port)
8618 (verilog-auto-inst-port port indent-pt
8619 tpl-list tpl-num for-star par-values))
8620 sig-list)))
8621 (let ((sig-list (verilog-signals-not-in
8622 (verilog-decls-get-inputs submoddecls)
8623 skip-pins))
8624 (vl-dir "input"))
8625 (when sig-list
8626 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8627 (indent-to indent-pt)
8628 (insert "// Inputs\n")
8629 (mapc (lambda (port)
8630 (verilog-auto-inst-port port indent-pt
8631 tpl-list tpl-num for-star par-values))
8632 sig-list)))
8633 ;; Kill extra semi
8634 (save-excursion
8635 (cond (did-first
8636 (re-search-backward "," pt t)
8637 (delete-char 1)
8638 (insert ");")
8639 (search-forward "\n") ;; Added by inst-port
8640 (delete-backward-char 1)
8641 (if (search-forward ")" nil t) ;; From user, moved up a line
8642 (delete-backward-char 1))
8643 (if (search-forward ";" nil t) ;; Don't error if user had syntax error and forgot it
8644 (delete-backward-char 1)))))))))
8645
8646 (defun verilog-auto-inst-param ()
8647 "Expand AUTOINSTPARAM statements, as part of \\[verilog-auto].
8648 Replace the parameter connections to an instantiation with ones
8649 automatically derived from the module header of the instantiated netlist.
8650
8651 See \\[verilog-auto-inst] for limitations, and templates to customize the
8652 output.
8653
8654 For example, first take the submodule InstModule.v:
8655
8656 module InstModule (o,i)
8657 parameter PAR;
8658 endmodule
8659
8660 This is then used in a upper level module:
8661
8662 module ExampInst (o,i)
8663 parameter PAR;
8664 InstModule #(/*AUTOINSTPARAM*/)
8665 instName (/*AUTOINST*/);
8666 endmodule
8667
8668 Typing \\[verilog-auto] will make this into:
8669
8670 module ExampInst (o,i)
8671 output o;
8672 input i;
8673 InstModule #(/*AUTOINSTPARAM*/
8674 // Parameters
8675 .PAR (PAR));
8676 instName (/*AUTOINST*/);
8677 endmodule
8678
8679 Where the list of parameter connections come from the inst module.
8680 \f
8681 Templates:
8682
8683 You can customize the parameter connections using AUTO_TEMPLATEs,
8684 just as you would with \\[verilog-auto-inst]."
8685 (save-excursion
8686 ;; Find beginning
8687 (let* ((pt (point))
8688 (indent-pt (save-excursion (verilog-backward-open-paren)
8689 (1+ (current-column))))
8690 (verilog-auto-inst-column (max verilog-auto-inst-column
8691 (+ 16 (* 8 (/ (+ indent-pt 7) 8)))))
8692 (modi (verilog-modi-current))
8693 (moddecls (verilog-modi-get-decls modi))
8694 (vector-skip-list (unless verilog-auto-inst-vector
8695 (verilog-decls-get-signals moddecls)))
8696 submod submodi submoddecls
8697 inst skip-pins tpl-list tpl-num did-first)
8698 ;; Find module name that is instantiated
8699 (setq submod (save-excursion
8700 ;; Get to the point where AUTOINST normally is to read the module
8701 (verilog-re-search-forward-quick "[(;]" nil nil)
8702 (verilog-read-inst-module))
8703 inst (save-excursion
8704 ;; Get to the point where AUTOINST normally is to read the module
8705 (verilog-re-search-forward-quick "[(;]" nil nil)
8706 (verilog-read-inst-name))
8707 vl-cell-type submod
8708 vl-cell-name inst
8709 skip-pins (aref (verilog-read-inst-pins) 0))
8710
8711 ;; Parse any AUTO_LISP() before here
8712 (verilog-read-auto-lisp (point-min) pt)
8713
8714 ;; Lookup position, etc of submodule
8715 ;; Note this may raise an error
8716 (when (setq submodi (verilog-modi-lookup submod t))
8717 (setq submoddecls (verilog-modi-get-decls submodi))
8718 ;; If there's a number in the instantiation, it may be a argument to the
8719 ;; automatic variable instantiation program.
8720 (let* ((tpl-info (verilog-read-auto-template submod))
8721 (tpl-regexp (aref tpl-info 0)))
8722 (setq tpl-num (if (string-match tpl-regexp inst)
8723 (match-string 1 inst)
8724 "")
8725 tpl-list (aref tpl-info 1)))
8726 ;; Find submodule's signals and dump
8727 (let ((sig-list (verilog-signals-not-in
8728 (verilog-decls-get-gparams submoddecls)
8729 skip-pins))
8730 (vl-dir "parameter"))
8731 (when sig-list
8732 (when (not did-first) (verilog-auto-inst-first) (setq did-first t))
8733 (indent-to indent-pt)
8734 ;; Note these are searched for in verilog-read-sub-decls.
8735 (insert "// Parameters\n")
8736 (mapc (lambda (port)
8737 (verilog-auto-inst-port port indent-pt
8738 tpl-list tpl-num nil nil))
8739 sig-list)))
8740 ;; Kill extra semi
8741 (save-excursion
8742 (cond (did-first
8743 (re-search-backward "," pt t)
8744 (delete-char 1)
8745 (insert ")")
8746 (search-forward "\n") ;; Added by inst-port
8747 (delete-backward-char 1)
8748 (if (search-forward ")" nil t) ;; From user, moved up a line
8749 (delete-backward-char 1)))))))))
8750
8751 (defun verilog-auto-reg ()
8752 "Expand AUTOREG statements, as part of \\[verilog-auto].
8753 Make reg statements for any output that isn't already declared,
8754 and isn't a wire output from a block.
8755
8756 Limitations:
8757 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8758
8759 This does NOT work on memories, declare those yourself.
8760
8761 An example:
8762
8763 module ExampReg (o,i)
8764 output o;
8765 input i;
8766 /*AUTOREG*/
8767 always o = i;
8768 endmodule
8769
8770 Typing \\[verilog-auto] will make this into:
8771
8772 module ExampReg (o,i)
8773 output o;
8774 input i;
8775 /*AUTOREG*/
8776 // Beginning of automatic regs (for this module's undeclared outputs)
8777 reg o;
8778 // End of automatics
8779 always o = i;
8780 endmodule"
8781 (save-excursion
8782 ;; Point must be at insertion point.
8783 (let* ((indent-pt (current-indentation))
8784 (modi (verilog-modi-current))
8785 (moddecls (verilog-modi-get-decls modi))
8786 (modsubdecls (verilog-modi-get-sub-decls modi))
8787 (sig-list (verilog-signals-not-in
8788 (verilog-decls-get-outputs moddecls)
8789 (append (verilog-decls-get-wires moddecls)
8790 (verilog-decls-get-regs moddecls)
8791 (verilog-decls-get-assigns moddecls)
8792 (verilog-decls-get-consts moddecls)
8793 (verilog-decls-get-gparams moddecls)
8794 (verilog-subdecls-get-outputs modsubdecls)
8795 (verilog-subdecls-get-inouts modsubdecls)))))
8796 (forward-line 1)
8797 (when sig-list
8798 (verilog-insert-indent "// Beginning of automatic regs (for this module's undeclared outputs)\n")
8799 (verilog-insert-definition sig-list "reg" indent-pt nil)
8800 (verilog-modi-cache-add-regs modi sig-list)
8801 (verilog-insert-indent "// End of automatics\n")))))
8802
8803 (defun verilog-auto-reg-input ()
8804 "Expand AUTOREGINPUT statements, as part of \\[verilog-auto].
8805 Make reg statements instantiation inputs that aren't already declared.
8806 This is useful for making a top level shell for testing the module that is
8807 to be instantiated.
8808
8809 Limitations:
8810 This ONLY detects inputs of AUTOINSTants (see `verilog-read-sub-decls').
8811
8812 This does NOT work on memories, declare those yourself.
8813
8814 An example (see `verilog-auto-inst' for what else is going on here):
8815
8816 module ExampRegInput (o,i)
8817 output o;
8818 input i;
8819 /*AUTOREGINPUT*/
8820 InstModule instName
8821 (/*AUTOINST*/);
8822 endmodule
8823
8824 Typing \\[verilog-auto] will make this into:
8825
8826 module ExampRegInput (o,i)
8827 output o;
8828 input i;
8829 /*AUTOREGINPUT*/
8830 // Beginning of automatic reg inputs (for undeclared ...
8831 reg [31:0] iv; // From inst of inst.v
8832 // End of automatics
8833 InstModule instName
8834 (/*AUTOINST*/
8835 // Outputs
8836 .o (o[31:0]),
8837 // Inputs
8838 .iv (iv));
8839 endmodule"
8840 (save-excursion
8841 ;; Point must be at insertion point.
8842 (let* ((indent-pt (current-indentation))
8843 (modi (verilog-modi-current))
8844 (moddecls (verilog-modi-get-decls modi))
8845 (modsubdecls (verilog-modi-get-sub-decls modi))
8846 (sig-list (verilog-signals-combine-bus
8847 (verilog-signals-not-in
8848 (append (verilog-subdecls-get-inputs modsubdecls)
8849 (verilog-subdecls-get-inouts modsubdecls))
8850 (verilog-decls-get-signals moddecls)))))
8851 (forward-line 1)
8852 (when sig-list
8853 (verilog-insert-indent "// Beginning of automatic reg inputs (for undeclared instantiated-module inputs)\n")
8854 (verilog-insert-definition sig-list "reg" indent-pt nil)
8855 (verilog-modi-cache-add-regs modi sig-list)
8856 (verilog-insert-indent "// End of automatics\n")))))
8857
8858 (defun verilog-auto-wire ()
8859 "Expand AUTOWIRE statements, as part of \\[verilog-auto].
8860 Make wire statements for instantiations outputs that aren't
8861 already declared.
8862
8863 Limitations:
8864 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls'),
8865 and all busses must have widths, such as those from AUTOINST, or using []
8866 in AUTO_TEMPLATEs.
8867
8868 This does NOT work on memories or SystemVerilog .name connections,
8869 declare those yourself.
8870
8871 Verilog mode will add \"Couldn't Merge\" comments to signals it cannot
8872 determine how to bus together. This occurs when you have ports with
8873 non-numeric or non-sequential bus subscripts. If Verilog mode
8874 mis-guessed, you'll have to declare them yourself.
8875
8876 An example (see `verilog-auto-inst' for what else is going on here):
8877
8878 module ExampWire (o,i)
8879 output o;
8880 input i;
8881 /*AUTOWIRE*/
8882 InstModule instName
8883 (/*AUTOINST*/);
8884 endmodule
8885
8886 Typing \\[verilog-auto] will make this into:
8887
8888 module ExampWire (o,i)
8889 output o;
8890 input i;
8891 /*AUTOWIRE*/
8892 // Beginning of automatic wires
8893 wire [31:0] ov; // From inst of inst.v
8894 // End of automatics
8895 InstModule instName
8896 (/*AUTOINST*/
8897 // Outputs
8898 .ov (ov[31:0]),
8899 // Inputs
8900 .i (i));
8901 wire o = | ov;
8902 endmodule"
8903 (save-excursion
8904 ;; Point must be at insertion point.
8905 (let* ((indent-pt (current-indentation))
8906 (modi (verilog-modi-current))
8907 (moddecls (verilog-modi-get-decls modi))
8908 (modsubdecls (verilog-modi-get-sub-decls modi))
8909 (sig-list (verilog-signals-combine-bus
8910 (verilog-signals-not-in
8911 (append (verilog-subdecls-get-outputs modsubdecls)
8912 (verilog-subdecls-get-inouts modsubdecls))
8913 (verilog-decls-get-signals moddecls)))))
8914 (forward-line 1)
8915 (when sig-list
8916 (verilog-insert-indent "// Beginning of automatic wires (for undeclared instantiated-module outputs)\n")
8917 (verilog-insert-definition sig-list "wire" indent-pt nil)
8918 (verilog-modi-cache-add-wires modi sig-list)
8919 (verilog-insert-indent "// End of automatics\n")
8920 (when nil ;; Too slow on huge modules, plus makes everyone's module change
8921 (beginning-of-line)
8922 (setq pnt (point))
8923 (verilog-pretty-declarations quiet)
8924 (goto-char pnt)
8925 (verilog-pretty-expr "//"))))))
8926
8927 (defun verilog-auto-output (&optional with-params)
8928 "Expand AUTOOUTPUT statements, as part of \\[verilog-auto].
8929 Make output statements for any output signal from an /*AUTOINST*/ that
8930 isn't a input to another AUTOINST. This is useful for modules which
8931 only instantiate other modules.
8932
8933 Limitations:
8934 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
8935
8936 If placed inside the parenthesis of a module declaration, it creates
8937 Verilog 2001 style, else uses Verilog 1995 style.
8938
8939 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
8940 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
8941
8942 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
8943
8944 Signals matching `verilog-auto-output-ignore-regexp' are not included.
8945
8946 An example (see `verilog-auto-inst' for what else is going on here):
8947
8948 module ExampOutput (ov,i)
8949 input i;
8950 /*AUTOOUTPUT*/
8951 InstModule instName
8952 (/*AUTOINST*/);
8953 endmodule
8954
8955 Typing \\[verilog-auto] will make this into:
8956
8957 module ExampOutput (ov,i)
8958 input i;
8959 /*AUTOOUTPUT*/
8960 // Beginning of automatic outputs (from unused autoinst outputs)
8961 output [31:0] ov; // From inst of inst.v
8962 // End of automatics
8963 InstModule instName
8964 (/*AUTOINST*/
8965 // Outputs
8966 .ov (ov[31:0]),
8967 // Inputs
8968 .i (i));
8969 endmodule
8970
8971 You may also provide an optional regular expression, in which case only
8972 signals matching the regular expression will be included. For example the
8973 same expansion will result from only extracting outputs starting with ov:
8974
8975 /*AUTOOUTPUT(\"^ov\")*/"
8976 (save-excursion
8977 ;; Point must be at insertion point.
8978 (let* ((indent-pt (current-indentation))
8979 (regexp (and with-params
8980 (nth 0 (verilog-read-auto-params 1))))
8981 (v2k (verilog-in-paren))
8982 (modi (verilog-modi-current))
8983 (moddecls (verilog-modi-get-decls modi))
8984 (modsubdecls (verilog-modi-get-sub-decls modi))
8985 (sig-list (verilog-signals-not-in
8986 (verilog-subdecls-get-outputs modsubdecls)
8987 (append (verilog-decls-get-outputs moddecls)
8988 (verilog-decls-get-inouts moddecls)
8989 (verilog-subdecls-get-inputs modsubdecls)
8990 (verilog-subdecls-get-inouts modsubdecls)))))
8991 (when regexp
8992 (setq sig-list (verilog-signals-matching-regexp
8993 sig-list regexp)))
8994 (setq sig-list (verilog-signals-not-matching-regexp
8995 sig-list verilog-auto-output-ignore-regexp))
8996 (forward-line 1)
8997 (when v2k (verilog-repair-open-comma))
8998 (when sig-list
8999 (verilog-insert-indent "// Beginning of automatic outputs (from unused autoinst outputs)\n")
9000 (verilog-insert-definition sig-list "output" indent-pt v2k)
9001 (verilog-modi-cache-add-outputs modi sig-list)
9002 (verilog-insert-indent "// End of automatics\n"))
9003 (when v2k (verilog-repair-close-comma)))))
9004
9005 (defun verilog-auto-output-every ()
9006 "Expand AUTOOUTPUTEVERY statements, as part of \\[verilog-auto].
9007 Make output statements for any signals that aren't primary inputs or
9008 outputs already. This makes every signal in the design a output. This is
9009 useful to get Synopsys to preserve every signal in the design, since it
9010 won't optimize away the outputs.
9011
9012 An example:
9013
9014 module ExampOutputEvery (o,i,tempa,tempb)
9015 output o;
9016 input i;
9017 /*AUTOOUTPUTEVERY*/
9018 wire tempa = i;
9019 wire tempb = tempa;
9020 wire o = tempb;
9021 endmodule
9022
9023 Typing \\[verilog-auto] will make this into:
9024
9025 module ExampOutputEvery (o,i,tempa,tempb)
9026 output o;
9027 input i;
9028 /*AUTOOUTPUTEVERY*/
9029 // Beginning of automatic outputs (every signal)
9030 output tempb;
9031 output tempa;
9032 // End of automatics
9033 wire tempa = i;
9034 wire tempb = tempa;
9035 wire o = tempb;
9036 endmodule"
9037 (save-excursion
9038 ;;Point must be at insertion point
9039 (let* ((indent-pt (current-indentation))
9040 (v2k (verilog-in-paren))
9041 (modi (verilog-modi-current))
9042 (moddecls (verilog-modi-get-decls modi))
9043 (sig-list (verilog-signals-combine-bus
9044 (verilog-signals-not-in
9045 (verilog-decls-get-signals moddecls)
9046 (verilog-decls-get-ports moddecls)))))
9047 (forward-line 1)
9048 (when v2k (verilog-repair-open-comma))
9049 (when sig-list
9050 (verilog-insert-indent "// Beginning of automatic outputs (every signal)\n")
9051 (verilog-insert-definition sig-list "output" indent-pt v2k)
9052 (verilog-modi-cache-add-outputs modi sig-list)
9053 (verilog-insert-indent "// End of automatics\n"))
9054 (when v2k (verilog-repair-close-comma)))))
9055
9056 (defun verilog-auto-input (&optional with-params)
9057 "Expand AUTOINPUT statements, as part of \\[verilog-auto].
9058 Make input statements for any input signal into an /*AUTOINST*/ that
9059 isn't declared elsewhere inside the module. This is useful for modules which
9060 only instantiate other modules.
9061
9062 Limitations:
9063 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9064
9065 If placed inside the parenthesis of a module declaration, it creates
9066 Verilog 2001 style, else uses Verilog 1995 style.
9067
9068 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
9069 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
9070
9071 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9072
9073 Signals matching `verilog-auto-input-ignore-regexp' are not included.
9074
9075 An example (see `verilog-auto-inst' for what else is going on here):
9076
9077 module ExampInput (ov,i)
9078 output [31:0] ov;
9079 /*AUTOINPUT*/
9080 InstModule instName
9081 (/*AUTOINST*/);
9082 endmodule
9083
9084 Typing \\[verilog-auto] will make this into:
9085
9086 module ExampInput (ov,i)
9087 output [31:0] ov;
9088 /*AUTOINPUT*/
9089 // Beginning of automatic inputs (from unused autoinst inputs)
9090 input i; // From inst of inst.v
9091 // End of automatics
9092 InstModule instName
9093 (/*AUTOINST*/
9094 // Outputs
9095 .ov (ov[31:0]),
9096 // Inputs
9097 .i (i));
9098 endmodule
9099
9100 You may also provide an optional regular expression, in which case only
9101 signals matching the regular expression will be included. For example the
9102 same expansion will result from only extracting inputs starting with i:
9103
9104 /*AUTOINPUT(\"^i\")*/"
9105 (save-excursion
9106 (let* ((indent-pt (current-indentation))
9107 (regexp (and with-params
9108 (nth 0 (verilog-read-auto-params 1))))
9109 (v2k (verilog-in-paren))
9110 (modi (verilog-modi-current))
9111 (moddecls (verilog-modi-get-decls modi))
9112 (modsubdecls (verilog-modi-get-sub-decls modi))
9113 (sig-list (verilog-signals-not-in
9114 (verilog-subdecls-get-inputs modsubdecls)
9115 (append (verilog-decls-get-inputs moddecls)
9116 (verilog-decls-get-inouts moddecls)
9117 (verilog-decls-get-wires moddecls)
9118 (verilog-decls-get-regs moddecls)
9119 (verilog-decls-get-consts moddecls)
9120 (verilog-decls-get-gparams moddecls)
9121 (verilog-subdecls-get-outputs modsubdecls)
9122 (verilog-subdecls-get-inouts modsubdecls)))))
9123 (when regexp
9124 (setq sig-list (verilog-signals-matching-regexp
9125 sig-list regexp)))
9126 (setq sig-list (verilog-signals-not-matching-regexp
9127 sig-list verilog-auto-input-ignore-regexp))
9128 (forward-line 1)
9129 (when v2k (verilog-repair-open-comma))
9130 (when sig-list
9131 (verilog-insert-indent "// Beginning of automatic inputs (from unused autoinst inputs)\n")
9132 (verilog-insert-definition sig-list "input" indent-pt v2k)
9133 (verilog-modi-cache-add-inputs modi sig-list)
9134 (verilog-insert-indent "// End of automatics\n"))
9135 (when v2k (verilog-repair-close-comma)))))
9136
9137 (defun verilog-auto-inout (&optional with-params)
9138 "Expand AUTOINOUT statements, as part of \\[verilog-auto].
9139 Make inout statements for any inout signal in an /*AUTOINST*/ that
9140 isn't declared elsewhere inside the module.
9141
9142 Limitations:
9143 This ONLY detects outputs of AUTOINSTants (see `verilog-read-sub-decls').
9144
9145 If placed inside the parenthesis of a module declaration, it creates
9146 Verilog 2001 style, else uses Verilog 1995 style.
9147
9148 If any concatenation, or bit-subscripts are missing in the AUTOINSTant's
9149 instantiation, all bets are off. (For example due to a AUTO_TEMPLATE).
9150
9151 Typedefs must match `verilog-typedef-regexp', which is disabled by default.
9152
9153 Signals matching `verilog-auto-inout-ignore-regexp' are not included.
9154
9155 An example (see `verilog-auto-inst' for what else is going on here):
9156
9157 module ExampInout (ov,i)
9158 input i;
9159 /*AUTOINOUT*/
9160 InstModule instName
9161 (/*AUTOINST*/);
9162 endmodule
9163
9164 Typing \\[verilog-auto] will make this into:
9165
9166 module ExampInout (ov,i)
9167 input i;
9168 /*AUTOINOUT*/
9169 // Beginning of automatic inouts (from unused autoinst inouts)
9170 inout [31:0] ov; // From inst of inst.v
9171 // End of automatics
9172 InstModule instName
9173 (/*AUTOINST*/
9174 // Inouts
9175 .ov (ov[31:0]),
9176 // Inputs
9177 .i (i));
9178 endmodule
9179
9180 You may also provide an optional regular expression, in which case only
9181 signals matching the regular expression will be included. For example the
9182 same expansion will result from only extracting inouts starting with i:
9183
9184 /*AUTOINOUT(\"^i\")*/"
9185 (save-excursion
9186 ;; Point must be at insertion point.
9187 (let* ((indent-pt (current-indentation))
9188 (regexp (and with-params
9189 (nth 0 (verilog-read-auto-params 1))))
9190 (v2k (verilog-in-paren))
9191 (modi (verilog-modi-current))
9192 (moddecls (verilog-modi-get-decls modi))
9193 (modsubdecls (verilog-modi-get-sub-decls modi))
9194 (sig-list (verilog-signals-not-in
9195 (verilog-subdecls-get-inouts modsubdecls)
9196 (append (verilog-decls-get-outputs moddecls)
9197 (verilog-decls-get-inouts moddecls)
9198 (verilog-decls-get-inputs moddecls)
9199 (verilog-subdecls-get-inputs modsubdecls)
9200 (verilog-subdecls-get-outputs modsubdecls)))))
9201 (when regexp
9202 (setq sig-list (verilog-signals-matching-regexp
9203 sig-list regexp)))
9204 (setq sig-list (verilog-signals-not-matching-regexp
9205 sig-list verilog-auto-inout-ignore-regexp))
9206 (forward-line 1)
9207 (when v2k (verilog-repair-open-comma))
9208 (when sig-list
9209 (verilog-insert-indent "// Beginning of automatic inouts (from unused autoinst inouts)\n")
9210 (verilog-insert-definition sig-list "inout" indent-pt v2k)
9211 (verilog-modi-cache-add-inouts modi sig-list)
9212 (verilog-insert-indent "// End of automatics\n"))
9213 (when v2k (verilog-repair-close-comma)))))
9214
9215 (defun verilog-auto-inout-module ()
9216 "Expand AUTOINOUTMODULE statements, as part of \\[verilog-auto].
9217 Take input/output/inout statements from the specified module and insert
9218 into the current module. This is useful for making null templates and
9219 shell modules which need to have identical I/O with another module.
9220 Any I/O which are already defined in this module will not be redefined.
9221
9222 Limitations:
9223 If placed inside the parenthesis of a module declaration, it creates
9224 Verilog 2001 style, else uses Verilog 1995 style.
9225
9226 Concatenation and outputting partial busses is not supported.
9227
9228 Module names must be resolvable to filenames. See `verilog-auto-inst'.
9229
9230 Signals are not inserted in the same order as in the original module,
9231 though they will appear to be in the same order to a AUTOINST
9232 instantiating either module.
9233
9234 An example:
9235
9236 module ExampShell (/*AUTOARG*/)
9237 /*AUTOINOUTMODULE(\"ExampMain\")*/
9238 endmodule
9239
9240 module ExampMain (i,o,io)
9241 input i;
9242 output o;
9243 inout io;
9244 endmodule
9245
9246 Typing \\[verilog-auto] will make this into:
9247
9248 module ExampShell (/*AUTOARG*/i,o,io)
9249 /*AUTOINOUTMODULE(\"ExampMain\")*/
9250 // Beginning of automatic in/out/inouts (from specific module)
9251 input i;
9252 output o;
9253 inout io;
9254 // End of automatics
9255 endmodule
9256
9257 You may also provide an optional regular expression, in which case only
9258 signals matching the regular expression will be included. For example the
9259 same expansion will result from only extracting signals starting with i:
9260
9261 /*AUTOINOUTMODULE(\"ExampMain\",\"^i\")*/"
9262 (save-excursion
9263 (let* ((params (verilog-read-auto-params 1 2))
9264 (submod (nth 0 params))
9265 (regexp (nth 1 params))
9266 submodi)
9267 ;; Lookup position, etc of co-module
9268 ;; Note this may raise an error
9269 (when (setq submodi (verilog-modi-lookup submod t))
9270 (let* ((indent-pt (current-indentation))
9271 (v2k (verilog-in-paren))
9272 (modi (verilog-modi-current))
9273 (moddecls (verilog-modi-get-decls modi))
9274 (submoddecls (verilog-modi-get-decls submodi))
9275 (sig-list-i (verilog-signals-not-in
9276 (verilog-decls-get-inputs submoddecls)
9277 (append (verilog-decls-get-inputs moddecls))))
9278 (sig-list-o (verilog-signals-not-in
9279 (verilog-decls-get-outputs submoddecls)
9280 (append (verilog-decls-get-outputs moddecls))))
9281 (sig-list-io (verilog-signals-not-in
9282 (verilog-decls-get-inouts submoddecls)
9283 (append (verilog-decls-get-inouts moddecls)))))
9284 (forward-line 1)
9285 (when regexp
9286 (setq sig-list-i (verilog-signals-matching-regexp
9287 sig-list-i regexp)
9288 sig-list-o (verilog-signals-matching-regexp
9289 sig-list-o regexp)
9290 sig-list-io (verilog-signals-matching-regexp
9291 sig-list-io regexp)))
9292 (when v2k (verilog-repair-open-comma))
9293 (when (or sig-list-i sig-list-o sig-list-io)
9294 (verilog-insert-indent "// Beginning of automatic in/out/inouts (from specific module)\n")
9295 ;; Don't sort them so a upper AUTOINST will match the main module
9296 (verilog-insert-definition sig-list-o "output" indent-pt v2k t)
9297 (verilog-insert-definition sig-list-io "inout" indent-pt v2k t)
9298 (verilog-insert-definition sig-list-i "input" indent-pt v2k t)
9299 (verilog-modi-cache-add-inputs modi sig-list-i)
9300 (verilog-modi-cache-add-outputs modi sig-list-o)
9301 (verilog-modi-cache-add-inouts modi sig-list-io)
9302 (verilog-insert-indent "// End of automatics\n"))
9303 (when v2k (verilog-repair-close-comma)))))))
9304
9305 (defun verilog-auto-sense-sigs (moddecls presense-sigs)
9306 "Return list of signals for current AUTOSENSE block."
9307 (let* ((sigss (verilog-read-always-signals))
9308 (sig-list (verilog-signals-not-params
9309 (verilog-signals-not-in (verilog-alw-get-inputs sigss)
9310 (append (and (not verilog-auto-sense-include-inputs)
9311 (verilog-alw-get-outputs sigss))
9312 (verilog-decls-get-consts moddecls)
9313 (verilog-decls-get-gparams moddecls)
9314 presense-sigs)))))
9315 sig-list))
9316
9317 (defun verilog-auto-sense ()
9318 "Expand AUTOSENSE statements, as part of \\[verilog-auto].
9319 Replace the always (/*AUTOSENSE*/) sensitivity list (/*AS*/ for short)
9320 with one automatically derived from all inputs declared in the always
9321 statement. Signals that are generated within the same always block are NOT
9322 placed into the sensitivity list (see `verilog-auto-sense-include-inputs').
9323 Long lines are split based on the `fill-column', see \\[set-fill-column].
9324
9325 Limitations:
9326 Verilog does not allow memories (multidimensional arrays) in sensitivity
9327 lists. AUTOSENSE will thus exclude them, and add a /*memory or*/ comment.
9328
9329 Constant signals:
9330 AUTOSENSE cannot always determine if a `define is a constant or a signal
9331 (it could be in a include file for example). If a `define or other signal
9332 is put into the AUTOSENSE list and is not desired, use the AUTO_CONSTANT
9333 declaration anywhere in the module (parenthesis are required):
9334
9335 /* AUTO_CONSTANT ( `this_is_really_constant_dont_autosense_it ) */
9336
9337 Better yet, use a parameter, which will be understood to be constant
9338 automatically.
9339
9340 OOps!
9341 If AUTOSENSE makes a mistake, please report it. (First try putting
9342 a begin/end after your always!) As a workaround, if a signal that
9343 shouldn't be in the sensitivity list was, use the AUTO_CONSTANT above.
9344 If a signal should be in the sensitivity list wasn't, placing it before
9345 the /*AUTOSENSE*/ comment will prevent it from being deleted when the
9346 autos are updated (or added if it occurs there already).
9347
9348 An example:
9349
9350 always @ (/*AS*/) begin
9351 /* AUTO_CONSTANT (`constant) */
9352 outin = ina | inb | `constant;
9353 out = outin;
9354 end
9355
9356 Typing \\[verilog-auto] will make this into:
9357
9358 always @ (/*AS*/ina or inb) begin
9359 /* AUTO_CONSTANT (`constant) */
9360 outin = ina | inb | `constant;
9361 out = outin;
9362 end
9363
9364 Note in Verilog 2001, you can often get the same result from the new @*
9365 operator. (This was added to the language in part due to AUTOSENSE!)
9366
9367 always @* begin
9368 outin = ina | inb | `constant;
9369 out = outin;
9370 end"
9371 (save-excursion
9372 ;; Find beginning
9373 (let* ((start-pt (save-excursion
9374 (verilog-re-search-backward "(" nil t)
9375 (point)))
9376 (indent-pt (save-excursion
9377 (or (and (goto-char start-pt) (1+ (current-column)))
9378 (current-indentation))))
9379 (modi (verilog-modi-current))
9380 (moddecls (verilog-modi-get-decls modi))
9381 (sig-memories (verilog-signals-memory
9382 (append
9383 (verilog-decls-get-regs moddecls)
9384 (verilog-decls-get-wires moddecls))))
9385 sig-list not-first presense-sigs)
9386 ;; Read signals in always, eliminate outputs from sense list
9387 (setq presense-sigs (verilog-signals-from-signame
9388 (save-excursion
9389 (verilog-read-signals start-pt (point)))))
9390 (setq sig-list (verilog-auto-sense-sigs moddecls presense-sigs))
9391 (when sig-memories
9392 (let ((tlen (length sig-list)))
9393 (setq sig-list (verilog-signals-not-in sig-list sig-memories))
9394 (if (not (eq tlen (length sig-list))) (insert " /*memory or*/ "))))
9395 (if (and presense-sigs ;; Add a "or" if not "(.... or /*AUTOSENSE*/"
9396 (save-excursion (goto-char (point))
9397 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
9398 (verilog-re-search-backward "\\s-" start-pt t)
9399 (while (looking-at "\\s-`endif")
9400 (verilog-re-search-backward "[a-zA-Z0-9$_.%`]+" start-pt t)
9401 (verilog-re-search-backward "\\s-" start-pt t))
9402 (not (looking-at "\\s-or\\b"))))
9403 (setq not-first t))
9404 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
9405 (while sig-list
9406 (cond ((> (+ 4 (current-column) (length (verilog-sig-name (car sig-list)))) fill-column) ;+4 for width of or
9407 (insert "\n")
9408 (indent-to indent-pt)
9409 (if not-first (insert "or ")))
9410 (not-first (insert " or ")))
9411 (insert (verilog-sig-name (car sig-list)))
9412 (setq sig-list (cdr sig-list)
9413 not-first t)))))
9414
9415 (defun verilog-auto-reset ()
9416 "Expand AUTORESET statements, as part of \\[verilog-auto].
9417 Replace the /*AUTORESET*/ comment with code to initialize all
9418 registers set elsewhere in the always block.
9419
9420 Limitations:
9421 AUTORESET will not clear memories.
9422
9423 AUTORESET uses <= if there are any <= in the block, else it uses =.
9424
9425 /*AUTORESET*/ presumes that any signals mentioned between the previous
9426 begin/case/if statement and the AUTORESET comment are being reset manually
9427 and should not be automatically reset. This includes omitting any signals
9428 used on the right hand side of assignments.
9429
9430 By default, AUTORESET will include the width of the signal in the autos,
9431 this is a recent change. To control this behavior, see
9432 `verilog-auto-reset-widths'.
9433
9434 AUTORESET ties signals to deasserted, which is presumed to be zero.
9435 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
9436 them to a one.
9437
9438 An example:
9439
9440 always @(posedge clk or negedge reset_l) begin
9441 if (!reset_l) begin
9442 c <= 1;
9443 /*AUTORESET*/
9444 end
9445 else begin
9446 a <= in_a;
9447 b <= in_b;
9448 c <= in_c;
9449 end
9450 end
9451
9452 Typing \\[verilog-auto] will make this into:
9453
9454 always @(posedge core_clk or negedge reset_l) begin
9455 if (!reset_l) begin
9456 c <= 1;
9457 /*AUTORESET*/
9458 // Beginning of autoreset for uninitialized flops
9459 a <= 0;
9460 b <= 0;
9461 // End of automatics
9462 end
9463 else begin
9464 a <= in_a;
9465 b <= in_b;
9466 c <= in_c;
9467 end
9468 end"
9469
9470 (interactive)
9471 (save-excursion
9472 ;; Find beginning
9473 (let* ((indent-pt (current-indentation))
9474 (modi (verilog-modi-current))
9475 (moddecls (verilog-modi-get-decls modi))
9476 (all-list (verilog-decls-get-signals moddecls))
9477 sigss sig-list prereset-sigs assignment-str)
9478 ;; Read signals in always, eliminate outputs from reset list
9479 (setq prereset-sigs (verilog-signals-from-signame
9480 (save-excursion
9481 (verilog-read-signals
9482 (save-excursion
9483 (verilog-re-search-backward "\\(@\\|\\<begin\\>\\|\\<if\\>\\|\\<case\\>\\)" nil t)
9484 (point))
9485 (point)))))
9486 (save-excursion
9487 (verilog-re-search-backward "@" nil t)
9488 (setq sigss (verilog-read-always-signals)))
9489 (setq assignment-str (if (verilog-alw-get-uses-delayed sigss)
9490 (concat " <= " verilog-assignment-delay)
9491 " = "))
9492 (setq sig-list (verilog-signals-not-in (verilog-alw-get-outputs sigss)
9493 prereset-sigs))
9494 (setq sig-list (sort sig-list `verilog-signals-sort-compare))
9495 (when sig-list
9496 (insert "\n");
9497 (indent-to indent-pt)
9498 (insert "// Beginning of autoreset for uninitialized flops\n");
9499 (indent-to indent-pt)
9500 (while sig-list
9501 (let ((sig (or (assoc (verilog-sig-name (car sig-list)) all-list) ;; As sig-list has no widths
9502 (car sig-list))))
9503 (insert (verilog-sig-name sig)
9504 assignment-str
9505 (verilog-sig-tieoff sig (not verilog-auto-reset-widths))
9506 ";\n")
9507 (indent-to indent-pt)
9508 (setq sig-list (cdr sig-list))))
9509 (insert "// End of automatics")))))
9510
9511 (defun verilog-auto-tieoff ()
9512 "Expand AUTOTIEOFF statements, as part of \\[verilog-auto].
9513 Replace the /*AUTOTIEOFF*/ comment with code to wire-tie all unused output
9514 signals to deasserted.
9515
9516 /*AUTOTIEOFF*/ is used to make stub modules; modules that have the same
9517 input/output list as another module, but no internals. Specifically, it
9518 finds all outputs in the module, and if that input is not otherwise declared
9519 as a register or wire, creates a tieoff.
9520
9521 AUTORESET ties signals to deasserted, which is presumed to be zero.
9522 Signals that match `verilog-active-low-regexp' will be deasserted by tieing
9523 them to a one.
9524
9525 An example of making a stub for another module:
9526
9527 module ExampStub (/*AUTOINST*/);
9528 /*AUTOINOUTMODULE(\"Foo\")*/
9529 /*AUTOTIEOFF*/
9530 // verilator lint_off UNUSED
9531 wire _unused_ok = &{1'b0,
9532 /*AUTOUNUSED*/
9533 1'b0};
9534 // verilator lint_on UNUSED
9535 endmodule
9536
9537 Typing \\[verilog-auto] will make this into:
9538
9539 module ExampStub (/*AUTOINST*/...);
9540 /*AUTOINOUTMODULE(\"Foo\")*/
9541 // Beginning of autotieoff
9542 output [2:0] foo;
9543 // End of automatics
9544
9545 /*AUTOTIEOFF*/
9546 // Beginning of autotieoff
9547 wire [2:0] foo = 3'b0;
9548 // End of automatics
9549 ...
9550 endmodule"
9551 (interactive)
9552 (save-excursion
9553 ;; Find beginning
9554 (let* ((indent-pt (current-indentation))
9555 (modi (verilog-modi-current))
9556 (moddecls (verilog-modi-get-decls modi))
9557 (modsubdecls (verilog-modi-get-sub-decls modi))
9558 (sig-list (verilog-signals-not-in
9559 (verilog-decls-get-outputs moddecls)
9560 (append (verilog-decls-get-wires moddecls)
9561 (verilog-decls-get-regs moddecls)
9562 (verilog-decls-get-assigns moddecls)
9563 (verilog-decls-get-consts moddecls)
9564 (verilog-decls-get-gparams moddecls)
9565 (verilog-subdecls-get-outputs modsubdecls)
9566 (verilog-subdecls-get-inouts modsubdecls)))))
9567 (when sig-list
9568 (forward-line 1)
9569 (verilog-insert-indent "// Beginning of automatic tieoffs (for this module's unterminated outputs)\n")
9570 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
9571 (verilog-modi-cache-add-wires modi sig-list) ; Before we trash list
9572 (while sig-list
9573 (let ((sig (car sig-list)))
9574 (verilog-insert-one-definition sig "wire" indent-pt)
9575 (indent-to (max 48 (+ indent-pt 40)))
9576 (insert "= " (verilog-sig-tieoff sig)
9577 ";\n")
9578 (setq sig-list (cdr sig-list))))
9579 (verilog-insert-indent "// End of automatics\n")))))
9580
9581 (defun verilog-auto-unused ()
9582 "Expand AUTOUNUSED statements, as part of \\[verilog-auto].
9583 Replace the /*AUTOUNUSED*/ comment with a comma separated list of all unused
9584 input and inout signals.
9585
9586 /*AUTOUNUSED*/ is used to make stub modules; modules that have the same
9587 input/output list as another module, but no internals. Specifically, it
9588 finds all inputs and inouts in the module, and if that input is not otherwise
9589 used, adds it to a comma separated list.
9590
9591 The comma separated list is intended to be used to create a _unused_ok
9592 signal. Using the exact name \"_unused_ok\" for name of the temporary
9593 signal is recommended as it will insure maximum forward compatibility, it
9594 also makes lint warnings easy to understand; ignore any unused warnings
9595 with \"unused\" in the signal name.
9596
9597 To reduce simulation time, the _unused_ok signal should be forced to a
9598 constant to prevent wiggling. The easiest thing to do is use a
9599 reduction-and with 1'b0 as shown.
9600
9601 This way all unused signals are in one place, making it convenient to add
9602 your tool's specific pragmas around the assignment to disable any unused
9603 warnings.
9604
9605 You can add signals you do not want included in AUTOUNUSED with
9606 `verilog-auto-unused-ignore-regexp'.
9607
9608 An example of making a stub for another module:
9609
9610 module ExampStub (/*AUTOINST*/);
9611 /*AUTOINOUTMODULE(\"Examp\")*/
9612 /*AUTOTIEOFF*/
9613 // verilator lint_off UNUSED
9614 wire _unused_ok = &{1'b0,
9615 /*AUTOUNUSED*/
9616 1'b0};
9617 // verilator lint_on UNUSED
9618 endmodule
9619
9620 Typing \\[verilog-auto] will make this into:
9621
9622 ...
9623 // verilator lint_off UNUSED
9624 wire _unused_ok = &{1'b0,
9625 /*AUTOUNUSED*/
9626 // Beginning of automatics
9627 unused_input_a,
9628 unused_input_b,
9629 unused_input_c,
9630 // End of automatics
9631 1'b0};
9632 // verilator lint_on UNUSED
9633 endmodule"
9634 (interactive)
9635 (save-excursion
9636 ;; Find beginning
9637 (let* ((indent-pt (progn (search-backward "/*") (current-column)))
9638 (modi (verilog-modi-current))
9639 (moddecls (verilog-modi-get-decls modi))
9640 (modsubdecls (verilog-modi-get-sub-decls modi))
9641 (sig-list (verilog-signals-not-in
9642 (append (verilog-decls-get-inputs moddecls)
9643 (verilog-decls-get-inouts moddecls))
9644 (append (verilog-subdecls-get-inputs modsubdecls)
9645 (verilog-subdecls-get-inouts modsubdecls)))))
9646 (setq sig-list (verilog-signals-not-matching-regexp
9647 sig-list verilog-auto-unused-ignore-regexp))
9648 (when sig-list
9649 (forward-line 1)
9650 (verilog-insert-indent "// Beginning of automatic unused inputs\n")
9651 (setq sig-list (sort (copy-alist sig-list) `verilog-signals-sort-compare))
9652 (while sig-list
9653 (let ((sig (car sig-list)))
9654 (indent-to indent-pt)
9655 (insert (verilog-sig-name sig) ",\n")
9656 (setq sig-list (cdr sig-list))))
9657 (verilog-insert-indent "// End of automatics\n")))))
9658
9659 (defun verilog-enum-ascii (signm elim-regexp)
9660 "Convert an enum name SIGNM to an ascii string for insertion.
9661 Remove user provided prefix ELIM-REGEXP."
9662 (or elim-regexp (setq elim-regexp "_ DONT MATCH IT_"))
9663 (let ((case-fold-search t))
9664 ;; All upper becomes all lower for readability
9665 (downcase (verilog-string-replace-matches elim-regexp "" nil nil signm))))
9666
9667 (defun verilog-auto-ascii-enum ()
9668 "Expand AUTOASCIIENUM statements, as part of \\[verilog-auto].
9669 Create a register to contain the ASCII decode of a enumerated signal type.
9670 This will allow trace viewers to show the ASCII name of states.
9671
9672 First, parameters are built into a enumeration using the synopsys enum
9673 comment. The comment must be between the keyword and the symbol.
9674 \(Annoying, but that's what Synopsys's dc_shell FSM reader requires.)
9675
9676 Next, registers which that enum applies to are also tagged with the same
9677 enum. Synopsys also suggests labeling state vectors, but `verilog-mode'
9678 doesn't care.
9679
9680 Finally, a AUTOASCIIENUM command is used.
9681
9682 The first parameter is the name of the signal to be decoded.
9683
9684 The second parameter is the name to store the ASCII code into. For the
9685 signal foo, I suggest the name _foo__ascii, where the leading _ indicates
9686 a signal that is just for simulation, and the magic characters _ascii
9687 tell viewers like Dinotrace to display in ASCII format.
9688
9689 The final optional parameter is a string which will be removed from the
9690 state names.
9691
9692 An example:
9693
9694 //== State enumeration
9695 parameter [2:0] // synopsys enum state_info
9696 SM_IDLE = 3'b000,
9697 SM_SEND = 3'b001,
9698 SM_WAIT1 = 3'b010;
9699 //== State variables
9700 reg [2:0] /* synopsys enum state_info */
9701 state_r; /* synopsys state_vector state_r */
9702 reg [2:0] /* synopsys enum state_info */
9703 state_e1;
9704
9705 //== ASCII state decoding
9706
9707 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
9708
9709 Typing \\[verilog-auto] will make this into:
9710
9711 ... same front matter ...
9712
9713 /*AUTOASCIIENUM(\"state_r\", \"state_ascii_r\", \"SM_\")*/
9714 // Beginning of automatic ASCII enum decoding
9715 reg [39:0] state_ascii_r; // Decode of state_r
9716 always @(state_r) begin
9717 case ({state_r})
9718 SM_IDLE: state_ascii_r = \"idle \";
9719 SM_SEND: state_ascii_r = \"send \";
9720 SM_WAIT1: state_ascii_r = \"wait1\";
9721 default: state_ascii_r = \"%Erro\";
9722 endcase
9723 end
9724 // End of automatics"
9725 (save-excursion
9726 (let* ((params (verilog-read-auto-params 2 3))
9727 (undecode-name (nth 0 params))
9728 (ascii-name (nth 1 params))
9729 (elim-regexp (nth 2 params))
9730 ;;
9731 (indent-pt (current-indentation))
9732 (modi (verilog-modi-current))
9733 (moddecls (verilog-modi-get-decls modi))
9734 ;;
9735 (sig-list-consts (append (verilog-decls-get-consts moddecls)
9736 (verilog-decls-get-gparams moddecls)))
9737 (sig-list-all (append (verilog-decls-get-regs moddecls)
9738 (verilog-decls-get-outputs moddecls)
9739 (verilog-decls-get-inouts moddecls)
9740 (verilog-decls-get-inputs moddecls)
9741 (verilog-decls-get-wires moddecls)))
9742 ;;
9743 (undecode-sig (or (assoc undecode-name sig-list-all)
9744 (error "%s: Signal %s not found in design" (verilog-point-text) undecode-name)))
9745 (undecode-enum (or (verilog-sig-enum undecode-sig)
9746 (error "%s: Signal %s does not have a enum tag" (verilog-point-text) undecode-name)))
9747 ;;
9748 (enum-sigs (or (verilog-signals-matching-enum sig-list-consts undecode-enum)
9749 (error "%s: No state definitions for %s" (verilog-point-text) undecode-enum)))
9750 ;;
9751 (enum-chars 0)
9752 (ascii-chars 0))
9753 ;;
9754 ;; Find number of ascii chars needed
9755 (let ((tmp-sigs enum-sigs))
9756 (while tmp-sigs
9757 (setq enum-chars (max enum-chars (length (verilog-sig-name (car tmp-sigs))))
9758 ascii-chars (max ascii-chars (length (verilog-enum-ascii
9759 (verilog-sig-name (car tmp-sigs))
9760 elim-regexp)))
9761 tmp-sigs (cdr tmp-sigs))))
9762 ;;
9763 (forward-line 1)
9764 (verilog-insert-indent "// Beginning of automatic ASCII enum decoding\n")
9765 (let ((decode-sig-list (list (list ascii-name (format "[%d:0]" (- (* ascii-chars 8) 1))
9766 (concat "Decode of " undecode-name) nil nil))))
9767 (verilog-insert-definition decode-sig-list "reg" indent-pt nil)
9768 (verilog-modi-cache-add-regs modi decode-sig-list))
9769 ;;
9770 (verilog-insert-indent "always @(" undecode-name ") begin\n")
9771 (setq indent-pt (+ indent-pt verilog-indent-level))
9772 (indent-to indent-pt)
9773 (insert "case ({" undecode-name "})\n")
9774 (setq indent-pt (+ indent-pt verilog-case-indent))
9775 ;;
9776 (let ((tmp-sigs enum-sigs)
9777 (chrfmt (format "%%-%ds %s = \"%%-%ds\";\n" (1+ (max 8 enum-chars))
9778 ascii-name ascii-chars))
9779 (errname (substring "%Error" 0 (min 6 ascii-chars))))
9780 (while tmp-sigs
9781 (verilog-insert-indent
9782 (format chrfmt (concat (verilog-sig-name (car tmp-sigs)) ":")
9783 (verilog-enum-ascii (verilog-sig-name (car tmp-sigs))
9784 elim-regexp)))
9785 (setq tmp-sigs (cdr tmp-sigs)))
9786 (verilog-insert-indent (format chrfmt "default:" errname)))
9787 ;;
9788 (setq indent-pt (- indent-pt verilog-case-indent))
9789 (verilog-insert-indent "endcase\n")
9790 (setq indent-pt (- indent-pt verilog-indent-level))
9791 (verilog-insert-indent "end\n"
9792 "// End of automatics\n"))))
9793
9794 (defun verilog-auto-templated-rel ()
9795 "Replace Templated relative line numbers with absolute line numbers.
9796 Internal use only. This hacks around the line numbers in AUTOINST Templates
9797 being different from the final output's line numbering."
9798 (let ((templateno 0) (template-line (list 0)))
9799 ;; Find line number each template is on
9800 (goto-char (point-min))
9801 (while (search-forward "AUTO_TEMPLATE" nil t)
9802 (setq templateno (1+ templateno))
9803 (setq template-line
9804 (cons (count-lines (point-min) (point)) template-line)))
9805 (setq template-line (nreverse template-line))
9806 ;; Replace T# L# with absolute line number
9807 (goto-char (point-min))
9808 (while (re-search-forward " Templated T\\([0-9]+\\) L\\([0-9]+\\)" nil t)
9809 (replace-match
9810 (concat " Templated "
9811 (int-to-string (+ (nth (string-to-number (match-string 1))
9812 template-line)
9813 (string-to-number (match-string 2)))))
9814 t t))))
9815
9816 \f
9817 ;;
9818 ;; Auto top level
9819 ;;
9820
9821 (defun verilog-auto (&optional inject) ; Use verilog-inject-auto instead of passing a arg
9822 "Expand AUTO statements.
9823 Look for any /*AUTO...*/ commands in the code, as used in
9824 instantiations or argument headers. Update the list of signals
9825 following the /*AUTO...*/ command.
9826
9827 Use \\[verilog-delete-auto] to remove the AUTOs.
9828
9829 Use \\[verilog-inject-auto] to insert AUTOs for the first time.
9830
9831 Use \\[verilog-faq] for a pointer to frequently asked questions.
9832
9833 The hooks `verilog-before-auto-hook' and `verilog-auto-hook' are
9834 called before and after this function, respectively.
9835
9836 For example:
9837 module ModuleName (/*AUTOARG*/)
9838 /*AUTOINPUT*/
9839 /*AUTOOUTPUT*/
9840 /*AUTOWIRE*/
9841 /*AUTOREG*/
9842 InstMod instName #(/*AUTOINSTPARAM*/) (/*AUTOINST*/);
9843
9844 You can also update the AUTOs from the shell using:
9845 emacs --batch <filenames.v> -f verilog-batch-auto
9846 Or fix indentation with:
9847 emacs --batch <filenames.v> -f verilog-batch-indent
9848 Likewise, you can delete or inject AUTOs with:
9849 emacs --batch <filenames.v> -f verilog-batch-delete-auto
9850 emacs --batch <filenames.v> -f verilog-batch-inject-auto
9851
9852 Using \\[describe-function], see also:
9853 `verilog-auto-arg' for AUTOARG module instantiations
9854 `verilog-auto-ascii-enum' for AUTOASCIIENUM enumeration decoding
9855 `verilog-auto-inout-module' for AUTOINOUTMODULE copying i/o from elsewhere
9856 `verilog-auto-inout' for AUTOINOUT making hierarchy inouts
9857 `verilog-auto-input' for AUTOINPUT making hierarchy inputs
9858 `verilog-auto-inst' for AUTOINST instantiation pins
9859 `verilog-auto-star' for AUTOINST .* SystemVerilog pins
9860 `verilog-auto-inst-param' for AUTOINSTPARAM instantiation params
9861 `verilog-auto-output' for AUTOOUTPUT making hierarchy outputs
9862 `verilog-auto-output-every' for AUTOOUTPUTEVERY making all outputs
9863 `verilog-auto-reg' for AUTOREG registers
9864 `verilog-auto-reg-input' for AUTOREGINPUT instantiation registers
9865 `verilog-auto-reset' for AUTORESET flop resets
9866 `verilog-auto-sense' for AUTOSENSE always sensitivity lists
9867 `verilog-auto-tieoff' for AUTOTIEOFF output tieoffs
9868 `verilog-auto-unused' for AUTOUNUSED unused inputs/inouts
9869 `verilog-auto-wire' for AUTOWIRE instantiation wires
9870
9871 `verilog-read-defines' for reading `define values
9872 `verilog-read-includes' for reading `includes
9873
9874 If you have bugs with these autos, try contacting the AUTOAUTHOR
9875 Wilson Snyder (wsnyder@wsnyder.org), and/or see http://www.veripool.com."
9876 (interactive)
9877 (unless noninteractive (message "Updating AUTOs..."))
9878 (if (fboundp 'dinotrace-unannotate-all)
9879 (dinotrace-unannotate-all))
9880 (let ((oldbuf (if (not (buffer-modified-p))
9881 (buffer-string)))
9882 ;; Before version 20, match-string with font-lock returns a
9883 ;; vector that is not equal to the string. IE if on "input"
9884 ;; nil==(equal "input" (progn (looking-at "input") (match-string 0)))
9885 (fontlocked (when (and (boundp 'font-lock-mode)
9886 font-lock-mode)
9887 (font-lock-mode nil)
9888 t))
9889 ;; Cache directories; we don't write new files, so can't change
9890 (verilog-dir-cache-preserving t))
9891 (unwind-protect
9892 (save-excursion
9893 ;; If we're not in verilog-mode, change syntax table so parsing works right
9894 (unless (eq major-mode `verilog-mode) (verilog-mode))
9895 ;; Allow user to customize
9896 (run-hooks 'verilog-before-auto-hook)
9897 ;; Try to save the user from needing to revert-file to reread file local-variables
9898 (verilog-auto-reeval-locals)
9899 (verilog-read-auto-lisp (point-min) (point-max))
9900 (verilog-getopt-flags)
9901 ;; From here on out, we can cache anything we read from disk
9902 (verilog-preserve-dir-cache
9903 ;; These two may seem obvious to do always, but on large includes it can be way too slow
9904 (when verilog-auto-read-includes
9905 (verilog-read-includes)
9906 (verilog-read-defines nil nil t))
9907 ;; This particular ordering is important
9908 ;; INST: Lower modules correct, no internal dependencies, FIRST
9909 (verilog-preserve-modi-cache
9910 ;; Clear existing autos else we'll be screwed by existing ones
9911 (verilog-delete-auto)
9912 ;; Injection if appropriate
9913 (when inject
9914 (verilog-inject-inst)
9915 (verilog-inject-sense)
9916 (verilog-inject-arg))
9917 ;;
9918 (verilog-auto-re-search-do "/\\*AUTOINSTPARAM\\*/" 'verilog-auto-inst-param)
9919 (verilog-auto-re-search-do "/\\*AUTOINST\\*/" 'verilog-auto-inst)
9920 (verilog-auto-re-search-do "\\.\\*" 'verilog-auto-star)
9921 ;; Doesn't matter when done, but combine it with a common changer
9922 (verilog-auto-re-search-do "/\\*\\(AUTOSENSE\\|AS\\)\\*/" 'verilog-auto-sense)
9923 (verilog-auto-re-search-do "/\\*AUTORESET\\*/" 'verilog-auto-reset)
9924 ;; Must be done before autoin/out as creates a reg
9925 (verilog-auto-re-search-do "/\\*AUTOASCIIENUM([^)]*)\\*/" 'verilog-auto-ascii-enum)
9926 ;;
9927 ;; first in/outs from other files
9928 (verilog-auto-re-search-do "/\\*AUTOINOUTMODULE([^)]*)\\*/" 'verilog-auto-inout-module)
9929 ;; next in/outs which need previous sucked inputs first
9930 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\((\"[^\"]*\")\\)\\*/"
9931 '(lambda () (verilog-auto-output t)))
9932 (verilog-auto-re-search-do "/\\*AUTOOUTPUT\\*/" 'verilog-auto-output)
9933 (verilog-auto-re-search-do "/\\*AUTOINPUT\\((\"[^\"]*\")\\)\\*/"
9934 '(lambda () (verilog-auto-input t)))
9935 (verilog-auto-re-search-do "/\\*AUTOINPUT\\*/" 'verilog-auto-input)
9936 (verilog-auto-re-search-do "/\\*AUTOINOUT\\((\"[^\"]*\")\\)\\*/"
9937 '(lambda () (verilog-auto-inout t)))
9938 (verilog-auto-re-search-do "/\\*AUTOINOUT\\*/" 'verilog-auto-inout)
9939 ;; Then tie off those in/outs
9940 (verilog-auto-re-search-do "/\\*AUTOTIEOFF\\*/" 'verilog-auto-tieoff)
9941 ;; Wires/regs must be after inputs/outputs
9942 (verilog-auto-re-search-do "/\\*AUTOWIRE\\*/" 'verilog-auto-wire)
9943 (verilog-auto-re-search-do "/\\*AUTOREG\\*/" 'verilog-auto-reg)
9944 (verilog-auto-re-search-do "/\\*AUTOREGINPUT\\*/" 'verilog-auto-reg-input)
9945 ;; outputevery needs AUTOOUTPUTs done first
9946 (verilog-auto-re-search-do "/\\*AUTOOUTPUTEVERY\\*/" 'verilog-auto-output-every)
9947 ;; After we've created all new variables
9948 (verilog-auto-re-search-do "/\\*AUTOUNUSED\\*/" 'verilog-auto-unused)
9949 ;; Must be after all inputs outputs are generated
9950 (verilog-auto-re-search-do "/\\*AUTOARG\\*/" 'verilog-auto-arg)
9951 ;; Fix line numbers (comments only)
9952 (verilog-auto-templated-rel)))
9953 ;;
9954 (run-hooks 'verilog-auto-hook)
9955 ;;
9956 (set (make-local-variable 'verilog-auto-update-tick) (buffer-modified-tick))
9957 ;;
9958 ;; If end result is same as when started, clear modified flag
9959 (cond ((and oldbuf (equal oldbuf (buffer-string)))
9960 (set-buffer-modified-p nil)
9961 (unless noninteractive (message "Updating AUTOs...done (no changes)")))
9962 (t (unless noninteractive (message "Updating AUTOs...done"))))))
9963 ;; Unwind forms
9964 (progn
9965 ;; Restore font-lock
9966 (when fontlocked (font-lock-mode t)))))
9967 \f
9968
9969 ;;
9970 ;; Skeleton based code insertion
9971 ;;
9972 (defvar verilog-template-map
9973 (let ((map (make-sparse-keymap)))
9974 (define-key map "a" 'verilog-sk-always)
9975 (define-key map "b" 'verilog-sk-begin)
9976 (define-key map "c" 'verilog-sk-case)
9977 (define-key map "f" 'verilog-sk-for)
9978 (define-key map "g" 'verilog-sk-generate)
9979 (define-key map "h" 'verilog-sk-header)
9980 (define-key map "i" 'verilog-sk-initial)
9981 (define-key map "j" 'verilog-sk-fork)
9982 (define-key map "m" 'verilog-sk-module)
9983 (define-key map "p" 'verilog-sk-primitive)
9984 (define-key map "r" 'verilog-sk-repeat)
9985 (define-key map "s" 'verilog-sk-specify)
9986 (define-key map "t" 'verilog-sk-task)
9987 (define-key map "w" 'verilog-sk-while)
9988 (define-key map "x" 'verilog-sk-casex)
9989 (define-key map "z" 'verilog-sk-casez)
9990 (define-key map "?" 'verilog-sk-if)
9991 (define-key map ":" 'verilog-sk-else-if)
9992 (define-key map "/" 'verilog-sk-comment)
9993 (define-key map "A" 'verilog-sk-assign)
9994 (define-key map "F" 'verilog-sk-function)
9995 (define-key map "I" 'verilog-sk-input)
9996 (define-key map "O" 'verilog-sk-output)
9997 (define-key map "S" 'verilog-sk-state-machine)
9998 (define-key map "=" 'verilog-sk-inout)
9999 (define-key map "W" 'verilog-sk-wire)
10000 (define-key map "R" 'verilog-sk-reg)
10001 (define-key map "D" 'verilog-sk-define-signal)
10002 map)
10003 "Keymap used in Verilog mode for smart template operations.")
10004
10005
10006 ;;
10007 ;; Place the templates into Verilog Mode. They may be inserted under any key.
10008 ;; C-c C-t will be the default. If you use templates a lot, you
10009 ;; may want to consider moving the binding to another key in your .emacs
10010 ;; file.
10011 ;;
10012 ;(define-key verilog-mode-map "\C-ct" verilog-template-map)
10013 (define-key verilog-mode-map "\C-c\C-t" verilog-template-map)
10014
10015 ;;; ---- statement skeletons ------------------------------------------
10016
10017 (define-skeleton verilog-sk-prompt-condition
10018 "Prompt for the loop condition."
10019 "[condition]: " str )
10020
10021 (define-skeleton verilog-sk-prompt-init
10022 "Prompt for the loop init statement."
10023 "[initial statement]: " str )
10024
10025 (define-skeleton verilog-sk-prompt-inc
10026 "Prompt for the loop increment statement."
10027 "[increment statement]: " str )
10028
10029 (define-skeleton verilog-sk-prompt-name
10030 "Prompt for the name of something."
10031 "[name]: " str)
10032
10033 (define-skeleton verilog-sk-prompt-clock
10034 "Prompt for the name of something."
10035 "name and edge of clock(s): " str)
10036
10037 (defvar verilog-sk-reset nil)
10038 (defun verilog-sk-prompt-reset ()
10039 "Prompt for the name of a state machine reset."
10040 (setq verilog-sk-reset (read-string "name of reset: " "rst")))
10041
10042
10043 (define-skeleton verilog-sk-prompt-state-selector
10044 "Prompt for the name of a state machine selector."
10045 "name of selector (eg {a,b,c,d}): " str )
10046
10047 (define-skeleton verilog-sk-prompt-output
10048 "Prompt for the name of something."
10049 "output: " str)
10050
10051 (define-skeleton verilog-sk-prompt-msb
10052 "Prompt for least significant bit specification."
10053 "msb:" str & ?: & '(verilog-sk-prompt-lsb) | -1 )
10054
10055 (define-skeleton verilog-sk-prompt-lsb
10056 "Prompt for least significant bit specification."
10057 "lsb:" str )
10058
10059 (defvar verilog-sk-p nil)
10060 (define-skeleton verilog-sk-prompt-width
10061 "Prompt for a width specification."
10062 ()
10063 (progn
10064 (setq verilog-sk-p (point))
10065 (verilog-sk-prompt-msb)
10066 (if (> (point) verilog-sk-p) "] " " ")))
10067
10068 (defun verilog-sk-header ()
10069 "Insert a descriptive header at the top of the file."
10070 (interactive "*")
10071 (save-excursion
10072 (goto-char (point-min))
10073 (verilog-sk-header-tmpl)))
10074
10075 (define-skeleton verilog-sk-header-tmpl
10076 "Insert a comment block containing the module title, author, etc."
10077 "[Description]: "
10078 "// -*- Mode: Verilog -*-"
10079 "\n// Filename : " (buffer-name)
10080 "\n// Description : " str
10081 "\n// Author : " (user-full-name)
10082 "\n// Created On : " (current-time-string)
10083 "\n// Last Modified By: ."
10084 "\n// Last Modified On: ."
10085 "\n// Update Count : 0"
10086 "\n// Status : Unknown, Use with caution!"
10087 "\n")
10088
10089 (define-skeleton verilog-sk-module
10090 "Insert a module definition."
10091 ()
10092 > "module " '(verilog-sk-prompt-name) " (/*AUTOARG*/ ) ;" \n
10093 > _ \n
10094 > (- verilog-indent-level-behavioral) "endmodule" (progn (electric-verilog-terminate-line) nil))
10095
10096 (define-skeleton verilog-sk-primitive
10097 "Insert a task definition."
10098 ()
10099 > "primitive " '(verilog-sk-prompt-name) " ( " '(verilog-sk-prompt-output) ("input:" ", " str ) " );"\n
10100 > _ \n
10101 > (- verilog-indent-level-behavioral) "endprimitive" (progn (electric-verilog-terminate-line) nil))
10102
10103 (define-skeleton verilog-sk-task
10104 "Insert a task definition."
10105 ()
10106 > "task " '(verilog-sk-prompt-name) & ?; \n
10107 > _ \n
10108 > "begin" \n
10109 > \n
10110 > (- verilog-indent-level-behavioral) "end" \n
10111 > (- verilog-indent-level-behavioral) "endtask" (progn (electric-verilog-terminate-line) nil))
10112
10113 (define-skeleton verilog-sk-function
10114 "Insert a function definition."
10115 ()
10116 > "function [" '(verilog-sk-prompt-width) | -1 '(verilog-sk-prompt-name) ?; \n
10117 > _ \n
10118 > "begin" \n
10119 > \n
10120 > (- verilog-indent-level-behavioral) "end" \n
10121 > (- verilog-indent-level-behavioral) "endfunction" (progn (electric-verilog-terminate-line) nil))
10122
10123 (define-skeleton verilog-sk-always
10124 "Insert always block. Uses the minibuffer to prompt
10125 for sensitivity list."
10126 ()
10127 > "always @ ( /*AUTOSENSE*/ ) begin\n"
10128 > _ \n
10129 > (- verilog-indent-level-behavioral) "end" \n >
10130 )
10131
10132 (define-skeleton verilog-sk-initial
10133 "Insert an initial block."
10134 ()
10135 > "initial begin\n"
10136 > _ \n
10137 > (- verilog-indent-level-behavioral) "end" \n > )
10138
10139 (define-skeleton verilog-sk-specify
10140 "Insert specify block. "
10141 ()
10142 > "specify\n"
10143 > _ \n
10144 > (- verilog-indent-level-behavioral) "endspecify" \n > )
10145
10146 (define-skeleton verilog-sk-generate
10147 "Insert generate block. "
10148 ()
10149 > "generate\n"
10150 > _ \n
10151 > (- verilog-indent-level-behavioral) "endgenerate" \n > )
10152
10153 (define-skeleton verilog-sk-begin
10154 "Insert begin end block. Uses the minibuffer to prompt for name."
10155 ()
10156 > "begin" '(verilog-sk-prompt-name) \n
10157 > _ \n
10158 > (- verilog-indent-level-behavioral) "end"
10159 )
10160
10161 (define-skeleton verilog-sk-fork
10162 "Insert a fork join block."
10163 ()
10164 > "fork\n"
10165 > "begin" \n
10166 > _ \n
10167 > (- verilog-indent-level-behavioral) "end" \n
10168 > "begin" \n
10169 > \n
10170 > (- verilog-indent-level-behavioral) "end" \n
10171 > (- verilog-indent-level-behavioral) "join" \n
10172 > )
10173
10174
10175 (define-skeleton verilog-sk-case
10176 "Build skeleton case statement, prompting for the selector expression,
10177 and the case items."
10178 "[selector expression]: "
10179 > "case (" str ") " \n
10180 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
10181 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
10182
10183 (define-skeleton verilog-sk-casex
10184 "Build skeleton casex statement, prompting for the selector expression,
10185 and the case items."
10186 "[selector expression]: "
10187 > "casex (" str ") " \n
10188 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
10189 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
10190
10191 (define-skeleton verilog-sk-casez
10192 "Build skeleton casez statement, prompting for the selector expression,
10193 and the case items."
10194 "[selector expression]: "
10195 > "casez (" str ") " \n
10196 > ("case selector: " str ": begin" \n > _ \n > (- verilog-indent-level-behavioral) "end" \n )
10197 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil))
10198
10199 (define-skeleton verilog-sk-if
10200 "Insert a skeleton if statement."
10201 > "if (" '(verilog-sk-prompt-condition) & ")" " begin" \n
10202 > _ \n
10203 > (- verilog-indent-level-behavioral) "end " \n )
10204
10205 (define-skeleton verilog-sk-else-if
10206 "Insert a skeleton else if statement."
10207 > (verilog-indent-line) "else if ("
10208 (progn (setq verilog-sk-p (point)) nil) '(verilog-sk-prompt-condition) (if (> (point) verilog-sk-p) ") " -1 ) & " begin" \n
10209 > _ \n
10210 > "end" (progn (electric-verilog-terminate-line) nil))
10211
10212 (define-skeleton verilog-sk-datadef
10213 "Common routine to get data definition."
10214 ()
10215 '(verilog-sk-prompt-width) | -1 ("name (RET to end):" str ", ") -2 ";" \n)
10216
10217 (define-skeleton verilog-sk-input
10218 "Insert an input definition."
10219 ()
10220 > "input [" '(verilog-sk-datadef))
10221
10222 (define-skeleton verilog-sk-output
10223 "Insert an output definition."
10224 ()
10225 > "output [" '(verilog-sk-datadef))
10226
10227 (define-skeleton verilog-sk-inout
10228 "Insert an inout definition."
10229 ()
10230 > "inout [" '(verilog-sk-datadef))
10231
10232 (defvar verilog-sk-signal nil)
10233 (define-skeleton verilog-sk-def-reg
10234 "Insert a reg definition."
10235 ()
10236 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-signal ";" \n (verilog-pretty-declarations) )
10237
10238 (defun verilog-sk-define-signal ()
10239 "Insert a definition of signal under point at top of module."
10240 (interactive "*")
10241 (let* ((sig-re "[a-zA-Z0-9_]*")
10242 (v1 (buffer-substring
10243 (save-excursion
10244 (skip-chars-backward sig-re)
10245 (point))
10246 (save-excursion
10247 (skip-chars-forward sig-re)
10248 (point)))))
10249 (if (not (member v1 verilog-keywords))
10250 (save-excursion
10251 (setq verilog-sk-signal v1)
10252 (verilog-beg-of-defun)
10253 (verilog-end-of-statement)
10254 (verilog-forward-syntactic-ws)
10255 (verilog-sk-def-reg)
10256 (message "signal at point is %s" v1))
10257 (message "object at point (%s) is a keyword" v1))))
10258
10259 (define-skeleton verilog-sk-wire
10260 "Insert a wire definition."
10261 ()
10262 > "wire [" '(verilog-sk-datadef))
10263
10264 (define-skeleton verilog-sk-reg
10265 "Insert a reg definition."
10266 ()
10267 > "reg [" '(verilog-sk-datadef))
10268
10269 (define-skeleton verilog-sk-assign
10270 "Insert a skeleton assign statement."
10271 ()
10272 > "assign " '(verilog-sk-prompt-name) " = " _ ";" \n)
10273
10274 (define-skeleton verilog-sk-while
10275 "Insert a skeleton while loop statement."
10276 ()
10277 > "while (" '(verilog-sk-prompt-condition) ") begin" \n
10278 > _ \n
10279 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
10280
10281 (define-skeleton verilog-sk-repeat
10282 "Insert a skeleton repeat loop statement."
10283 ()
10284 > "repeat (" '(verilog-sk-prompt-condition) ") begin" \n
10285 > _ \n
10286 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
10287
10288 (define-skeleton verilog-sk-for
10289 "Insert a skeleton while loop statement."
10290 ()
10291 > "for ("
10292 '(verilog-sk-prompt-init) "; "
10293 '(verilog-sk-prompt-condition) "; "
10294 '(verilog-sk-prompt-inc)
10295 ") begin" \n
10296 > _ \n
10297 > (- verilog-indent-level-behavioral) "end " (progn (electric-verilog-terminate-line) nil))
10298
10299 (define-skeleton verilog-sk-comment
10300 "Inserts three comment lines, making a display comment."
10301 ()
10302 > "/*\n"
10303 > "* " _ \n
10304 > "*/")
10305
10306 (define-skeleton verilog-sk-state-machine
10307 "Insert a state machine definition."
10308 "Name of state variable: "
10309 '(setq input "state")
10310 > "// State registers for " str | -23 \n
10311 '(setq verilog-sk-state str)
10312 > "reg [" '(verilog-sk-prompt-width) | -1 verilog-sk-state ", next_" verilog-sk-state ?; \n
10313 '(setq input nil)
10314 > \n
10315 > "// State FF for " verilog-sk-state \n
10316 > "always @ ( " (read-string "clock:" "posedge clk") " or " (verilog-sk-prompt-reset) " ) begin" \n
10317 > "if ( " verilog-sk-reset " ) " verilog-sk-state " = 0; else" \n
10318 > verilog-sk-state " = next_" verilog-sk-state ?; \n
10319 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil)
10320 > \n
10321 > "// Next State Logic for " verilog-sk-state \n
10322 > "always @ ( /*AUTOSENSE*/ ) begin\n"
10323 > "case (" '(verilog-sk-prompt-state-selector) ") " \n
10324 > ("case selector: " str ": begin" \n > "next_" verilog-sk-state " = " _ ";" \n > (- verilog-indent-level-behavioral) "end" \n )
10325 resume: > (- verilog-case-indent) "endcase" (progn (electric-verilog-terminate-line) nil)
10326 > (- verilog-indent-level-behavioral) "end" (progn (electric-verilog-terminate-line) nil))
10327 \f
10328
10329 ;;
10330 ;; Include file loading with mouse/return event
10331 ;;
10332 ;; idea & first impl.: M. Rouat (eldo-mode.el)
10333 ;; second (emacs/xemacs) impl.: G. Van der Plas (spice-mode.el)
10334
10335 (if (featurep 'xemacs)
10336 (require 'overlay)
10337 (require 'lucid)) ;; what else can we do ??
10338
10339 (defconst verilog-include-file-regexp
10340 "^`include\\s-+\"\\([^\n\"]*\\)\""
10341 "Regexp that matches the include file.")
10342
10343 (defvar verilog-mode-mouse-map
10344 (let ((map (make-sparse-keymap))) ; as described in info pages, make a map
10345 (set-keymap-parent map verilog-mode-map)
10346 ;; mouse button bindings
10347 (define-key map "\r" 'verilog-load-file-at-point)
10348 (if (featurep 'xemacs)
10349 (define-key map 'button2 'verilog-load-file-at-mouse);ffap-at-mouse ?
10350 (define-key map [mouse-2] 'verilog-load-file-at-mouse))
10351 (if (featurep 'xemacs)
10352 (define-key map 'Sh-button2 'mouse-yank) ; you wanna paste don't you ?
10353 (define-key map [S-mouse-2] 'mouse-yank-at-click))
10354 map)
10355 "Map containing mouse bindings for `verilog-mode'.")
10356
10357
10358 (defun verilog-colorize-include-files (beg end old-len)
10359 "This function colorizes included files when the mouse passes over them.
10360 Clicking on the middle-mouse button loads them in a buffer (as in dired)."
10361 (save-excursion
10362 (save-match-data
10363 (let (end-point)
10364 (goto-char end)
10365 (setq end-point (verilog-get-end-of-line))
10366 (goto-char beg)
10367 (beginning-of-line) ; scan entire line !
10368 ;; delete overlays existing on this line
10369 (let ((overlays (overlays-in (point) end-point)))
10370 (while overlays
10371 (if (and
10372 (overlay-get (car overlays) 'detachable)
10373 (overlay-get (car overlays) 'verilog-include-file))
10374 (delete-overlay (car overlays)))
10375 (setq overlays (cdr overlays)))) ; let
10376 ;; make new ones, could reuse deleted one ?
10377 (while (search-forward-regexp verilog-include-file-regexp end-point t)
10378 (let (ov)
10379 (goto-char (match-beginning 1))
10380 (setq ov (make-overlay (match-beginning 1) (match-end 1)))
10381 (overlay-put ov 'start-closed 't)
10382 (overlay-put ov 'end-closed 't)
10383 (overlay-put ov 'evaporate 't)
10384 (overlay-put ov 'verilog-include-file 't)
10385 (overlay-put ov 'mouse-face 'highlight)
10386 (overlay-put ov 'local-map verilog-mode-mouse-map)))))))
10387
10388
10389 (defun verilog-colorize-include-files-buffer ()
10390 "Colorize an include file."
10391 (interactive)
10392 ;; delete overlays
10393 (let ((overlays (overlays-in (point-min) (point-max))))
10394 (while overlays
10395 (if (and
10396 (overlay-get (car overlays) 'detachable)
10397 (overlay-get (car overlays) 'verilog-include-file))
10398 (delete-overlay (car overlays)))
10399 (setq overlays (cdr overlays)))) ; let
10400 ;; remake overlays
10401 (verilog-colorize-include-files (point-min) (point-max) nil))
10402
10403 ;; ffap-at-mouse isn't useful for Verilog mode. It uses library paths.
10404 ;; so define this function to do more or less the same as ffap-at-mouse
10405 ;; but first resolve filename...
10406 (defun verilog-load-file-at-mouse (event)
10407 "Load file under button 2 click's EVENT.
10408 Files are checked based on `verilog-library-directories'."
10409 (interactive "@e")
10410 (save-excursion ;; implement a Verilog specific ffap-at-mouse
10411 (mouse-set-point event)
10412 (beginning-of-line)
10413 (if (looking-at verilog-include-file-regexp)
10414 (if (and (car (verilog-library-filenames
10415 (match-string 1) (buffer-file-name)))
10416 (file-readable-p (car (verilog-library-filenames
10417 (match-string 1) (buffer-file-name)))))
10418 (find-file (car (verilog-library-filenames
10419 (match-string 1) (buffer-file-name))))
10420 (progn
10421 (message
10422 "File '%s' isn't readable, use shift-mouse2 to paste in this field"
10423 (match-string 1)))))))
10424
10425 ;; ffap isn't useable for Verilog mode. It uses library paths.
10426 ;; so define this function to do more or less the same as ffap
10427 ;; but first resolve filename...
10428 (defun verilog-load-file-at-point ()
10429 "Load file under point.
10430 Files are checked based on `verilog-library-directories'."
10431 (interactive)
10432 (save-excursion ;; implement a Verilog specific ffap
10433 (beginning-of-line)
10434 (if (looking-at verilog-include-file-regexp)
10435 (if (and
10436 (car (verilog-library-filenames
10437 (match-string 1) (buffer-file-name)))
10438 (file-readable-p (car (verilog-library-filenames
10439 (match-string 1) (buffer-file-name)))))
10440 (find-file (car (verilog-library-filenames
10441 (match-string 1) (buffer-file-name))))))))
10442
10443
10444 ;;
10445 ;; Bug reporting
10446 ;;
10447
10448 (defun verilog-faq ()
10449 "Tell the user their current version, and where to get the FAQ etc."
10450 (interactive)
10451 (with-output-to-temp-buffer "*verilog-mode help*"
10452 (princ (format "You are using verilog-mode %s\n" verilog-mode-version))
10453 (princ "\n")
10454 (princ "For new releases, see http://www.verilog.com\n")
10455 (princ "\n")
10456 (princ "For frequently asked questions, see http://www.veripool.com/verilog-mode-faq.html\n")
10457 (princ "\n")
10458 (princ "To submit a bug, use M-x verilog-submit-bug-report\n")
10459 (princ "\n")))
10460
10461 (autoload 'reporter-submit-bug-report "reporter")
10462 (defvar reporter-prompt-for-summary-p)
10463
10464 (defun verilog-submit-bug-report ()
10465 "Submit via mail a bug report on verilog-mode.el."
10466 (interactive)
10467 (let ((reporter-prompt-for-summary-p t))
10468 (reporter-submit-bug-report
10469 "mac@verilog.com"
10470 (concat "verilog-mode v" verilog-mode-version)
10471 '(
10472 verilog-align-ifelse
10473 verilog-auto-endcomments
10474 verilog-auto-hook
10475 verilog-auto-indent-on-newline
10476 verilog-auto-inst-vector
10477 verilog-auto-inst-template-numbers
10478 verilog-auto-lineup
10479 verilog-auto-newline
10480 verilog-auto-save-policy
10481 verilog-auto-sense-defines-constant
10482 verilog-auto-sense-include-inputs
10483 verilog-before-auto-hook
10484 verilog-case-indent
10485 verilog-cexp-indent
10486 verilog-compiler
10487 verilog-coverage
10488 verilog-highlight-translate-off
10489 verilog-indent-begin-after-if
10490 verilog-indent-declaration-macros
10491 verilog-indent-level
10492 verilog-indent-level-behavioral
10493 verilog-indent-level-declaration
10494 verilog-indent-level-directive
10495 verilog-indent-level-module
10496 verilog-indent-lists
10497 verilog-library-flags
10498 verilog-library-directories
10499 verilog-library-extensions
10500 verilog-library-files
10501 verilog-linter
10502 verilog-minimum-comment-distance
10503 verilog-mode-hook
10504 verilog-simulator
10505 verilog-tab-always-indent
10506 verilog-tab-to-comment
10507 )
10508 nil nil
10509 (concat "Hi Mac,
10510
10511 I want to report a bug. I've read the `Bugs' section of `Info' on
10512 Emacs, so I know how to make a clear and unambiguous report. To get
10513 to that Info section, I typed
10514
10515 M-x info RET m " invocation-name " RET m bugs RET
10516
10517 Before I go further, I want to say that Verilog mode has changed my life.
10518 I save so much time, my files are colored nicely, my co workers respect
10519 my coding ability... until now. I'd really appreciate anything you
10520 could do to help me out with this minor deficiency in the product.
10521
10522 If you have bugs with the AUTO functions, please CC the AUTOAUTHOR Wilson
10523 Snyder (wsnyder@wsnyder.org) and/or see http://www.veripool.com.
10524 You may also want to look at the Verilog-Mode FAQ, see
10525 http://www.veripool.com/verilog-mode-faq.html.
10526
10527 To reproduce the bug, start a fresh Emacs via " invocation-name "
10528 -no-init-file -no-site-file'. In a new buffer, in Verilog mode, type
10529 the code included below.
10530
10531 Given those lines, I expected [[Fill in here]] to happen;
10532 but instead, [[Fill in here]] happens!.
10533
10534 == The code: =="))))
10535
10536 (provide 'verilog-mode)
10537
10538 ;; Local Variables:
10539 ;; checkdoc-permit-comma-termination-flag:t
10540 ;; checkdoc-force-docstrings-flag:nil
10541 ;; End:
10542
10543 ;; arch-tag: 87923725-57b3-41b5-9494-be21118c6a6f
10544 ;;; verilog-mode.el ends here